prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Enumeration;
using System.Linq;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using Microsoft.Build.Utilities;
using Microsoft.VisualBasic.FileIO;
namespace Microsoft.Build.Shared
{
internal class FileMatcher
{
private class TaskOptions
{
public readonly int MaxTasks;
public int AvailableTasks;
public int MaxTasksPerIteration;
public TaskOptions(int maxTasks)
{
MaxTasks = maxTasks;
}
}
private struct RecursiveStepResult
{
public string RemainingWildcardDirectory;
public bool ConsiderFiles;
public bool NeedsToProcessEachFile;
public string DirectoryPattern;
public bool NeedsDirectoryRecursion;
}
private enum SearchAction
{
RunSearch,
ReturnFileSpec,
ReturnEmptyList
}
internal enum FileSystemEntity
{
Files,
Directories,
FilesAndDirectories
}
private class FilesSearchData
{
public string Filespec { get; }
public string DirectoryPattern { get; }
public Regex RegexFileMatch { get; }
public bool NeedsRecursion { get; }
public FilesSearchData(string filespec, string directoryPattern, Regex regexFileMatch, bool needsRecursion)
{
Filespec = filespec;
DirectoryPattern = directoryPattern;
RegexFileMatch = regexFileMatch;
NeedsRecursion = needsRecursion;
}
}
internal sealed class Result
{
internal bool isLegalFileSpec;
internal bool isMatch;
internal bool isFileSpecRecursive;
internal string wildcardDirectoryPart = string.Empty;
internal Result()
{
}
}
private struct RecursionState
{
public string BaseDirectory;
public string RemainingWildcardDirectory;
public bool IsInsideMatchingDirectory;
public FilesSearchData SearchData;
public bool IsLookingForMatchingDirectory
{
get
{
if (SearchData.DirectoryPattern != null)
{
return !IsInsideMatchingDirectory;
}
return false;
}
}
}
private static readonly string s_directorySeparator = new string(Path.DirectorySeparatorChar, 1);
private static readonly string s_thisDirectory = "." + s_directorySeparator;
public static FileMatcher Default = new FileMatcher(FileSystems.Default);
private static readonly char[] s_wildcardCharacters = new char[2] { '*', '?' };
internal delegate IReadOnlyList<string> GetFileSystemEntries(FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory);
private readonly ConcurrentDictionary<string, IReadOnlyList<string>> _cachedGlobExpansions;
private readonly Lazy<ConcurrentDictionary<string, object>> _cachedGlobExpansionsLock = new Lazy<ConcurrentDictionary<string, object>>(() => new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase));
private static readonly Lazy<ConcurrentDictionary<string, IReadOnlyList<string>>> s_cachedGlobExpansions = new Lazy<ConcurrentDictionary<string, IReadOnlyList<string>>>(() => new ConcurrentDictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase));
private static readonly Lazy<ConcurrentDictionary<string, object>> s_cachedGlobExpansionsLock = new Lazy<ConcurrentDictionary<string, object>>(() => new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase));
private readonly IFileSystem _fileSystem;
private readonly GetFileSystemEntries _getFileSystemEntries;
internal static readonly char[] directorySeparatorCharacters = FileUtilities.Slashes;
private static readonly char[] s_invalidPathChars = Path.GetInvalidPathChars();
public FileMatcher(IFileSystem fileSystem, ConcurrentDictionary<string, IReadOnlyList<string>> fileEntryExpansionCache = null)
: this(fileSystem, (FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory) => GetAccessibleFileSystemEntries(fileSystem, entityType, path, pattern, projectDirectory, stripProjectDirectory).ToArray(), fileEntryExpansionCache)
{
}
internal FileMatcher( | IFileSystem fileSystem, GetFileSystemEntries getFileSystemEntries, ConcurrentDictionary<string, IReadOnlyList<string>> getFileSystemDirectoryEntriesCache = null)
{ |
if (/*Traits.Instance.MSBuildCacheFileEnumerations*/false)
{
_cachedGlobExpansions = s_cachedGlobExpansions.Value;
_cachedGlobExpansionsLock = s_cachedGlobExpansionsLock;
}
else
{
_cachedGlobExpansions = getFileSystemDirectoryEntriesCache;
}
_fileSystem = fileSystem;
_getFileSystemEntries = ((getFileSystemDirectoryEntriesCache == null) ? getFileSystemEntries : ((GetFileSystemEntries)delegate (FileSystemEntity type, string path, string pattern, string directory, bool stripProjectDirectory)
{
#if __
if (ChangeWaves.AreFeaturesEnabled(ChangeWaves.Wave16_10))
{
string key = type switch
{
FileSystemEntity.Files => "F",
FileSystemEntity.Directories => "D",
FileSystemEntity.FilesAndDirectories => "A",
_ => throw new NotImplementedException(),
} + ";" + path;
IReadOnlyList<string> orAdd = getFileSystemDirectoryEntriesCache.GetOrAdd(key, (string s) => getFileSystemEntries(type, path, "*", directory, stripProjectDirectory: false));
IEnumerable<string> enumerable2;
if (pattern == null || IsAllFilesWildcard(pattern))
{
IEnumerable<string> enumerable = orAdd;
enumerable2 = enumerable;
}
else
{
enumerable2 = orAdd.Where((string o) => IsMatch(Path.GetFileName(o), pattern));
}
IEnumerable<string> enumerable3 = enumerable2;
if (!stripProjectDirectory)
{
return enumerable3.ToArray();
}
return RemoveProjectDirectory(enumerable3, directory).ToArray();
}
#endif
return (type == FileSystemEntity.Directories) ? getFileSystemDirectoryEntriesCache.GetOrAdd("D;" + path + ";" + (pattern ?? "*"), (string s) => getFileSystemEntries(type, path, pattern, directory, stripProjectDirectory).ToArray()) : getFileSystemEntries(type, path, pattern, directory, stripProjectDirectory);
}));
}
internal static bool HasWildcards(string filespec)
{
return -1 != filespec.LastIndexOfAny(s_wildcardCharacters);
}
private static IReadOnlyList<string> GetAccessibleFileSystemEntries(IFileSystem fileSystem, FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory)
{
path = FileUtilities.FixFilePath(path);
switch (entityType)
{
case FileSystemEntity.Files:
return GetAccessibleFiles(fileSystem, path, pattern, projectDirectory, stripProjectDirectory);
case FileSystemEntity.Directories:
return GetAccessibleDirectories(fileSystem, path, pattern);
case FileSystemEntity.FilesAndDirectories:
return GetAccessibleFilesAndDirectories(fileSystem, path, pattern);
default:
ErrorUtilities.VerifyThrow(condition: false, "Unexpected filesystem entity type.");
return Array.Empty<string>();
}
}
private static IReadOnlyList<string> GetAccessibleFilesAndDirectories(IFileSystem fileSystem, string path, string pattern)
{
if (fileSystem.DirectoryExists(path))
{
try
{
return (ShouldEnforceMatching(pattern) ? (from o in fileSystem.EnumerateFileSystemEntries(path, pattern)
where IsMatch(Path.GetFileName(o), pattern)
select o) : fileSystem.EnumerateFileSystemEntries(path, pattern)).ToArray();
}
catch (UnauthorizedAccessException)
{
}
catch (SecurityException)
{
}
}
return Array.Empty<string>();
}
private static bool ShouldEnforceMatching(string searchPattern)
{
if (searchPattern == null)
{
return false;
}
if (searchPattern.IndexOf("?.", StringComparison.Ordinal) == -1 && (Path.GetExtension(searchPattern).Length != 4 || searchPattern.IndexOf('*') == -1))
{
return searchPattern.EndsWith("?", StringComparison.Ordinal);
}
return true;
}
private static IReadOnlyList<string> GetAccessibleFiles(IFileSystem fileSystem, string path, string filespec, string projectDirectory, bool stripProjectDirectory)
{
try
{
string path2 = ((path.Length == 0) ? s_thisDirectory : path);
IEnumerable<string> enumerable;
if (filespec == null)
{
enumerable = fileSystem.EnumerateFiles(path2);
}
else
{
enumerable = fileSystem.EnumerateFiles(path2, filespec);
if (ShouldEnforceMatching(filespec))
{
enumerable = enumerable.Where((string o) => IsMatch(Path.GetFileName(o), filespec));
}
}
if (stripProjectDirectory)
{
enumerable = RemoveProjectDirectory(enumerable, projectDirectory);
}
else if (!path.StartsWith(s_thisDirectory, StringComparison.Ordinal))
{
enumerable = RemoveInitialDotSlash(enumerable);
}
return enumerable.ToArray();
}
catch (SecurityException)
{
return Array.Empty<string>();
}
catch (UnauthorizedAccessException)
{
return Array.Empty<string>();
}
}
private static IReadOnlyList<string> GetAccessibleDirectories(IFileSystem fileSystem, string path, string pattern)
{
try
{
IEnumerable<string> enumerable = null;
if (pattern == null)
{
enumerable = fileSystem.EnumerateDirectories((path.Length == 0) ? s_thisDirectory : path);
}
else
{
enumerable = fileSystem.EnumerateDirectories((path.Length == 0) ? s_thisDirectory : path, pattern);
if (ShouldEnforceMatching(pattern))
{
enumerable = enumerable.Where((string o) => IsMatch(Path.GetFileName(o), pattern));
}
}
if (!path.StartsWith(s_thisDirectory, StringComparison.Ordinal))
{
enumerable = RemoveInitialDotSlash(enumerable);
}
return enumerable.ToArray();
}
catch (SecurityException)
{
return Array.Empty<string>();
}
catch (UnauthorizedAccessException)
{
return Array.Empty<string>();
}
}
private static IEnumerable<string> RemoveInitialDotSlash(IEnumerable<string> paths)
{
foreach (string path in paths)
{
if (path.StartsWith(s_thisDirectory, StringComparison.Ordinal))
{
yield return path.Substring(2);
}
else
{
yield return path;
}
}
}
internal static bool IsDirectorySeparator(char c)
{
if (c != Path.DirectorySeparatorChar)
{
return c == Path.AltDirectorySeparatorChar;
}
return true;
}
internal static IEnumerable<string> RemoveProjectDirectory(IEnumerable<string> paths, string projectDirectory)
{
bool directoryLastCharIsSeparator = IsDirectorySeparator(projectDirectory[projectDirectory.Length - 1]);
foreach (string path in paths)
{
if (path.StartsWith(projectDirectory, StringComparison.Ordinal))
{
if (!directoryLastCharIsSeparator)
{
if (path.Length <= projectDirectory.Length || !IsDirectorySeparator(path[projectDirectory.Length]))
{
yield return path;
}
else
{
yield return path.Substring(projectDirectory.Length + 1);
}
}
else
{
yield return path.Substring(projectDirectory.Length);
}
}
else
{
yield return path;
}
}
}
internal static bool IsMatch(string input, string pattern)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
if (pattern == null)
{
throw new ArgumentNullException("pattern");
}
int num = pattern.Length;
int num2 = input.Length;
int num3 = -1;
int num4 = -1;
int i = 0;
int num5 = 0;
bool flag = false;
while (num5 < num2)
{
if (i < num)
{
if (pattern[i] == '*')
{
while (++i < num && pattern[i] == '*')
{
}
if (i >= num)
{
return true;
}
if (!flag)
{
int num6 = num2;
int num7 = num;
while (i < num7 && num6 > num5)
{
num7--;
num6--;
if (pattern[num7] == '*')
{
break;
}
if (!CompareIgnoreCase(input[num6], pattern[num7], num7, num6) && pattern[num7] != '?')
{
return false;
}
if (i == num7)
{
return true;
}
}
num2 = num6 + 1;
num = num7 + 1;
flag = true;
}
if (pattern[i] != '?')
{
while (!CompareIgnoreCase(input[num5], pattern[i], num5, i))
{
if (++num5 >= num2)
{
return false;
}
}
}
num3 = i;
num4 = num5;
continue;
}
if (CompareIgnoreCase(input[num5], pattern[i], num5, i) || pattern[i] == '?')
{
i++;
num5++;
continue;
}
}
if (num3 < 0)
{
return false;
}
i = num3;
num5 = num4++;
}
for (; i < num && pattern[i] == '*'; i++)
{
}
return i >= num;
bool CompareIgnoreCase(char inputChar, char patternChar, int iIndex, int pIndex)
{
char c = (char)(inputChar | 0x20u);
if (c >= 'a' && c <= 'z')
{
return c == (patternChar | 0x20);
}
if (inputChar < '\u0080' || patternChar < '\u0080')
{
return inputChar == patternChar;
}
return string.Compare(input, iIndex, pattern, pIndex, 1, StringComparison.OrdinalIgnoreCase) == 0;
}
}
private static string ComputeFileEnumerationCacheKey(string projectDirectoryUnescaped, string filespecUnescaped, List<string> excludes)
{
int num = 0;
if (excludes != null)
{
foreach (string exclude in excludes)
{
num += exclude.Length;
}
}
using ReuseableStringBuilder reuseableStringBuilder = new ReuseableStringBuilder(projectDirectoryUnescaped.Length + filespecUnescaped.Length + num);
bool flag = false;
try
{
string text = Path.Combine(projectDirectoryUnescaped, filespecUnescaped);
if (text.Equals(filespecUnescaped, StringComparison.Ordinal))
{
reuseableStringBuilder.Append(filespecUnescaped);
}
else
{
reuseableStringBuilder.Append("p");
reuseableStringBuilder.Append(text);
}
}
catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
{
flag = true;
}
if (flag)
{
reuseableStringBuilder.Append("e");
reuseableStringBuilder.Append("p");
reuseableStringBuilder.Append(projectDirectoryUnescaped);
reuseableStringBuilder.Append(filespecUnescaped);
}
if (excludes != null)
{
foreach (string exclude2 in excludes)
{
reuseableStringBuilder.Append(exclude2);
}
}
return reuseableStringBuilder.ToString();
}
internal string[] GetFiles(string projectDirectoryUnescaped, string filespecUnescaped, List<string> excludeSpecsUnescaped = null)
{
if (!HasWildcards(filespecUnescaped))
{
return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped);
}
if (_cachedGlobExpansions == null)
{
return GetFilesImplementation(projectDirectoryUnescaped, filespecUnescaped, excludeSpecsUnescaped);
}
string key = ComputeFileEnumerationCacheKey(projectDirectoryUnescaped, filespecUnescaped, excludeSpecsUnescaped);
if (!_cachedGlobExpansions.TryGetValue(key, out var value))
{
lock (_cachedGlobExpansionsLock.Value.GetOrAdd(key, (string _) => new object()))
{
if (!_cachedGlobExpansions.TryGetValue(key, out value))
{
value = _cachedGlobExpansions.GetOrAdd(key, (string _) => GetFilesImplementation(projectDirectoryUnescaped, filespecUnescaped, excludeSpecsUnescaped));
}
}
}
return value.ToArray();
}
internal static bool RawFileSpecIsValid(string filespec)
{
if (-1 != filespec.IndexOfAny(s_invalidPathChars))
{
return false;
}
if (-1 != filespec.IndexOf("...", StringComparison.Ordinal))
{
return false;
}
int num = filespec.LastIndexOf(":", StringComparison.Ordinal);
if (-1 != num && 1 != num)
{
return false;
}
return true;
}
private static void PreprocessFileSpecForSplitting(string filespec, out string fixedDirectoryPart, out string wildcardDirectoryPart, out string filenamePart)
{
filespec = FileUtilities.FixFilePath(filespec);
int num = filespec.LastIndexOfAny(directorySeparatorCharacters);
if (-1 == num)
{
fixedDirectoryPart = string.Empty;
wildcardDirectoryPart = string.Empty;
filenamePart = filespec;
return;
}
int num2 = filespec.IndexOfAny(s_wildcardCharacters);
if (-1 == num2 || num2 > num)
{
fixedDirectoryPart = filespec.Substring(0, num + 1);
wildcardDirectoryPart = string.Empty;
filenamePart = filespec.Substring(num + 1);
return;
}
int num3 = filespec.Substring(0, num2).LastIndexOfAny(directorySeparatorCharacters);
if (-1 == num3)
{
fixedDirectoryPart = string.Empty;
wildcardDirectoryPart = filespec.Substring(0, num + 1);
filenamePart = filespec.Substring(num + 1);
}
else
{
fixedDirectoryPart = filespec.Substring(0, num3 + 1);
wildcardDirectoryPart = filespec.Substring(num3 + 1, num - num3);
filenamePart = filespec.Substring(num + 1);
}
}
internal string GetLongPathName(string path)
{
return GetLongPathName(path, _getFileSystemEntries);
}
internal static string GetLongPathName(string path, GetFileSystemEntries getFileSystemEntries)
{
return path;
}
internal void SplitFileSpec(string filespec, out string fixedDirectoryPart, out string wildcardDirectoryPart, out string filenamePart)
{
PreprocessFileSpecForSplitting(filespec, out fixedDirectoryPart, out wildcardDirectoryPart, out filenamePart);
if ("**" == filenamePart)
{
wildcardDirectoryPart += "**";
wildcardDirectoryPart += s_directorySeparator;
filenamePart = "*.*";
}
fixedDirectoryPart = GetLongPathName(fixedDirectoryPart, _getFileSystemEntries);
}
private static bool HasDotDot(string str)
{
for (int i = 0; i < str.Length - 1; i++)
{
if (str[i] == '.' && str[i + 1] == '.')
{
return true;
}
}
return false;
}
private static bool HasMisplacedRecursiveOperator(string str)
{
for (int i = 0; i < str.Length - 1; i++)
{
bool num = str[i] == '*' && str[i + 1] == '*';
bool flag = (i == 0 || FileUtilities.IsAnySlash(str[i - 1])) && i < str.Length - 2 && FileUtilities.IsAnySlash(str[i + 2]);
if (num && !flag)
{
return true;
}
}
return false;
}
private static bool IsLegalFileSpec(string wildcardDirectoryPart, string filenamePart)
{
if (!HasDotDot(wildcardDirectoryPart) && !HasMisplacedRecursiveOperator(wildcardDirectoryPart))
{
return !HasMisplacedRecursiveOperator(filenamePart);
}
return false;
}
internal delegate (string fixedDirectoryPart, string recursiveDirectoryPart, string fileNamePart) FixupParts(string fixedDirectoryPart, string recursiveDirectoryPart, string filenamePart);
internal void GetFileSpecInfo(string filespec, out string fixedDirectoryPart, out string wildcardDirectoryPart, out string filenamePart, out bool needsRecursion, out bool isLegalFileSpec, FixupParts fixupParts = null)
{
needsRecursion = false;
fixedDirectoryPart = string.Empty;
wildcardDirectoryPart = string.Empty;
filenamePart = string.Empty;
if (!RawFileSpecIsValid(filespec))
{
isLegalFileSpec = false;
return;
}
SplitFileSpec(filespec, out fixedDirectoryPart, out wildcardDirectoryPart, out filenamePart);
if (fixupParts != null)
{
(fixedDirectoryPart, wildcardDirectoryPart, filenamePart) = fixupParts(fixedDirectoryPart, wildcardDirectoryPart, filenamePart);
}
isLegalFileSpec = IsLegalFileSpec(wildcardDirectoryPart, filenamePart);
if (isLegalFileSpec)
{
needsRecursion = wildcardDirectoryPart.Length != 0;
}
}
private SearchAction GetFileSearchData(string projectDirectoryUnescaped, string filespecUnescaped, out bool stripProjectDirectory, out RecursionState result)
{
stripProjectDirectory = false;
result = default(RecursionState);
GetFileSpecInfo(filespecUnescaped, out var fixedDirectoryPart, out var wildcardDirectoryPart, out var filenamePart, out var needsRecursion, out var isLegalFileSpec);
if (!isLegalFileSpec)
{
return SearchAction.ReturnFileSpec;
}
string text = fixedDirectoryPart;
if (projectDirectoryUnescaped != null)
{
if (fixedDirectoryPart != null)
{
try
{
fixedDirectoryPart = Path.Combine(projectDirectoryUnescaped, fixedDirectoryPart);
}
catch (ArgumentException)
{
return SearchAction.ReturnEmptyList;
}
stripProjectDirectory = !string.Equals(fixedDirectoryPart, text, StringComparison.OrdinalIgnoreCase);
}
else
{
fixedDirectoryPart = projectDirectoryUnescaped;
stripProjectDirectory = true;
}
}
if (fixedDirectoryPart.Length > 0 && !_fileSystem.DirectoryExists(fixedDirectoryPart))
{
return SearchAction.ReturnEmptyList;
}
string text2 = null;
if (wildcardDirectoryPart.Length > 0)
{
string text3 = wildcardDirectoryPart.TrimTrailingSlashes();
int length = text3.Length;
if (length > 6 && text3[0] == '*' && text3[1] == '*' && FileUtilities.IsAnySlash(text3[2]) && FileUtilities.IsAnySlash(text3[length - 3]) && text3[length - 2] == '*' && text3[length - 1] == '*' && text3.IndexOfAny(FileUtilities.Slashes, 3, length - 6) == -1)
{
text2 = text3.Substring(3, length - 6);
}
}
bool flag = wildcardDirectoryPart.Length > 0 && text2 == null && !IsRecursiveDirectoryMatch(wildcardDirectoryPart);
FilesSearchData searchData = new FilesSearchData(flag ? null : filenamePart, text2, flag ? new Regex(RegularExpressionFromFileSpec(text, wildcardDirectoryPart, filenamePart), RegexOptions.IgnoreCase) : null, needsRecursion);
result.SearchData = searchData;
result.BaseDirectory = Normalize(fixedDirectoryPart);
result.RemainingWildcardDirectory = Normalize(wildcardDirectoryPart);
return SearchAction.RunSearch;
}
internal static string RegularExpressionFromFileSpec(string fixedDirectoryPart, string wildcardDirectoryPart, string filenamePart)
{
using ReuseableStringBuilder reuseableStringBuilder = new ReuseableStringBuilder(291);
AppendRegularExpressionFromFixedDirectory(reuseableStringBuilder, fixedDirectoryPart);
AppendRegularExpressionFromWildcardDirectory(reuseableStringBuilder, wildcardDirectoryPart);
AppendRegularExpressionFromFilename(reuseableStringBuilder, filenamePart);
return reuseableStringBuilder.ToString();
}
private static int LastIndexOfDirectorySequence(string str, int startIndex)
{
if (startIndex >= str.Length || !FileUtilities.IsAnySlash(str[startIndex]))
{
return startIndex;
}
int num = startIndex;
bool flag = false;
while (!flag && num < str.Length)
{
bool num2 = num < str.Length - 1 && FileUtilities.IsAnySlash(str[num + 1]);
bool flag2 = num < str.Length - 2 && str[num + 1] == '.' && FileUtilities.IsAnySlash(str[num + 2]);
if (num2)
{
num++;
}
else if (flag2)
{
num += 2;
}
else
{
flag = true;
}
}
return num;
}
private static int LastIndexOfDirectoryOrRecursiveSequence(string str, int startIndex)
{
if (startIndex >= str.Length - 1 || str[startIndex] != '*' || str[startIndex + 1] != '*')
{
return LastIndexOfDirectorySequence(str, startIndex);
}
int num = startIndex + 2;
bool flag = false;
while (!flag && num < str.Length)
{
num = LastIndexOfDirectorySequence(str, num);
if (num < str.Length - 2 && str[num + 1] == '*' && str[num + 2] == '*')
{
num += 3;
}
else
{
flag = true;
}
}
return num + 1;
}
private static void AppendRegularExpressionFromFixedDirectory(ReuseableStringBuilder regex, string fixedDir)
{
regex.Append("^");
int num;
//if (NativeMethodsShared.IsWindows && fixedDir.Length > 1 && fixedDir[0] == '\\')
//{
// num = ((fixedDir[1] == '\\') ? 1 : 0);
// if (num != 0)
// {
// regex.Append("\\\\\\\\");
// }
//}
//else
{
num = 0;
}
for (int num2 = ((num != 0) ? (LastIndexOfDirectorySequence(fixedDir, 0) + 1) : LastIndexOfDirectorySequence(fixedDir, 0)); num2 < fixedDir.Length; num2 = LastIndexOfDirectorySequence(fixedDir, num2 + 1))
{
AppendRegularExpressionFromChar(regex, fixedDir[num2]);
}
}
private static void AppendRegularExpressionFromWildcardDirectory(ReuseableStringBuilder regex, string wildcardDir)
{
regex.Append("(?<WILDCARDDIR>");
if (wildcardDir.Length > 2 && wildcardDir[0] == '*' && wildcardDir[1] == '*')
{
regex.Append("((.*/)|(.*\\\\)|())");
}
for (int num = LastIndexOfDirectoryOrRecursiveSequence(wildcardDir, 0); num < wildcardDir.Length; num = LastIndexOfDirectoryOrRecursiveSequence(wildcardDir, num + 1))
{
char ch = wildcardDir[num];
if (num < wildcardDir.Length - 2 && wildcardDir[num + 1] == '*' && wildcardDir[num + 2] == '*')
{
regex.Append("((/)|(\\\\)|(/.*/)|(/.*\\\\)|(\\\\.*\\\\)|(\\\\.*/))");
}
else
{
AppendRegularExpressionFromChar(regex, ch);
}
}
regex.Append(")");
}
private static void AppendRegularExpressionFromFilename(ReuseableStringBuilder regex, string filename)
{
regex.Append("(?<FILENAME>");
bool flag = filename.Length > 0 && filename[filename.Length - 1] == '.';
int num = (flag ? (filename.Length - 1) : filename.Length);
for (int i = 0; i < num; i++)
{
char c = filename[i];
if (flag && c == '*')
{
regex.Append("[^\\.]*");
}
else if (flag && c == '?')
{
regex.Append("[^\\.].");
}
else
{
AppendRegularExpressionFromChar(regex, c);
}
if (!flag && i < num - 2 && c == '*' && filename[i + 1] == '.' && filename[i + 2] == '*')
{
i += 2;
}
}
regex.Append(")");
regex.Append("$");
}
private static void AppendRegularExpressionFromChar(ReuseableStringBuilder regex, char ch)
{
switch (ch)
{
case '*':
regex.Append("[^/\\\\]*");
return;
case '?':
regex.Append(".");
return;
}
if (FileUtilities.IsAnySlash(ch))
{
regex.Append("[/\\\\]+");
}
else if (IsSpecialRegexCharacter(ch))
{
regex.Append('\\');
regex.Append(ch);
}
else
{
regex.Append(ch);
}
}
private static bool IsSpecialRegexCharacter(char ch)
{
if (ch != '$' && ch != '(' && ch != ')' && ch != '+' && ch != '.' && ch != '[' && ch != '^' && ch != '{')
{
return ch == '|';
}
return true;
}
private static bool IsValidDriveChar(char value)
{
if (value < 'A' || value > 'Z')
{
if (value >= 'a')
{
return value <= 'z';
}
return false;
}
return true;
}
private static int SkipSlashes(string aString, int startingIndex)
{
int i;
for (i = startingIndex; i < aString.Length && FileUtilities.IsAnySlash(aString[i]); i++)
{
}
return i;
}
internal static bool IsRecursiveDirectoryMatch(string path)
{
return path.TrimTrailingSlashes() == "**";
}
internal static string Normalize(string aString)
{
if (string.IsNullOrEmpty(aString))
{
return aString;
}
StringBuilder stringBuilder = new StringBuilder(aString.Length);
int num = 0;
if (aString.Length >= 2 && aString[1] == ':' && IsValidDriveChar(aString[0]))
{
stringBuilder.Append(aString[0]);
stringBuilder.Append(aString[1]);
int num2 = SkipSlashes(aString, 2);
if (num != num2)
{
stringBuilder.Append('\\');
}
num = num2;
}
else if (aString.StartsWith("/", StringComparison.Ordinal))
{
stringBuilder.Append('/');
num = SkipSlashes(aString, 1);
}
else if (aString.StartsWith("\\\\", StringComparison.Ordinal))
{
stringBuilder.Append("\\\\");
num = SkipSlashes(aString, 2);
}
else if (aString.StartsWith("\\", StringComparison.Ordinal))
{
stringBuilder.Append("\\");
num = SkipSlashes(aString, 1);
}
while (num < aString.Length)
{
int num3 = SkipSlashes(aString, num);
if (num3 >= aString.Length)
{
break;
}
if (num3 > num)
{
stringBuilder.Append(s_directorySeparator);
}
int num4 = aString.IndexOfAny(directorySeparatorCharacters, num3);
int num5 = ((num4 == -1) ? aString.Length : num4);
stringBuilder.Append(aString, num3, num5 - num3);
num = num5;
}
return stringBuilder.ToString();
}
private string[] GetFilesImplementation(string projectDirectoryUnescaped, string filespecUnescaped, List<string> excludeSpecsUnescaped)
{
bool stripProjectDirectory;
RecursionState result;
SearchAction fileSearchData = GetFileSearchData(projectDirectoryUnescaped, filespecUnescaped, out stripProjectDirectory, out result);
switch (fileSearchData)
{
case SearchAction.ReturnEmptyList:
return Array.Empty<string>();
case SearchAction.ReturnFileSpec:
return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped);
default:
throw new NotSupportedException(fileSearchData.ToString());
case SearchAction.RunSearch:
{
List<RecursionState> list2 = null;
Dictionary<string, List<RecursionState>> dictionary = null;
HashSet<string> resultsToExclude = null;
if (excludeSpecsUnescaped != null)
{
list2 = new List<RecursionState>();
foreach (string item in excludeSpecsUnescaped)
{
bool stripProjectDirectory2;
RecursionState result2;
SearchAction fileSearchData2 = GetFileSearchData(projectDirectoryUnescaped, item, out stripProjectDirectory2, out result2);
switch (fileSearchData2)
{
case SearchAction.ReturnFileSpec:
if (resultsToExclude == null)
{
resultsToExclude = new HashSet<string>();
}
resultsToExclude.Add(item);
break;
default:
throw new NotSupportedException(fileSearchData2.ToString());
case SearchAction.RunSearch:
{
string baseDirectory = result2.BaseDirectory;
string baseDirectory2 = result.BaseDirectory;
if (!string.Equals(baseDirectory, baseDirectory2, StringComparison.OrdinalIgnoreCase))
{
if (baseDirectory.Length == baseDirectory2.Length)
{
break;
}
if (baseDirectory.Length > baseDirectory2.Length)
{
if (IsSubdirectoryOf(baseDirectory, baseDirectory2))
{
if (dictionary == null)
{
dictionary = new Dictionary<string, List<RecursionState>>(StringComparer.OrdinalIgnoreCase);
}
if (!dictionary.TryGetValue(baseDirectory, out var value))
{
value = (dictionary[baseDirectory] = new List<RecursionState>());
}
value.Add(result2);
}
}
else if (IsSubdirectoryOf(result.BaseDirectory, result2.BaseDirectory) && result2.RemainingWildcardDirectory.Length != 0)
{
if (IsRecursiveDirectoryMatch(result2.RemainingWildcardDirectory))
{
result2.BaseDirectory = result.BaseDirectory;
list2.Add(result2);
}
else
{
result2.BaseDirectory = result.BaseDirectory;
result2.RemainingWildcardDirectory = "**" + s_directorySeparator;
list2.Add(result2);
}
}
}
else
{
string text = result.SearchData.Filespec ?? string.Empty;
string text2 = result2.SearchData.Filespec ?? string.Empty;
int num = Math.Min(text.Length - text.LastIndexOfAny(s_wildcardCharacters) - 1, text2.Length - text2.LastIndexOfAny(s_wildcardCharacters) - 1);
if (string.Compare(text, text.Length - num, text2, text2.Length - num, num, StringComparison.OrdinalIgnoreCase) == 0)
{
list2.Add(result2);
}
}
break;
}
case SearchAction.ReturnEmptyList:
break;
}
}
}
if (list2 != null && list2.Count == 0)
{
list2 = null;
}
ConcurrentStack<List<string>> concurrentStack = new ConcurrentStack<List<string>>();
try
{
int num2 = Math.Max(1, /*NativeMethodsShared.GetLogicalCoreCount()*/Environment.ProcessorCount / 2);
TaskOptions taskOptions = new TaskOptions(num2)
{
AvailableTasks = num2,
MaxTasksPerIteration = num2
};
GetFilesRecursive(concurrentStack, result, projectDirectoryUnescaped, stripProjectDirectory, list2, dictionary, taskOptions);
}
catch (AggregateException ex)
{
if (ex.Flatten().InnerExceptions.All(ExceptionHandling.IsIoRelatedException))
{
return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped);
}
throw;
}
catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
{
return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped);
}
if (resultsToExclude == null)
{
return concurrentStack.SelectMany((List<string> list) => list).ToArray();
}
return (from f in concurrentStack.SelectMany((List<string> list) => list)
where !resultsToExclude.Contains(f)
select f).ToArray();
}
}
}
private IEnumerable<string> GetFilesForStep(RecursiveStepResult stepResult, RecursionState recursionState, string projectDirectory, bool stripProjectDirectory)
{
if (!stepResult.ConsiderFiles)
{
return Enumerable.Empty<string>();
}
string pattern;
if (/*NativeMethodsShared.IsLinux*/true && recursionState.SearchData.DirectoryPattern != null)
{
pattern = "*.*";
stepResult.NeedsToProcessEachFile = true;
}
else
{
pattern = recursionState.SearchData.Filespec;
}
IEnumerable<string> enumerable = _getFileSystemEntries(FileSystemEntity.Files, recursionState.BaseDirectory, pattern, projectDirectory, stripProjectDirectory);
if (!stepResult.NeedsToProcessEachFile)
{
return enumerable;
}
return enumerable.Where((string o) => MatchFileRecursionStep(recursionState, o));
}
private static bool IsAllFilesWildcard(string pattern)
{
return pattern?.Length switch
{
1 => pattern[0] == '*',
3 => pattern[0] == '*' && pattern[1] == '.' && pattern[2] == '*',
_ => false,
};
}
private static bool MatchFileRecursionStep(RecursionState recursionState, string file)
{
if (IsAllFilesWildcard(recursionState.SearchData.Filespec))
{
return true;
}
if (recursionState.SearchData.Filespec != null)
{
return IsMatch(Path.GetFileName(file), recursionState.SearchData.Filespec);
}
return recursionState.SearchData.RegexFileMatch.IsMatch(file);
}
private static RecursiveStepResult GetFilesRecursiveStep(RecursionState recursionState)
{
RecursiveStepResult result = default(RecursiveStepResult);
bool flag = false;
if (recursionState.SearchData.DirectoryPattern != null)
{
flag = recursionState.IsInsideMatchingDirectory;
}
else if (recursionState.RemainingWildcardDirectory.Length == 0)
{
flag = true;
}
else if (recursionState.RemainingWildcardDirectory.IndexOf("**", StringComparison.Ordinal) == 0)
{
flag = true;
}
result.ConsiderFiles = flag;
if (flag)
{
result.NeedsToProcessEachFile = recursionState.SearchData.Filespec == null;
}
if (recursionState.SearchData.NeedsRecursion && recursionState.RemainingWildcardDirectory.Length > 0)
{
string text = null;
if (!IsRecursiveDirectoryMatch(recursionState.RemainingWildcardDirectory))
{
int num = recursionState.RemainingWildcardDirectory.IndexOfAny(directorySeparatorCharacters);
text = ((num != -1) ? recursionState.RemainingWildcardDirectory.Substring(0, num) : recursionState.RemainingWildcardDirectory);
if (text == "**")
{
text = null;
recursionState.RemainingWildcardDirectory = "**";
}
else
{
recursionState.RemainingWildcardDirectory = ((num != -1) ? recursionState.RemainingWildcardDirectory.Substring(num + 1) : string.Empty);
}
}
result.NeedsDirectoryRecursion = true;
result.RemainingWildcardDirectory = recursionState.RemainingWildcardDirectory;
result.DirectoryPattern = text;
}
return result;
}
private void GetFilesRecursive(ConcurrentStack<List<string>> listOfFiles, RecursionState recursionState, string projectDirectory, bool stripProjectDirectory, IList<RecursionState> searchesToExclude, Dictionary<string, List<RecursionState>> searchesToExcludeInSubdirs, TaskOptions taskOptions)
{
ErrorUtilities.VerifyThrow(recursionState.SearchData.Filespec == null || recursionState.SearchData.RegexFileMatch == null, "File-spec overrides the regular expression -- pass null for file-spec if you want to use the regular expression.");
ErrorUtilities.VerifyThrow(recursionState.SearchData.Filespec != null || recursionState.SearchData.RegexFileMatch != null, "Need either a file-spec or a regular expression to match files.");
ErrorUtilities.VerifyThrow(recursionState.RemainingWildcardDirectory != null, "Expected non-null remaning wildcard directory.");
RecursiveStepResult[] excludeNextSteps = null;
if (searchesToExclude != null)
{
excludeNextSteps = new RecursiveStepResult[searchesToExclude.Count];
for (int i = 0; i < searchesToExclude.Count; i++)
{
RecursionState recursionState2 = searchesToExclude[i];
excludeNextSteps[i] = GetFilesRecursiveStep(searchesToExclude[i]);
if (!recursionState2.IsLookingForMatchingDirectory && recursionState2.SearchData.Filespec != null && recursionState2.RemainingWildcardDirectory == recursionState.RemainingWildcardDirectory && (IsAllFilesWildcard(recursionState2.SearchData.Filespec) || recursionState2.SearchData.Filespec == recursionState.SearchData.Filespec))
{
return;
}
}
}
RecursiveStepResult nextStep = GetFilesRecursiveStep(recursionState);
List<string> list = null;
foreach (string item2 in GetFilesForStep(nextStep, recursionState, projectDirectory, stripProjectDirectory))
{
if (excludeNextSteps != null)
{
bool flag = false;
for (int j = 0; j < excludeNextSteps.Length; j++)
{
if (excludeNextSteps[j].ConsiderFiles && MatchFileRecursionStep(searchesToExclude[j], item2))
{
flag = true;
break;
}
}
if (flag)
{
continue;
}
}
if (list == null)
{
list = new List<string>();
}
list.Add(item2);
}
if (list != null && list.Count > 0)
{
listOfFiles.Push(list);
}
if (!nextStep.NeedsDirectoryRecursion)
{
return;
}
Action<string> action = delegate (string subdir)
{
RecursionState recursionState3 = recursionState;
recursionState3.BaseDirectory = subdir;
recursionState3.RemainingWildcardDirectory = nextStep.RemainingWildcardDirectory;
if (recursionState3.IsLookingForMatchingDirectory && DirectoryEndsWithPattern(subdir, recursionState.SearchData.DirectoryPattern))
{
recursionState3.IsInsideMatchingDirectory = true;
}
List<RecursionState> list2 = null;
if (excludeNextSteps != null)
{
list2 = new List<RecursionState>();
for (int k = 0; k < excludeNextSteps.Length; k++)
{
if (excludeNextSteps[k].NeedsDirectoryRecursion && (excludeNextSteps[k].DirectoryPattern == null || IsMatch(Path.GetFileName(subdir), excludeNextSteps[k].DirectoryPattern)))
{
RecursionState item = searchesToExclude[k];
item.BaseDirectory = subdir;
item.RemainingWildcardDirectory = excludeNextSteps[k].RemainingWildcardDirectory;
if (item.IsLookingForMatchingDirectory && DirectoryEndsWithPattern(subdir, item.SearchData.DirectoryPattern))
{
item.IsInsideMatchingDirectory = true;
}
list2.Add(item);
}
}
}
if (searchesToExcludeInSubdirs != null && searchesToExcludeInSubdirs.TryGetValue(subdir, out var value))
{
if (list2 == null)
{
list2 = new List<RecursionState>();
}
list2.AddRange(value);
}
GetFilesRecursive(listOfFiles, recursionState3, projectDirectory, stripProjectDirectory, list2, searchesToExcludeInSubdirs, taskOptions);
};
int num = 0;
if (taskOptions.MaxTasks > 1 && taskOptions.MaxTasksPerIteration > 1)
{
if (taskOptions.MaxTasks == taskOptions.MaxTasksPerIteration)
{
num = taskOptions.AvailableTasks;
taskOptions.AvailableTasks = 0;
}
else
{
lock (taskOptions)
{
num = Math.Min(taskOptions.MaxTasksPerIteration, taskOptions.AvailableTasks);
taskOptions.AvailableTasks -= num;
}
}
}
if (num < 2)
{
foreach (string item3 in _getFileSystemEntries(FileSystemEntity.Directories, recursionState.BaseDirectory, nextStep.DirectoryPattern, null, stripProjectDirectory: false))
{
action(item3);
}
}
else
{
Parallel.ForEach(_getFileSystemEntries(FileSystemEntity.Directories, recursionState.BaseDirectory, nextStep.DirectoryPattern, null, stripProjectDirectory: false), new ParallelOptions
{
MaxDegreeOfParallelism = num
}, action);
}
if (num <= 0)
{
return;
}
if (taskOptions.MaxTasks == taskOptions.MaxTasksPerIteration)
{
taskOptions.AvailableTasks = taskOptions.MaxTasks;
return;
}
lock (taskOptions)
{
taskOptions.AvailableTasks += num;
}
}
private static bool IsSubdirectoryOf(string possibleChild, string possibleParent)
{
if (possibleParent == string.Empty)
{
return true;
}
if (!possibleChild.StartsWith(possibleParent, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (directorySeparatorCharacters.Contains(possibleParent[possibleParent.Length - 1]))
{
return true;
}
return directorySeparatorCharacters.Contains(possibleChild[possibleParent.Length]);
}
private static bool DirectoryEndsWithPattern(string directoryPath, string pattern)
{
int num = directoryPath.LastIndexOfAny(FileUtilities.Slashes);
if (num != -1)
{
return IsMatch(directoryPath.Substring(num + 1), pattern);
}
return false;
}
internal void GetFileSpecInfoWithRegexObject(string filespec, out Regex regexFileMatch, out bool needsRecursion, out bool isLegalFileSpec)
{
GetFileSpecInfo(filespec, out var fixedDirectoryPart, out var wildcardDirectoryPart, out var filenamePart, out needsRecursion, out isLegalFileSpec);
if (isLegalFileSpec)
{
string pattern = RegularExpressionFromFileSpec(fixedDirectoryPart, wildcardDirectoryPart, filenamePart);
regexFileMatch = new Regex(pattern, RegexOptions.IgnoreCase);
}
else
{
regexFileMatch = null;
}
}
internal static void GetRegexMatchInfo(string fileToMatch, Regex fileSpecRegex, out bool isMatch, out string wildcardDirectoryPart, out string filenamePart)
{
Match match = fileSpecRegex.Match(fileToMatch);
isMatch = match.Success;
wildcardDirectoryPart = string.Empty;
filenamePart = string.Empty;
if (isMatch)
{
wildcardDirectoryPart = match.Groups["WILDCARDDIR"].Value;
filenamePart = match.Groups["FILENAME"].Value;
}
}
internal Result FileMatch(string filespec, string fileToMatch)
{
Result result = new Result();
fileToMatch = GetLongPathName(fileToMatch, _getFileSystemEntries);
GetFileSpecInfoWithRegexObject(filespec, out var regexFileMatch, out result.isFileSpecRecursive, out result.isLegalFileSpec);
if (result.isLegalFileSpec)
{
GetRegexMatchInfo(fileToMatch, regexFileMatch, out result.isMatch, out result.wildcardDirectoryPart, out var _);
}
return result;
}
private static string[] CreateArrayWithSingleItemIfNotExcluded(string filespecUnescaped, List<string> excludeSpecsUnescaped)
{
if (excludeSpecsUnescaped != null)
{
foreach (string item in excludeSpecsUnescaped)
{
if (FileUtilities.PathsEqual(filespecUnescaped, item))
{
return Array.Empty<string>();
}
Result result = Default.FileMatch(item, filespecUnescaped);
if (result.isLegalFileSpec && result.isMatch)
{
return Array.Empty<string>();
}
}
}
return new string[1] { filespecUnescaped };
}
}
} | Microsoft.Build.Shared/FileMatcher.cs | Chuyu-Team-MSBuildCppCrossToolset-6c84a69 | [
{
"filename": "Microsoft.Build.Utilities/CanonicalTrackedInputFiles.cs",
"retrieved_chunk": " private bool _useMinimalRebuildOptimization;\n private bool _tlogAvailable;\n private bool _maintainCompositeRootingMarkers;\n private readonly HashSet<string> _excludedInputPaths = new HashSet<string>(StringComparer.Ordinal);\n private readonly ConcurrentDictionary<string, DateTime> _lastWriteTimeCache = new ConcurrentDictionary<string, DateTime>(StringComparer.Ordinal);\n internal ITaskItem[] SourcesNeedingCompilation { get; set; }\n public Dictionary<string, Dictionary<string, string>> DependencyTable { get; private set; }\n public CanonicalTrackedInputFiles(ITaskItem[] tlogFiles, ITaskItem[] sourceFiles, CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers)\n {\n InternalConstruct(null, tlogFiles, sourceFiles, null, null, outputs, useMinimalRebuildOptimization, maintainCompositeRootingMarkers);",
"score": 0.8239625692367554
},
{
"filename": "Microsoft.Build.Shared/FileSystem/FileSystems.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace Microsoft.Build.Shared.FileSystem\n{\n internal interface IFileSystem\n {\n TextReader ReadFile(string path);\n Stream GetFileStream(string path, FileMode mode, FileAccess access, FileShare share);\n string ReadFileAllText(string path);",
"score": 0.809930682182312
},
{
"filename": "Microsoft.Build.Shared/FileSystem/ManagedFileSystem.cs",
"retrieved_chunk": " public virtual IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption)\n {\n return Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption);\n }\n public FileAttributes GetAttributes(string path)\n {\n return File.GetAttributes(path);\n }\n public virtual DateTime GetLastWriteTimeUtc(string path)\n {",
"score": 0.804898202419281
},
{
"filename": "Microsoft.Build.Shared/FileSystem/ManagedFileSystem.cs",
"retrieved_chunk": " return File.ReadAllBytes(path);\n }\n public virtual IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption)\n {\n return Directory.EnumerateFiles(path, searchPattern, searchOption);\n }\n public virtual IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption)\n {\n return Directory.EnumerateDirectories(path, searchPattern, searchOption);\n }",
"score": 0.7996640801429749
},
{
"filename": "Microsoft.Build.Shared/FileUtilities.cs",
"retrieved_chunk": " internal static string ToSlash(this string s)\n {\n return s.Replace('\\\\', '/');\n }\n internal static bool FileExistsNoThrow(string fullPath, IFileSystem fileSystem = null)\n {\n fullPath = AttemptToShortenPath(fullPath);\n try\n {\n if (fileSystem == null)",
"score": 0.7957814931869507
}
] | csharp | IFileSystem fileSystem, GetFileSystemEntries getFileSystemEntries, ConcurrentDictionary<string, IReadOnlyList<string>> getFileSystemDirectoryEntriesCache = null)
{ |
using LegendaryLibraryNS.Models;
using Playnite.SDK.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace LegendaryLibraryNS.Services
{
public class WebStoreClient : IDisposable
{
private HttpClient httpClient = new HttpClient();
public const string GraphQLEndpoint = @"https://graphql.epicgames.com/graphql";
public const string ProductUrlBase = @"https://store-content.ak.epicgames.com/api/en-US/content/products/{0}";
public WebStoreClient()
{
}
public void Dispose()
{
httpClient.Dispose();
}
public async Task<List<WebStoreModels.QuerySearchResponse.SearchStoreElement>> QuerySearch(string searchTerm)
{
var query = new WebStoreModels.QuerySearch();
query.variables.keywords = HttpUtility.UrlPathEncode(searchTerm);
var content = new StringContent(Serialization.ToJson(query), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(GraphQLEndpoint, content);
var str = await response.Content.ReadAsStringAsync();
var data = Serialization.FromJson<WebStoreModels.QuerySearchResponse>(str);
return data.data.Catalog.searchStore.elements;
}
public async Task< | WebStoreModels.ProductResponse> GetProductInfo(string productSlug)
{ |
var slugUri = productSlug.Split('/').First();
var productUrl = string.Format(ProductUrlBase, slugUri);
var str = await httpClient.GetStringAsync(productUrl);
return Serialization.FromJson<WebStoreModels.ProductResponse>(str);
}
}
}
| src/Services/WebStoreClient.cs | hawkeye116477-playnite-legendary-plugin-d7af6b2 | [
{
"filename": "src/Services/EpicAccountClient.cs",
"retrieved_chunk": " }\n if (result == null)\n {\n var url = string.Format(\"{0}/bulk/items?id={1}&country=US&locale=en-US\", nameSpace, id);\n var catalogResponse = InvokeRequest<Dictionary<string, CatalogItem>>(catalogUrl + url, loadTokens()).GetAwaiter().GetResult();\n result = catalogResponse.Item2;\n FileSystem.WriteStringToFile(cachePath, catalogResponse.Item1);\n }\n if (result.TryGetValue(id, out var catalogItem))\n {",
"score": 0.761878490447998
},
{
"filename": "src/Services/EpicAccountClient.cs",
"retrieved_chunk": " var response = await httpClient.GetAsync(url);\n var str = await response.Content.ReadAsStringAsync();\n if (Serialization.TryFromJson<ErrorResponse>(str, out var error) && !string.IsNullOrEmpty(error.errorCode))\n {\n throw new TokenException(error.errorCode);\n }\n else\n {\n try\n {",
"score": 0.7576921582221985
},
{
"filename": "src/LegendaryGameInstaller.xaml.cs",
"retrieved_chunk": " if (!File.Exists(cacheSDLFile))\n {\n var httpClient = new HttpClient();\n var response = await httpClient.GetAsync(\"https://api.legendary.gl/v1/sdl/\" + GameID + \".json\");\n if (response.IsSuccessStatusCode)\n {\n content = await response.Content.ReadAsStringAsync();\n if (!Directory.Exists(cacheSDLPath))\n {\n Directory.CreateDirectory(cacheSDLPath);",
"score": 0.7435175180435181
},
{
"filename": "src/Services/EpicAccountClient.cs",
"retrieved_chunk": " var authorizationCode = Serialization.FromJson<ApiRedirectResponse>(apiRedirectContent).authorizationCode;\n FileSystem.DeleteFile(tokensPath);\n if (string.IsNullOrEmpty(authorizationCode))\n {\n logger.Error(\"Failed to get login exchange key for Epic account.\");\n return;\n }\n var result = await Cli.Wrap(LegendaryLauncher.ClientExecPath)\n .WithArguments(new[] { \"auth\", \"--code\", authorizationCode })\n .WithValidation(CommandResultValidation.None)",
"score": 0.7370415329933167
},
{
"filename": "src/Services/EpicAccountClient.cs",
"retrieved_chunk": " {\n throw new Exception(\"User is not authenticated.\");\n }\n var tokens = loadTokens();\n var formattedPlaytimeUrl = string.Format(playtimeUrl, tokens.account_id);\n return InvokeRequest<List<PlaytimeItem>>(formattedPlaytimeUrl, tokens).GetAwaiter().GetResult().Item2;\n }\n public CatalogItem GetCatalogItem(string nameSpace, string id, string cachePath)\n {\n Dictionary<string, CatalogItem> result = null;",
"score": 0.7369066476821899
}
] | csharp | WebStoreModels.ProductResponse> GetProductInfo(string productSlug)
{ |
using DotNetDevBadgeWeb.Common;
using DotNetDevBadgeWeb.Interfaces;
using DotNetDevBadgeWeb.Model;
namespace DotNetDevBadgeWeb.Core.Badge
{
internal class BadgeCreatorV1 : IBadgeV1
{
private const float MAX_WIDTH = 193f;
private const float LOGO_X = 164.5f;
private const float TEXT_X = 75.5f;
private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;
private readonly IProvider _forumProvider;
private readonly IMeasureTextV1 _measureTextV1;
public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)
{
_forumProvider = forumProvider;
_measureTextV1 = measureTextV1;
}
public async Task<string> GetSmallBadge(string id, ETheme theme, CancellationToken token)
{
(UserSummary summary, User user) = await _forumProvider.GetUserInfoAsync(id, token);
ColorSet colorSet = Palette.GetColorSet(theme);
string trustColor = Palette.GetTrustColor(user.Level);
string svg = $@"
<svg width=""110"" height=""20"" viewBox=""0 0 110 20"" fill=""none"" xmlns=""http://www.w3.org/2000/svg""
xmlns:xlink=""http://www.w3.org/1999/xlink"">
<style>
.text {{
font: 800 12px 'Segoe UI';
fill: #{colorSet.FontColor};
}}
</style>
<path
d=""M10 0.5H100C105.247 0.5 109.5 4.75329 109.5 10C109.5 15.2467 105.247 19.5 100 19.5H10C4.75329 19.5 0.5 15.2467 0.5 10C0.5 4.75329 4.7533 0.5 10 0.5Z""
fill=""#{colorSet.BackgroundColor}"" stroke=""#4D1877"" />
<path d=""M10 0.5H27.5V19.5H10C4.7533 19.5 0.5 15.2467 0.5 10C0.5 4.75329 4.7533 0.5 10 0.5Z"" fill=""#6E20A0""
stroke=""#{trustColor}"" />
<g>
<path
d=""M15 10C17.2094 10 19 8.4332 19 6.5C19 4.5668 17.2094 3 15 3C12.7906 3 11 4.5668 11 6.5C11 8.4332 12.7906 10 15 10ZM17.8 10.875H17.2781C16.5844 11.1539 15.8125 11.3125 15 11.3125C14.1875 11.3125 13.4188 11.1539 12.7219 10.875H12.2C9.88125 10.875 8 12.5211 8 14.55V15.6875C8 16.4121 8.67188 17 9.5 17H20.5C21.3281 17 22 16.4121 22 15.6875V14.55C22 12.5211 20.1188 10.875 17.8 10.875Z""
fill=""#{trustColor}"" />
</g>
<g>
<path
d=""M37.0711 4.79317C37.5874 4.7052 38.1168 4.73422 38.6204 4.87808C39.124 5.02195 39.5888 5.27699 39.9807 5.62442L40.0023 5.64367L40.0222 5.62617C40.3962 5.29792 40.8359 5.05321 41.312 4.90836C41.7881 4.76352 42.2896 4.72186 42.7831 4.78617L42.9266 4.80717C43.5486 4.91456 44.13 5.18817 44.6092 5.59902C45.0884 6.00987 45.4476 6.54267 45.6487 7.14099C45.8498 7.73931 45.8853 8.38088 45.7516 8.99776C45.6178 9.61464 45.3198 10.1839 44.8889 10.6452L44.7839 10.7531L44.7559 10.777L40.4101 15.0814C40.3098 15.1807 40.1769 15.2402 40.0361 15.249C39.8953 15.2578 39.756 15.2153 39.6442 15.1292L39.5893 15.0814L35.2184 10.7519C34.7554 10.3014 34.4261 9.73148 34.267 9.10532C34.1079 8.47917 34.1252 7.82119 34.317 7.20427C34.5088 6.58734 34.8676 6.03555 35.3537 5.60999C35.8398 5.18443 36.4342 4.90172 37.0711 4.79317Z""
fill=""#FA6C8D"" />
</g>
<text class=""text"" x=""49"" y=""14.5"" >{summary.LikesReceived}</text>
<rect x=""88"" y=""1"" width=""18"" height=""18"" fill=""url(#pattern0)"" />
<defs>
<pattern id=""pattern0"" patternContentUnits=""objectBoundingBox"" width=""1"" height=""1"">
<use xlink:href=""#image0_16_373"" transform=""translate(-0.0541796) scale(0.00154799)"" />
</pattern>
<image id=""image0_16_373"" width=""716"" height=""646""
xlink:href=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAswAAAKGCAMAAABpzD0iAAABF1BMVEUAAABNGHduIKBNGHduIKBNGHduIKBNGHduIKBNGHdaG4duIKBNGHduIKBNGHduIKBNGHdRGXxeHIxmHpZuIKBNGHduIKBNGHduIKBNGHdZG4ZuIKBNGHdTGX5YG4VgHY9jHZJpH5luIKBNGHdhHZBuIKBNGHduIKBNGHduIKBNGHdPGXpRGXxTGn9VGoFXG4RYJoBZG4ZbHIleHIxgHY5iHZFjNYhkHpNmHpZoH5hqH5tsIJ1uIKBuQ5F3LqZ6UpmAPKyFYKKJSrKNYqyQb6qSWLibZr6bfbOkdMSmjLuqjcCtgsqxmsS3kNC8qMzAndXHt9XJq9vOuNzSueHTxd3bx+fe1Obk1e3p4u7t4/P08ff28fn///8PlaBgAAAAKnRSTlMAEBAgIDAwQEBQUFBgYHBwgICAgICPj5+fr6+vv7+/v7+/v8/Pz9/f7++nTCEdAAAriklEQVR42u2da18TW5PF41EPMF5gnuGiI3PDEaRRjCKRS0IDE4QeQoAhCSHk+3+OARGE0OnetXfta6/14nnx/I4hhH8qVavW3imVIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIDGN3ujV5D29uPn/nuHVgZzH98UVsHNzcwtVAX2Ym3t39Z+Pjv6NVw5yh+HJyXdiAA8H+83kOKiGLFL84grixSqjFq6gfgGmIYP6a3R8mpfiQaYnX43iZYY069mLSbWOgtB7vJsc/QuvOKSL48WqYS2AaIi7PR5/t1C1pg9vXqGRhlga5Mm5qn0tXpVo/DEgBb2Y/lB1SHOTqNCQjP52oiI/rtDjWCBCpN7i1ZvFqrNamH6BPxEkWJI/VJ0XCjQk0CUvVD3RB3TQUAbJLjcX6Q0HeIZCIBk8QyGRDJ6hwYnPnz55KM+YB6FS6dm49yT/3qi8Qoij4O3Fu2o4WnyDjXdxi/L0YjUwLYyjPBdRr+aqQQrluXBFeXKxGqwW0D0XSKPvqmFr8Q3MjYL0FwvVAmgO3Ubw+ivk/mKw28CfO+hW+U21SFqcRPMcbKtcLJR/4TyN5jlIlOeqhRRmQaAMnCGgDJwhoAycIaAMnIEycIbgK/sr+M7e6i+g/HiNAiy8RLk4i2ssuQNXMeJEiCAVYe77AGiH6x0mQcx9mAQh00KzLNA64+5FLzoMNMtirTN6Dec7jHfAFL1GGBpHh4FeIwz9DQ+D6mugODu6JZkGnPSV4DjAweCHQRBCWUZeA8rWCwx+CvqA+50dKsvw41RdOkCEbhmdM4RuGbYGBG9ZY3GG52xZk4CQrzhjIWhTz3BclVXTKM4w5GDSQYrC5Ic5MJQWA5OfFiF7hBYjHC2g1UCLEU6rgdsI0GKEozdoNYxpFC2GblcD221DGgdsWKCEIdwgZ0YI0qFdRuMMoV1G41w0vQJiJhtnOM4ahXbZsOA4axv9kJEzrmlgh9EPYyCUob8x+tkZA0EzuxAssiUEj2BjwNSA0oWQHEwNWHIQaHbLksOFRbDoQmEZlpwLFh1ABMugGcKqxDnhpKuDq5LdPkGHaj/rrE9UG+sTsEzQTwpcF2o/65wK8ymWgWCZoCMSXXtKP4vKcv8Iq22wrO2jX6lU7pFh3quCZrAsrgsSXZdbCj/qgAzzVhU0g2VtH/0Hxjqa67eO854GaHaJZepH/7nCz2qHZGaAZudYpn/078r/rEvqzzqugmawLK5jc4BtkVvmgypoBssaP/ovjXU0zpsZoNktlukf/fLl8pD8ozzZbINmN1imf/TLT2Wn1J90UQXNgUlrTo7+0d/vb5vqaM78SR0BU/ss061fhR1zYMvsB0Ii1D7L9I9++U//bfIP+lkFzUFJ8xmptgTMkpDRO5pdj2DGnbf50n12VYZlyV72KFQz47dwyjVHuu8U2JaCWS7/E1QyHzSTpf2ul59yMEsdOAkrmZ8i3A5jlWUpM0N2BAzZzADNNpclsh/98nvmXRM/BMsTR/XMwN2I55IwS3QA4SXzQbMrBrOCmSF34CTAZD7sZlGZuBd/TxZmibRRO3QzA3azNYNZ8qNf/sDJBfVHHHsJMww6G0aGgpkhkzYKNJmfIlgaAxo187q35WE+1t7R7HkK8yKGQNOm3C9dysNMHc+CTebD0nDAyJD66JfvAo6NLGZgaRQtKcdgZtDTRgEn8x9rHAzfatLUa36oAjNxBAx/mX1fo6DY6PBXlUvmS9IWdjL/8RCIL403tsVWNzOoTW3gyfzHQyBAvpbBq/H7aqLUzqPimBkYAs1u/mQ/+uXTRsEn87EJtLX5u9FPRZgpsbbgk/mP2+bCbwKNfr37kSrMhAMnxTIzsDspmf5etDNVmMVHwCIk89E2W2uYq/LJfAnHoRDJfLTN9/XC7GutzLJ4Y1uMZD7aZisOs/Iym3jgpF04M6PobvOc2Vf6QB1m4bRRUZL5gyrsF8ZPGn6hjxhgFjxwUpxkPkIaN66c6de5zQCzYNpor4hmxk3bXEh/7q8F06/zJQfMYu1AgZL5gyrkzc3Tpl/lLQ6WBV2HIiXz4c+ZduV4zAzh5rZQyfzBRqNwadC/Fo2/yIc8MAthV8Bl9h/NFQ3md+Zf41MemEVGwIIl8wc1jibDCzNDrIgWLZlf6EbDQpPBscwWntWOimtmFK/RsNBkKCfzKZZw8ZL5xW00bDQZ6sl8QtqoeMn8wjYa5tclXMts0bRmoc2MYjUa01Ze3jM+mPMOnBQymT+gF8VgedTOq3vOB3Ne2qiYyfyBRqMYGY0Pdl7dPqN2mTuay2p4KsQZqkk7r+0eJ8ynzI52O0CYixAGfbZo56U94IQ558BJUZP5D7UQPsxzll7aI06Ys9NGxU3mP1Tw33bywtYr22aFuc3b0eg2M9bWvq+sfFleXo4e6ur/WV5Z+b62BrPZG4v5WpesMGemjdxJ5m9eQfyI4HR9Xr6CepP3xwee05+0xfIWL8uZXa4TyfyNHyvLSxFVS8srq+uYAcWmP2v92x4zzJecHQ13Mn9NhuMHRDPV6KBnwHfWYD5khjkrgGx1mb327XPEoc/ffmAGdHD3d61TbpiHV1N7yfyN718iTi1/V205At4DLtiDuc0N8/AR0FIyf/3bp4hfn76p8RzsHvCVPZar7CwP7w1sJPP1kPy7hf6qwnOgt8/9tWiP5W1+mIdaEMaT+RsaSVauz4FmQSctFuaf/DAP3XSYTeZvrn6OTOjzqqTBEaQ998wiy8zL7GwGTZoZ61+XImOSazeCtOfe2IT5TAPMQ0LIBpP5q8uRWX1elXiWAd5w9LdNljmT+XnxIFPJ/M2VT5F5La2Qu42F8Oy5Oasw62B5yIETM8n8jRXl/qLZylR9qLmxUfTNyahVlve0wJzuD5tI5m98ZSiyOU9rP6N5puEc3ObEbmE+0ANz6gioP5nPgnJUy3laceYsuFHg0my3MGsxM4Y0CNqT+ZsrPN3vTs7TKudYG4TeObBg8we7MLf1wJzGoeZk/uYKlxeXZD+rHucoGNRS+5VdlrmT+Vntrt5k/iqfg9HKflYtAWdD3KgLqTQv2GV5q69Lj9NGOpP5a5y+cjf7aSVCvvNa8Uqz7cK8pw3mY/WORjiZv/mV1THOeVp1wa3gZtFKs+XCzJ/Mzyir2pbZq7yL61jFzLjfa3wvVmm2XZj5k/nDc/W6kvkb3Jvr/ZynRYjwrxepNNsuzNrMjJQmQVMyfyXiViP7WXUoj7VSnNI8apvlal+jtg0k89c1pDxzzIwTWgBJoDiHsQacs83ytk6YD/Un87/riHn2GMwMUnGeRGF2NZk/bATkT+Zvasl5VnKe1g758GvegjuIhIb1wqxrmZ26wGM3M37oSd/nmRkVejj0R/il+W/rLOtJ5qeXVvZk/jdNueSEzcz4o2/ZnvMiDpi4msxPz9YzJ/M3tJ3vayovs9PmwI2wj5w8s88y+aOfCP+BtmT+mr4Dfp3sp9WUPIeS2Wp4fxpw2j7LZOuXGK8415XM/67x+JN8Ml/B1fD8S3ts3pUh/dFPpX9XTzL/q0aWlZL5mfqS0Th7fofGuANdxpFumI91JPM3tV6HoZjMl22c/b7eaMEBmNvkNla67+VL5q/rPXqtmszPbJzXw9xpv3CAZXIyv12VLq9syfw1zXe7tHSYGQJjoM+LkzkHWN6iz2QXslMcVzJ/Vff1FxzJ/AytBrg4ccGXo3/0t+mexDavmZHLcjneSa7UajWv/rceV7jNjLrqm2UlPHdu2gWYyR/9R/SV4RHrMjtz61feabQeh4RaCSlMEWszM+5OoIS2OHHBl5NI5h/R/Y8LzmR+hiVXa2QsO07qwh4EXzKfSrO37twrF1imf/QfSMTsfvIl84eyXElyOt1+rynYcHAm84k0+3ri5IMTMMu4ZeTdxxlbMn8Yy/GJ0AOK4cyazKfRPI28nMlk/pYMlVtS8bxzUZbjlvBjNoY2G/W7SxFzkvndgTsUa4w0e5qde+MEzOSW4VLqHXDIk8xPZ7nWojxoN5arx5zh5gyaX2H8M7fMbks12hcsZkYqy+UG9WEbUuayhnnwaygjoBvjn6TNdiDTaSsn81NZjiUYbKW1GmVZllu8fbOPI+CcGzCTP/oPpHbg1x0D3QTZzt+VNKT465Tp5jK10IudPgliBHzmBstVyWp5KtFqKybz01iudCQBTKF5XxbmfRVPYzWELeC0GyzTrV/5w3xy7fndydW0ya8nfZjrMc0N2YdS2weuBpDRX3ADZnLzey7fnpDb8/vJ/PWUnFxd5Whik83MKCvB/DgR6l0QdNSRLoNcLc/kIx1kC+TeBTKb3Cw/7g5kH6eruDx5TLNvQdA3jsDcpjMpmRw9o/+svcxzJYos9/s10rUvmsLN12dPNj23mhcdgZm8mP4pG1Bq0zuTTFNOmeUBCqXNjER5sb088Ed5hyMmRpL5f9wy6uhIPm11L5m/ooPlgVhywvIoPAadX1bzu6rfZoZMUSfD3M4wMmIGlvu9svi1L6LdCoulMe7VKtsRluljXFt+diTvTG7b840lTk9uWIcga2Z0GVgeHAI/YJUtIfKhvFP5vB15z3Lbnj8e/sodFpYfgCgLc4MD5sEh8Bm6DANmxqF8rIM8a+4OHf5O+kyqK/fMvQoLzAMpjXF0GcaW2ZILF6n2/IfU8HcdORZIILXE733Rscse2jZ/QJdhJpkvf+OGzK4xpWGu5DXM3f3K74NUua11RfiuRME9IlPb/AxdhnYz41Kt45Zozz/TQ/QJobneV2rEe2x1+bpt9rLPcKfLUIv+6P0ylBszg+4w92qUUfHB4qR+QjFJuoTj3mS32Zs+44UzMEtfgCGbNqK25+spGfoegeX8+zyN3JkvqDUP+4w3zsAsmcw3MwJupzcZDRLLuXDGRu7MF9OnTf/yGYthmBnX23CNI+BlepORkwfaof6DxMyd+eRGw5N8xqgzLNMT9oOPoPGLitupTUZO4WyQD12fEK+ZS3TCfL/R8CMHOu0MzNLJfIVsh7COU5uMinjYQqzP6Bi7M1+o0fDtvMmCv2bGmXqElLBrXCEX5rrELYjm7synXQ/qxXmTZ86wLJ/MV0gqibfnKeuSnMKcnvkpk+jUeWe+iDa8Otc67g7M8sl8hUC0cHv+hacw53XBscE780lBfR++4MSZ9Z9KMl/BqhaNJa1FVI+5V2aAuWsiI5elu++I8OEWfXcKs0oy/066vkW+/Yl8b3IzYoBZPGan22z24J4ud9Z/Ssl87SPg/9Jvg9thgFn/nfniM6D75pw7xpxSMl972iiNzJrcbEbB08Cd+bnxuQ1vzLkPHpsZhzwxUiHVyONfkwPmnGuNugZgvsvpO3/pnDuJOfVltux7Qkhpf+WeVDsbU2A2cme+oD23gJbZVDJfb9oo7WtDdoRz9pTIaEx4v2heZg/ac64n5954bGZcDnkgHWmjJv322niImgSYKxKdvL6IhuvJOXd22arJfL1po4TzZnvxgh5LdPL6SrPjG22HdtnKyXyF8F2+YnL4k6U5t5jMTynNjjfNrxyCWTWZr/XASYW6MeGB2WIyP600u900T4dnZmhJG6V5xidaWG45k8xPKc1uN80OuczqyXyNaaMW2ZiT1Yk7yfzHpdnpptkll5nsqF0Mfyz2EbBhrGVO3EnmP/aanT6j7ZDLzJHM15c22tdzh22e2WY5mf94DehyPGPSIZgZkvn60kYx2WVmmTRtJ/Pv61d4btRhmOccgpkhma9Q5ukWWEsPzE4l8x+F51zONDvEMn1o22VdjZPzPHpYbrmVzL8fnnM80/y3QzCzJPN1HThpGZv/mm4l8wevBV3EysRcMl9T2ighZ99YJk0HkvmD7py7BwEdShkxJfM1pY12qLdf8EyaDiTzB905d9cmH0I1M7gPnNSMwVx2LZk/cFnXNOY/o8tsDWkjY2ZGz71k/sMR0NkJcNQhlrmS+VrSRh1jMLfcS+YP3DqA+c9gMl/HCNg0lsxIHEzm/9EXhydAlyJzbMn8P8b1pR7EhFyzXktOOw4m8x9uAV2dAF3a/5F94ePch+RLG8VkmFnWGa4k8x9YzZOY/wwm8xXWMIRkfmSgnXUlmf+gz3B0AnwWspnBmTbqqd4XIClnkvn3+4xFmBkGk/n8B05almB2Jpn/oM9wMwXqUv6TM5nPnjZq0GHm+M5fh5L59/sMN1Ogb3w2M860TJXCyXzi9fdSciiZf7/PGIeZYXiZzXrgJLYDs0vJ/Ht7k2mYGSaT+dwjYNoftaIfZpeS+fdOT83BzDCZzGdOG3UlpjOOntmlZP69fMYCzAyjyXzeEbAlATPHcOZUMv9O606mMxi/mGd7b0vtAZiT+Qq9uLAF1pOJTTSyl9l1d5P5d/rupJ3BkszYPTy73d21Tw+kkeZO5rOmjXYkOtr0N0CZ8pMcS+b/OW/yIkgzY/tocMBqH7hkZjCljWoSMKe3JnUKn44l8+/kZDpD9ZjJdmqQ5/JI5rF0LLPZ0kZSxllZYqRrum9mXGntTXjO3NGwmnexR39fsCfzGQ+cdCKZKps2nu2T+pmeozCvzIXmzG2fK6UztSfzGQ+cNKWWzSldQK1H+id9R2H+shCYM7eb3YqeEydB/mQ+Y9poWJ6HeqapnHfR/j7pXo6OLZiXHPTmVM5M5XoERJo1JPMV9jGCFlje9cwDc2Otkxc0LVP25Tx7GbkbB9w7OTWpkWUqzRqS+Xwj4DBo8jrg3oMWuN4jfgLkwnxiC+ZV94zmN7p6DAma9ZkZ6mmjoXme/Pu5mnfFuZ5/lrsbEWHut3as5Oaib+4dA5S2mbfE0junhHeHpmU2S9qoJXsQ5BehzSRJmi2ZbibmaYZ0rE3cM5qlbWbRBvcnZ9tCT+YrjJeCeR7WL+g5idRgNlikl9wLgWrPBF1uaaPtjPSM1dJG+0P/qGVGlrtlas7IYrj5v4KBWfxDW3gXqG2ZzZE2iqVPTyuuzJmaIQ36T9dY/lufk0EuzZqS+Txpo4w/Kt8VzXV6Nl/MDNezAwxlZ3LOX0B1JfP/SCFt1FW42EKtL2+ovhv0nTYJBGaS8XDB3IXLmRlqB04yP7+ZSnNT6jyrvXDzsmu3DUjuTI41VFBtyXyOtFGicuZUKfxBuprR7EJ7NAyYabu6Iz1181Tz085P5lO8ZlmWKU2M4aBGGDBv6Sihus0MpREw56bNWk9Lv0xtYgyvtv8piAXgno7mVusyWzVtlPd3Vf2e1jrLfGn4pq5/BAEzdb2xbTeZr542yv/8Vmqbu5mFv9Jjaoa49c+FhHlPh5lxaeAjJbehZfHnTnKW0MILc8Nx0AnHYF6UgvlUA8w6k/nKaSORz2/ZL9Hu5dfTE6ZmiFn/FsQ2u60BZp3JfOUDJ0L+rVzf3BTIBpXF3BLTR6hmAbONZL5q2kjs87vWJT9wS2zNIUbzfrFh/svMZS17bpgZUh8AlDBamdhqdIQ3dmWBTqNnOqQ/H8Q2W8MAqDmZr3bgRNy/jVvsVfl2CuxxNPa8CgJmaucpYKKR9xlnck9dKm1E+fyui/W33QbVeqg0nVr/BQMz0eG61GFmSN4AJpU2onEX57p03aaUI1xJMpryVhkwy4m/iFJnykvJZy4zApK/z6lcbw5tCnon+wrfQllL0vuYrpWbbZ8GcdEADb1DDQbwkSzMEgdOpOCr1RutgULaaiU7DF+nWouT5MGluI39WmRFI07B/C9VE02zwDabmpq4kGaZ3p2rfNFeOb6VJd4KBPM/THxWn2vYM+/Jw0y93rZbjqCQYSbZtQf8/shhVUG0ZXyvBmjDbjMolfSC32M4VWGZaGnXwawnME8aGKMO2KcyNZZpwyZYLgDM25wdM83rO1BkmdDToMcoBMzCW45d5oHyfFeVZXHr5P8w+xUDZsHO4JC3Bb88qjJIbAS8+LkGXgsC89Y5X3srWuZPtzlYFkobXVy9bQBzUWAWuaD5lLNUnh9uVZmUOwKe/WrMAXNhYK7uXnDZDnkty0X7+GC7yqesT4Lz9tHP3+8awFwcmPM6jeOq5/oBXj2CeVxjibv86TvL1RXw6hHMo8p/791hHcLpVhUwB65SYDBXqwfn+mwHwAyYjcJ8VZ1PLwZshyBQBsxFhPma54Pj9i+dHf0MhOQrfQGvHsFcqkIZWgavWXLtEpg1EAuYQ4F5FcRmaAnA+gTzf4PYDIHXTM04BvN/gNjh2gCvmXLtStt/B7LDhWiGXzD/K5BFNCMUmCeALHYmYUQzrmDeBLND9RW8egXzaxjNsJll9dwxmEdgNMNmDmSbXRpZAbOwmQOB+ckymIUzJ6d512AufQK0w7QKXr3aZpdKHwHtMH0Dr57BPAs7A2ZGGDuTK5i/g1rMf4HAPPEV1KZrHbhma8w9mD8DW8x/QSwAS6WRCAttzH9SeuIgzJgA0/UZuPq1M7lShB0g5j8ZvXcRZuwAsf8Lw2YulWYjgJsmhJm9c+ZKpbdomrEykdFrB2GeQNOcpk3Q6p0zVyq9jOA0pwjn//L01EGYRyI4zXCZw3DmSqUo+gF2H+kTaPXPmSuVPkaIZzwS7n/J01snYZ6NlgDvoL6DVg+duVJpKorWQS922d5n5n7dNhBF37wCjfSl8cO+Pajdbp8eHe3twpiT1HMnYR6JIr8OAl72OXV+drSH+GcgZsa1neFVn7Hd51f78GGJxvc/+GlmlErzfvUZe30tujjeRZchrhlHYX7rV59x1Nel84MteBlemxnX6YzIp7DRaV+fLo+34WV4m8y41tjVc/Nob3Le16rjLWxMBPTEUZifXj23JX/yGX3NujxCLiNX8yVX9fHq2XlzG+huX7u6MWj1cpl9s9CO/MmB/uwbUKMMXr2c/24mQG+s5iMTMPc7NQDr4/x3MwF6MwK2jcDc79VBrIfzX6n0JPJoBLzoG1ICZD2c/37tAKPoO8yMh2oCWt/2f9eauX6CfmwB9/qg2b5eOwzz61/P0IvTU4d90Gxfzx2G+fmvZ+jF1UbHfdBsXyWXdfMU12BmPDKcAW6KZp2Gedab0nxpFuY+HDqvViZ3axMfFifbfdPC9sSnlcnvo1N+LE72jMPcxWbbr5b5tmmONrDMfqQTwOtVy3zbNLvfNZ+ah7m/A3x9apnvmmbnDY1zCzD30Gj41DLfNc3Ol+a+DcGf86plvgnou1+ad63A3K8AYI9a5l9HtCP3Exo/7cCMRaAvwYz78YzI8fNTR32UZgQzhE61/pLTueZ2H6XZtj6W3Nf87ZN1+XajC0sw92Fo3GnGA5hn7p7tOswMHDsZrpcewDx292zdtef2rMHcBcS3euIBzE/+PF1nZ8BDazAjb3Sr9yUf9DZyfgYkJPN/plb2vaMzLE7C3mUPmHNR9MV/M2N32GNsHVygzwjamHtgzkXOHgckJPOzHubgElazrOZLfuh95HijQUjmtzMfaEvCr94HyNea8gTmicjxRoNgZpyyR0kRa/6lMU9gfh453mgQltlHeY91hqY51PXfwBLwutFw8NAJoZzu5T3W1gWWgIGu/240df9pO7g6ISTzt/gXMLi02aMuY6DPiFY8XmZfajiBhQnQpy7jYZ/hXk5/l8vMkLu1APEMn7qMgT7DOX+OkMw/1nA4tgWWPeoyBvsM19pmgplxoOFCGcDsVZcx2Gc4Fm1uM5oZElH/DmCe8QrmqYFn71R+7oJnmX1vrU0rzYB5zCuYB/qMaMmloL44dhdiD7gFmAPuMh7kM37pkztDIMEYPhN7xJUWYA63y3iQA73RZ2doPmRcZv/SapQA5vDSn+k50Bs5czOoajJ/UOtLUQyYA0x/pp03cc3S4EjmP2Q5igAzQRPewfzy8S/hiKVxyWpmbH6+/tU6gFlcT72D+e7SOddo3mZdZt+wHJ0AZmHN+sfyvfsz3EppMCbz71imTYAFh/mlhzA/T/k9XLCbOZP51a8RHeaCbwA/PvEQ5kdWsyM0cybzb1km2RkFz2bM+MjyY6vZDZoZk/l3LAPmcE3mGz2JnKSZL5n/h2USzMXOM78v+akZF2nmS+bfYxkwBz3+XWskcpBmtmT+fZZJMBf6S6f8HP+GjYDXNK/5YWZkJfM3lyNZmAt9oHXGV5bTtoDWtyc8yfxbf1kG5kJfNfDUW5iffHSPZpZk/iDLJJ8Z2z8/NTX0t/rmvplxkZ0tkoW50DuTMY9hfjr81/pqJ9/Mkcxfe8Ry1ITNLKL5ks96O/wXs5PWZ0jmr6b8Mi04cyJ67TXMIxm/2ScbFp16Mv9rpAZzgS808teXy3Tnbiy6VafNjF0BS+5WcObC9uVy3DlLY6BiMn/9U6QKc4Fvzn/qOcyD18EMaNlw47yltsxeHfJrxHDmClCYh2TnrG0DlZL5m18jdZgL7MyNeA/z8MXJbxm98VYlmb/+eejvkMCZC3thcquJvF9y2eDd+grJ/O8Zv0ICZ64IhVmgNEdLP1w0M7ZEXAy6M1fHwsRnzeT/ol9MzYGyyfwfS5nPvwNnLlcvg4D5qcBvaqg4SybzN7/kPH1k5gpSmIVKs6HiLJfMX13Kee4V8YftoTCHX5qvivN3p8yMw9t/s7Gc+9RjmBlFKcyCpTmKlrWHNc7oZsaKwBPfF3/YJgpzIUrz9Xpbc69BTub/+CTytBtw5gpTmIVLs/Zeg5jMF+gwqM5cjMJcmNIcRZ80+hp7JDNj+PZ6UF3EjIpTmAml+bp11hbXIHyRztHmypLwM0bMqECFmVSaNeJMSOb/jzjKGs2MShzHFRRm7xIaJnAmLLNrhCdbF3/YE7FHLMdJs9X7Y063mvtx5n+eoYz3CfXfyGosMJjzExoGcL7U0w4wx4ziRup2vHdSL8t8NFToff4JL8uzpVKxS/M1ztynqgjJfFLqmGBm5F7NVWv0slzqGr1pTy+zOwan1JHgYCaX5mtn4/umJTODtNvosnUv9dz3RatGfQY75DdgE4VZ7TTgMN/567qVZTZpt8FlZtSF3hXNMg3NhKsxkdXTAGHOOQ04VJ9XucrzqZ7dBtOZqVi0W+nFpK49FeYTc4V5JkSWM+/QyNbXH6bNDEpxYjEzyoSV+GM+94luYMVcYf4YZGEulWblXxKWdkNTUJPDzIgJfXdK8YyJMDfNFeaJMFlO/f4pwjSoWp8JyXzSboPBzKB99/Zj4sq0N2bZXGGefxIozKSldnp9VumfCcn8hiYzIx2U8km/r0gzbehMzBXml6GyLGXPPZoHv63pNzMo98GVVc2McqcvoX3hT4dH76Byz1hhni2Fq9c8L9Hytx8SFZqQzNdkZrT4WB6wrJuUX6ZurjCPBAyzrD2X1kJ/WVmjEX2hWEGHSPGYSWaZzFK3LNg47FD6It7CPBMyywr2XHoTvfzt+9oGu5nRpTyHplL3IluXB6yRmGChmCvMH58EDXPW7eMKVXr568rK2lpqM72+tra6srK8rC2oqXRnhgLLD6pojQBzx1hhfh02y6WnHyO9Wlq+02fZ3YauZXaZtIkjdS3ib83YWGF+XwpdryNLIqzYKF87Gat0L0lfSRWhctsSt8V5C/NI8DBn3qWvUy1Jo4Bv/mspvBHyPkFORLcmFWOFeSp8lrlnQGERXANN819CMjK6zSRJTnqCpT4R/XWapgpz6NPfjaassEzYbZCS+R357iWrYW79HhbLidhHSF2QUXOFeawILJeezNuAOZYbrDjnv4HCtyNm4tWF1u6xoImSmCrMs6ViaMwGzJruAye8RwYSP+WuYGJ5X+gzROwTIauzYS3MoSY/DZnNfL0tZZktP/8lwv1IR8Ts6wm9OfdNFebXRWGZJXCk0cyg/FVPZAt+hWVltyPy+yVCm+wETYY3jYamZH5Pdv5rEvaPIgQ2RM63ZLwteqy3oD8vEMzmG42anmV2RXb+q1Bc7pYAp/siv5CpwjxRJJbNNxo7epL5ddmC36TMYYkAp7GAHR0bKszvS8WS6UaDYGZQkvmEsfJEsDBXKE++J/QZQeur0WS43mgQBjWKmdGVnP8S0gHuWGS7lx9wqhkqzK+LxrLpRoNAnaaWORabG3dkYW7l/uimmcI8WyqezDYaepL5hJa5L9bB9yJZmJt5MFfMFObirEtsZTQ0JfMJLXNHrOlpEht+of8oyTPvOAvzyyKybDSjoSmZT3CZG2Khp7o0zDs5v1LGJpuzML8tFVPPzcGsJ5lPMK8fPGydchgl+wNA6MmcCFVuFs0/KSjMEnc2G1hm17S8RR5QekJs2DtCnXhO52SmMI+UCqtZUzDrSeZ35VpmyrUxhE1MJ/MtUjdSmCeKy7Ixf05PMp/SZTTktpGUabWV+QbtmijM70tFliF/Tk8yvyHZMjf0wJxk9Tg7JgpzMV050/6cnmR+V7Jl7vDBnIiNlXFG2WYszGOlgsvIYW0tyXxKt6CpZX6QI8n4+IlrJgrzVNFZ1n8rDNHMEE/mn/BDR1Ys9iaJGwYK8/sSZOLqAR3JfEou44HflzDCXBazbDIu5k/QMPvlNmtJ5lPGuK5sRSe99YZ//uwbKMwjINlIGlRHMp90FW1Ddm4kvfWGv70S/YV5AhybCWnoSOYnsl1GxNhlJIJPqaW9ML8FxrchDc1DoIZkPqkwdyU971zVI8VHrnMNf09A8a1e6oVZQzKftPhoyDp6tLdehfzvu0wv8MfnYNjU7oT/r0vjpibdn9DeetYK8xgINjUEakjmtyjIdORrOi1H0rJUmDH8DQyBGjeB/Mn8fRIz+0rE9fvCh19P7BTmGeBrbghkT+ZXaN8QVRaFuUVUXcVhYSvMGP5MbgLZk/m04toU/cfKcO3YKMwfwbJJS4M7mU/semuiU1rL4HDAVphhZBi1NLiT+XUayy1hy6Gh/KtaKMwwMoZoRgvMzMn8HcUpS2cYs2u8ML8EtUYtDd5kfq2nOGXphLllujDDyDBMM2syv95Ttb90wpwYLsxg2bRBx5nMJ/bLaczohHnfbGGGKWecZsZkfpPKcgozLY0wx0YLM1g2bjfzJfNr9JOoXcoHRZqbUY6HS8W4YSjMOFpi3m5mS+bLJIRiCswtmqfdUbDUGQozDGYLNDMl8+syB0RapOfTo5ltDYX5oA6WDYn3UCBHMr+8L3fWqUIb0mLSx0pNvqlnKMxYlthYnqgm88txIht0S4hDWpPy5DsKH0PqhRnLEis0962pWyZu1x+dyGtQgYwNFWawbIXm2B7MQ7qWjnBAOcvVTj+KWjNTmMGyHZrr1lhuSITuEuGeIZH/HOqCZU9pbthiuVOW8QpP7v5VnOlqD7sjoCP/iSGs16DTEs0tSyz3apL56mY9juN6oyvXKQh4N6qxaQQyrIWOepZgrnMuxcWBTLQXZrBsjeayJZabWmfS4RcR1XUXZrBsr9OwZGZ02DL0xOIaay7MYNkizYkdlstaHZZ9BVtdrTDDx7BJc9MGy728Q94dbS1MbtWPwbK3NLdcZFmt+Wmq/MItsOwvzU6yrOR+N5UeOQbL3tJcc5PlqNzVxHLOyakWWLYrlXzzjpss0w95C8cqYk2F+SO+5sE2zcbNjE5F59uslw9jWU9hRhafjWbpU64nhlluiX+tgoQ/d1JWnBJisGxf0me2O2ZZJl2wtUPsNHpiV5S2NBRmnMN2gWaz7fIOcTolvdUagkW/STtoBZZ9CWoYXWa3KtSnVxZ36JoV9TFB9l4OrLDZaZ51O5nf25d6t3WYUc6YLJuSLOMrsd0wnBOHy/Lt+y3Xce7sk76sr8bMMuxlLXrtLMzdnUhecTNjEuwkNZY5Qe6DA/ayQxadGZh7ier3nO400tqNVmNH5oE7aW8JyWc4D0vOGVPDCMzNSsShuJ40br955yRJYlnrIaoN3kkn/1aDjeGQqbHvDcpOCjaGS2NgDJQVhFPYbo2BPb29csgoY/QzoZGPTjTNrXoUst7j9mUjeireOJc1lebOfiVolKMZjH7uNc4xSEa7HIzjHPPW5m6zXg6dZAQ+TTvO88KdBtcB7W4r2Qkf5CvNosUw7Ti/FW+c6ycqueZOq9VIduKoKJoAXBY8uo8RBEculFbjPdjj1lu0GLZajRnQBxcjGI2h1eBclMDFsLtAmQWDXJpCi2F9DgSFPJMfvtkPcyAmP4hTE2ARZRnFGcLOD8U5qLIMQw7FGd0yhOKMbhmC58wvhPDd9ZyxECRpHqkih4W0BkUIezqukXlAKujH4ciqB4Mgeg2RDgODH3qNQDyMCQx+3vQaMJ2zrWV0GD7pJXqNoXoPD8O3XgOt85BmGbeH+7hDQeuMZjkgnLESxMIvoEkQON9HGXMfliiBLElwXDUAYwM4X6MMCwM4A2UIOANlCDgDZShXY4V0NmYw9sGogxkHOa5CbQWx7Qse56JkNuZfAmXMgmFMfcjeF6Z5fht2f4FWuWDdxjz6Cygcqy7I8jwDVxnlOQi9R1EudHkOx6v7OIX9SNH15GUQp1/fwr6Agmg30F5A9/R8ylue37+GEQeFwDNIhsLgGSRD2f3za0/mwbfokyERf2PG8TDS/BS8C0i84ZhwtkC/fQ0/GaIW6DH3Ouj3U9hWQ7Id9MuZeXdAHkOXDCkCPTZlveWYnRgByBCTRibeWirR8zPokSENJXpi1qjNMf8WBRnSORaOTMwYOOQ9O/Uaox5kxrm7RlpLlf44OzUxgsUeZL5Kj10xzdRLv7+ieAzVGLLdTF9BPfF2dlaqEM/OTEyMoDWGHHQ9RkZeTkxMTM1eK8XR+/X/X9XgiasqPAKXAoIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCHJV/w9YmztbIVgQTgAAAABJRU5ErkJggg=="" />
</defs>
</svg>";
return svg;
}
public async | Task<string> GetMediumBadge(string id, ETheme theme, CancellationToken token)
{ |
(byte[] avatar, UserSummary summary, User user) = await _forumProvider.GetUserInfoWithAvatarAsync(id, token);
(int gold, int silver, int bronze) = await _forumProvider.GetBadgeCountAsync(id, token);
ColorSet colorSet = Palette.GetColorSet(theme);
string trustColor = Palette.GetTrustColor(user.Level);
float width = MAX_WIDTH;
float logoX = LOGO_X;
if (_measureTextV1.IsMediumIdWidthGreater(id, out float idWidth))
{
if (idWidth > TEXT_MAX_WIDTH)
{
width += idWidth - TEXT_MAX_WIDTH;
logoX += idWidth - TEXT_MAX_WIDTH;
}
}
string svg = $@"
<svg width=""{width}"" height=""60"" viewBox=""0 0 {width} 60"" fill=""none"" xmlns=""http://www.w3.org/2000/svg"" xmlns:xlink=""http://www.w3.org/1999/xlink"">
<style>
.text {{
font: 800 10px 'Segoe UI';
fill: #{colorSet.FontColor};
}}
.anime {{
opacity: 0;
animation: fadein 0.9s ease-in-out forwards;
}}
@keyframes fadein {{
from {{
opacity: 0;
}}
to {{
opacity: 1;
}}
}}
</style>
<path d=""M1 1H{width - 1}V59H1V1Z"" fill=""#{colorSet.BackgroundColor}"" stroke=""#4D1877"" stroke-width=""2"" />
<g id=""name_group"" class=""anime"" style=""animation-delay: 200ms"">
<text id=""name_text"" class=""text"" x=""75.5"" y=""16.5"">{id}</text>
<path id=""name_shape""
d=""M67 13C68.5781 13 69.8571 11.8809 69.8571 10.5C69.8571 9.11914 68.5781 8 67 8C65.4219 8 64.1429 9.11914 64.1429 10.5C64.1429 11.8809 65.4219 13 67 13ZM69 13.625H68.6272C68.1317 13.8242 67.5804 13.9375 67 13.9375C66.4196 13.9375 65.8705 13.8242 65.3728 13.625H65C63.3437 13.625 62 14.8008 62 16.25V17.0625C62 17.5801 62.4799 18 63.0714 18H70.9286C71.5201 18 72 17.5801 72 17.0625V16.25C72 14.8008 70.6563 13.625 69 13.625Z""
fill=""#{trustColor}"" />
</g>
<g id=""heart_group"" class=""anime"" style=""animation-delay: 400ms"">
<text id=""heart_text"" class=""text"" x=""75.5"" y=""33.5"">{summary.LikesReceived}</text>
<path id=""heart_shape""
d=""M64.4895 25.537C64.932 25.4616 65.3858 25.4865 65.8175 25.6098C66.2491 25.7331 66.6476 25.9517 66.9835 26.2495L67.002 26.266L67.019 26.251C67.3396 25.9697 67.7165 25.7599 68.1246 25.6357C68.5327 25.5116 68.9625 25.4759 69.3855 25.531L69.5085 25.549C70.0417 25.6411 70.54 25.8756 70.9507 26.2277C71.3615 26.5799 71.6693 27.0366 71.8417 27.5494C72.0141 28.0623 72.0446 28.6122 71.93 29.1409C71.8153 29.6697 71.5598 30.1576 71.1905 30.553L71.1005 30.6455L71.0765 30.666L67.3515 34.3555C67.2655 34.4406 67.1517 34.4916 67.0309 34.4992C66.9102 34.5067 66.7909 34.4702 66.695 34.3965L66.648 34.3555L62.9015 30.6445C62.5046 30.2583 62.2224 29.7698 62.086 29.2331C61.9496 28.6964 61.9645 28.1325 62.1289 27.6037C62.2933 27.0749 62.6008 26.6019 63.0175 26.2371C63.4341 25.8724 63.9436 25.6301 64.4895 25.537Z""
fill=""#FA6C8D"" />
</g>
<g id=""badge_group"" class=""anime"" style=""animation-delay: 600ms"">
<text id=""gold_text"" class=""text"" x=""75.5"" y=""51.5"">{gold}</text>
<path id=""gold_shape""
d=""M70.9575 47.9984L71.8556 47.1194C72.1234 46.866 71.9985 46.4156 71.6473 46.3316L70.4237 46.0193L70.7687 44.808C70.8661 44.4596 70.5376 44.131 70.1893 44.2285L68.9785 44.5736L68.6663 43.3495C68.5837 43.0039 68.1282 42.8774 67.8787 43.1412L67 44.0463L66.1213 43.1412C65.8746 42.8804 65.4173 42.9999 65.3337 43.3496L65.0215 44.5736L63.8107 44.2285C63.4623 44.131 63.1339 44.4597 63.2314 44.8081L63.5763 46.0193L62.3527 46.3316C62.0013 46.4156 61.8768 46.8661 62.1444 47.1194L63.0425 47.9984L62.1444 48.8774C61.8766 49.1309 62.0015 49.5813 62.3527 49.6653L63.5763 49.9776L63.2313 51.1888C63.1339 51.5372 63.4624 51.8658 63.8107 51.7683L65.0215 51.4233L65.3337 52.6473C65.4204 53.0101 65.8746 53.1164 66.1213 52.8557L67 51.9572L67.8787 52.8557C68.1228 53.1191 68.5816 53.0019 68.6663 52.6473L68.9785 51.4233L70.1893 51.7683C70.5377 51.8659 70.8661 51.5371 70.7686 51.1888L70.4237 49.9776L71.6473 49.6653C71.9986 49.5813 72.1232 49.1308 71.8556 48.8774L70.9575 47.9984Z""
fill=""#E7C300"" />
<text id=""silver_text"" class=""text"" x=""105.5"" y=""51.5"">{silver}</text>
<path id=""silver_shape""
d=""M101.957 47.9984L102.856 47.1194C103.123 46.866 102.999 46.4156 102.647 46.3316L101.424 46.0193L101.769 44.808C101.866 44.4596 101.538 44.131 101.189 44.2285L99.9785 44.5736L99.6663 43.3495C99.5837 43.0039 99.1282 42.8774 98.8787 43.1412L98 44.0463L97.1213 43.1412C96.8746 42.8804 96.4173 42.9999 96.3337 43.3496L96.0215 44.5736L94.8107 44.2285C94.4623 44.131 94.1339 44.4597 94.2314 44.8081L94.5763 46.0193L93.3527 46.3316C93.0013 46.4156 92.8768 46.8661 93.1444 47.1194L94.0425 47.9984L93.1444 48.8774C92.8766 49.1309 93.0015 49.5813 93.3527 49.6653L94.5763 49.9776L94.2313 51.1888C94.1339 51.5372 94.4624 51.8658 94.8107 51.7683L96.0215 51.4233L96.3337 52.6473C96.4204 53.0101 96.8746 53.1164 97.1213 52.8557L98 51.9572L98.8787 52.8557C99.1228 53.1191 99.5816 53.0019 99.6663 52.6473L99.9785 51.4233L101.189 51.7683C101.538 51.8659 101.866 51.5371 101.769 51.1888L101.424 49.9776L102.647 49.6653C102.999 49.5813 103.123 49.1308 102.856 48.8774L101.957 47.9984Z""
fill=""#C0C0C0"" />
<text id=""bronze_text"" class=""text"" x=""135.5"" y=""51.5"">{bronze}</text>
<path id=""bronze_shape""
d=""M131.957 47.9984L132.856 47.1194C133.123 46.866 132.999 46.4156 132.647 46.3316L131.424 46.0193L131.769 44.808C131.866 44.4596 131.538 44.131 131.189 44.2285L129.979 44.5736L129.666 43.3495C129.584 43.0039 129.128 42.8774 128.879 43.1412L128 44.0463L127.121 43.1412C126.875 42.8804 126.417 42.9999 126.334 43.3496L126.022 44.5736L124.811 44.2285C124.462 44.131 124.134 44.4597 124.231 44.8081L124.576 46.0193L123.353 46.3316C123.001 46.4156 122.877 46.8661 123.144 47.1194L124.043 47.9984L123.144 48.8774C122.877 49.1309 123.001 49.5813 123.353 49.6653L124.576 49.9776L124.231 51.1888C124.134 51.5372 124.462 51.8658 124.811 51.7683L126.021 51.4233L126.334 52.6473C126.42 53.0101 126.875 53.1164 127.121 52.8557L128 51.9572L128.879 52.8557C129.123 53.1191 129.582 53.0019 129.666 52.6473L129.978 51.4233L131.189 51.7683C131.538 51.8659 131.866 51.5371 131.769 51.1888L131.424 49.9776L132.647 49.6653C132.999 49.5813 133.123 49.1308 132.856 48.8774L131.957 47.9984Z""
fill=""#CD7F32"" />
</g>
<rect class=""anime"" x=""{logoX}"" y=""3"" width=""25"" height=""25"" rx=""12.5"" fill=""url(#pattern_logo)"" />
<rect class=""anime"" x=""7"" y=""6"" width=""48"" height=""48"" rx=""24"" fill=""url(#pattern_profile)"" />
<defs>
<pattern id=""pattern_logo"" patternContentUnits=""objectBoundingBox"" width=""1"" height=""1"">
<use xlink:href=""#image_logo"" transform=""translate(-0.0541796) scale(0.00154799)"" />
</pattern>
<pattern id=""pattern_profile"" patternContentUnits=""objectBoundingBox"" width=""1"" height=""1"">
<use xlink:href=""#image_profile"" transform=""scale(0.00833333)"" />
</pattern>
<image id=""image_logo"" width=""716"" height=""646""
xlink:href=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAswAAAKGCAMAAABpzD0iAAABF1BMVEUAAABNGHduIKBNGHduIKBNGHduIKBNGHduIKBNGHdaG4duIKBNGHduIKBNGHduIKBNGHdRGXxeHIxmHpZuIKBNGHduIKBNGHduIKBNGHdZG4ZuIKBNGHdTGX5YG4VgHY9jHZJpH5luIKBNGHdhHZBuIKBNGHduIKBNGHduIKBNGHdPGXpRGXxTGn9VGoFXG4RYJoBZG4ZbHIleHIxgHY5iHZFjNYhkHpNmHpZoH5hqH5tsIJ1uIKBuQ5F3LqZ6UpmAPKyFYKKJSrKNYqyQb6qSWLibZr6bfbOkdMSmjLuqjcCtgsqxmsS3kNC8qMzAndXHt9XJq9vOuNzSueHTxd3bx+fe1Obk1e3p4u7t4/P08ff28fn///8PlaBgAAAAKnRSTlMAEBAgIDAwQEBQUFBgYHBwgICAgICPj5+fr6+vv7+/v7+/v8/Pz9/f7++nTCEdAAAriklEQVR42u2da18TW5PF41EPMF5gnuGiI3PDEaRRjCKRS0IDE4QeQoAhCSHk+3+OARGE0OnetXfta6/14nnx/I4hhH8qVavW3imVIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIDGN3ujV5D29uPn/nuHVgZzH98UVsHNzcwtVAX2Ym3t39Z+Pjv6NVw5yh+HJyXdiAA8H+83kOKiGLFL84grixSqjFq6gfgGmIYP6a3R8mpfiQaYnX43iZYY069mLSbWOgtB7vJsc/QuvOKSL48WqYS2AaIi7PR5/t1C1pg9vXqGRhlga5Mm5qn0tXpVo/DEgBb2Y/lB1SHOTqNCQjP52oiI/rtDjWCBCpN7i1ZvFqrNamH6BPxEkWJI/VJ0XCjQk0CUvVD3RB3TQUAbJLjcX6Q0HeIZCIBk8QyGRDJ6hwYnPnz55KM+YB6FS6dm49yT/3qi8Qoij4O3Fu2o4WnyDjXdxi/L0YjUwLYyjPBdRr+aqQQrluXBFeXKxGqwW0D0XSKPvqmFr8Q3MjYL0FwvVAmgO3Ubw+ivk/mKw28CfO+hW+U21SFqcRPMcbKtcLJR/4TyN5jlIlOeqhRRmQaAMnCGgDJwhoAycIaAMnIEycIbgK/sr+M7e6i+g/HiNAiy8RLk4i2ssuQNXMeJEiCAVYe77AGiH6x0mQcx9mAQh00KzLNA64+5FLzoMNMtirTN6Dec7jHfAFL1GGBpHh4FeIwz9DQ+D6mugODu6JZkGnPSV4DjAweCHQRBCWUZeA8rWCwx+CvqA+50dKsvw41RdOkCEbhmdM4RuGbYGBG9ZY3GG52xZk4CQrzhjIWhTz3BclVXTKM4w5GDSQYrC5Ic5MJQWA5OfFiF7hBYjHC2g1UCLEU6rgdsI0GKEozdoNYxpFC2GblcD221DGgdsWKCEIdwgZ0YI0qFdRuMMoV1G41w0vQJiJhtnOM4ahXbZsOA4axv9kJEzrmlgh9EPYyCUob8x+tkZA0EzuxAssiUEj2BjwNSA0oWQHEwNWHIQaHbLksOFRbDoQmEZlpwLFh1ABMugGcKqxDnhpKuDq5LdPkGHaj/rrE9UG+sTsEzQTwpcF2o/65wK8ymWgWCZoCMSXXtKP4vKcv8Iq22wrO2jX6lU7pFh3quCZrAsrgsSXZdbCj/qgAzzVhU0g2VtH/0Hxjqa67eO854GaHaJZepH/7nCz2qHZGaAZudYpn/078r/rEvqzzqugmawLK5jc4BtkVvmgypoBssaP/ovjXU0zpsZoNktlukf/fLl8pD8ozzZbINmN1imf/TLT2Wn1J90UQXNgUlrTo7+0d/vb5vqaM78SR0BU/ss061fhR1zYMvsB0Ii1D7L9I9++U//bfIP+lkFzUFJ8xmptgTMkpDRO5pdj2DGnbf50n12VYZlyV72KFQz47dwyjVHuu8U2JaCWS7/E1QyHzSTpf2ul59yMEsdOAkrmZ8i3A5jlWUpM0N2BAzZzADNNpclsh/98nvmXRM/BMsTR/XMwN2I55IwS3QA4SXzQbMrBrOCmSF34CTAZD7sZlGZuBd/TxZmibRRO3QzA3azNYNZ8qNf/sDJBfVHHHsJMww6G0aGgpkhkzYKNJmfIlgaAxo187q35WE+1t7R7HkK8yKGQNOm3C9dysNMHc+CTebD0nDAyJD66JfvAo6NLGZgaRQtKcdgZtDTRgEn8x9rHAzfatLUa36oAjNxBAx/mX1fo6DY6PBXlUvmS9IWdjL/8RCIL403tsVWNzOoTW3gyfzHQyBAvpbBq/H7aqLUzqPimBkYAs1u/mQ/+uXTRsEn87EJtLX5u9FPRZgpsbbgk/mP2+bCbwKNfr37kSrMhAMnxTIzsDspmf5etDNVmMVHwCIk89E2W2uYq/LJfAnHoRDJfLTN9/XC7GutzLJ4Y1uMZD7aZisOs/Iym3jgpF04M6PobvOc2Vf6QB1m4bRRUZL5gyrsF8ZPGn6hjxhgFjxwUpxkPkIaN66c6de5zQCzYNpor4hmxk3bXEh/7q8F06/zJQfMYu1AgZL5gyrkzc3Tpl/lLQ6WBV2HIiXz4c+ZduV4zAzh5rZQyfzBRqNwadC/Fo2/yIc8MAthV8Bl9h/NFQ3md+Zf41MemEVGwIIl8wc1jibDCzNDrIgWLZlf6EbDQpPBscwWntWOimtmFK/RsNBkKCfzKZZw8ZL5xW00bDQZ6sl8QtqoeMn8wjYa5tclXMts0bRmoc2MYjUa01Ze3jM+mPMOnBQymT+gF8VgedTOq3vOB3Ne2qiYyfyBRqMYGY0Pdl7dPqN2mTuay2p4KsQZqkk7r+0eJ8ynzI52O0CYixAGfbZo56U94IQ558BJUZP5D7UQPsxzll7aI06Ys9NGxU3mP1Tw33bywtYr22aFuc3b0eg2M9bWvq+sfFleXo4e6ur/WV5Z+b62BrPZG4v5WpesMGemjdxJ5m9eQfyI4HR9Xr6CepP3xwee05+0xfIWL8uZXa4TyfyNHyvLSxFVS8srq+uYAcWmP2v92x4zzJecHQ13Mn9NhuMHRDPV6KBnwHfWYD5khjkrgGx1mb327XPEoc/ffmAGdHD3d61TbpiHV1N7yfyN718iTi1/V205At4DLtiDuc0N8/AR0FIyf/3bp4hfn76p8RzsHvCVPZar7CwP7w1sJPP1kPy7hf6qwnOgt8/9tWiP5W1+mIdaEMaT+RsaSVauz4FmQSctFuaf/DAP3XSYTeZvrn6OTOjzqqTBEaQ998wiy8zL7GwGTZoZ61+XImOSazeCtOfe2IT5TAPMQ0LIBpP5q8uRWX1elXiWAd5w9LdNljmT+XnxIFPJ/M2VT5F5La2Qu42F8Oy5Oasw62B5yIETM8n8jRXl/qLZylR9qLmxUfTNyahVlve0wJzuD5tI5m98ZSiyOU9rP6N5puEc3ObEbmE+0ANz6gioP5nPgnJUy3laceYsuFHg0my3MGsxM4Y0CNqT+ZsrPN3vTs7TKudYG4TeObBg8we7MLf1wJzGoeZk/uYKlxeXZD+rHucoGNRS+5VdlrmT+Vntrt5k/iqfg9HKflYtAWdD3KgLqTQv2GV5q69Lj9NGOpP5a5y+cjf7aSVCvvNa8Uqz7cK8pw3mY/WORjiZv/mV1THOeVp1wa3gZtFKs+XCzJ/Mzyir2pbZq7yL61jFzLjfa3wvVmm2XZj5k/nDc/W6kvkb3Jvr/ZynRYjwrxepNNsuzNrMjJQmQVMyfyXiViP7WXUoj7VSnNI8apvlal+jtg0k89c1pDxzzIwTWgBJoDiHsQacs83ytk6YD/Un87/riHn2GMwMUnGeRGF2NZk/bATkT+Zvasl5VnKe1g758GvegjuIhIb1wqxrmZ26wGM3M37oSd/nmRkVejj0R/il+W/rLOtJ5qeXVvZk/jdNueSEzcz4o2/ZnvMiDpi4msxPz9YzJ/M3tJ3vayovs9PmwI2wj5w8s88y+aOfCP+BtmT+mr4Dfp3sp9WUPIeS2Wp4fxpw2j7LZOuXGK8415XM/67x+JN8Ml/B1fD8S3ts3pUh/dFPpX9XTzL/q0aWlZL5mfqS0Th7fofGuANdxpFumI91JPM3tV6HoZjMl22c/b7eaMEBmNvkNla67+VL5q/rPXqtmszPbJzXw9xpv3CAZXIyv12VLq9syfw1zXe7tHSYGQJjoM+LkzkHWN6iz2QXslMcVzJ/Vff1FxzJ/AytBrg4ccGXo3/0t+mexDavmZHLcjneSa7UajWv/rceV7jNjLrqm2UlPHdu2gWYyR/9R/SV4RHrMjtz61feabQeh4RaCSlMEWszM+5OoIS2OHHBl5NI5h/R/Y8LzmR+hiVXa2QsO07qwh4EXzKfSrO37twrF1imf/QfSMTsfvIl84eyXElyOt1+rynYcHAm84k0+3ri5IMTMMu4ZeTdxxlbMn8Yy/GJ0AOK4cyazKfRPI28nMlk/pYMlVtS8bxzUZbjlvBjNoY2G/W7SxFzkvndgTsUa4w0e5qde+MEzOSW4VLqHXDIk8xPZ7nWojxoN5arx5zh5gyaX2H8M7fMbks12hcsZkYqy+UG9WEbUuayhnnwaygjoBvjn6TNdiDTaSsn81NZjiUYbKW1GmVZllu8fbOPI+CcGzCTP/oPpHbg1x0D3QTZzt+VNKT465Tp5jK10IudPgliBHzmBstVyWp5KtFqKybz01iudCQBTKF5XxbmfRVPYzWELeC0GyzTrV/5w3xy7fndydW0ya8nfZjrMc0N2YdS2weuBpDRX3ADZnLzey7fnpDb8/vJ/PWUnFxd5Whik83MKCvB/DgR6l0QdNSRLoNcLc/kIx1kC+TeBTKb3Cw/7g5kH6eruDx5TLNvQdA3jsDcpjMpmRw9o/+svcxzJYos9/s10rUvmsLN12dPNj23mhcdgZm8mP4pG1Bq0zuTTFNOmeUBCqXNjER5sb088Ed5hyMmRpL5f9wy6uhIPm11L5m/ooPlgVhywvIoPAadX1bzu6rfZoZMUSfD3M4wMmIGlvu9svi1L6LdCoulMe7VKtsRluljXFt+diTvTG7b840lTk9uWIcga2Z0GVgeHAI/YJUtIfKhvFP5vB15z3Lbnj8e/sodFpYfgCgLc4MD5sEh8Bm6DANmxqF8rIM8a+4OHf5O+kyqK/fMvQoLzAMpjXF0GcaW2ZILF6n2/IfU8HcdORZIILXE733Rscse2jZ/QJdhJpkvf+OGzK4xpWGu5DXM3f3K74NUua11RfiuRME9IlPb/AxdhnYz41Kt45Zozz/TQ/QJobneV2rEe2x1+bpt9rLPcKfLUIv+6P0ylBszg+4w92qUUfHB4qR+QjFJuoTj3mS32Zs+44UzMEtfgCGbNqK25+spGfoegeX8+zyN3JkvqDUP+4w3zsAsmcw3MwJupzcZDRLLuXDGRu7MF9OnTf/yGYthmBnX23CNI+BlepORkwfaof6DxMyd+eRGw5N8xqgzLNMT9oOPoPGLitupTUZO4WyQD12fEK+ZS3TCfL/R8CMHOu0MzNLJfIVsh7COU5uMinjYQqzP6Bi7M1+o0fDtvMmCv2bGmXqElLBrXCEX5rrELYjm7synXQ/qxXmTZ86wLJ/MV0gqibfnKeuSnMKcnvkpk+jUeWe+iDa8Otc67g7M8sl8hUC0cHv+hacw53XBscE780lBfR++4MSZ9Z9KMl/BqhaNJa1FVI+5V2aAuWsiI5elu++I8OEWfXcKs0oy/066vkW+/Yl8b3IzYoBZPGan22z24J4ud9Z/Ssl87SPg/9Jvg9thgFn/nfniM6D75pw7xpxSMl972iiNzJrcbEbB08Cd+bnxuQ1vzLkPHpsZhzwxUiHVyONfkwPmnGuNugZgvsvpO3/pnDuJOfVltux7Qkhpf+WeVDsbU2A2cme+oD23gJbZVDJfb9oo7WtDdoRz9pTIaEx4v2heZg/ac64n5954bGZcDnkgHWmjJv322niImgSYKxKdvL6IhuvJOXd22arJfL1po4TzZnvxgh5LdPL6SrPjG22HdtnKyXyF8F2+YnL4k6U5t5jMTynNjjfNrxyCWTWZr/XASYW6MeGB2WIyP600u900T4dnZmhJG6V5xidaWG45k8xPKc1uN80OuczqyXyNaaMW2ZiT1Yk7yfzHpdnpptkll5nsqF0Mfyz2EbBhrGVO3EnmP/aanT6j7ZDLzJHM15c22tdzh22e2WY5mf94DehyPGPSIZgZkvn60kYx2WVmmTRtJ/Pv61d4btRhmOccgpkhma9Q5ukWWEsPzE4l8x+F51zONDvEMn1o22VdjZPzPHpYbrmVzL8fnnM80/y3QzCzJPN1HThpGZv/mm4l8wevBV3EysRcMl9T2ighZ99YJk0HkvmD7py7BwEdShkxJfM1pY12qLdf8EyaDiTzB905d9cmH0I1M7gPnNSMwVx2LZk/cFnXNOY/o8tsDWkjY2ZGz71k/sMR0NkJcNQhlrmS+VrSRh1jMLfcS+YP3DqA+c9gMl/HCNg0lsxIHEzm/9EXhydAlyJzbMn8P8b1pR7EhFyzXktOOw4m8x9uAV2dAF3a/5F94ePch+RLG8VkmFnWGa4k8x9YzZOY/wwm8xXWMIRkfmSgnXUlmf+gz3B0AnwWspnBmTbqqd4XIClnkvn3+4xFmBkGk/n8B05almB2Jpn/oM9wMwXqUv6TM5nPnjZq0GHm+M5fh5L59/sMN1Ogb3w2M860TJXCyXzi9fdSciiZf7/PGIeZYXiZzXrgJLYDs0vJ/Ht7k2mYGSaT+dwjYNoftaIfZpeS+fdOT83BzDCZzGdOG3UlpjOOntmlZP69fMYCzAyjyXzeEbAlATPHcOZUMv9O606mMxi/mGd7b0vtAZiT+Qq9uLAF1pOJTTSyl9l1d5P5d/rupJ3BkszYPTy73d21Tw+kkeZO5rOmjXYkOtr0N0CZ8pMcS+b/OW/yIkgzY/tocMBqH7hkZjCljWoSMKe3JnUKn44l8+/kZDpD9ZjJdmqQ5/JI5rF0LLPZ0kZSxllZYqRrum9mXGntTXjO3NGwmnexR39fsCfzGQ+cdCKZKps2nu2T+pmeozCvzIXmzG2fK6UztSfzGQ+cNKWWzSldQK1H+id9R2H+shCYM7eb3YqeEydB/mQ+Y9poWJ6HeqapnHfR/j7pXo6OLZiXHPTmVM5M5XoERJo1JPMV9jGCFlje9cwDc2Otkxc0LVP25Tx7GbkbB9w7OTWpkWUqzRqS+Xwj4DBo8jrg3oMWuN4jfgLkwnxiC+ZV94zmN7p6DAma9ZkZ6mmjoXme/Pu5mnfFuZ5/lrsbEWHut3as5Oaib+4dA5S2mbfE0junhHeHpmU2S9qoJXsQ5BehzSRJmi2ZbibmaYZ0rE3cM5qlbWbRBvcnZ9tCT+YrjJeCeR7WL+g5idRgNlikl9wLgWrPBF1uaaPtjPSM1dJG+0P/qGVGlrtlas7IYrj5v4KBWfxDW3gXqG2ZzZE2iqVPTyuuzJmaIQ36T9dY/lufk0EuzZqS+Txpo4w/Kt8VzXV6Nl/MDNezAwxlZ3LOX0B1JfP/SCFt1FW42EKtL2+ovhv0nTYJBGaS8XDB3IXLmRlqB04yP7+ZSnNT6jyrvXDzsmu3DUjuTI41VFBtyXyOtFGicuZUKfxBuprR7EJ7NAyYabu6Iz1181Tz085P5lO8ZlmWKU2M4aBGGDBv6Sihus0MpREw56bNWk9Lv0xtYgyvtv8piAXgno7mVusyWzVtlPd3Vf2e1jrLfGn4pq5/BAEzdb2xbTeZr542yv/8Vmqbu5mFv9Jjaoa49c+FhHlPh5lxaeAjJbehZfHnTnKW0MILc8Nx0AnHYF6UgvlUA8w6k/nKaSORz2/ZL9Hu5dfTE6ZmiFn/FsQ2u60BZp3JfOUDJ0L+rVzf3BTIBpXF3BLTR6hmAbONZL5q2kjs87vWJT9wS2zNIUbzfrFh/svMZS17bpgZUh8AlDBamdhqdIQ3dmWBTqNnOqQ/H8Q2W8MAqDmZr3bgRNy/jVvsVfl2CuxxNPa8CgJmaucpYKKR9xlnck9dKm1E+fyui/W33QbVeqg0nVr/BQMz0eG61GFmSN4AJpU2onEX57p03aaUI1xJMpryVhkwy4m/iFJnykvJZy4zApK/z6lcbw5tCnon+wrfQllL0vuYrpWbbZ8GcdEADb1DDQbwkSzMEgdOpOCr1RutgULaaiU7DF+nWouT5MGluI39WmRFI07B/C9VE02zwDabmpq4kGaZ3p2rfNFeOb6VJd4KBPM/THxWn2vYM+/Jw0y93rZbjqCQYSbZtQf8/shhVUG0ZXyvBmjDbjMolfSC32M4VWGZaGnXwawnME8aGKMO2KcyNZZpwyZYLgDM25wdM83rO1BkmdDToMcoBMzCW45d5oHyfFeVZXHr5P8w+xUDZsHO4JC3Bb88qjJIbAS8+LkGXgsC89Y5X3srWuZPtzlYFkobXVy9bQBzUWAWuaD5lLNUnh9uVZmUOwKe/WrMAXNhYK7uXnDZDnkty0X7+GC7yqesT4Lz9tHP3+8awFwcmPM6jeOq5/oBXj2CeVxjibv86TvL1RXw6hHMo8p/791hHcLpVhUwB65SYDBXqwfn+mwHwAyYjcJ8VZ1PLwZshyBQBsxFhPma54Pj9i+dHf0MhOQrfQGvHsFcqkIZWgavWXLtEpg1EAuYQ4F5FcRmaAnA+gTzf4PYDIHXTM04BvN/gNjh2gCvmXLtStt/B7LDhWiGXzD/K5BFNCMUmCeALHYmYUQzrmDeBLND9RW8egXzaxjNsJll9dwxmEdgNMNmDmSbXRpZAbOwmQOB+ckymIUzJ6d512AufQK0w7QKXr3aZpdKHwHtMH0Dr57BPAs7A2ZGGDuTK5i/g1rMf4HAPPEV1KZrHbhma8w9mD8DW8x/QSwAS6WRCAttzH9SeuIgzJgA0/UZuPq1M7lShB0g5j8ZvXcRZuwAsf8Lw2YulWYjgJsmhJm9c+ZKpbdomrEykdFrB2GeQNOcpk3Q6p0zVyq9jOA0pwjn//L01EGYRyI4zXCZw3DmSqUo+gF2H+kTaPXPmSuVPkaIZzwS7n/J01snYZ6NlgDvoL6DVg+duVJpKorWQS922d5n5n7dNhBF37wCjfSl8cO+Pajdbp8eHe3twpiT1HMnYR6JIr8OAl72OXV+drSH+GcgZsa1neFVn7Hd51f78GGJxvc/+GlmlErzfvUZe30tujjeRZchrhlHYX7rV59x1Nel84MteBlemxnX6YzIp7DRaV+fLo+34WV4m8y41tjVc/Nob3Le16rjLWxMBPTEUZifXj23JX/yGX3NujxCLiNX8yVX9fHq2XlzG+huX7u6MWj1cpl9s9CO/MmB/uwbUKMMXr2c/24mQG+s5iMTMPc7NQDr4/x3MwF6MwK2jcDc79VBrIfzX6n0JPJoBLzoG1ICZD2c/37tAKPoO8yMh2oCWt/2f9eauX6CfmwB9/qg2b5eOwzz61/P0IvTU4d90Gxfzx2G+fmvZ+jF1UbHfdBsXyWXdfMU12BmPDKcAW6KZp2Gedab0nxpFuY+HDqvViZ3axMfFifbfdPC9sSnlcnvo1N+LE72jMPcxWbbr5b5tmmONrDMfqQTwOtVy3zbNLvfNZ+ah7m/A3x9apnvmmbnDY1zCzD30Gj41DLfNc3Ol+a+DcGf86plvgnou1+ad63A3K8AYI9a5l9HtCP3Exo/7cCMRaAvwYz78YzI8fNTR32UZgQzhE61/pLTueZ2H6XZtj6W3Nf87ZN1+XajC0sw92Fo3GnGA5hn7p7tOswMHDsZrpcewDx292zdtef2rMHcBcS3euIBzE/+PF1nZ8BDazAjb3Sr9yUf9DZyfgYkJPN/plb2vaMzLE7C3mUPmHNR9MV/M2N32GNsHVygzwjamHtgzkXOHgckJPOzHubgElazrOZLfuh95HijQUjmtzMfaEvCr94HyNea8gTmicjxRoNgZpyyR0kRa/6lMU9gfh453mgQltlHeY91hqY51PXfwBLwutFw8NAJoZzu5T3W1gWWgIGu/240df9pO7g6ISTzt/gXMLi02aMuY6DPiFY8XmZfajiBhQnQpy7jYZ/hXk5/l8vMkLu1APEMn7qMgT7DOX+OkMw/1nA4tgWWPeoyBvsM19pmgplxoOFCGcDsVZcx2Gc4Fm1uM5oZElH/DmCe8QrmqYFn71R+7oJnmX1vrU0rzYB5zCuYB/qMaMmloL44dhdiD7gFmAPuMh7kM37pkztDIMEYPhN7xJUWYA63y3iQA73RZ2doPmRcZv/SapQA5vDSn+k50Bs5czOoajJ/UOtLUQyYA0x/pp03cc3S4EjmP2Q5igAzQRPewfzy8S/hiKVxyWpmbH6+/tU6gFlcT72D+e7SOddo3mZdZt+wHJ0AZmHN+sfyvfsz3EppMCbz71imTYAFh/mlhzA/T/k9XLCbOZP51a8RHeaCbwA/PvEQ5kdWsyM0cybzb1km2RkFz2bM+MjyY6vZDZoZk/l3LAPmcE3mGz2JnKSZL5n/h2USzMXOM78v+akZF2nmS+bfYxkwBz3+XWskcpBmtmT+fZZJMBf6S6f8HP+GjYDXNK/5YWZkJfM3lyNZmAt9oHXGV5bTtoDWtyc8yfxbf1kG5kJfNfDUW5iffHSPZpZk/iDLJJ8Z2z8/NTX0t/rmvplxkZ0tkoW50DuTMY9hfjr81/pqJ9/Mkcxfe8Ry1ITNLKL5ks96O/wXs5PWZ0jmr6b8Mi04cyJ67TXMIxm/2ScbFp16Mv9rpAZzgS808teXy3Tnbiy6VafNjF0BS+5WcObC9uVy3DlLY6BiMn/9U6QKc4Fvzn/qOcyD18EMaNlw47yltsxeHfJrxHDmClCYh2TnrG0DlZL5m18jdZgL7MyNeA/z8MXJbxm98VYlmb/+eejvkMCZC3thcquJvF9y2eDd+grJ/O8Zv0ICZ64IhVmgNEdLP1w0M7ZEXAy6M1fHwsRnzeT/ol9MzYGyyfwfS5nPvwNnLlcvg4D5qcBvaqg4SybzN7/kPH1k5gpSmIVKs6HiLJfMX13Kee4V8YftoTCHX5qvivN3p8yMw9t/s7Gc+9RjmBlFKcyCpTmKlrWHNc7oZsaKwBPfF3/YJgpzIUrz9Xpbc69BTub/+CTytBtw5gpTmIVLs/Zeg5jMF+gwqM5cjMJcmNIcRZ80+hp7JDNj+PZ6UF3EjIpTmAml+bp11hbXIHyRztHmypLwM0bMqECFmVSaNeJMSOb/jzjKGs2MShzHFRRm7xIaJnAmLLNrhCdbF3/YE7FHLMdJs9X7Y063mvtx5n+eoYz3CfXfyGosMJjzExoGcL7U0w4wx4ziRup2vHdSL8t8NFToff4JL8uzpVKxS/M1ztynqgjJfFLqmGBm5F7NVWv0slzqGr1pTy+zOwan1JHgYCaX5mtn4/umJTODtNvosnUv9dz3RatGfQY75DdgE4VZ7TTgMN/567qVZTZpt8FlZtSF3hXNMg3NhKsxkdXTAGHOOQ04VJ9XucrzqZ7dBtOZqVi0W+nFpK49FeYTc4V5JkSWM+/QyNbXH6bNDEpxYjEzyoSV+GM+94luYMVcYf4YZGEulWblXxKWdkNTUJPDzIgJfXdK8YyJMDfNFeaJMFlO/f4pwjSoWp8JyXzSboPBzKB99/Zj4sq0N2bZXGGefxIozKSldnp9VumfCcn8hiYzIx2U8km/r0gzbehMzBXml6GyLGXPPZoHv63pNzMo98GVVc2McqcvoX3hT4dH76Byz1hhni2Fq9c8L9Hytx8SFZqQzNdkZrT4WB6wrJuUX6ZurjCPBAyzrD2X1kJ/WVmjEX2hWEGHSPGYSWaZzFK3LNg47FD6It7CPBMyywr2XHoTvfzt+9oGu5nRpTyHplL3IluXB6yRmGChmCvMH58EDXPW7eMKVXr568rK2lpqM72+tra6srK8rC2oqXRnhgLLD6pojQBzx1hhfh02y6WnHyO9Wlq+02fZ3YauZXaZtIkjdS3ib83YWGF+XwpdryNLIqzYKF87Gat0L0lfSRWhctsSt8V5C/NI8DBn3qWvUy1Jo4Bv/mspvBHyPkFORLcmFWOFeSp8lrlnQGERXANN819CMjK6zSRJTnqCpT4R/XWapgpz6NPfjaassEzYbZCS+R357iWrYW79HhbLidhHSF2QUXOFeawILJeezNuAOZYbrDjnv4HCtyNm4tWF1u6xoImSmCrMs6ViaMwGzJruAye8RwYSP+WuYGJ5X+gzROwTIauzYS3MoSY/DZnNfL0tZZktP/8lwv1IR8Ts6wm9OfdNFebXRWGZJXCk0cyg/FVPZAt+hWVltyPy+yVCm+wETYY3jYamZH5Pdv5rEvaPIgQ2RM63ZLwteqy3oD8vEMzmG42anmV2RXb+q1Bc7pYAp/siv5CpwjxRJJbNNxo7epL5ddmC36TMYYkAp7GAHR0bKszvS8WS6UaDYGZQkvmEsfJEsDBXKE++J/QZQeur0WS43mgQBjWKmdGVnP8S0gHuWGS7lx9wqhkqzK+LxrLpRoNAnaaWORabG3dkYW7l/uimmcI8WyqezDYaepL5hJa5L9bB9yJZmJt5MFfMFObirEtsZTQ0JfMJLXNHrOlpEht+of8oyTPvOAvzyyKybDSjoSmZT3CZG2Khp7o0zDs5v1LGJpuzML8tFVPPzcGsJ5lPMK8fPGydchgl+wNA6MmcCFVuFs0/KSjMEnc2G1hm17S8RR5QekJs2DtCnXhO52SmMI+UCqtZUzDrSeZ35VpmyrUxhE1MJ/MtUjdSmCeKy7Ixf05PMp/SZTTktpGUabWV+QbtmijM70tFliF/Tk8yvyHZMjf0wJxk9Tg7JgpzMV050/6cnmR+V7Jl7vDBnIiNlXFG2WYszGOlgsvIYW0tyXxKt6CpZX6QI8n4+IlrJgrzVNFZ1n8rDNHMEE/mn/BDR1Ys9iaJGwYK8/sSZOLqAR3JfEou44HflzDCXBazbDIu5k/QMPvlNmtJ5lPGuK5sRSe99YZ//uwbKMwjINlIGlRHMp90FW1Ddm4kvfWGv70S/YV5AhybCWnoSOYnsl1GxNhlJIJPqaW9ML8FxrchDc1DoIZkPqkwdyU971zVI8VHrnMNf09A8a1e6oVZQzKftPhoyDp6tLdehfzvu0wv8MfnYNjU7oT/r0vjpibdn9DeetYK8xgINjUEakjmtyjIdORrOi1H0rJUmDH8DQyBGjeB/Mn8fRIz+0rE9fvCh19P7BTmGeBrbghkT+ZXaN8QVRaFuUVUXcVhYSvMGP5MbgLZk/m04toU/cfKcO3YKMwfwbJJS4M7mU/semuiU1rL4HDAVphhZBi1NLiT+XUayy1hy6Gh/KtaKMwwMoZoRgvMzMn8HcUpS2cYs2u8ML8EtUYtDd5kfq2nOGXphLllujDDyDBMM2syv95Ttb90wpwYLsxg2bRBx5nMJ/bLaczohHnfbGGGKWecZsZkfpPKcgozLY0wx0YLM1g2bjfzJfNr9JOoXcoHRZqbUY6HS8W4YSjMOFpi3m5mS+bLJIRiCswtmqfdUbDUGQozDGYLNDMl8+syB0RapOfTo5ltDYX5oA6WDYn3UCBHMr+8L3fWqUIb0mLSx0pNvqlnKMxYlthYnqgm88txIht0S4hDWpPy5DsKH0PqhRnLEis0962pWyZu1x+dyGtQgYwNFWawbIXm2B7MQ7qWjnBAOcvVTj+KWjNTmMGyHZrr1lhuSITuEuGeIZH/HOqCZU9pbthiuVOW8QpP7v5VnOlqD7sjoCP/iSGs16DTEs0tSyz3apL56mY9juN6oyvXKQh4N6qxaQQyrIWOepZgrnMuxcWBTLQXZrBsjeayJZabWmfS4RcR1XUXZrBsr9OwZGZ02DL0xOIaay7MYNkizYkdlstaHZZ9BVtdrTDDx7BJc9MGy728Q94dbS1MbtWPwbK3NLdcZFmt+Wmq/MItsOwvzU6yrOR+N5UeOQbL3tJcc5PlqNzVxHLOyakWWLYrlXzzjpss0w95C8cqYk2F+SO+5sE2zcbNjE5F59uslw9jWU9hRhafjWbpU64nhlluiX+tgoQ/d1JWnBJisGxf0me2O2ZZJl2wtUPsNHpiV5S2NBRmnMN2gWaz7fIOcTolvdUagkW/STtoBZZ9CWoYXWa3KtSnVxZ36JoV9TFB9l4OrLDZaZ51O5nf25d6t3WYUc6YLJuSLOMrsd0wnBOHy/Lt+y3Xce7sk76sr8bMMuxlLXrtLMzdnUhecTNjEuwkNZY5Qe6DA/ayQxadGZh7ier3nO400tqNVmNH5oE7aW8JyWc4D0vOGVPDCMzNSsShuJ40br955yRJYlnrIaoN3kkn/1aDjeGQqbHvDcpOCjaGS2NgDJQVhFPYbo2BPb29csgoY/QzoZGPTjTNrXoUst7j9mUjeireOJc1lebOfiVolKMZjH7uNc4xSEa7HIzjHPPW5m6zXg6dZAQ+TTvO88KdBtcB7W4r2Qkf5CvNosUw7Ti/FW+c6ycqueZOq9VIduKoKJoAXBY8uo8RBEculFbjPdjj1lu0GLZajRnQBxcjGI2h1eBclMDFsLtAmQWDXJpCi2F9DgSFPJMfvtkPcyAmP4hTE2ARZRnFGcLOD8U5qLIMQw7FGd0yhOKMbhmC58wvhPDd9ZyxECRpHqkih4W0BkUIezqukXlAKujH4ciqB4Mgeg2RDgODH3qNQDyMCQx+3vQaMJ2zrWV0GD7pJXqNoXoPD8O3XgOt85BmGbeH+7hDQeuMZjkgnLESxMIvoEkQON9HGXMfliiBLElwXDUAYwM4X6MMCwM4A2UIOANlCDgDZShXY4V0NmYw9sGogxkHOa5CbQWx7Qse56JkNuZfAmXMgmFMfcjeF6Z5fht2f4FWuWDdxjz6Cygcqy7I8jwDVxnlOQi9R1EudHkOx6v7OIX9SNH15GUQp1/fwr6Agmg30F5A9/R8ylue37+GEQeFwDNIhsLgGSRD2f3za0/mwbfokyERf2PG8TDS/BS8C0i84ZhwtkC/fQ0/GaIW6DH3Ouj3U9hWQ7Id9MuZeXdAHkOXDCkCPTZlveWYnRgByBCTRibeWirR8zPokSENJXpi1qjNMf8WBRnSORaOTMwYOOQ9O/Uaox5kxrm7RlpLlf44OzUxgsUeZL5Kj10xzdRLv7+ieAzVGLLdTF9BPfF2dlaqEM/OTEyMoDWGHHQ9RkZeTkxMTM1eK8XR+/X/X9XgiasqPAKXAoIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCHJV/w9YmztbIVgQTgAAAABJRU5ErkJggg=="" />
<image id=""image_profile"" width=""120"" height=""120""
xlink:href=""data:image/png;base64,{Convert.ToBase64String(avatar)}"" />
</defs>
</svg>";
return svg;
}
}
}
| src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs | chanos-dev-dotnetdev-badge-5740a40 | [
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Program.cs",
"retrieved_chunk": "builder.Services.AddResponseCaching();\nbuilder.WebHost.UseUrls(\"http://0.0.0.0:5000\");\nvar app = builder.Build();\napp.MapBadgeEndpoints();\napp.UseResponseCaching();\napp.Run(); ",
"score": 0.4860069751739502
},
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Program.cs",
"retrieved_chunk": "using DotNetDevBadgeWeb.Core.Badge;\nusing DotNetDevBadgeWeb.Core.Provider;\nusing DotNetDevBadgeWeb.Core.MeasureText;\nusing DotNetDevBadgeWeb.Endpoints.BadgeEndPoints;\nusing DotNetDevBadgeWeb.Interfaces;\nvar builder = WebApplication.CreateBuilder(args);\nbuilder.Services.AddHttpClient();\nbuilder.Services.AddSingleton<IBadgeV1, BadgeCreatorV1>();\nbuilder.Services.AddSingleton<IMeasureTextV1, MeasureTextV1>();\nbuilder.Services.AddSingleton<IProvider, ForumDataProvider>();",
"score": 0.4416016638278961
},
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs",
"retrieved_chunk": "using DotNetDevBadgeWeb.Interfaces;\nusing DotNetDevBadgeWeb.Model;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nnamespace DotNetDevBadgeWeb.Core.Provider\n{\n internal class ForumDataProvider : IProvider\n {\n private const string UNKOWN_IMG_PATH = \"Assets/unknown.png\";\n private const string BASE_URL = \"https://forum.dotnetdev.kr\";",
"score": 0.4086475670337677
},
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/MeasureText/MeasureTextV1.cs",
"retrieved_chunk": " 5.6103515625f,\n 6.4208984375f,\n 4.951171875f,\n 6.4208984375f,\n 5.6005859375f,\n 4.3115234375f,\n 6.4208984375f,\n 6.171875f,\n 3.0810546875f,\n 3.0810546875f,",
"score": 0.39745545387268066
},
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/MeasureText/MeasureTextV1.cs",
"retrieved_chunk": " 5.41015625f,\n 9.8681640625f,\n 8.1201171875f,\n 7.6513671875f,\n 6.5576171875f,\n 7.6513671875f,\n 6.8212890625f,\n 5.7177734375f,\n 6.3623046875f,\n 7.40234375f,",
"score": 0.38664764165878296
}
] | csharp | Task<string> GetMediumBadge(string id, ETheme theme, CancellationToken token)
{ |
using HarmonyLib;
using System.Reflection;
using UnityEngine;
namespace Ultrapain.Patches
{
class Mindflayer_Start_Patch
{
static void Postfix(Mindflayer __instance, ref EnemyIdentifier ___eid)
{
__instance.gameObject.AddComponent<MindflayerPatch>();
//___eid.SpeedBuff();
}
}
class Mindflayer_ShootProjectiles_Patch
{
public static float maxProjDistance = 5;
public static float initialProjectileDistance = -1f;
public static float distancePerProjShot = 0.2f;
static bool Prefix(Mindflayer __instance, ref | EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)
{ |
/*for(int i = 0; i < 20; i++)
{
Quaternion randomRotation = Quaternion.LookRotation(MonoSingleton<PlayerTracker>.Instance.GetTarget().position - __instance.transform.position);
randomRotation.eulerAngles += new Vector3(UnityEngine.Random.Range(-15.0f, 15.0f), UnityEngine.Random.Range(-15.0f, 15.0f), UnityEngine.Random.Range(-15.0f, 15.0f));
Projectile componentInChildren = GameObject.Instantiate(Plugin.homingProjectile.gameObject, __instance.transform.position + __instance.transform.forward, randomRotation).GetComponentInChildren<Projectile>();
Vector3 randomPos = __instance.tentacles[UnityEngine.Random.RandomRangeInt(0, __instance.tentacles.Length)].position;
if (!Physics.Raycast(__instance.transform.position, randomPos - __instance.transform.position, Vector3.Distance(randomPos, __instance.transform.position), ___environmentMask))
componentInChildren.transform.position = randomPos;
componentInChildren.speed = 10f * ___eid.totalSpeedModifier * UnityEngine.Random.Range(0.5f, 1.5f);
componentInChildren.turnSpeed *= UnityEngine.Random.Range(0.5f, 1.5f);
componentInChildren.target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
componentInChildren.safeEnemyType = EnemyType.Mindflayer;
componentInChildren.damage *= ___eid.totalDamageModifier;
}
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
__instance.cooldown = (float)UnityEngine.Random.Range(4, 5);
return false;*/
MindflayerPatch counter = __instance.GetComponent<MindflayerPatch>();
if (counter == null)
return true;
if (counter.shotsLeft == 0)
{
counter.shotsLeft = ConfigManager.mindflayerShootAmount.value;
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
__instance.cooldown = (float)UnityEngine.Random.Range(4, 5);
return false;
}
Quaternion randomRotation = Quaternion.LookRotation(MonoSingleton<PlayerTracker>.Instance.GetTarget().position - __instance.transform.position);
randomRotation.eulerAngles += new Vector3(UnityEngine.Random.Range(-10.0f, 10.0f), UnityEngine.Random.Range(-10.0f, 10.0f), UnityEngine.Random.Range(-10.0f, 10.0f));
Projectile componentInChildren = GameObject.Instantiate(Plugin.homingProjectile, __instance.transform.position + __instance.transform.forward, randomRotation).GetComponentInChildren<Projectile>();
Vector3 randomPos = __instance.tentacles[UnityEngine.Random.RandomRangeInt(0, __instance.tentacles.Length)].position;
if (!Physics.Raycast(__instance.transform.position, randomPos - __instance.transform.position, Vector3.Distance(randomPos, __instance.transform.position), ___environmentMask))
componentInChildren.transform.position = randomPos;
int shotCount = ConfigManager.mindflayerShootAmount.value - counter.shotsLeft;
componentInChildren.transform.position += componentInChildren.transform.forward * Mathf.Clamp(initialProjectileDistance + shotCount * distancePerProjShot, 0, maxProjDistance);
componentInChildren.speed = ConfigManager.mindflayerShootInitialSpeed.value * ___eid.totalSpeedModifier;
componentInChildren.turningSpeedMultiplier = ConfigManager.mindflayerShootTurnSpeed.value;
componentInChildren.target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
componentInChildren.safeEnemyType = EnemyType.Mindflayer;
componentInChildren.damage *= ___eid.totalDamageModifier;
componentInChildren.sourceWeapon = __instance.gameObject;
counter.shotsLeft -= 1;
__instance.Invoke("ShootProjectiles", ConfigManager.mindflayerShootDelay.value / ___eid.totalSpeedModifier);
return false;
}
}
class EnemyIdentifier_DeliverDamage_MF
{
static bool Prefix(EnemyIdentifier __instance, ref float __3, GameObject __6)
{
if (__instance.enemyType != EnemyType.Mindflayer)
return true;
if (__6 == null || __6.GetComponent<Mindflayer>() == null)
return true;
__3 *= ConfigManager.mindflayerProjectileSelfDamageMultiplier.value / 100f;
return true;
}
}
class SwingCheck2_CheckCollision_Patch
{
static FieldInfo goForward = typeof(Mindflayer).GetField("goForward", BindingFlags.NonPublic | BindingFlags.Instance);
static MethodInfo meleeAttack = typeof(Mindflayer).GetMethod("MeleeAttack", BindingFlags.NonPublic | BindingFlags.Instance);
static bool Prefix(Collider __0, out int __state)
{
__state = __0.gameObject.layer;
return true;
}
static void Postfix(SwingCheck2 __instance, Collider __0, int __state)
{
if (__0.tag == "Player")
Debug.Log($"Collision with {__0.name} with tag {__0.tag} and layer {__state}");
if (__0.gameObject.tag != "Player" || __state == 15)
return;
if (__instance.transform.parent == null)
return;
Debug.Log("Parent check");
Mindflayer mf = __instance.transform.parent.gameObject.GetComponent<Mindflayer>();
if (mf == null)
return;
//MindflayerPatch patch = mf.gameObject.GetComponent<MindflayerPatch>();
Debug.Log("Attempting melee combo");
__instance.DamageStop();
goForward.SetValue(mf, false);
meleeAttack.Invoke(mf, new object[] { });
/*if (patch.swingComboLeft > 0)
{
patch.swingComboLeft -= 1;
__instance.DamageStop();
goForward.SetValue(mf, false);
meleeAttack.Invoke(mf, new object[] { });
}
else
patch.swingComboLeft = 2;*/
}
}
class Mindflayer_MeleeTeleport_Patch
{
public static Vector3 deltaPosition = new Vector3(0, -10, 0);
static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged)
{
if (___eid.drillers.Count > 0)
return false;
Vector3 targetPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.9f) + deltaPosition;
float distance = Vector3.Distance(__instance.transform.position, targetPosition);
Ray targetRay = new Ray(__instance.transform.position, targetPosition - __instance.transform.position);
RaycastHit hit;
if (Physics.Raycast(targetRay, out hit, distance, ___environmentMask, QueryTriggerInteraction.Ignore))
{
targetPosition = targetRay.GetPoint(Mathf.Max(0.0f, hit.distance - 1.0f));
}
MonoSingleton<HookArm>.Instance.StopThrow(1f, true);
__instance.transform.position = targetPosition;
___goingLeft = !___goingLeft;
GameObject.Instantiate<GameObject>(__instance.teleportSound, __instance.transform.position, Quaternion.identity);
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.decoy, __instance.transform.GetChild(0).position, __instance.transform.GetChild(0).rotation);
Animator componentInChildren = gameObject.GetComponentInChildren<Animator>();
AnimatorStateInfo currentAnimatorStateInfo = ___anim.GetCurrentAnimatorStateInfo(0);
componentInChildren.Play(currentAnimatorStateInfo.shortNameHash, 0, currentAnimatorStateInfo.normalizedTime);
componentInChildren.speed = 0f;
if (___enraged)
{
gameObject.GetComponent<MindflayerDecoy>().enraged = true;
}
___anim.speed = 0f;
__instance.CancelInvoke("ResetAnimSpeed");
__instance.Invoke("ResetAnimSpeed", 0.25f / ___eid.totalSpeedModifier);
return false;
}
}
class SwingCheck2_DamageStop_Patch
{
static void Postfix(SwingCheck2 __instance)
{
if (__instance.transform.parent == null)
return;
GameObject parent = __instance.transform.parent.gameObject;
Mindflayer mf = parent.GetComponent<Mindflayer>();
if (mf == null)
return;
MindflayerPatch patch = parent.GetComponent<MindflayerPatch>();
patch.swingComboLeft = 2;
}
}
class MindflayerPatch : MonoBehaviour
{
public int shotsLeft = ConfigManager.mindflayerShootAmount.value;
public int swingComboLeft = 2;
}
}
| Ultrapain/Patches/Mindflayer.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " /*__instance.projectile = Plugin.homingProjectile;\n __instance.decProjectile = Plugin.decorativeProjectile2;*/\n }\n }\n public class ZombieProjectile_ThrowProjectile_Patch\n {\n public static float normalizedTime = 0f;\n public static float animSpeed = 20f;\n public static float projectileSpeed = 75;\n public static float turnSpeedMultiplier = 0.45f;",
"score": 0.8788167238235474
},
{
"filename": "Ultrapain/Patches/V2Common.cs",
"retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;",
"score": 0.8720611929893494
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " class EnemyIdentifier_DeliverDamage\n {\n static Coin lastExplosiveCoin = null;\n class StateInfo\n {\n public bool canPostStyle = false;\n public OrbitalExplosionInfo info = null;\n }\n static bool Prefix(EnemyIdentifier __instance, out StateInfo __state, Vector3 __2, ref float __3)\n {",
"score": 0.8719538450241089
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " class Leviathan_FixedUpdate\n {\n public static float projectileForward = 10f;\n static bool Roll(float chancePercent)\n {\n return UnityEngine.Random.Range(0, 99.9f) <= chancePercent;\n }\n static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown,\n Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack)\n {",
"score": 0.8715771436691284
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " }\n return false;\n }\n }\n class Leviathan_ProjectileBurst\n {\n static bool Prefix(LeviathanHead __instance, Animator ___anim,\n ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction)\n {\n if (!__instance.active)",
"score": 0.8663383722305298
}
] | csharp | EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)
{ |
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
namespace Microsoft.Build.CPPTasks
{
public abstract class TrackedVCToolTask : VCToolTask
{
private bool skippedExecution;
private CanonicalTrackedInputFiles sourceDependencies;
private | CanonicalTrackedOutputFiles sourceOutputs; |
private bool trackFileAccess;
private bool trackCommandLines = true;
private bool minimalRebuildFromTracking;
private bool deleteOutputBeforeExecute;
private string rootSource;
private ITaskItem[] tlogReadFiles;
private ITaskItem[] tlogWriteFiles;
private ITaskItem tlogCommandFile;
private ITaskItem[] sourcesCompiled;
private ITaskItem[] trackedInputFilesToIgnore;
private ITaskItem[] trackedOutputFilesToIgnore;
private ITaskItem[] excludedInputPaths = new TaskItem[0];
private string pathOverride;
private static readonly char[] NewlineArray = Environment.NewLine.ToCharArray();
private static readonly Regex extraNewlineRegex = new Regex("(\\r?\\n)?(\\r?\\n)+");
protected abstract string TrackerIntermediateDirectory { get; }
protected abstract ITaskItem[] TrackedInputFiles { get; }
protected CanonicalTrackedInputFiles SourceDependencies
{
get
{
return sourceDependencies;
}
set
{
sourceDependencies = value;
}
}
protected CanonicalTrackedOutputFiles SourceOutputs
{
get
{
return sourceOutputs;
}
set
{
sourceOutputs = value;
}
}
[Output]
public bool SkippedExecution
{
get
{
return skippedExecution;
}
set
{
skippedExecution = value;
}
}
public string RootSource
{
get
{
return rootSource;
}
set
{
rootSource = value;
}
}
protected virtual bool TrackReplaceFile => false;
protected virtual string[] ReadTLogNames
{
get
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ToolExe);
return new string[4]
{
fileNameWithoutExtension + ".read.*.tlog",
fileNameWithoutExtension + ".*.read.*.tlog",
fileNameWithoutExtension + "-*.read.*.tlog",
GetType().FullName + ".read.*.tlog"
};
}
}
protected virtual string[] WriteTLogNames
{
get
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ToolExe);
return new string[4]
{
fileNameWithoutExtension + ".write.*.tlog",
fileNameWithoutExtension + ".*.write.*.tlog",
fileNameWithoutExtension + "-*.write.*.tlog",
GetType().FullName + ".write.*.tlog"
};
}
}
protected virtual string[] DeleteTLogNames
{
get
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ToolExe);
return new string[4]
{
fileNameWithoutExtension + ".delete.*.tlog",
fileNameWithoutExtension + ".*.delete.*.tlog",
fileNameWithoutExtension + "-*.delete.*.tlog",
GetType().FullName + ".delete.*.tlog"
};
}
}
protected virtual string CommandTLogName
{
get
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ToolExe);
return fileNameWithoutExtension + ".command.1.tlog";
}
}
public ITaskItem[] TLogReadFiles
{
get
{
return tlogReadFiles;
}
set
{
tlogReadFiles = value;
}
}
public ITaskItem[] TLogWriteFiles
{
get
{
return tlogWriteFiles;
}
set
{
tlogWriteFiles = value;
}
}
public ITaskItem[] TLogDeleteFiles { get; set; }
public ITaskItem TLogCommandFile
{
get
{
return tlogCommandFile;
}
set
{
tlogCommandFile = value;
}
}
public bool TrackFileAccess
{
get
{
return trackFileAccess;
}
set
{
trackFileAccess = value;
}
}
public bool TrackCommandLines
{
get
{
return trackCommandLines;
}
set
{
trackCommandLines = value;
}
}
public bool PostBuildTrackingCleanup { get; set; }
public bool EnableExecuteTool { get; set; }
public bool MinimalRebuildFromTracking
{
get
{
return minimalRebuildFromTracking;
}
set
{
minimalRebuildFromTracking = value;
}
}
public virtual bool AttributeFileTracking => false;
[Output]
public ITaskItem[] SourcesCompiled
{
get
{
return sourcesCompiled;
}
set
{
sourcesCompiled = value;
}
}
public ITaskItem[] TrackedOutputFilesToIgnore
{
get
{
return trackedOutputFilesToIgnore;
}
set
{
trackedOutputFilesToIgnore = value;
}
}
public ITaskItem[] TrackedInputFilesToIgnore
{
get
{
return trackedInputFilesToIgnore;
}
set
{
trackedInputFilesToIgnore = value;
}
}
public bool DeleteOutputOnExecute
{
get
{
return deleteOutputBeforeExecute;
}
set
{
deleteOutputBeforeExecute = value;
}
}
public bool DeleteOutputBeforeExecute
{
get
{
return deleteOutputBeforeExecute;
}
set
{
deleteOutputBeforeExecute = value;
}
}
protected virtual bool MaintainCompositeRootingMarkers => false;
protected virtual bool UseMinimalRebuildOptimization => false;
public virtual string SourcesPropertyName => "Sources";
// protected virtual ExecutableType? ToolType => null;
public string ToolArchitecture { get; set; }
public string TrackerFrameworkPath { get; set; }
public string TrackerSdkPath { get; set; }
public ITaskItem[] ExcludedInputPaths
{
get
{
return excludedInputPaths;
}
set
{
List<ITaskItem> list = new List<ITaskItem>(value);
excludedInputPaths = list.ToArray();
}
}
public string PathOverride
{
get
{
return pathOverride;
}
set
{
pathOverride = value;
}
}
protected TrackedVCToolTask(System.Resources.ResourceManager taskResources)
: base(taskResources)
{
PostBuildTrackingCleanup = true;
EnableExecuteTool = true;
}
protected virtual void AssignDefaultTLogPaths()
{
string trackerIntermediateDirectory = TrackerIntermediateDirectory;
if (TLogReadFiles == null)
{
string[] readTLogNames = ReadTLogNames;
TLogReadFiles = new ITaskItem[readTLogNames.Length];
for (int i = 0; i < readTLogNames.Length; i++)
{
TLogReadFiles[i] = new TaskItem(Path.Combine(trackerIntermediateDirectory, readTLogNames[i]));
}
}
if (TLogWriteFiles == null)
{
string[] writeTLogNames = WriteTLogNames;
TLogWriteFiles = new ITaskItem[writeTLogNames.Length];
for (int j = 0; j < writeTLogNames.Length; j++)
{
TLogWriteFiles[j] = new TaskItem(Path.Combine(trackerIntermediateDirectory, writeTLogNames[j]));
}
}
if (TLogDeleteFiles == null)
{
string[] deleteTLogNames = DeleteTLogNames;
TLogDeleteFiles = new ITaskItem[deleteTLogNames.Length];
for (int k = 0; k < deleteTLogNames.Length; k++)
{
TLogDeleteFiles[k] = new TaskItem(Path.Combine(trackerIntermediateDirectory, deleteTLogNames[k]));
}
}
if (TLogCommandFile == null)
{
TLogCommandFile = new TaskItem(Path.Combine(trackerIntermediateDirectory, CommandTLogName));
}
}
protected override bool SkipTaskExecution()
{
return ComputeOutOfDateSources();
}
protected internal virtual bool ComputeOutOfDateSources()
{
if (MinimalRebuildFromTracking || TrackFileAccess)
{
AssignDefaultTLogPaths();
}
if (MinimalRebuildFromTracking && !ForcedRebuildRequired())
{
sourceOutputs = new CanonicalTrackedOutputFiles(this, TLogWriteFiles);
sourceDependencies = new CanonicalTrackedInputFiles(this, TLogReadFiles, TrackedInputFiles, ExcludedInputPaths, sourceOutputs, UseMinimalRebuildOptimization, MaintainCompositeRootingMarkers);
ITaskItem[] sourcesOutOfDateThroughTracking = SourceDependencies.ComputeSourcesNeedingCompilation(searchForSubRootsInCompositeRootingMarkers: false);
List<ITaskItem> sourcesWithChangedCommandLines = GenerateSourcesOutOfDateDueToCommandLine();
SourcesCompiled = MergeOutOfDateSourceLists(sourcesOutOfDateThroughTracking, sourcesWithChangedCommandLines);
if (SourcesCompiled.Length == 0)
{
SkippedExecution = true;
return SkippedExecution;
}
SourcesCompiled = AssignOutOfDateSources(SourcesCompiled);
SourceDependencies.RemoveEntriesForSource(SourcesCompiled);
SourceDependencies.SaveTlog();
if (DeleteOutputOnExecute)
{
DeleteFiles(sourceOutputs.OutputsForSource(SourcesCompiled, searchForSubRootsInCompositeRootingMarkers: false));
}
sourceOutputs.RemoveEntriesForSource(SourcesCompiled);
sourceOutputs.SaveTlog();
}
else
{
SourcesCompiled = TrackedInputFiles;
if (SourcesCompiled == null || SourcesCompiled.Length == 0)
{
SkippedExecution = true;
return SkippedExecution;
}
}
if ((TrackFileAccess || TrackCommandLines) && string.IsNullOrEmpty(RootSource))
{
RootSource = FileTracker.FormatRootingMarker(SourcesCompiled);
}
SkippedExecution = false;
return SkippedExecution;
}
protected virtual ITaskItem[] AssignOutOfDateSources(ITaskItem[] sources)
{
return sources;
}
protected virtual bool ForcedRebuildRequired()
{
string text = null;
try
{
text = TLogCommandFile.GetMetadata("FullPath");
}
catch (Exception ex)
{
if (!(ex is InvalidOperationException) && !(ex is NullReferenceException))
{
throw;
}
base.Log.LogWarningWithCodeFromResources("TrackedVCToolTask.RebuildingDueToInvalidTLog", ex.Message);
return true;
}
if (!File.Exists(text))
{
base.Log.LogMessageFromResources(MessageImportance.Low, "TrackedVCToolTask.RebuildingNoCommandTLog", TLogCommandFile.GetMetadata("FullPath"));
return true;
}
return false;
}
protected virtual List<ITaskItem> GenerateSourcesOutOfDateDueToCommandLine()
{
IDictionary<string, string> dictionary = MapSourcesToCommandLines();
List<ITaskItem> list = new List<ITaskItem>();
if (!TrackCommandLines)
{
return list;
}
if (dictionary.Count == 0)
{
ITaskItem[] trackedInputFiles = TrackedInputFiles;
foreach (ITaskItem item in trackedInputFiles)
{
list.Add(item);
}
}
else if (MaintainCompositeRootingMarkers)
{
string text = ApplyPrecompareCommandFilter(GenerateCommandLine(CommandLineFormat.ForTracking));
string value = null;
if (dictionary.TryGetValue(FileTracker.FormatRootingMarker(TrackedInputFiles), out value))
{
value = ApplyPrecompareCommandFilter(value);
if (value == null || !text.Equals(value, StringComparison.Ordinal))
{
ITaskItem[] trackedInputFiles2 = TrackedInputFiles;
foreach (ITaskItem item2 in trackedInputFiles2)
{
list.Add(item2);
}
}
}
else
{
ITaskItem[] trackedInputFiles3 = TrackedInputFiles;
foreach (ITaskItem item3 in trackedInputFiles3)
{
list.Add(item3);
}
}
}
else
{
string text2 = SourcesPropertyName ?? "Sources";
string text3 = GenerateCommandLineExceptSwitches(new string[1] { text2 }, CommandLineFormat.ForTracking);
ITaskItem[] trackedInputFiles4 = TrackedInputFiles;
foreach (ITaskItem taskItem in trackedInputFiles4)
{
string text4 = ApplyPrecompareCommandFilter(text3 + " " + taskItem.GetMetadata("FullPath")/*.ToUpperInvariant()*/);
string value2 = null;
if (dictionary.TryGetValue(FileTracker.FormatRootingMarker(taskItem), out value2))
{
value2 = ApplyPrecompareCommandFilter(value2);
if (value2 == null || !text4.Equals(value2, StringComparison.Ordinal))
{
list.Add(taskItem);
}
}
else
{
list.Add(taskItem);
}
}
}
return list;
}
protected ITaskItem[] MergeOutOfDateSourceLists(ITaskItem[] sourcesOutOfDateThroughTracking, List<ITaskItem> sourcesWithChangedCommandLines)
{
if (sourcesWithChangedCommandLines.Count == 0)
{
return sourcesOutOfDateThroughTracking;
}
if (sourcesOutOfDateThroughTracking.Length == 0)
{
if (sourcesWithChangedCommandLines.Count == TrackedInputFiles.Length)
{
base.Log.LogMessageFromResources(MessageImportance.Low, "TrackedVCToolTask.RebuildingAllSourcesCommandLineChanged");
}
else
{
foreach (ITaskItem sourcesWithChangedCommandLine in sourcesWithChangedCommandLines)
{
base.Log.LogMessageFromResources(MessageImportance.Low, "TrackedVCToolTask.RebuildingSourceCommandLineChanged", sourcesWithChangedCommandLine.GetMetadata("FullPath"));
}
}
return sourcesWithChangedCommandLines.ToArray();
}
if (sourcesOutOfDateThroughTracking.Length == TrackedInputFiles.Length)
{
return TrackedInputFiles;
}
if (sourcesWithChangedCommandLines.Count == TrackedInputFiles.Length)
{
base.Log.LogMessageFromResources(MessageImportance.Low, "TrackedVCToolTask.RebuildingAllSourcesCommandLineChanged");
return TrackedInputFiles;
}
Dictionary<ITaskItem, bool> dictionary = new Dictionary<ITaskItem, bool>();
foreach (ITaskItem key in sourcesOutOfDateThroughTracking)
{
dictionary[key] = false;
}
foreach (ITaskItem sourcesWithChangedCommandLine2 in sourcesWithChangedCommandLines)
{
if (!dictionary.ContainsKey(sourcesWithChangedCommandLine2))
{
dictionary.Add(sourcesWithChangedCommandLine2, value: true);
}
}
List<ITaskItem> list = new List<ITaskItem>();
ITaskItem[] trackedInputFiles = TrackedInputFiles;
foreach (ITaskItem taskItem in trackedInputFiles)
{
bool value = false;
if (dictionary.TryGetValue(taskItem, out value))
{
list.Add(taskItem);
if (value)
{
base.Log.LogMessageFromResources(MessageImportance.Low, "TrackedVCToolTask.RebuildingSourceCommandLineChanged", taskItem.GetMetadata("FullPath"));
}
}
}
return list.ToArray();
}
protected IDictionary<string, string> MapSourcesToCommandLines()
{
IDictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
string metadata = TLogCommandFile.GetMetadata("FullPath");
if (File.Exists(metadata))
{
using (StreamReader streamReader = File.OpenText(metadata))
{
bool flag = false;
string text = string.Empty;
for (string text2 = streamReader.ReadLine(); text2 != null; text2 = streamReader.ReadLine())
{
if (text2.Length == 0)
{
flag = true;
break;
}
if (text2[0] == '^')
{
if (text2.Length == 1)
{
flag = true;
break;
}
text = text2.Substring(1);
}
else
{
string value = null;
if (!dictionary.TryGetValue(text, out value))
{
dictionary[text] = text2;
}
else
{
IDictionary<string, string> dictionary2 = dictionary;
string key = text;
dictionary2[key] = dictionary2[key] + "\r\n" + text2;
}
}
}
if (flag)
{
base.Log.LogWarningWithCodeFromResources("TrackedVCToolTask.RebuildingDueToInvalidTLogContents", metadata);
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
return dictionary;
}
}
return dictionary;
}
protected void WriteSourcesToCommandLinesTable(IDictionary<string, string> sourcesToCommandLines)
{
string metadata = TLogCommandFile.GetMetadata("FullPath");
Directory.CreateDirectory(Path.GetDirectoryName(metadata));
using StreamWriter streamWriter = new StreamWriter(metadata, append: false, Encoding.Unicode);
foreach (KeyValuePair<string, string> sourcesToCommandLine in sourcesToCommandLines)
{
streamWriter.WriteLine("^" + sourcesToCommandLine.Key);
streamWriter.WriteLine(ApplyPrecompareCommandFilter(sourcesToCommandLine.Value));
}
}
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
int num = 0;
if (EnableExecuteTool)
{
try
{
num = TrackerExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
finally
{
PrintMessage(ParseLine(null), base.StandardOutputImportanceToUse);
if (PostBuildTrackingCleanup)
{
num = PostExecuteTool(num);
}
}
}
return num;
}
protected virtual int PostExecuteTool(int exitCode)
{
if (MinimalRebuildFromTracking || TrackFileAccess)
{
SourceOutputs = new CanonicalTrackedOutputFiles(TLogWriteFiles);
SourceDependencies = new CanonicalTrackedInputFiles(TLogReadFiles, TrackedInputFiles, ExcludedInputPaths, SourceOutputs, useMinimalRebuildOptimization: false, MaintainCompositeRootingMarkers);
string[] array = null;
IDictionary<string, string> dictionary = MapSourcesToCommandLines();
if (exitCode != 0)
{
SourceOutputs.RemoveEntriesForSource(SourcesCompiled);
SourceOutputs.SaveTlog();
SourceDependencies.RemoveEntriesForSource(SourcesCompiled);
SourceDependencies.SaveTlog();
if (TrackCommandLines)
{
if (MaintainCompositeRootingMarkers)
{
dictionary.Remove(RootSource);
}
else
{
ITaskItem[] array2 = SourcesCompiled;
foreach (ITaskItem source in array2)
{
dictionary.Remove(FileTracker.FormatRootingMarker(source));
}
}
WriteSourcesToCommandLinesTable(dictionary);
}
}
else
{
AddTaskSpecificOutputs(SourcesCompiled, SourceOutputs);
RemoveTaskSpecificOutputs(SourceOutputs);
SourceOutputs.RemoveDependenciesFromEntryIfMissing(SourcesCompiled);
if (MaintainCompositeRootingMarkers)
{
array = SourceOutputs.RemoveRootsWithSharedOutputs(SourcesCompiled);
string[] array3 = array;
foreach (string rootingMarker in array3)
{
SourceDependencies.RemoveEntryForSourceRoot(rootingMarker);
}
}
if (TrackedOutputFilesToIgnore != null && TrackedOutputFilesToIgnore.Length != 0)
{
Dictionary<string, ITaskItem> trackedOutputFilesToRemove = new Dictionary<string, ITaskItem>(StringComparer.OrdinalIgnoreCase);
ITaskItem[] array4 = TrackedOutputFilesToIgnore;
foreach (ITaskItem taskItem in array4)
{
string key = taskItem.GetMetadata("FullPath")/*.ToUpperInvariant()*/;
if (!trackedOutputFilesToRemove.ContainsKey(key))
{
trackedOutputFilesToRemove.Add(key, taskItem);
}
}
SourceOutputs.SaveTlog((string fullTrackedPath) => (!trackedOutputFilesToRemove.ContainsKey(fullTrackedPath/*.ToUpperInvariant()*/)) ? true : false);
}
else
{
SourceOutputs.SaveTlog();
}
DeleteEmptyFile(TLogWriteFiles);
RemoveTaskSpecificInputs(SourceDependencies);
SourceDependencies.RemoveDependenciesFromEntryIfMissing(SourcesCompiled);
if (TrackedInputFilesToIgnore != null && TrackedInputFilesToIgnore.Length != 0)
{
Dictionary<string, ITaskItem> trackedInputFilesToRemove = new Dictionary<string, ITaskItem>(StringComparer.OrdinalIgnoreCase);
ITaskItem[] array5 = TrackedInputFilesToIgnore;
foreach (ITaskItem taskItem2 in array5)
{
string key2 = taskItem2.GetMetadata("FullPath")/*.ToUpperInvariant()*/;
if (!trackedInputFilesToRemove.ContainsKey(key2))
{
trackedInputFilesToRemove.Add(key2, taskItem2);
}
}
SourceDependencies.SaveTlog((string fullTrackedPath) => (!trackedInputFilesToRemove.ContainsKey(fullTrackedPath)) ? true : false);
}
else
{
SourceDependencies.SaveTlog();
}
DeleteEmptyFile(TLogReadFiles);
DeleteFiles(TLogDeleteFiles);
if (TrackCommandLines)
{
if (MaintainCompositeRootingMarkers)
{
string value = GenerateCommandLine(CommandLineFormat.ForTracking);
dictionary[RootSource] = value;
if (array != null)
{
string[] array6 = array;
foreach (string key3 in array6)
{
dictionary.Remove(key3);
}
}
}
else
{
string text = SourcesPropertyName ?? "Sources";
string text2 = GenerateCommandLineExceptSwitches(new string[1] { text }, CommandLineFormat.ForTracking);
ITaskItem[] array7 = SourcesCompiled;
foreach (ITaskItem taskItem3 in array7)
{
dictionary[FileTracker.FormatRootingMarker(taskItem3)] = text2 + " " + taskItem3.GetMetadata("FullPath")/*.ToUpperInvariant()*/;
}
}
WriteSourcesToCommandLinesTable(dictionary);
}
}
}
return exitCode;
}
protected virtual void RemoveTaskSpecificOutputs(CanonicalTrackedOutputFiles compactOutputs)
{
}
protected virtual void RemoveTaskSpecificInputs(CanonicalTrackedInputFiles compactInputs)
{
}
protected virtual void AddTaskSpecificOutputs(ITaskItem[] sources, CanonicalTrackedOutputFiles compactOutputs)
{
}
protected override void LogPathToTool(string toolName, string pathToTool)
{
base.LogPathToTool(toolName, base.ResolvedPathToTool);
}
protected virtual void SaveTracking()
{
// 微软没有此函数,自己重写的版本,保存跟踪文件,增量编译使用。
}
protected int TrackerExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
string dllName = null;
string text = null;
bool flag = TrackFileAccess;
string text2 = Environment.ExpandEnvironmentVariables(pathToTool);
string text3 = Environment.ExpandEnvironmentVariables(commandLineCommands);
// 微软的方案严重不适合Linux,因为tracker什么的再Linux等非Windows 平台都是没有的。
// 因此这方面重写。
var ErrorCode = base.ExecuteTool(text2, responseFileCommands, text3);
if(ErrorCode == 0 && (MinimalRebuildFromTracking || TrackFileAccess))
{
// 将数据生成数据会回写到Write文件。
SaveTracking();
}
return ErrorCode;
#if __
try
{
string text4;
if (flag)
{
ExecutableType result = ExecutableType.SameAsCurrentProcess;
if (!string.IsNullOrEmpty(ToolArchitecture))
{
if (!Enum.TryParse<ExecutableType>(ToolArchitecture, out result))
{
base.Log.LogErrorWithCodeFromResources("General.InvalidValue", "ToolArchitecture", GetType().Name);
return -1;
}
}
else if (ToolType.HasValue)
{
result = ToolType.Value;
}
if ((result == ExecutableType.Native32Bit || result == ExecutableType.Native64Bit) && Microsoft.Build.Shared.NativeMethodsShared.Is64bitApplication(text2, out var is64bit))
{
result = (is64bit ? ExecutableType.Native64Bit : ExecutableType.Native32Bit);
}
try
{
text4 = FileTracker.GetTrackerPath(result, TrackerSdkPath);
if (text4 == null)
{
base.Log.LogErrorFromResources("Error.MissingFile", "tracker.exe");
}
}
catch (Exception e)
{
if (Microsoft.Build.Shared.ExceptionHandling.NotExpectedException(e))
{
throw;
}
base.Log.LogErrorWithCodeFromResources("General.InvalidValue", "TrackerSdkPath", GetType().Name);
return -1;
}
try
{
dllName = FileTracker.GetFileTrackerPath(result, TrackerFrameworkPath);
}
catch (Exception e2)
{
if (Microsoft.Build.Shared.ExceptionHandling.NotExpectedException(e2))
{
throw;
}
base.Log.LogErrorWithCodeFromResources("General.InvalidValue", "TrackerFrameworkPath", GetType().Name);
return -1;
}
}
else
{
text4 = text2;
}
if (!string.IsNullOrEmpty(text4))
{
Microsoft.Build.Shared.ErrorUtilities.VerifyThrowInternalRooted(text4);
string commandLineCommands2;
if (flag)
{
string text5 = FileTracker.TrackerArguments(text2, text3, dllName, TrackerIntermediateDirectory, RootSource, base.CancelEventName);
base.Log.LogMessageFromResources(MessageImportance.Low, "Native_TrackingCommandMessage");
string message = text4 + (AttributeFileTracking ? " /a " : " ") + (TrackReplaceFile ? "/f " : "") + text5 + " " + responseFileCommands;
base.Log.LogMessage(MessageImportance.Low, message);
text = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
using (StreamWriter streamWriter = new StreamWriter(text, append: false, Encoding.Unicode))
{
streamWriter.Write(FileTracker.TrackerResponseFileArguments(dllName, TrackerIntermediateDirectory, RootSource, base.CancelEventName));
}
commandLineCommands2 = (AttributeFileTracking ? "/a @\"" : "@\"") + text + "\"" + (TrackReplaceFile ? " /f " : "") + FileTracker.TrackerCommandArguments(text2, text3);
}
else
{
commandLineCommands2 = text3;
}
return base.ExecuteTool(text4, responseFileCommands, commandLineCommands2);
}
return -1;
}
finally
{
if (text != null)
{
DeleteTempFile(text);
}
}
#endif
}
protected override void ProcessStarted()
{
}
public virtual string ApplyPrecompareCommandFilter(string value)
{
return extraNewlineRegex.Replace(value, "$2");
}
public static string RemoveSwitchFromCommandLine(string removalWord, string cmdString, bool removeMultiple = false)
{
int num = 0;
while ((num = cmdString.IndexOf(removalWord, num, StringComparison.Ordinal)) >= 0)
{
if (num == 0 || cmdString[num - 1] == ' ')
{
int num2 = cmdString.IndexOf(' ', num);
if (num2 >= 0)
{
num2++;
}
else
{
num2 = cmdString.Length;
num--;
}
cmdString = cmdString.Remove(num, num2 - num);
if (!removeMultiple)
{
break;
}
}
num++;
if (num >= cmdString.Length)
{
break;
}
}
return cmdString;
}
protected static int DeleteFiles(ITaskItem[] filesToDelete)
{
if (filesToDelete == null)
{
return 0;
}
ITaskItem[] array = TrackedDependencies.ExpandWildcards(filesToDelete);
if (array.Length == 0)
{
return 0;
}
int num = 0;
ITaskItem[] array2 = array;
foreach (ITaskItem taskItem in array2)
{
try
{
FileInfo fileInfo = new FileInfo(taskItem.ItemSpec);
if (fileInfo.Exists)
{
fileInfo.Delete();
num++;
}
}
catch (Exception ex)
{
if (ex is SecurityException || ex is ArgumentException || ex is UnauthorizedAccessException || ex is PathTooLongException || ex is NotSupportedException)
{
continue;
}
throw;
}
}
return num;
}
protected static int DeleteEmptyFile(ITaskItem[] filesToDelete)
{
if (filesToDelete == null)
{
return 0;
}
ITaskItem[] array = TrackedDependencies.ExpandWildcards(filesToDelete);
if (array.Length == 0)
{
return 0;
}
int num = 0;
ITaskItem[] array2 = array;
foreach (ITaskItem taskItem in array2)
{
bool flag = false;
try
{
FileInfo fileInfo = new FileInfo(taskItem.ItemSpec);
if (fileInfo.Exists)
{
if (fileInfo.Length <= 4)
{
flag = true;
}
if (flag)
{
fileInfo.Delete();
num++;
}
}
}
catch (Exception ex)
{
if (ex is SecurityException || ex is ArgumentException || ex is UnauthorizedAccessException || ex is PathTooLongException || ex is NotSupportedException)
{
continue;
}
throw;
}
}
return num;
}
}
}
| Microsoft.Build.CPPTasks/TrackedVCToolTask.cs | Chuyu-Team-MSBuildCppCrossToolset-6c84a69 | [
{
"filename": "Microsoft.Build.CPPTasks/VCToolTask.cs",
"retrieved_chunk": "using Microsoft.Build.Shared;\nusing Microsoft.Build.Utilities;\nnamespace Microsoft.Build.CPPTasks\n{\n public abstract class VCToolTask : ToolTask\n {\n public enum CommandLineFormat\n {\n ForBuildLog,\n ForTracking",
"score": 0.8948262333869934
},
{
"filename": "YY.Build.Cross.Tasks/Cross/Compile.cs",
"retrieved_chunk": "using System.Text;\nusing System;\nnamespace YY.Build.Cross.Tasks.Cross\n{\n public class Compile : TrackedVCToolTask\n {\n public Compile()\n : base(Microsoft.Build.CppTasks.Common.Properties.Microsoft_Build_CPPTasks_Strings.ResourceManager)\n {\n UseCommandProcessor = false;",
"score": 0.8588788509368896
},
{
"filename": "YY.Build.Cross.Tasks/Cross/Ld.cs",
"retrieved_chunk": "// using Microsoft.Build.Linux.Tasks;\nusing Microsoft.Build.Utilities;\nusing System.Text.RegularExpressions;\nusing Microsoft.Build.Shared;\nusing System.IO;\nnamespace YY.Build.Cross.Tasks.Cross\n{\n public class Ld : TrackedVCToolTask\n {\n public Ld()",
"score": 0.8500124216079712
},
{
"filename": "YY.Build.Cross.Tasks/Cross/Ar.cs",
"retrieved_chunk": "{\n public class Ar : TrackedVCToolTask\n {\n private ArrayList switchOrderList;\n protected override ArrayList SwitchOrderList => switchOrderList;\n protected override string ToolName => \"ar\";\n public Ar()\n : base(Microsoft.Build.CppTasks.Common.Properties.Microsoft_Build_CPPTasks_Strings.ResourceManager)\n {\n switchOrderList = new ArrayList();",
"score": 0.8491893410682678
},
{
"filename": "Microsoft.Build.CPPTasks/Helpers.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace Microsoft.Build.CPPTasks\n{\n public sealed class Helpers\n {\n private Helpers()\n {\n }",
"score": 0.8447558283805847
}
] | csharp | CanonicalTrackedOutputFiles sourceOutputs; |
#nullable enable
using System;
using System.Collections.Generic;
namespace Mochineko.RelentStateMachine
{
public sealed class TransitionMapBuilder<TEvent, TContext>
: ITransitionMapBuilder<TEvent, TContext>
{
private readonly IState<TEvent, TContext> initialState;
private readonly List<IState<TEvent, TContext>> states = new();
private readonly Dictionary<IState<TEvent, TContext>, Dictionary<TEvent, IState<TEvent, TContext>>>
transitionMap = new();
private readonly Dictionary<TEvent, IState<TEvent, TContext>>
anyTransitionMap = new();
private bool disposed = false;
public static TransitionMapBuilder<TEvent, TContext> Create<TInitialState>()
where TInitialState : IState<TEvent, TContext>, new()
{
var initialState = new TInitialState();
return new TransitionMapBuilder<TEvent, TContext>(initialState);
}
private TransitionMapBuilder(IState<TEvent, TContext> initialState)
{
this.initialState = initialState;
states.Add(this.initialState);
}
public void Dispose()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));
}
disposed = true;
}
public void RegisterTransition<TFromState, TToState>(TEvent @event)
where TFromState : IState<TEvent, TContext>, new()
where TToState : IState<TEvent, TContext>, new()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));
}
var fromState = GetOrCreateState<TFromState>();
var toState = GetOrCreateState<TToState>();
if (transitionMap.TryGetValue(fromState, out var transitions))
{
if (transitions.TryGetValue(@event, out var nextState))
{
throw new InvalidOperationException(
$"Already exists transition from {fromState.GetType()} to {nextState.GetType()} with event {@event}.");
}
else
{
transitions.Add(@event, toState);
}
}
else
{
var newTransitions = new Dictionary<TEvent, IState<TEvent, TContext>>();
newTransitions.Add(@event, toState);
transitionMap.Add(fromState, newTransitions);
}
}
public void RegisterAnyTransition<TToState>(TEvent @event)
where TToState : IState<TEvent, TContext>, new()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));
}
var toState = GetOrCreateState<TToState>();
if (anyTransitionMap.TryGetValue(@event, out var nextState))
{
throw new InvalidOperationException(
$"Already exists transition from any state to {nextState.GetType()} with event {@event}.");
}
else
{
anyTransitionMap.Add(@event, toState);
}
}
public | ITransitionMap<TEvent, TContext> Build()
{ |
if (disposed)
{
throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));
}
var result = new TransitionMap<TEvent, TContext>(
initialState,
states,
BuildReadonlyTransitionMap(),
anyTransitionMap);
// Cannot reuse builder after build.
this.Dispose();
return result;
}
private IReadOnlyDictionary<
IState<TEvent, TContext>,
IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>
BuildReadonlyTransitionMap()
{
var result = new Dictionary<
IState<TEvent, TContext>,
IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>();
foreach (var (key, value) in transitionMap)
{
result.Add(key, value);
}
return result;
}
private TState GetOrCreateState<TState>()
where TState : IState<TEvent, TContext>, new()
{
foreach (var state in states)
{
if (state is TState target)
{
return target;
}
}
var newState = new TState();
states.Add(newState);
return newState;
}
}
} | Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs | mochi-neko-RelentStateMachine-64762eb | [
{
"filename": "Assets/Mochineko/RelentStateMachine/StateStoreBuilder.cs",
"retrieved_chunk": " {\n throw new InvalidOperationException($\"Already registered state: {typeof(TState)}\");\n }\n }\n states.Add(new TState());\n }\n public IStateStore<TContext> Build()\n {\n if (disposed)\n {",
"score": 0.8666771650314331
},
{
"filename": "Assets/Mochineko/RelentStateMachine/FiniteStateMachine.cs",
"retrieved_chunk": " return instance;;\n default:\n throw new ArgumentOutOfRangeException(nameof(enterResult));\n }\n }\n private FiniteStateMachine(\n ITransitionMap<TEvent, TContext> transitionMap,\n TContext context,\n TimeSpan? semaphoreTimeout = null)\n {",
"score": 0.8354730606079102
},
{
"filename": "Assets/Mochineko/RelentStateMachine/StateStoreBuilder.cs",
"retrieved_chunk": " public void Register<TState>()\n where TState : IStackState<TContext>, new()\n {\n if (disposed)\n {\n throw new ObjectDisposedException(nameof(StateStoreBuilder<TContext>));\n }\n foreach (var state in states)\n {\n if (state is TState)",
"score": 0.8297911882400513
},
{
"filename": "Assets/Mochineko/RelentStateMachine/FiniteStateMachine.cs",
"retrieved_chunk": " catch (OperationCanceledException exception)\n {\n return StateResults.Fail<TEvent>(\n $\"Cancelled to transit state because of {exception}.\");\n }\n finally\n {\n semaphore.Release();\n }\n }",
"score": 0.8284960389137268
},
{
"filename": "Assets/Mochineko/RelentStateMachine.Tests/ContinuousStateMachineTest.cs",
"retrieved_chunk": " internal sealed class ContinuousStateMachineTest\n {\n [Test]\n [RequiresPlayMode(false)]\n public async Task StateMachineShouldTransitByEvent()\n {\n // NOTE: Initial state is specified at constructor.\n var transitionMapBuilder = TransitionMapBuilder<MockContinueEvent, MockContinueContext>\n .Create<Phase1State>();\n // NOTE: Register sequential transitions to builder.",
"score": 0.8223510980606079
}
] | csharp | ITransitionMap<TEvent, TContext> Build()
{ |
using JdeJabali.JXLDataTableExtractor.Configuration;
using JdeJabali.JXLDataTableExtractor.DataExtraction;
using JdeJabali.JXLDataTableExtractor.Exceptions;
using JdeJabali.JXLDataTableExtractor.JXLExtractedData;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace JdeJabali.JXLDataTableExtractor
{
public class DataTableExtractor :
IDataTableExtractorConfiguration,
IDataTableExtractorWorkbookConfiguration,
IDataTableExtractorSearchConfiguration,
IDataTableExtractorWorksheetConfiguration
{
private bool _readAllWorksheets;
private int _searchLimitRow;
private int _searchLimitColumn;
private readonly List<string> _workbooks = new List<string>();
private readonly List<int> _worksheetIndexes = new List<int>();
private readonly List<string> _worksheets = new List<string>();
private readonly List<HeaderToSearch> _headersToSearch = new List<HeaderToSearch>();
private HeaderToSearch _headerToSearch;
private DataReader _reader;
private DataTableExtractor()
{
}
public static IDataTableExtractorConfiguration Configure()
{
return new DataTableExtractor();
}
public IDataTableExtractorWorkbookConfiguration Workbook(string workbook)
{
if (string.IsNullOrEmpty(workbook))
{
throw new ArgumentException($"{nameof(workbook)} cannot be null or empty.");
}
// You can't add more than one workbook anyway, so there is no need to check for duplicates.
// This would imply that there is a configuration for each workbook.
_workbooks.Add(workbook);
return this;
}
public IDataTableExtractorWorkbookConfiguration Workbooks(string[] workbooks)
{
if (workbooks is null)
{
throw new ArgumentNullException($"{nameof(workbooks)} cannot be null.");
}
foreach (string workbook in workbooks)
{
if (_workbooks.Contains(workbook))
{
throw new DuplicateWorkbookException("Cannot search for more than one workbook with the same name: " +
$@"""{workbook}"".");
}
_workbooks.Add(workbook);
}
return this;
}
public IDataTableExtractorSearchConfiguration SearchLimits(int searchLimitRow, int searchLimitColumn)
{
_searchLimitRow = searchLimitRow;
_searchLimitColumn = searchLimitColumn;
return this;
}
public IDataTableExtractorSearchConfiguration Worksheet(int worksheetIndex)
{
if (worksheetIndex < 0)
{
throw new ArgumentException($"{nameof(worksheetIndex)} cannot be less than zero.");
}
if (_worksheetIndexes.Contains(worksheetIndex))
{
throw new ArgumentException("Cannot search for more than one worksheet with the same name: " +
$@"""{worksheetIndex}"".");
}
_worksheetIndexes.Add(worksheetIndex);
return this;
}
public IDataTableExtractorSearchConfiguration Worksheets(int[] worksheetIndexes)
{
if (worksheetIndexes is null)
{
throw new ArgumentException($"{nameof(worksheetIndexes)} cannot be null or empty.");
}
_worksheetIndexes.AddRange(worksheetIndexes);
return this;
}
public IDataTableExtractorSearchConfiguration Worksheet(string worksheet)
{
if (string.IsNullOrEmpty(worksheet))
{
throw new ArgumentException($"{nameof(worksheet)} cannot be null or empty.");
}
if (_worksheets.Contains(worksheet))
{
throw new ArgumentException("Cannot search for more than one worksheet with the same name: " +
$@"""{worksheet}"".");
}
_worksheets.Add(worksheet);
return this;
}
public IDataTableExtractorSearchConfiguration Worksheets(string[] worksheets)
{
if (worksheets is null)
{
throw new ArgumentException($"{nameof(worksheets)} cannot be null or empty.");
}
_worksheets.AddRange(worksheets);
return this;
}
public | IDataTableExtractorWorksheetConfiguration ReadOnlyTheIndicatedSheets()
{ |
_readAllWorksheets = false;
if (_worksheetIndexes.Count == 0 && _worksheets.Count == 0)
{
throw new InvalidOperationException("No worksheets selected.");
}
return this;
}
public IDataTableExtractorWorksheetConfiguration ReadAllWorksheets()
{
_readAllWorksheets = true;
return this;
}
IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.ColumnHeader(string columnHeader)
{
if (string.IsNullOrEmpty(columnHeader))
{
throw new ArgumentException($"{nameof(columnHeader)} cannot be null or empty.");
}
if (_headersToSearch.FirstOrDefault(h => h.ColumnHeaderName == columnHeader) != null)
{
throw new DuplicateColumnException("Cannot search for more than one column header with the same name: " +
$@"""{columnHeader}"".");
}
_headerToSearch = new HeaderToSearch()
{
ColumnHeaderName = columnHeader,
};
_headersToSearch.Add(_headerToSearch);
return this;
}
IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.ColumnIndex(int columnIndex)
{
if (columnIndex < 0)
{
throw new ArgumentException($"{nameof(columnIndex)} cannot be less than zero.");
}
if (_headersToSearch.FirstOrDefault(h => h.ColumnIndex == columnIndex) != null)
{
throw new DuplicateColumnException("Cannot search for more than one column with the same index: " +
$@"""{columnIndex}"".");
}
_headerToSearch = new HeaderToSearch()
{
ColumnIndex = columnIndex,
};
_headersToSearch.Add(_headerToSearch);
return this;
}
IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.CustomColumnHeaderMatch(Func<string, bool> conditional)
{
if (conditional is null)
{
throw new ArgumentNullException("Conditional cannot be null.");
}
_headerToSearch = new HeaderToSearch()
{
ConditionalToReadColumnHeader = conditional,
};
_headersToSearch.Add(_headerToSearch);
return this;
}
IDataTableExtractorWorksheetConfiguration IDataTableExtractorColumnConfiguration.ConditionToExtractRow(Func<string, bool> conditional)
{
if (conditional is null)
{
throw new ArgumentNullException("Conditional cannot be null.");
}
if (_headerToSearch is null)
{
throw new InvalidOperationException(nameof(_headerToSearch));
}
_headerToSearch.ConditionalToReadRow = conditional;
return this;
}
public List<JXLWorkbookData> GetWorkbooksData()
{
_reader = new DataReader()
{
Workbooks = _workbooks,
SearchLimitRow = _searchLimitRow,
SearchLimitColumn = _searchLimitColumn,
WorksheetIndexes = _worksheetIndexes,
Worksheets = _worksheets,
ReadAllWorksheets = _readAllWorksheets,
HeadersToSearch = _headersToSearch,
};
return _reader.GetWorkbooksData();
}
public List<JXLExtractedRow> GetExtractedRows()
{
_reader = new DataReader()
{
Workbooks = _workbooks,
SearchLimitRow = _searchLimitRow,
SearchLimitColumn = _searchLimitColumn,
WorksheetIndexes = _worksheetIndexes,
Worksheets = _worksheets,
ReadAllWorksheets = _readAllWorksheets,
HeadersToSearch = _headersToSearch,
};
return _reader.GetJXLExtractedRows();
}
public DataTable GetDataTable()
{
_reader = new DataReader()
{
Workbooks = _workbooks,
SearchLimitRow = _searchLimitRow,
SearchLimitColumn = _searchLimitColumn,
WorksheetIndexes = _worksheetIndexes,
Worksheets = _worksheets,
ReadAllWorksheets = _readAllWorksheets,
HeadersToSearch = _headersToSearch,
};
return _reader.GetDataTable();
}
}
} | JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs | JdeJabali-JXLDataTableExtractor-90a12f4 | [
{
"filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs",
"retrieved_chunk": " GetHeadersCoordinates(sheet);\n if (!AreHeadersInTheSameRow())\n {\n throw new InvalidOperationException(\n $\"The headers to look for found in {worksheetData.WorksheetName} do not match in the same row. Cannot continue.\");\n }\n worksheetData = GetWorksheetData(sheet);\n return worksheetData;\n }\n private JXLWorksheetData GetWorksheetData(ExcelWorksheet sheet)",
"score": 0.8196077346801758
},
{
"filename": "JdeJabali.JXLDataTableExtractor/Configuration/IDataTableExtractorSearchConfiguration.cs",
"retrieved_chunk": " /// <exception cref=\"ArgumentException\"/>\n IDataTableExtractorSearchConfiguration Worksheets(string[] worksheets);\n /// <summary>\n /// Read all the worksheets in the workbook(s) specified.\n /// </summary>\n /// <returns></returns>\n IDataTableExtractorWorksheetConfiguration ReadAllWorksheets();\n IDataTableExtractorWorksheetConfiguration ReadOnlyTheIndicatedSheets();\n }\n}",
"score": 0.8077088594436646
},
{
"filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReaderHelpers.cs",
"retrieved_chunk": " throw new IndexOutOfRangeException($@\"Worksheet index not found: \"\"{index}\"\" in \"\"{workbook}\"\".\");\n }\n return worksheet;\n }\n public static ExcelWorksheet GetWorksheetByName(string worksheetName, string workbook, ExcelPackage excel)\n {\n ExcelWorksheet worksheet = excel.Workbook.Worksheets\n .AsEnumerable()\n .FirstOrDefault(ws => ws.Name == worksheetName);\n if (worksheet is null)",
"score": 0.805482029914856
},
{
"filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReaderHelpers.cs",
"retrieved_chunk": " bufferSize: 4096,\n useAsync: false);\n }\n public static ExcelWorksheet GetWorksheetByIndex(int index, string workbook, ExcelPackage excel)\n {\n ExcelWorksheet worksheet = excel.Workbook.Worksheets\n .AsEnumerable()\n .FirstOrDefault(ws => ws.Index == index);\n if (worksheet is null)\n {",
"score": 0.8052128553390503
},
{
"filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs",
"retrieved_chunk": " }\n }\n return worksheetsData;\n }\n private JXLWorksheetData ExtractRows(ExcelWorksheet sheet)\n {\n JXLWorksheetData worksheetData = new JXLWorksheetData()\n {\n WorksheetName = sheet.Name\n };",
"score": 0.8039933443069458
}
] | csharp | IDataTableExtractorWorksheetConfiguration ReadOnlyTheIndicatedSheets()
{ |
using System;
using Sandland.SceneTool.Editor.Common.Data;
using Sandland.SceneTool.Editor.Common.Utils;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.UIElements;
namespace Sandland.SceneTool.Editor.Views
{
internal class SceneItemView : VisualElement, IDisposable
{
public const float FixedHeight = 100;
private readonly Image _iconImage;
private readonly FavoritesButton _favoritesButton;
private readonly Label _button;
private readonly Label _typeLabel;
private readonly VisualElement _textWrapper;
private readonly Clickable _clickManipulator;
private | AssetFileInfo _sceneInfo; |
public SceneItemView()
{
var visualTree = AssetDatabaseUtils.FindAndLoadVisualTreeAsset("SceneItemView");
visualTree.CloneTree(this);
_iconImage = this.Q<Image>("scene-icon");
_button = this.Q<Label>("scene-button");
_favoritesButton = this.Q<FavoritesButton>("favorites-button");
_typeLabel = this.Q<Label>("scene-type-label");
_textWrapper = this.Q<VisualElement>("scene-text-wrapper");
_clickManipulator = new Clickable(OnOpenSceneButtonClicked);
_textWrapper.AddManipulator(_clickManipulator);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
_iconImage.AddManipulator(new Clickable(OnIconClick));
}
private void OnIconClick()
{
Selection.activeObject = AssetDatabase.LoadAssetAtPath<SceneAsset>(_sceneInfo.Path);
}
public void Init(SceneInfo info)
{
_sceneInfo = info;
_button.text = _sceneInfo.Name;
_favoritesButton.Init(_sceneInfo);
_typeLabel.text = info.ImportType.ToDescription();
// TODO: Support dynamic themes
_iconImage.image = Icons.GetSceneIcon(true);
ResetInlineStyles();
}
private void ResetInlineStyles()
{
// ListView sets inline attributes that we want to control from UCSS
style.height = StyleKeyword.Null;
style.flexGrow = StyleKeyword.Null;
style.flexShrink = StyleKeyword.Null;
style.marginBottom = StyleKeyword.Null;
style.marginTop = StyleKeyword.Null;
style.paddingBottom = StyleKeyword.Null;
}
private void OnOpenSceneButtonClicked()
{
EditorSceneManager.OpenScene(_sceneInfo.Path);
}
private void OnDetachFromPanel(DetachFromPanelEvent evt)
{
Dispose();
}
public void Dispose()
{
UnregisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
}
}
} | Assets/SceneTools/Editor/Views/SceneSelectorWindow/SceneListItem/SceneItemView.cs | migus88-Sandland.SceneTools-64e9f8c | [
{
"filename": "Assets/SceneTools/Editor/Views/SceneToolsSetupWindow/Handlers/SceneClassGenerationUiHandler.cs",
"retrieved_chunk": " private const string ScriptDefine = \"SANDLAND_SCENE_CLASS_GEN\";\n private const string AddressablesSupportDefine = \"SANDLAND_ADDRESSABLES\";\n private readonly Toggle _mainToggle;\n private readonly Toggle _autogenerateOnChangeToggle;\n private readonly Toggle _addressableScenesSupportToggle;\n private readonly VisualElement _section;\n private readonly TextField _locationText;\n private readonly TextField _namespaceText;\n private readonly TextField _classNameText;\n private readonly Button _locationButton;",
"score": 0.8781447410583496
},
{
"filename": "Assets/SceneTools/Editor/Views/SceneSelectorWindow/FavoritesButton/FavoritesButton.cs",
"retrieved_chunk": " private const string FavoriteClassName = \"favorite\";\n public bool IsFavorite { get; private set; }\n //private Image _starImage;\n private AssetFileInfo _fileInfo;\n public FavoritesButton()\n {\n this.AddManipulator(new Clickable(OnClick));\n }\n public void Init(AssetFileInfo info)\n {",
"score": 0.830058217048645
},
{
"filename": "Assets/SceneTools/Editor/Views/Base/SceneToolsWindowBase.cs",
"retrieved_chunk": " public abstract float MinWidth { get; }\n public abstract float MinHeight { get; }\n public abstract string WindowName { get; }\n public abstract string VisualTreeName { get; }\n public abstract string StyleSheetName { get; }\n private StyleSheet _theme;\n protected void InitWindow(Texture2D overrideIcon = null)\n {\n minSize = new Vector2(MinWidth, MinHeight);\n // TODO: support dynamic theme",
"score": 0.8232138156890869
},
{
"filename": "Assets/SceneTools/Editor/Views/SceneToolsSetupWindow/SceneToolsSetupWindow.cs",
"retrieved_chunk": " internal class SceneToolsSetupWindow : SceneToolsWindowBase\n {\n private const string WindowMenuItem = MenuItems.Tools.Root + \"Setup Scene Tools\";\n public override float MinWidth => 600;\n public override float MinHeight => 600;\n public override string WindowName => \"Scene Tools Setup\";\n public override string VisualTreeName => nameof(SceneToolsSetupWindow);\n public override string StyleSheetName => nameof(SceneToolsSetupWindow);\n private readonly List<ISceneToolsSetupUiHandler> _uiHandlers = new();\n private Button _saveAllButton;",
"score": 0.8202799558639526
},
{
"filename": "Assets/SceneTools/Editor/Views/SceneSelectorWindow/SceneSelectorWindow.cs",
"retrieved_chunk": " internal class SceneSelectorWindow : SceneToolsWindowBase\n {\n private const string WindowNameInternal = \"Scene Selector\";\n private const string KeyboardShortcut = \" %g\";\n private const string WindowMenuItem = MenuItems.Tools.Root + WindowNameInternal + KeyboardShortcut;\n public override float MinWidth => 460;\n public override float MinHeight => 600;\n public override string WindowName => WindowNameInternal;\n public override string VisualTreeName => nameof(SceneSelectorWindow);\n public override string StyleSheetName => nameof(SceneSelectorWindow);",
"score": 0.799849808216095
}
] | csharp | AssetFileInfo _sceneInfo; |
namespace Client.ClientBase
{
public static class ModuleManager
{
public static List< | Module> modules = new List<Module>(); |
public static void AddModule(Module module)
{
modules.Add(module);
}
public static void RemoveModule(Module module)
{
modules.Remove(module);
}
public static void Init()
{
Console.WriteLine("Initializing modules...");
AddModule(new Modules.AimAssist());
AddModule(new Modules.Aura());
AddModule(new Modules.ArrayList());
Console.WriteLine("Modules initialized.");
}
public static Module GetModule(string name)
{
foreach (Module module in modules)
{
if (module.name == name)
{
return module;
}
}
return null;
}
public static List<Module> GetModules()
{
return modules;
}
public static List<Module> GetModulesInCategory(string category)
{
List<Module> modulesInCategory = new List<Module>();
foreach (Module module in modules)
{
if (module.category == category)
{
modulesInCategory.Add(module);
}
}
return modulesInCategory;
}
public static List<Module> GetEnabledModules()
{
List<Module> enabledModules = new List<Module>();
foreach (Module module in modules)
{
if (module.enabled)
{
enabledModules.Add(module);
}
}
return enabledModules;
}
public static List<Module> GetEnabledModulesInCategory(string category)
{
List<Module> enabledModulesInCategory = new List<Module>();
foreach (Module module in modules)
{
if (module.enabled && module.category == category)
{
enabledModulesInCategory.Add(module);
}
}
return enabledModulesInCategory;
}
public static void OnTick()
{
foreach (Module module in modules)
{
if (module.enabled && module.tickable)
{
module.OnTick();
}
}
}
public static void OnKeyPress(char keyChar)
{
foreach (Module module in modules)
{
if (module.MatchesKey(keyChar))
{
if (module.enabled)
{
module.OnDisable();
Console.WriteLine("Disabled " + module.name);
}
else
{
module.OnEnable();
Console.WriteLine("Enabled " + module.name);
}
}
}
}
}
} | ClientBase/ModuleManager.cs | R1ck404-External-Cheat-Base-65a7014 | [
{
"filename": "ClientBase/UI/Notification/NotificationManager.cs",
"retrieved_chunk": "using Client.ClientBase.Fonts;\nnamespace Client.ClientBase.UI.Notification\n{\n public static class NotificationManager\n {\n public static Form overlay = null!;\n public static List<Notification> notifications = new List<Notification>();\n public static void Init(Form form)\n {\n overlay = form;",
"score": 0.7977946400642395
},
{
"filename": "ClientBase/Module.cs",
"retrieved_chunk": "using System.Diagnostics;\nusing System.Runtime.InteropServices;\nnamespace Client.ClientBase\n{\n public class Module\n {\n public readonly string category;\n public readonly string name;\n public readonly string desc;\n public bool enabled;",
"score": 0.7715260982513428
},
{
"filename": "ClientBase/Modules/ClickGUI.cs",
"retrieved_chunk": "using System;\nusing System.Linq;\nusing System.Windows.Forms;\nnamespace Client.ClientBase.Modules\n{\n public class ModuleList : VisualModule\n {\n private bool uiVisible = false;\n private Point uiPosition = new Point(10, 10);\n private Font uiFont = new Font(FontFamily.GenericSansSerif, 15);",
"score": 0.7671916484832764
},
{
"filename": "ClientBase/Modules/Aura.cs",
"retrieved_chunk": "using System.Collections;\nusing System.Drawing.Imaging;\nusing System.Numerics;\nusing System.Runtime.InteropServices;\nnamespace Client.ClientBase.Modules\n{\n public class Aura : Module\n {\n const int heightOffset = 7;\n const int shotKnockback = 1;",
"score": 0.7496433258056641
},
{
"filename": "ClientBase/Fonts/FontRenderer.cs",
"retrieved_chunk": "using System.Drawing.Text;\nusing System.IO;\nusing Client.ClientBase.Utils;\nnamespace Client.ClientBase.Fonts\n{\n public static class FontRenderer\n {\n public static FontFamily comfortaaFamily = FontFamily.GenericSerif;\n public static FontFamily sigmaFamily = FontFamily.GenericSerif;\n public static void Init()",
"score": 0.7459048628807068
}
] | csharp | Module> modules = new List<Module>(); |
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Timeline;
using UnityEngine;
using UnityEngine.Timeline;
namespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor
{
internal static class AbstractBoolValueControlTrackEditorUtility
{
internal static Color PrimaryColor = new(0.5f, 1f, 0.5f);
}
[CustomTimelineEditor(typeof(AbstractBoolValueControlTrack))]
public class AbstractBoolValueControlTrackCustomEditor : TrackEditor
{
public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)
{
track.name = "CustomTrack";
var options = base.GetTrackOptions(track, binding);
options.trackColor = AbstractBoolValueControlTrackEditorUtility.PrimaryColor;
// Debug.Log(binding.GetType());
return options;
}
}
[CustomTimelineEditor(typeof( | AbstractBoolValueControlClip))]
public class AbstractBoolValueControlCustomEditor : ClipEditor
{ |
Dictionary<AbstractBoolValueControlClip, Texture2D> textures = new();
public override ClipDrawOptions GetClipOptions(TimelineClip clip)
{
var clipOptions = base.GetClipOptions(clip);
clipOptions.icons = null;
clipOptions.highlightColor = AbstractBoolValueControlTrackEditorUtility.PrimaryColor;
return clipOptions;
}
public override void DrawBackground(TimelineClip clip, ClipBackgroundRegion region)
{
var tex = GetSolidColorTexture(clip);
if (tex) GUI.DrawTexture(region.position, tex);
}
public override void OnClipChanged(TimelineClip clip)
{
GetSolidColorTexture(clip, true);
}
Texture2D GetSolidColorTexture(TimelineClip clip, bool update = false)
{
var tex = Texture2D.blackTexture;
var customClip = clip.asset as AbstractBoolValueControlClip;
if (update)
{
textures.Remove(customClip);
}
else
{
textures.TryGetValue(customClip, out tex);
if (tex) return tex;
}
var c = customClip.Value ? new Color(0.8f, 0.8f, 0.8f) : new Color(0.2f, 0.2f, 0.2f);
tex = new Texture2D(1, 1);
tex.SetPixel(0, 0, c);
tex.Apply();
if (textures.ContainsKey(customClip))
{
textures[customClip] = tex;
}
else
{
textures.Add(customClip, tex);
}
return tex;
}
}
[CanEditMultipleObjects]
[CustomEditor(typeof(AbstractBoolValueControlClip))]
public class AbstractBoolValueControlClipEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
}
}
} | Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs | nmxi-Unity_AbstractTimelineExtention-b518049 | [
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractColorValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractColorValueControlTrack))]\n public class AbstractColorValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractColorValueControlTrackEditorUtility.PrimaryColor;\n return options;",
"score": 0.8972523808479309
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs",
"retrieved_chunk": " [CustomTimelineEditor(typeof(AbstractIntValueControlTrack))]\n public class AbstractIntValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor;\n return options;\n }",
"score": 0.8941072821617126
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs",
"retrieved_chunk": " [CustomTimelineEditor(typeof(AbstractFloatValueControlTrack))]\n public class AbstractFloatValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor;\n return options;\n }",
"score": 0.8900301456451416
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractIntValueControlClip))]\n public class AbstractIntValueControlCustomEditor : ClipEditor\n {\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);\n clipOptions.icons = null;\n clipOptions.highlightColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor;\n return clipOptions;",
"score": 0.8706697225570679
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractFloatValueControlClip))]\n public class AbstractFloatValueControlCustomEditor : ClipEditor\n {\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);\n clipOptions.icons = null;\n clipOptions.highlightColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor;\n return clipOptions;",
"score": 0.8666777014732361
}
] | csharp | AbstractBoolValueControlClip))]
public class AbstractBoolValueControlCustomEditor : ClipEditor
{ |
using ChatGPTConnection;
using ChatUI.Core;
using ChatUI.MVVM.Model;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace ChatUI.MVVM.ViewModel
{
internal class MainViewModel : ObservableObject
{
public ObservableCollection<MessageModel> Messages { get; set; }
private MainWindow MainWindow { get; set; }
public | RelayCommand SendCommand { | get; set; }
private string _message = "";
public string Message
{
get { return _message; }
set
{
_message = value;
OnPropertyChanged();
}
}
private string CatIconPath => Path.Combine(MainWindow.DllDirectory, "Icons/cat.jpeg");
public MainViewModel()
{
Messages = new ObservableCollection<MessageModel>();
//ビュー(?)を取得
var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x is MainWindow);
MainWindow = (MainWindow)window;
//キーを押したらメッセージが追加されるコマンド
SendCommand = new RelayCommand(o =>
{
if (Message == "") return;
//自分のメッセージを追加
AddMyMessages(Message);
//ChatGPTにメッセージをおくり、返信をメッセージに追加
SendToChatGPT(Message);
//メッセージボックスを空にする
Message = "";
});
//Test_Message();
}
private void AddMyMessages(string message)
{
Messages.Add(new MessageModel
{
Username = "You",
UsernameColor = "White",
Time = DateTime.Now,
MainMessage = message,
IsMyMessage = true
});
ScrollToBottom();
}
//TODO: 多責務になっているので分割したい
private async void SendToChatGPT(string message)
{
//LoadingSpinnerを表示
AddLoadingSpinner();
//APIキーをセッティングファイルから取得
Settings settings = Settings.LoadSettings();
if (settings == null || settings.APIKey == "")
{
MessageBox.Show("API key not found. Please set from the options.");
return;
}
string apiKey = settings.APIKey;
string systemMessage = settings.SystemMessage;
//ChatGPTにメッセージを送る
ChatGPTConnector connector = new ChatGPTConnector(apiKey, systemMessage);
var response = await connector.RequestAsync(message);
//LoadingSpinnerを削除
DeleteLoadingSpinner();
if (!response.isSuccess)
{
AddChatGPTMessage("API request failed. API key may be wrong.", null);
return;
}
//返信をチャット欄に追加
string conversationText = response.GetConversation();
string fullText = response.GetMessage();
AddChatGPTMessage(conversationText, fullText);
//イベントを実行
MainWindow.OnResponseReceived(new ChatGPTResponseEventArgs(response));
}
private void AddChatGPTMessage(string mainMessage, string subMessage)
{
Messages.Add(new MessageModel
{
Username = "ChatGPT",
UsernameColor = "#738CBA",
ImageSource = CatIconPath,
Time = DateTime.Now,
MainMessage = mainMessage,
SubMessage = subMessage,
UseSubMessage = MainWindow.IsDebagMode,
IsMyMessage = false
});
ScrollToBottom();
}
private void ScrollToBottom()
{
int lastIndex = MainWindow.ChatView.Items.Count - 1;
var item = MainWindow.ChatView.Items[lastIndex];
MainWindow.ChatView.ScrollIntoView(item);
}
private void AddLoadingSpinner()
{
Messages.Add(new MessageModel
{
IsLoadingSpinner = true
});
ScrollToBottom();
}
private void DeleteLoadingSpinner()
{
for (int i = 0; i < Messages.Count; i++)
{
var item = Messages[i];
if (item.IsLoadingSpinner)
{
Messages.Remove(item);
}
}
}
}
}
| ChatUI/MVVM/ViewModel/MainViewModel.cs | 4kk11-ChatGPTforRhino-382323e | [
{
"filename": "ChatUI/MainWindow.xaml.cs",
"retrieved_chunk": "using ChatUI.MVVM.ViewModel;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing ChatGPTConnection;\nnamespace ChatUI\n{\n\tpublic partial class MainWindow : Window\n\t{\n\t\tpublic static string DllDirectory\n\t\t{",
"score": 0.8424824476242065
},
{
"filename": "ChatUI/MVVM/Model/MessageModel.cs",
"retrieved_chunk": "{\n\tclass MessageModel : INotifyPropertyChanged\n\t{\n\t\tpublic event PropertyChangedEventHandler PropertyChanged;\n\t\tpublic string Username { get; set; }\n\t\tpublic string UsernameColor { get; set; }\n\t\tpublic string ImageSource { get; set; }\n\t\tpublic bool UseSubMessage {\n\t\t\tget { return useSubMessage; }\n\t\t\tset { ",
"score": 0.7972524166107178
},
{
"filename": "ChatUI/MVVM/Model/MessageModel.cs",
"retrieved_chunk": "\t\t\t\tuseSubMessage = value;\n\t\t\t\tOnPropertyChanged(\"Message\");\n\t\t\t}\n\t\t}\n\t\tprivate bool useSubMessage ;\n\t\tpublic string Message {\n\t\t\tget { \n\t\t\t\treturn (UseSubMessage && SubMessage != null)? SubMessage : MainMessage; \n\t\t\t}\n\t\t\tset { MainMessage = value; }",
"score": 0.7786707878112793
},
{
"filename": "ChatUI/ChatGPTResponseEvent.cs",
"retrieved_chunk": "using ChatGPTConnection;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace ChatUI\n{\n\tpublic delegate void ChatGPTResponseEventHandler(object sender, ChatGPTResponseEventArgs e);\n\tpublic class ChatGPTResponseEventArgs : EventArgs",
"score": 0.7756882905960083
},
{
"filename": "ChatUI/Core/ObservableObject.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace ChatUI.Core\n{\n\tinternal class ObservableObject : INotifyPropertyChanged",
"score": 0.7746835947036743
}
] | csharp | RelayCommand SendCommand { |
#nullable enable
using System;
using System.Collections.Generic;
namespace Mochineko.RelentStateMachine
{
public sealed class TransitionMapBuilder<TEvent, TContext>
: ITransitionMapBuilder<TEvent, TContext>
{
private readonly IState<TEvent, TContext> initialState;
private readonly List<IState<TEvent, TContext>> states = new();
private readonly Dictionary<IState<TEvent, TContext>, Dictionary<TEvent, IState<TEvent, TContext>>>
transitionMap = new();
private readonly Dictionary<TEvent, | IState<TEvent, TContext>>
anyTransitionMap = new(); |
private bool disposed = false;
public static TransitionMapBuilder<TEvent, TContext> Create<TInitialState>()
where TInitialState : IState<TEvent, TContext>, new()
{
var initialState = new TInitialState();
return new TransitionMapBuilder<TEvent, TContext>(initialState);
}
private TransitionMapBuilder(IState<TEvent, TContext> initialState)
{
this.initialState = initialState;
states.Add(this.initialState);
}
public void Dispose()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));
}
disposed = true;
}
public void RegisterTransition<TFromState, TToState>(TEvent @event)
where TFromState : IState<TEvent, TContext>, new()
where TToState : IState<TEvent, TContext>, new()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));
}
var fromState = GetOrCreateState<TFromState>();
var toState = GetOrCreateState<TToState>();
if (transitionMap.TryGetValue(fromState, out var transitions))
{
if (transitions.TryGetValue(@event, out var nextState))
{
throw new InvalidOperationException(
$"Already exists transition from {fromState.GetType()} to {nextState.GetType()} with event {@event}.");
}
else
{
transitions.Add(@event, toState);
}
}
else
{
var newTransitions = new Dictionary<TEvent, IState<TEvent, TContext>>();
newTransitions.Add(@event, toState);
transitionMap.Add(fromState, newTransitions);
}
}
public void RegisterAnyTransition<TToState>(TEvent @event)
where TToState : IState<TEvent, TContext>, new()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));
}
var toState = GetOrCreateState<TToState>();
if (anyTransitionMap.TryGetValue(@event, out var nextState))
{
throw new InvalidOperationException(
$"Already exists transition from any state to {nextState.GetType()} with event {@event}.");
}
else
{
anyTransitionMap.Add(@event, toState);
}
}
public ITransitionMap<TEvent, TContext> Build()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));
}
var result = new TransitionMap<TEvent, TContext>(
initialState,
states,
BuildReadonlyTransitionMap(),
anyTransitionMap);
// Cannot reuse builder after build.
this.Dispose();
return result;
}
private IReadOnlyDictionary<
IState<TEvent, TContext>,
IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>
BuildReadonlyTransitionMap()
{
var result = new Dictionary<
IState<TEvent, TContext>,
IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>();
foreach (var (key, value) in transitionMap)
{
result.Add(key, value);
}
return result;
}
private TState GetOrCreateState<TState>()
where TState : IState<TEvent, TContext>, new()
{
foreach (var state in states)
{
if (state is TState target)
{
return target;
}
}
var newState = new TState();
states.Add(newState);
return newState;
}
}
} | Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs | mochi-neko-RelentStateMachine-64762eb | [
{
"filename": "Assets/Mochineko/RelentStateMachine/TransitionMap.cs",
"retrieved_chunk": " private readonly IReadOnlyDictionary<\n IState<TEvent, TContext>,\n IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>\n transitionMap;\n private readonly IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>\n anyTransitionMap;\n public TransitionMap(\n IState<TEvent, TContext> initialState,\n IReadOnlyList<IState<TEvent, TContext>> states,\n IReadOnlyDictionary<",
"score": 0.9246053695678711
},
{
"filename": "Assets/Mochineko/RelentStateMachine/TransitionMap.cs",
"retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing Mochineko.Relent.Result;\nnamespace Mochineko.RelentStateMachine\n{\n internal sealed class TransitionMap<TEvent, TContext>\n : ITransitionMap<TEvent, TContext>\n {\n private readonly IState<TEvent, TContext> initialState;\n private readonly IReadOnlyList<IState<TEvent, TContext>> states;",
"score": 0.9041918516159058
},
{
"filename": "Assets/Mochineko/RelentStateMachine/TransitionMap.cs",
"retrieved_chunk": " IState<TEvent, TContext>,\n IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>\n transitionMap,\n IReadOnlyDictionary<TEvent, IState<TEvent, TContext>> anyTransitionMap)\n {\n this.initialState = initialState;\n this.states = states;\n this.transitionMap = transitionMap;\n this.anyTransitionMap = anyTransitionMap;\n }",
"score": 0.9034744501113892
},
{
"filename": "Assets/Mochineko/RelentStateMachine/TransitionMap.cs",
"retrieved_chunk": " IState<TEvent, TContext> ITransitionMap<TEvent, TContext>.InitialState\n => initialState;\n IResult<IState<TEvent, TContext>> ITransitionMap<TEvent, TContext>.AllowedToTransit(\n IState<TEvent, TContext> currentState,\n TEvent @event)\n {\n if (transitionMap.TryGetValue(currentState, out var candidates))\n {\n if (candidates.TryGetValue(@event, out var nextState))\n {",
"score": 0.8871052861213684
},
{
"filename": "Assets/Mochineko/RelentStateMachine/ITransitionMap.cs",
"retrieved_chunk": "#nullable enable\nusing System;\nusing Mochineko.Relent.Result;\nnamespace Mochineko.RelentStateMachine\n{\n public interface ITransitionMap<TEvent, TContext> : IDisposable\n {\n internal IState<TEvent, TContext> InitialState { get; }\n internal IResult<IState<TEvent, TContext>> AllowedToTransit(IState<TEvent, TContext> currentState, TEvent @event);\n }",
"score": 0.8667321801185608
}
] | csharp | IState<TEvent, TContext>>
anyTransitionMap = new(); |
#nullable enable
using System;
using System.Runtime.InteropServices;
namespace Mochineko.FacialExpressions.Emotion
{
/// <summary>
/// Frame of emotion animation.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public readonly struct EmotionAnimationFrame<TEmotion>
: IEquatable<EmotionAnimationFrame<TEmotion>>
where TEmotion : Enum
{
/// <summary>
/// Sample of emotion morphing.
/// </summary>
public readonly | EmotionSample<TEmotion> sample; |
/// <summary>
/// Duration of this frame in seconds.
/// </summary>
public readonly float durationSeconds;
/// <summary>
/// Creates a new instance of <see cref="EmotionAnimationFrame{TEmotion}"/>.
/// </summary>
/// <param name="sample">Sample of emotion morphing.</param>
/// <param name="durationSeconds">Duration of this frame in seconds.</param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public EmotionAnimationFrame(EmotionSample<TEmotion> sample, float durationSeconds)
{
if (durationSeconds < 0f)
{
throw new ArgumentOutOfRangeException(
nameof(durationSeconds), durationSeconds,
"Duration must be greater than or equal to 0.");
}
this.sample = sample;
this.durationSeconds = durationSeconds;
}
public bool Equals(EmotionAnimationFrame<TEmotion> other)
{
return sample.Equals(other.sample)
&& durationSeconds.Equals(other.durationSeconds);
}
public override bool Equals(object? obj)
{
return obj is EmotionAnimationFrame<TEmotion> other && Equals(other);
}
public override int GetHashCode()
{
return HashCode.Combine(sample, durationSeconds);
}
}
}
| Assets/Mochineko/FacialExpressions/Emotion/EmotionAnimationFrame.cs | mochi-neko-facial-expressions-unity-ab0d020 | [
{
"filename": "Assets/Mochineko/FacialExpressions/Emotion/EmotionSample.cs",
"retrieved_chunk": " public readonly struct EmotionSample<TEmotion>\n : IEquatable<EmotionSample<TEmotion>>\n where TEmotion : Enum\n {\n /// <summary>\n /// Target emotion.\n /// </summary>\n public readonly TEmotion emotion;\n /// <summary>\n /// Weight of morphing.",
"score": 0.9098377227783203
},
{
"filename": "Assets/Mochineko/FacialExpressions/Emotion/LoopEmotionAnimator.cs",
"retrieved_chunk": " public sealed class LoopEmotionAnimator<TEmotion>\n : IDisposable\n where TEmotion : Enum\n {\n private readonly ISequentialEmotionAnimator<TEmotion> animator;\n private readonly IEnumerable<EmotionAnimationFrame<TEmotion>> frames;\n private readonly CancellationTokenSource cancellationTokenSource = new();\n /// <summary>\n /// Creates a new instance of <see cref=\"LoopEmotionAnimator\"/>.\n /// </summary>",
"score": 0.8900160193443298
},
{
"filename": "Assets/Mochineko/FacialExpressions/Emotion/ExclusiveFollowingEmotionAnimator.cs",
"retrieved_chunk": " : IFramewiseEmotionAnimator<TEmotion>\n where TEmotion : Enum\n {\n private readonly IEmotionMorpher<TEmotion> morpher;\n private readonly float followingTime;\n private readonly Dictionary<TEmotion, EmotionSample<TEmotion>> targets = new();\n private readonly Dictionary<TEmotion, float> velocities = new();\n /// <summary>\n /// Creates a new instance of <see cref=\"ExclusiveFollowingEmotionAnimator{TEmotion}\"/>.\n /// </summary>",
"score": 0.8891956806182861
},
{
"filename": "Assets/Mochineko/FacialExpressions/Emotion/IFramewiseEmotionAnimator.cs",
"retrieved_chunk": "#nullable enable\nusing System;\nnamespace Mochineko.FacialExpressions.Emotion\n{\n /// <summary>\n /// Defines an animator of emotion per game engine frame.\n /// </summary>\n /// <typeparam name=\"TEmotion\"></typeparam>\n public interface IFramewiseEmotionAnimator<TEmotion>\n where TEmotion : Enum",
"score": 0.8660328388214111
},
{
"filename": "Assets/Mochineko/FacialExpressions.Extensions/VRM/VRMEmotionMorpher.cs",
"retrieved_chunk": " // ReSharper disable once InconsistentNaming\n public sealed class VRMEmotionMorpher<TEmotion> :\n IEmotionMorpher<TEmotion>\n where TEmotion: Enum\n {\n private readonly Vrm10RuntimeExpression expression;\n private readonly IReadOnlyDictionary<TEmotion, ExpressionKey> keyMap;\n /// <summary>\n /// Creates a new instance of <see cref=\"VRMEmotionMorpher\"/>.\n /// </summary>",
"score": 0.8619841933250427
}
] | csharp | EmotionSample<TEmotion> sample; |
using BepInEx;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using HarmonyLib;
using System.IO;
using Ultrapain.Patches;
using System.Linq;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Reflection;
using Steamworks;
using Unity.Audio;
using System.Text;
using System.Collections.Generic;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.ResourceManagement.ResourceLocations;
using UnityEngine.UIElements;
using PluginConfig.API;
namespace Ultrapain
{
[BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)]
[BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")]
public class Plugin : BaseUnityPlugin
{
public const string PLUGIN_GUID = "com.eternalUnion.ultraPain";
public const string PLUGIN_NAME = "Ultra Pain";
public const string PLUGIN_VERSION = "1.1.0";
public static Plugin instance;
private static bool addressableInit = false;
public static T LoadObject<T>(string path)
{
if (!addressableInit)
{
Addressables.InitializeAsync().WaitForCompletion();
addressableInit = true;
}
return Addressables.LoadAssetAsync<T>(path).WaitForCompletion();
}
public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod)
{
Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f)
return target.position;
RaycastHit raycastHit;
if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider)
return target.position;
else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide))
{
return raycastHit.point;
}
else {
Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod;
return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z);
}
}
public static GameObject projectileSpread;
public static GameObject homingProjectile;
public static GameObject hideousMassProjectile;
public static GameObject decorativeProjectile2;
public static GameObject shotgunGrenade;
public static GameObject beam;
public static GameObject turretBeam;
public static GameObject lightningStrikeExplosiveSetup;
public static GameObject lightningStrikeExplosive;
public static GameObject lighningStrikeWindup;
public static GameObject explosion;
public static GameObject bigExplosion;
public static GameObject sandExplosion;
public static GameObject virtueInsignia;
public static | GameObject rocket; |
public static GameObject revolverBullet;
public static GameObject maliciousCannonBeam;
public static GameObject lightningBoltSFX;
public static GameObject revolverBeam;
public static GameObject blastwave;
public static GameObject cannonBall;
public static GameObject shockwave;
public static GameObject sisyphiusExplosion;
public static GameObject sisyphiusPrimeExplosion;
public static GameObject explosionWaveKnuckleblaster;
public static GameObject chargeEffect;
public static GameObject maliciousFaceProjectile;
public static GameObject hideousMassSpear;
public static GameObject coin;
public static GameObject sisyphusDestroyExplosion;
//public static GameObject idol;
public static GameObject ferryman;
public static GameObject minosPrime;
//public static GameObject maliciousFace;
public static GameObject somethingWicked;
public static Turret turret;
public static GameObject turretFinalFlash;
public static GameObject enrageEffect;
public static GameObject v2flashUnparryable;
public static GameObject ricochetSfx;
public static GameObject parryableFlash;
public static AudioClip cannonBallChargeAudio;
public static Material gabrielFakeMat;
public static Sprite blueRevolverSprite;
public static Sprite greenRevolverSprite;
public static Sprite redRevolverSprite;
public static Sprite blueShotgunSprite;
public static Sprite greenShotgunSprite;
public static Sprite blueNailgunSprite;
public static Sprite greenNailgunSprite;
public static Sprite blueSawLauncherSprite;
public static Sprite greenSawLauncherSprite;
public static GameObject rocketLauncherAlt;
public static GameObject maliciousRailcannon;
// Variables
public static float SoliderShootAnimationStart = 1.2f;
public static float SoliderGrenadeForce = 10000f;
public static float SwordsMachineKnockdownTimeNormalized = 0.8f;
public static float SwordsMachineCoreSpeed = 80f;
public static float MinGrenadeParryVelocity = 40f;
public static GameObject _lighningBoltSFX;
public static GameObject lighningBoltSFX
{
get
{
if (_lighningBoltSFX == null)
_lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject;
return _lighningBoltSFX;
}
}
private static bool loadedPrefabs = false;
public void LoadPrefabs()
{
if (loadedPrefabs)
return;
loadedPrefabs = true;
// Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab
projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab");
// Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab
homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab");
// Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab
decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab");
// Assets/Prefabs/Attacks and Projectiles/Grenade.prefab
shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab");
// Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab
turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab");
// Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab
beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab
lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab");
// Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab
lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab");
//[bundle-0][assets/prefabs/enemies/idol.prefab]
//idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab");
// Assets/Prefabs/Enemies/Ferryman.prefab
ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab
explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab");
//Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab
bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab");
//Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab
sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab");
// Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab
virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab");
// Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab
hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab");
// Assets/Particles/Enemies/RageEffect.prefab
enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab");
// Assets/Particles/Flashes/V2FlashUnparriable.prefab
v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab");
// Assets/Prefabs/Attacks and Projectiles/Rocket.prefab
rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab");
// Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab
revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab");
// Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab
maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab");
// Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab
revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab
blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab");
// Assets/Prefabs/Enemies/MinosPrime.prefab
minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab");
// Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab
cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab");
// get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab
cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip;
// Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab
shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab
sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab
sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab
explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab]
lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab");
// Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab
rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab");
// Assets/Prefabs/Weapons/Railcannon Malicious.prefab
maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab");
//Assets/Particles/SoundBubbles/Ricochet.prefab
ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab");
//Assets/Particles/Flashes/Flash.prefab
parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab");
//Assets/Prefabs/Attacks and Projectiles/Spear.prefab
hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab");
//Assets/Prefabs/Enemies/Wicked.prefab
somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab");
//Assets/Textures/UI/SingleRevolver.png
blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png");
//Assets/Textures/UI/RevolverSpecial.png
greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png");
//Assets/Textures/UI/RevolverSharp.png
redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png");
//Assets/Textures/UI/Shotgun.png
blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png");
//Assets/Textures/UI/Shotgun1.png
greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png");
//Assets/Textures/UI/Nailgun2.png
blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png");
//Assets/Textures/UI/NailgunOverheat.png
greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png");
//Assets/Textures/UI/SawbladeLauncher.png
blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png");
//Assets/Textures/UI/SawbladeLauncherOverheat.png
greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png");
//Assets/Prefabs/Attacks and Projectiles/Coin.prefab
coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab");
//Assets/Materials/GabrielFake.mat
gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat");
//Assets/Prefabs/Enemies/Turret.prefab
turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>();
//Assets/Particles/Flashes/GunFlashDistant.prefab
turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab");
//Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab
sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab");
//Assets/Prefabs/Effects/Charge Effect.prefab
chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab");
//Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab
maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab");
}
public static bool ultrapainDifficulty = false;
public static bool realUltrapainDifficulty = false;
public static GameObject currentDifficultyButton;
public static GameObject currentDifficultyPanel;
public static Text currentDifficultyInfoText;
public void OnSceneChange(Scene before, Scene after)
{
StyleIDs.RegisterIDs();
ScenePatchCheck();
string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902";
string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d";
string currentSceneName = SceneManager.GetActiveScene().name;
if (currentSceneName == mainMenuSceneName)
{
LoadPrefabs();
//Canvas/Difficulty Select (1)/Violent
Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)");
GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect);
currentDifficultyButton = ultrapainButton;
ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value;
ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5;
RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>();
ultrapainTrans.anchoredPosition = new Vector2(20f, -104f);
//Canvas/Difficulty Select (1)/Violent Info
GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect);
currentDifficultyPanel = info;
currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>();
currentDifficultyInfoText.text = ConfigManager.pluginInfo.value;
Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>();
currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--";
currentDifficultyHeaderText.resizeTextForBestFit = true;
currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap;
currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate;
info.SetActive(false);
EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>();
evt.triggers.Clear();
/*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent();
activate.AddListener((BaseEventData data) => info.SetActive(true));
EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent();
activate.AddListener((BaseEventData data) => info.SetActive(false));*/
EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter };
trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true));
EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit };
trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false));
evt.triggers.Add(trigger1);
evt.triggers.Add(trigger2);
foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>())
{
if (trigger.gameObject == ultrapainButton)
continue;
EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter };
closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false));
trigger.triggers.Add(closeTrigger);
}
}
else if(currentSceneName == bootSequenceSceneName)
{
LoadPrefabs();
//Canvas/Difficulty Select (1)/Violent
Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select");
GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect);
currentDifficultyButton = ultrapainButton;
ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value;
ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5;
RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>();
ultrapainTrans.anchoredPosition = new Vector2(20f, -104f);
//Canvas/Difficulty Select (1)/Violent Info
GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect);
currentDifficultyPanel = info;
currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>();
currentDifficultyInfoText.text = ConfigManager.pluginInfo.value;
Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>();
currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--";
currentDifficultyHeaderText.resizeTextForBestFit = true;
currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap;
currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate;
info.SetActive(false);
EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>();
evt.triggers.Clear();
/*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent();
activate.AddListener((BaseEventData data) => info.SetActive(true));
EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent();
activate.AddListener((BaseEventData data) => info.SetActive(false));*/
EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter };
trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true));
EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit };
trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false));
evt.triggers.Add(trigger1);
evt.triggers.Add(trigger2);
foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>())
{
if (trigger.gameObject == ultrapainButton)
continue;
EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter };
closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false));
trigger.triggers.Add(closeTrigger);
}
}
// LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG
MinosPrimeCharge.CreateDecoy();
GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave;
}
public static class StyleIDs
{
private static bool registered = false;
public static void RegisterIDs()
{
registered = false;
if (MonoSingleton<StyleHUD>.Instance == null)
return;
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString);
registered = true;
Debug.Log("Registered all style ids");
}
private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
public static void UpdateID(string id, string newName)
{
if (!registered || StyleHUD.Instance == null)
return;
(idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName;
}
}
public static Harmony harmonyTweaks;
public static Harmony harmonyBase;
private static MethodInfo GetMethod<T>(string name)
{
return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
}
private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>();
private static HarmonyMethod GetHarmonyMethod(MethodInfo method)
{
if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod))
return harmonyMethod;
else
{
harmonyMethod = new HarmonyMethod(method);
methodCache.Add(method, harmonyMethod);
return harmonyMethod;
}
}
private static void PatchAllEnemies()
{
if (!ConfigManager.enemyTweakToggle.value)
return;
if (ConfigManager.friendlyFireDamageOverrideToggle.value)
{
harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix")));
harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix")));
harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix")));
}
harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix")));
harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix")));
if (ConfigManager.cerberusDashToggle.value)
harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix")));
if(ConfigManager.cerberusParryable.value)
{
harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix")));
if(ConfigManager.droneHomeToggle.value)
{
harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix")));
if(ConfigManager.ferrymanComboToggle.value)
harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix")));
if(ConfigManager.filthExplodeToggle.value)
harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix")));
if(ConfigManager.fleshPrisonSpinAttackToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix")));
if (ConfigManager.hideousMassInsigniaToggle.value)
{
harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix")));
harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix")));
if (ConfigManager.maliciousFaceHomingProjectileToggle.value)
{
harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix")));
}
if (ConfigManager.maliciousFaceRadianceOnEnrage.value)
harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix")));
if (ConfigManager.mindflayerShootTweakToggle.value)
{
harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix")));
}
if (ConfigManager.mindflayerTeleportComboToggle.value)
{
harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix")));
//harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix")));
}
if (ConfigManager.minosPrimeRandomTeleportToggle.value)
harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix")));
if (ConfigManager.minosPrimeTeleportTrail.value)
harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix")));
if (ConfigManager.minosPrimeCrushAttackToggle.value)
harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix")));
if (ConfigManager.minosPrimeComboExplosiveEndToggle.value)
harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix")));
if (ConfigManager.schismSpreadAttackToggle.value)
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix")));
if (ConfigManager.soliderShootTweakToggle.value)
{
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix")));
}
if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value)
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix")));
if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value)
{
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix")));
if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value)
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix")));
if (ConfigManager.strayShootToggle.value)
{
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix")));
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix")));
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix")));
}
if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value)
harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix")));
if(ConfigManager.streetCleanerPredictiveDodgeToggle.value)
harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix")));
if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None)
{
harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix")));
//harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix")));
}
if (ConfigManager.swordsMachineExplosiveSwordToggle.value)
{
harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix")));
}
harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix")));
if(ConfigManager.turretBurstFireToggle.value)
{
harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix")));
harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix")));
}
harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix")));
harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix")));
harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix")));
harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix")));
harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix")));
//if(ConfigManager.v2SecondStartEnraged.value)
// harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix")));
harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix")));
//harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix")));
harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix")));
harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix")));
if(ConfigManager.v2SecondFastCoinToggle.value)
harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix")));
harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix")));
if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value)
{
harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix")));
harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix")));
harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix")));
if (ConfigManager.sisyInstJumpShockwave.value)
{
harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix")));
}
if(ConfigManager.sisyInstBoulderShockwave.value)
harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix")));
if(ConfigManager.sisyInstStrongerExplosion.value)
harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix")));
if (ConfigManager.somethingWickedSpear.value)
{
harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix")));
}
if(ConfigManager.somethingWickedSpawnOn43.value)
{
harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix")));
harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix")));
}
if (ConfigManager.panopticonFullPhase.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix")));
if (ConfigManager.panopticonAxisBeam.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix")));
if (ConfigManager.panopticonSpinAttackToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix")));
if (ConfigManager.panopticonBlackholeProj.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix")));
if (ConfigManager.panopticonBalanceEyes.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix")));
if (ConfigManager.panopticonBlueProjToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler")));
if (ConfigManager.idolExplosionToggle.value)
harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix")));
// ADDME
/*
harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix")));
harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix")));
harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix")));
harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix")));
*/
}
private static void PatchAllPlayers()
{
if (!ConfigManager.playerTweakToggle.value)
return;
harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix")));
harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix")));
if (ConfigManager.rocketBoostToggle.value)
harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix")));
if (ConfigManager.rocketGrabbingToggle.value)
harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix")));
if (ConfigManager.orbStrikeToggle.value)
{
harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix")));
harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix")));
harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix")));
harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix")));
harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix")));
harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix")));
harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix")));
harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix")));
harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix")));
harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix")));
harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix")));
}
if(ConfigManager.chargedRevRegSpeedMulti.value != 1)
harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix")));
if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1
|| ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1
|| ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1
|| ConfigManager.sawAmmoRegSpeedMulti.value != 1)
harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix")));
if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1)
harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix")));
if(ConfigManager.staminaRegSpeedMulti.value != 1)
harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix")));
if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1)
{
harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix")));
harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix")));
harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix")));
harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler")));
harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler")));
harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler")));
}
// ADDME
harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler")));
harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix")));
harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler")));
harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler")));
harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler")));
if (ConfigManager.hardDamagePercent.normalizedValue != 1)
harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix")));
harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler")));
foreach (HealthBarTracker hb in HealthBarTracker.instances)
{
if (hb != null)
hb.SetSliderRange();
}
harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix")));
if(ConfigManager.screwDriverHomeToggle.value)
harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix")));
if(ConfigManager.screwDriverSplitToggle.value)
harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix")));
}
private static void PatchAllMemes()
{
if (ConfigManager.enrageSfxToggle.value)
harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix")));
if(ConfigManager.funnyDruidKnightSFXToggle.value)
{
harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix")));
harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix")));
}
if (ConfigManager.fleshObamiumToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix")));
if (ConfigManager.obamapticonToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix")));
}
public static bool methodsPatched = false;
public static void ScenePatchCheck()
{
if(methodsPatched && !ultrapainDifficulty)
{
harmonyTweaks.UnpatchSelf();
methodsPatched = false;
}
else if(!methodsPatched && ultrapainDifficulty)
{
PatchAll();
}
}
public static void PatchAll()
{
harmonyTweaks.UnpatchSelf();
methodsPatched = false;
if (!ultrapainDifficulty)
return;
if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value)
harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix")));
if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value)
harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix")));
PatchAllEnemies();
PatchAllPlayers();
PatchAllMemes();
methodsPatched = true;
}
public static string workingPath;
public static string workingDir;
public static AssetBundle bundle;
public static AudioClip druidKnightFullAutoAud;
public static AudioClip druidKnightFullerAutoAud;
public static AudioClip druidKnightDeathAud;
public static AudioClip enrageAudioCustom;
public static GameObject fleshObamium;
public static GameObject obamapticon;
public void Awake()
{
instance = this;
workingPath = Assembly.GetExecutingAssembly().Location;
workingDir = Path.GetDirectoryName(workingPath);
Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}");
try
{
bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain"));
druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav");
druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav");
druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav");
enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav");
fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab");
obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab");
}
catch (Exception e)
{
Logger.LogError($"Could not load the asset bundle:\n{e}");
}
// DEBUG
/*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt");
Logger.LogInfo($"Saving to {logPath}");
List<string> assetPaths = new List<string>()
{
"fonts.bundle",
"videos.bundle",
"shaders.bundle",
"particles.bundle",
"materials.bundle",
"animations.bundle",
"prefabs.bundle",
"physicsmaterials.bundle",
"models.bundle",
"textures.bundle",
};
//using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write))
//{
foreach(string assetPath in assetPaths)
{
Logger.LogInfo($"Attempting to load {assetPath}");
AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath));
bundles.Add(bundle);
//foreach (string name in bundle.GetAllAssetNames())
//{
// string line = $"[{bundle.name}][{name}]\n";
// log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length);
//}
bundle.LoadAllAssets();
}
//}
*/
// Plugin startup logic
Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!");
harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks");
harmonyBase = new Harmony(PLUGIN_GUID + "_base");
harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix")));
harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix")));
harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix")));
harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix")));
harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix")));
LoadPrefabs();
ConfigManager.Initialize();
SceneManager.activeSceneChanged += OnSceneChange;
}
}
public static class Tools
{
private static Transform _target;
private static Transform target { get
{
if(_target == null)
_target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
return _target;
}
}
public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null)
{
Vector3 projectedPlayerPos;
if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f)
{
return target.position;
}
RaycastHit raycastHit;
if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol)
{
projectedPlayerPos = target.position;
}
else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide))
{
projectedPlayerPos = raycastHit.point;
}
else
{
projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod;
projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z);
}
return projectedPlayerPos;
}
}
// Asset destroyer tracker
/*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })]
public class TempClass1
{
static void Postfix(UnityEngine.Object __0)
{
if (__0 != null && __0 == Plugin.homingProjectile)
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
Debug.LogError("Projectile destroyed");
Debug.LogError(t.ToString());
throw new Exception("Attempted to destroy proj");
}
}
}
[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })]
public class TempClass2
{
static void Postfix(UnityEngine.Object __0)
{
if (__0 != null && __0 == Plugin.homingProjectile)
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
Debug.LogError("Projectile destroyed");
Debug.LogError(t.ToString());
throw new Exception("Attempted to destroy proj");
}
}
}
[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })]
public class TempClass3
{
static void Postfix(UnityEngine.Object __0)
{
if (__0 != null && __0 == Plugin.homingProjectile)
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
Debug.LogError("Projectile destroyed");
Debug.LogError(t.ToString());
throw new Exception("Attempted to destroy proj");
}
}
}
[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })]
public class TempClass4
{
static void Postfix(UnityEngine.Object __0)
{
if (__0 != null && __0 == Plugin.homingProjectile)
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
Debug.LogError("Projectile destroyed");
Debug.LogError(t.ToString());
throw new Exception("Attempted to destroy proj");
}
}
}*/
}
| Ultrapain/Plugin.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static ConfigPanel leviathanPanel;\n public static ConfigPanel somethingWickedPanel;\n public static ConfigPanel panopticonPanel;\n public static ConfigPanel idolPanel;\n // GLOBAL ENEMY CONFIG\n public static BoolField friendlyFireDamageOverrideToggle;\n public static FloatSliderField friendlyFireDamageOverrideExplosion;\n public static FloatSliderField friendlyFireDamageOverrideProjectile;\n public static FloatSliderField friendlyFireDamageOverrideFire;\n public static FloatSliderField friendlyFireDamageOverrideMelee;",
"score": 0.862168550491333
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static ConfigPanel cerberusPanel;\n public static ConfigPanel dronePanel;\n public static ConfigPanel filthPanel;\n public static ConfigPanel hideousMassPanel;\n public static ConfigPanel maliciousFacePanel;\n public static ConfigPanel mindflayerPanel;\n public static ConfigPanel schismPanel;\n public static ConfigPanel soliderPanel;\n public static ConfigPanel stalkerPanel;\n public static ConfigPanel strayPanel;",
"score": 0.8520862460136414
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static ConfigPanel streetCleanerPanel;\n public static ConfigPanel swordsMachinePanel;\n public static ConfigPanel virtuePanel;\n public static ConfigPanel ferrymanPanel;\n public static ConfigPanel turretPanel;\n public static ConfigPanel fleshPrisonPanel;\n public static ConfigPanel minosPrimePanel;\n public static ConfigPanel v2FirstPanel;\n public static ConfigPanel v2SecondPanel;\n public static ConfigPanel sisyInstPanel;",
"score": 0.8507876396179199
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static FloatField rocketBoostSpeedMultiplierPerHit;\n public static FormattedStringField rocketBoostStyleText;\n public static IntField rocketBoostStylePoints;\n public static BoolField rocketGrabbingToggle;\n public static BoolField grenadeBoostToggle;\n public static FloatField grenadeBoostDamageMultiplier;\n public static FloatField grenadeBoostSizeMultiplier;\n public static FormattedStringField grenadeBoostStyleText;\n public static IntField grenadeBoostStylePoints;\n public static BoolField orbStrikeToggle;",
"score": 0.835506021976471
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static IntField cerberusTotalDashCount;\n public static BoolField cerberusParryable;\n public static FloatField cerberusParryableDuration;\n public static IntField cerberusParryDamage;\n // DRONE\n public static BoolField droneProjectileToggle;\n public static FloatField droneProjectileDelay;\n public static FloatSliderField droneProjectileChance;\n public static BoolField droneExplosionBeamToggle;\n public static FloatField droneExplosionBeamDelay;",
"score": 0.8352691531181335
}
] | csharp | GameObject rocket; |
using System.Text.Json;
namespace WAGIapp.AI
{
internal class Master
{
private static Master singleton;
public static Master Singleton
{
get
{
if (singleton == null)
{
Console.WriteLine("Create master");
singleton = new Master();
Console.WriteLine("Master created");
}
return singleton;
}
}
public LongTermMemory Memory;
public ActionList Actions;
public ScriptFile scriptFile;
public bool Done = true;
private string nextMemoryPrompt = "";
private string lastCommandOuput = "";
public List<string> Notes;
private List<ChatMessage> LastMessages = new List<ChatMessage>();
private List< | ChatMessage> LastCommand = new List<ChatMessage>(); |
public string FormatedNotes
{
get
{
string output = "";
for (int i = 0; i < Notes.Count; i++)
{
output += (i + 1) + ". " + Notes[i] + "\n";
}
return output;
}
}
public Master()
{
Notes = new List<string>();
Memory = new LongTermMemory(1024);
Actions = new ActionList(10);
scriptFile = new ScriptFile();
singleton = this;
}
public async Task Tick()
{
Console.WriteLine("master tick -master");
if (Done)
return;
if (Memory.memories.Count == 0)
{
await Memory.MakeMemory(Settings.Goal);
Console.WriteLine("master start memory done");
}
var masterInput = await GetMasterInput();
string responseString;
MasterResponse response;
var action = Actions.AddAction("Thinking", LogAction.ThinkIcon);
while (true)
{
try
{
responseString = await OpenAI.GetChatCompletion(ChatModel.ChatGPT, masterInput);
response = Utils.GetObjectFromJson<MasterResponse>(responseString) ?? new();
break;
}
catch (Exception)
{
Console.WriteLine("Master failed - trying again");
}
}
nextMemoryPrompt = response.thoughts;
lastCommandOuput = await Commands.TryToRun(this, response.command);
LastMessages.Add(new ChatMessage(ChatRole.Assistant, responseString));
LastCommand.Add(new ChatMessage(ChatRole.System, "Command output:\n" + lastCommandOuput));
if (LastMessages.Count >= 10)
LastMessages.RemoveAt(0);
if (LastCommand.Count >= 10)
LastCommand.RemoveAt(0);
action.Text = response.thoughts;
masterInput.Add(LastMessages.Last());
masterInput.Add(LastCommand.Last());
Console.WriteLine(JsonSerializer.Serialize(masterInput, new JsonSerializerOptions() { WriteIndented = true }));
Console.WriteLine(scriptFile.GetText());
Console.WriteLine("------------------------------------------------------------------------");
Actions.AddAction("Memory", LogAction.MemoryIcon);
await Memory.MakeMemory(responseString);
}
public async Task<List<ChatMessage>> GetMasterInput()
{
List<ChatMessage> messages = new List<ChatMessage>();
messages.Add(Texts.MasterStartText);
messages.Add(new ChatMessage(ChatRole.System, "Memories:\n" + await Memory.GetMemories(nextMemoryPrompt)));
messages.Add(new ChatMessage(ChatRole.System, "Notes:\n" + FormatedNotes));
messages.Add(new ChatMessage(ChatRole.System, "Commands:\n" + Commands.GetCommands()));
messages.Add(new ChatMessage(ChatRole.System, "Main Goal:\n" + Settings.Goal));
messages.Add(new ChatMessage(ChatRole.System, "Script file:\n" + scriptFile.GetText() + "\nEnd of script file"));
messages.Add(Texts.MasterStartText);
messages.Add(Texts.MasterOutputFormat);
for (int i = 0; i < LastMessages.Count; i++)
{
messages.Add(LastMessages[i]);
messages.Add(LastCommand[i]);
}
return messages;
}
}
class MasterResponse
{
public string thoughts { get; set; } = "";
public string command { get; set; } = "";
}
}
| WAGIapp/AI/Master.cs | Woltvint-WAGI-d808927 | [
{
"filename": "WAGIapp/AI/ActionList.cs",
"retrieved_chunk": "namespace WAGIapp.AI\n{\n public class ActionList\n {\n private readonly object dataLock = new object(); \n private List<LogAction> Actions;\n private int MaxActions;\n public ActionList(int maxActions) \n {\n Actions = new List<LogAction>();",
"score": 0.835648775100708
},
{
"filename": "WAGIapp/AI/OpenAI.cs",
"retrieved_chunk": " public struct ChatRequest\n {\n public string model { get; set; }\n public List<ChatMessage> messages { get; set; }\n }\n public struct ChatResponse\n {\n public string id { get; set; }\n public List<ChatChoice> choices { get; set; }\n }",
"score": 0.8080596923828125
},
{
"filename": "WAGIapp/AI/LongTermMemory.cs",
"retrieved_chunk": " private int maxMemorySize;\n public LongTermMemory(int maxMem = 256)\n {\n memories = new List<Memory>();\n lastUsedMemories = new HashSet<int>();\n tags = new HashSet<string>();\n maxMemorySize = maxMem;\n }\n public async Task MakeMemory(string state)\n {",
"score": 0.806858241558075
},
{
"filename": "WAGIapp/AI/ScriptFile.cs",
"retrieved_chunk": "namespace WAGIapp.AI\n{\n public class ScriptFile\n {\n public List<string> Lines { get; set; }\n public ScriptFile() \n {\n Lines = new List<string>();\n for (int i = 0; i < 21; i++)\n Lines.Add(string.Empty);",
"score": 0.793627917766571
},
{
"filename": "WAGIapp/AI/LogAction.cs",
"retrieved_chunk": "using MudBlazor;\nnamespace WAGIapp.AI\n{\n public class LogAction\n {\n public string Title { get; set; } = \"\";\n public string Icon { get; set; } = \"\";\n public string Text { get; set; } = \"\";\n public bool Last { get; set; } = false;\n public const string InfoIcon = Icons.Material.Filled.Info;",
"score": 0.7884979844093323
}
] | csharp | ChatMessage> LastCommand = new List<ChatMessage>(); |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Experimental.GraphView;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
namespace QuestSystem.QuestEditor
{
public class QuestGraphView : GraphView
{
public string misionName;
private QuestNodeSearchWindow _searchWindow;
public Quest questRef;
private QuestGraphView _self;
private QuestGraphEditor editorWindow;
public QuestGraphView(EditorWindow _editorWindow, Quest q = null)
{
questRef = q;
editorWindow = (QuestGraphEditor)_editorWindow;
styleSheets.Add(Resources.Load<StyleSheet>("QuestGraph"));
SetupZoom(ContentZoomer.DefaultMinScale, ContentZoomer.DefaultMaxScale);
this.AddManipulator(new ContentDragger());
this.AddManipulator(new SelectionDragger());
this.AddManipulator(new RectangleSelector());
//Grid
var grid = new GridBackground();
Insert(0, grid);
grid.StretchToParentSize();
this.AddElement(GenerateEntryPointNode());
this.AddSearchWindow(editorWindow);
_self = this;
}
//TODO: Create node at desired position with fewer hide
/*public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
base.BuildContextualMenu(evt);
if (evt.target is GraphView)
{
evt.menu.InsertAction(1,"Create Node", (e) => {
var a = editorWindow.rootVisualElement; var b = editorWindow.position.position; var c = editorWindow.rootVisualElement.parent;
var context = new SearchWindowContext(e.eventInfo.mousePosition, a.worldBound.x, a.worldBound.y);
Vector2 mousePosition = editorWindow.rootVisualElement.ChangeCoordinatesTo(editorWindow.rootVisualElement, context.screenMousePosition - editorWindow.position.position);
Vector2 graphViewMousePosition = this.contentViewContainer.WorldToLocal(mousePosition);
CreateNode("NodeQuest", mousePosition);
});
}
}*/
private void AddSearchWindow(EditorWindow editorWindow)
{
_searchWindow = ScriptableObject.CreateInstance<QuestNodeSearchWindow>();
_searchWindow.Init(this, editorWindow);
nodeCreationRequest = context => SearchWindow.Open(new SearchWindowContext(context.screenMousePosition),_searchWindow);
}
private Port GeneratePort( | NodeQuestGraph node, Direction direction, Port.Capacity capacity = Port.Capacity.Single)
{ |
return node.InstantiatePort(Orientation.Horizontal, direction, capacity, typeof(float));
}
public NodeQuestGraph GenerateEntryPointNode()
{
var node = new NodeQuestGraph
{
title = "Start",
GUID = Guid.NewGuid().ToString(),
entryPoint = true
};
//Add ouput port
var generatetPort = GeneratePort(node, Direction.Output);
generatetPort.portName = "Next";
node.outputContainer.Add(generatetPort);
//Quest params
var box = new Box();
//
var misionName = new TextField("Mision Name:")
{
value = "Temp name"
};
misionName.RegisterValueChangedCallback(evt =>
{
node.misionName = evt.newValue;
});
box.Add(misionName);
//
var isMain = new Toggle();
isMain.label = "isMain";
isMain.value = false;
isMain.RegisterValueChangedCallback(evt =>
{
node.isMain = evt.newValue;
});
//isMain.SetValueWithoutNotify(false);
box.Add(isMain);
//
var startDay = new IntegerField("Start Day:")
{
value = 0
};
startDay.RegisterValueChangedCallback(evt =>
{
node.startDay = evt.newValue;
});
box.Add(startDay);
//
var limitDay = new IntegerField("Limit Day:")
{
value = 0
};
limitDay.RegisterValueChangedCallback(evt =>
{
node.limitDay = evt.newValue;
});
box.Add(limitDay);
node.mainContainer.Add(box);
//Refresh visual part
node.RefreshExpandedState();
node.RefreshPorts();
node.SetPosition(new Rect(100, 200, 100, 150));
return node;
}
public override List<Port> GetCompatiblePorts(Port startPort, NodeAdapter nodeAdapter)
{
var compatiblePorts = new List<Port>();
//Reglas de conexions
ports.ForEach(port =>
{
if (startPort != port && startPort.node != port.node)
compatiblePorts.Add(port);
});
return compatiblePorts;
}
public void CreateNode(string nodeName, Vector2 position)
{
AddElement(CreateNodeQuest(nodeName,position));
}
public NodeQuestGraph CreateNodeQuest(string nodeName, Vector2 position, TextAsset ta = null, bool end = false)
{
var node = new NodeQuestGraph
{
title = nodeName,
GUID = Guid.NewGuid().ToString(),
questObjectives = new List<QuestObjectiveGraph>(),
};
//Add Input port
var generatetPortIn = GeneratePort(node, Direction.Input, Port.Capacity.Multi);
generatetPortIn.portName = "Input";
node.inputContainer.Add(generatetPortIn);
node.styleSheets.Add(Resources.Load<StyleSheet>("Node"));
//Add button to add ouput
var button = new Button(clickEvent: () =>
{
AddNextNodePort(node);
});
button.text = "New Next Node";
node.titleContainer.Add(button);
//Button to add more objectives
var button2 = new Button(clickEvent: () =>
{
AddNextQuestObjective(node);
});
button2.text = "Add new Objective";
//Hide/Unhide elements
var hideButton = new Button(clickEvent: () =>
{
HideUnhide(node, button2);
});
hideButton.text = "Hide/Unhide";
//Extra information
var extraText = new ObjectField("Extra information:");
extraText.objectType = typeof(TextAsset);
extraText.RegisterValueChangedCallback(evt =>
{
node.extraText = evt.newValue as TextAsset;
});
extraText.SetValueWithoutNotify(ta);
//Bool es final
var togle = new Toggle();
togle.label = "isFinal";
togle.RegisterValueChangedCallback(evt =>
{
node.isFinal = evt.newValue;
});
togle.SetValueWithoutNotify(end);
var container = new Box();
node.mainContainer.Add(container);// Container per a tenir fons solid
container.Add(extraText);
container.Add(togle);
container.Add(hideButton);
container.Add(button2);
node.objectivesRef = new Box();
container.Add(node.objectivesRef);
//Refresh la part Visual
node.RefreshExpandedState();
node.RefreshPorts();
node.SetPosition(new Rect(position.x, position.y, 400, 450));
return node;
}
private void HideUnhide(NodeQuestGraph node, Button b)
{
bool show = !b.visible;
b.visible = show;
foreach (var objective in node.questObjectives)
{
if (show)
{
node.objectivesRef.Add(objective);
}
else
{
node.objectivesRef.Remove(objective);
}
}
node.RefreshExpandedState();
node.RefreshPorts();
}
public void AddNextNodePort(NodeQuestGraph node, string overrideName = "")
{
var generatetPort = GeneratePort(node, Direction.Output);
int nPorts = node.outputContainer.Query("connector").ToList().Count;
//generatetPort.portName = "NextNode " + nPorts;
string choicePortName = string.IsNullOrEmpty(overrideName) ? "NextNode " + nPorts : overrideName;
generatetPort.portName = choicePortName;
var deleteButton = new Button(clickEvent: () => RemovePort(node, generatetPort))
{
text = "x"
};
generatetPort.contentContainer.Add(deleteButton);
node.outputContainer.Add(generatetPort);
node.RefreshPorts();
node.RefreshExpandedState();
}
private void RemovePort(NodeQuestGraph node, Port p)
{
var targetEdge = edges.ToList().Where(x => x.output.portName == p.portName && x.output.node == p.node);
if (targetEdge.Any())
{
var edge = targetEdge.First();
edge.input.Disconnect(edge);
RemoveElement(targetEdge.First());
}
node.outputContainer.Remove(p);
node.RefreshPorts();
node.RefreshExpandedState();
}
public void removeQuestObjective(NodeQuestGraph nodes, QuestObjectiveGraph objective)
{
nodes.objectivesRef.Remove(objective);
nodes.questObjectives.Remove(objective);
nodes.RefreshExpandedState();
}
private void AddNextQuestObjective(NodeQuestGraph node)
{
var Q = new QuestObjectiveGraph();
var deleteButton = new Button(clickEvent: () => removeQuestObjective(node, Q))
{
text = "x"
};
Q.contentContainer.Add(deleteButton);
//Visual Box separator
var newBox = new Box();
Q.Add(newBox);
node.objectivesRef.Add(Q);
node.questObjectives.Add(Q);
node.RefreshPorts();
node.RefreshExpandedState();
}
public NodeQuestGraph GetEntryPointNode()
{
List<NodeQuestGraph> nodeList = this.nodes.ToList().Cast<NodeQuestGraph>().ToList();
return nodeList.First(node => node.entryPoint);
}
}
} | Editor/GraphEditor/QuestGraphView.cs | lluispalerm-QuestSystem-cd836cc | [
{
"filename": "Editor/GraphEditor/QuestGraphEditor.cs",
"retrieved_chunk": " };\n if (questForGraph != null)\n _questGraph.misionName = questForGraph.misionName;\n _questGraph.StretchToParentSize();\n rootVisualElement.Add(_questGraph);\n }\n private void GenerateToolBar()\n {\n var toolbar = new Toolbar();\n var nodeCreateButton = new Button(clickEvent: () => { _questGraph.CreateNode(\"NodeQuest\", Vector2.zero); });",
"score": 0.8350882530212402
},
{
"filename": "Editor/GraphEditor/QuestGraphEditor.cs",
"retrieved_chunk": " questForGraph = evt.newValue as Quest;\n });\n toolbar.Add(Ins);\n rootVisualElement.Add(toolbar);\n }\n private void CreateQuest()\n {\n // create new scriptableObject \n //questForGraph =\n Quest newQuest = ScriptableObject.CreateInstance<Quest>();",
"score": 0.7984411716461182
},
{
"filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs",
"retrieved_chunk": "namespace QuestSystem.QuestEditor\n{\n public class QuestGraphSaveUtility\n {\n private QuestGraphView _targetGraphView;\n private List<Edge> Edges => _targetGraphView.edges.ToList();\n private List<NodeQuestGraph> node => _targetGraphView.nodes.ToList().Cast<NodeQuestGraph>().ToList();\n private List<NodeQuest> _cacheNodes = new List<NodeQuest>();\n public static QuestGraphSaveUtility GetInstance(QuestGraphView targetGraphView)\n {",
"score": 0.7932752370834351
},
{
"filename": "Editor/GraphEditor/QuestNodeSearchWindow.cs",
"retrieved_chunk": " private QuestGraphView _graphView;\n private EditorWindow _window;\n private Texture2D _textureForTable; \n public void Init(QuestGraphView graphView, EditorWindow window){\n _graphView = graphView;\n _window = window;\n _textureForTable = new Texture2D(1,1);\n _textureForTable.SetPixel(0,0, new Color(0,0,0,0));\n _textureForTable.Apply();\n }",
"score": 0.7879270315170288
},
{
"filename": "Runtime/QuestGiver.cs",
"retrieved_chunk": " showDialogue();\n questManagerRef.AddMisionToCurrent(questToGive);\n questAlreadyGiven = true;\n QuestManager.GetInstance().Save();\n }\n public void showDialogue()\n {\n //if (conversation != null) FindObjectOfType<DialogueWindow>().StartDialogue(conversation, null);\n //else return;\n }",
"score": 0.7855243682861328
}
] | csharp | NodeQuestGraph node, Direction direction, Port.Capacity capacity = Port.Capacity.Single)
{ |
using Microsoft.Extensions.Logging;
using System;
namespace ServiceSelf
{
/// <summary>
/// 命名管道日志
/// </summary>
sealed class NamedPipeLogger : ILogger
{
private readonly string categoryName;
private readonly | NamedPipeClient pipeClient; |
public NamedPipeLogger(string categoryName, NamedPipeClient pipeClient)
{
this.categoryName = categoryName;
this.pipeClient = pipeClient;
}
public IDisposable BeginScope<TState>(TState state)
{
return NullScope.Instance;
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel != LogLevel.None && this.pipeClient.CanWrite;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (this.IsEnabled(logLevel))
{
var logItem = new LogItem
{
LoggerName = this.categoryName,
Level = (int)logLevel,
Message = formatter(state, exception)
};
this.pipeClient.Write(logItem);
}
}
private class NullScope : IDisposable
{
public static NullScope Instance { get; } = new();
public void Dispose()
{
}
}
}
}
| ServiceSelf/NamedPipeLogger.cs | xljiulang-ServiceSelf-7f8604b | [
{
"filename": "ServiceSelf/NamedPipeLoggerProvider.cs",
"retrieved_chunk": "using Microsoft.Extensions.Logging;\nusing System;\nnamespace ServiceSelf\n{\n /// <summary>\n /// 命名管道日志提供者\n /// </summary>\n sealed class NamedPipeLoggerProvider : ILoggerProvider\n {\n private static readonly NamedPipeClient pipeClient = CreateNamedPipeClient();",
"score": 0.9095809459686279
},
{
"filename": "ServiceSelf/NamedPipeClient.cs",
"retrieved_chunk": " /// </summary>\n sealed class NamedPipeClient : IDisposable\n {\n /// <summary>\n /// 当前实例\n /// </summary>\n private Instance instance;\n /// <summary>\n /// 关闭tokenSource\n /// </summary>",
"score": 0.8795128464698792
},
{
"filename": "ServiceSelf/LogItem.cs",
"retrieved_chunk": "using Microsoft.Extensions.Logging;\nusing System;\nusing System.IO;\nnamespace ServiceSelf\n{\n partial class LogItem\n {\n /// <summary>\n /// 日志级别\n /// </summary>",
"score": 0.8581832647323608
},
{
"filename": "ServiceSelf/SystemdServiceSection.cs",
"retrieved_chunk": "namespace ServiceSelf\n{\n /// <summary>\n /// Service章节\n /// </summary>\n public sealed class SystemdServiceSection : SystemdSection\n {\n /// <summary>\n /// Service章节\n /// </summary>",
"score": 0.8570060133934021
},
{
"filename": "ServiceSelf/WindowsServiceOptions.cs",
"retrieved_chunk": "namespace ServiceSelf\n{\n /// <summary>\n /// windows独有的服务选项\n /// </summary>\n public sealed class WindowsServiceOptions\n {\n /// <summary>\n /// 在服务控制管理器中显示的服务名称\n /// </summary>",
"score": 0.8564131855964661
}
] | csharp | NamedPipeClient pipeClient; |
using CommunityToolkit.Mvvm.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Media.Core;
using Windows.Media.Playback;
using wingman.Helpers;
using wingman.Interfaces;
using wingman.ViewModels;
namespace wingman.Services
{
public class EventHandlerService : IEventHandlerService, IDisposable
{
private readonly IGlobalHotkeyService globalHotkeyService;
private readonly IMicrophoneDeviceService micService;
private readonly IStdInService stdInService;
private readonly ISettingsService settingsService;
private readonly ILoggingService Logger;
private readonly IWindowingService windowingService;
private readonly OpenAIControlViewModel openAIControlViewModel;
private readonly MediaPlayer mediaPlayer;
private readonly Stopwatch micQueueDebouncer = new Stopwatch();
private bool isDisposed;
private bool isRecording;
private bool isProcessing;
public EventHandler<bool> InferenceCallback { get; set; }
public EventHandlerService(OpenAIControlViewModel openAIControlViewModel,
IGlobalHotkeyService globalHotkeyService,
IMicrophoneDeviceService micService,
IStdInService stdInService,
ISettingsService settingsService,
ILoggingService loggingService,
| IWindowingService windowingService
)
{ |
this.globalHotkeyService = globalHotkeyService;
this.micService = micService;
this.stdInService = stdInService;
this.settingsService = settingsService;
Logger = loggingService;
this.windowingService = windowingService;
mediaPlayer = new MediaPlayer();
this.openAIControlViewModel = openAIControlViewModel;
Initialize();
}
private void Initialize()
{
globalHotkeyService.RegisterHotkeyDown(WingmanSettings.Main_Hotkey, Events_OnMainHotkey);
globalHotkeyService.RegisterHotkeyUp(WingmanSettings.Main_Hotkey, Events_OnMainHotkeyRelease);
globalHotkeyService.RegisterHotkeyDown(WingmanSettings.Modal_Hotkey, Events_OnModalHotkey);
globalHotkeyService.RegisterHotkeyUp(WingmanSettings.Modal_Hotkey, Events_OnModalHotkeyRelease);
isDisposed = false;
isRecording = false;
isProcessing = false;
Logger.LogDebug("EventHandler initialized.");
}
public void Dispose()
{
if (!isDisposed)
{
globalHotkeyService.UnregisterHotkeyDown(WingmanSettings.Main_Hotkey, Events_OnMainHotkey);
globalHotkeyService.UnregisterHotkeyUp(WingmanSettings.Main_Hotkey, Events_OnMainHotkeyRelease);
globalHotkeyService.UnregisterHotkeyDown(WingmanSettings.Modal_Hotkey, Events_OnModalHotkey);
globalHotkeyService.UnregisterHotkeyUp(WingmanSettings.Modal_Hotkey, Events_OnModalHotkeyRelease);
mediaPlayer.Dispose();
Debug.WriteLine("EventHandler disposed.");
isDisposed = true;
}
}
private async Task PlayChime(string chime)
{
var uri = new Uri(AppDomain.CurrentDomain.BaseDirectory + $"Assets\\{chime}.aac");
mediaPlayer.Source = MediaSource.CreateFromUri(uri);
mediaPlayer.Play();
Logger.LogDebug("Chime played.");
}
private async Task MouseWait(bool wait)
{
InferenceCallback?.Invoke(this, wait);
}
private async Task<bool> HandleHotkey(Func<Task<bool>> action)
{
if (isDisposed || !openAIControlViewModel.IsValidKey())
{
return await Task.FromResult(false);
}
if (isRecording || isProcessing || micQueueDebouncer.IsRunning && micQueueDebouncer.Elapsed.TotalSeconds < 1)
{
return await Task.FromResult(true);
}
#if DEBUG
Logger.LogDebug("Hotkey Down Caught");
#else
Logger.LogInfo("Recording has started ...");
#endif
micQueueDebouncer.Restart();
await PlayChime("normalchime");
await micService.StartRecording();
isRecording = true;
return await action();
}
private async Task<bool> HandleHotkeyRelease(Func<string, Task<bool>> action, string callername)
{
if (!isRecording || isProcessing)
{
return await Task.FromResult(true);
}
try
{
Logger.LogDebug("Hotkey Up Caught");
isProcessing = true;
await MouseWait(true);
await PlayChime("lowchime");
micQueueDebouncer.Stop();
var elapsed = micQueueDebouncer.Elapsed;
#if DEBUG
Logger.LogDebug("Stop recording");
#else
Logger.LogInfo("Stopping recording...");
#endif
if (elapsed.TotalSeconds < 1)
await Task.Delay(1000);
var file = await micService.StopRecording();
await Task.Delay(100);
isRecording = false;
if (elapsed.TotalMilliseconds < 1500)
{
Logger.LogError("Recording was too short.");
return await Task.FromResult(true);
}
if (file == null)
{
throw new Exception("File is null");
}
#if DEBUG
Logger.LogDebug("Send recording to Whisper API");
#else
Logger.LogInfo("Initiating Whisper API request...");
#endif
windowingService.UpdateStatus("Waiting for Whisper API Response... (This can lag)");
string prompt = string.Empty;
var taskwatch = new Stopwatch();
taskwatch.Start();
using (var scope = Ioc.Default.CreateScope())
{
var openAIAPIService = scope.ServiceProvider.GetRequiredService<IOpenAIAPIService>();
var whisperResponseTask = openAIAPIService.GetWhisperResponse(file);
while (!whisperResponseTask.IsCompleted)
{
await Task.Delay(50);
if (taskwatch.Elapsed.TotalSeconds >= 3)
{
taskwatch.Restart();
Logger.LogInfo(" Still waiting...");
}
}
prompt = await whisperResponseTask;
}
taskwatch.Stop();
windowingService.UpdateStatus("Whisper API Responded...");
#if DEBUG
Logger.LogDebug("WhisperAPI Prompt Received: " + prompt);
#else
#endif
if (string.IsNullOrEmpty(prompt))
{
Logger.LogError("WhisperAPI Prompt was Empty");
return await Task.FromResult(true);
}
Logger.LogInfo("Whisper API responded: " + prompt);
string? cbstr = "";
if ((settingsService.Load<bool>(WingmanSettings.Append_Clipboard) && callername=="MAIN_HOTKEY") || (settingsService.Load<bool>(WingmanSettings.Append_Clipboard_Modal) && callername=="MODAL_HOTKEY"))
{
#if DEBUG
Logger.LogDebug("WingmanSettings.Append_Clipboard is true.");
#else
Logger.LogInfo("Appending clipboard to prompt...");
#endif
cbstr = await ClipboardHelper.GetTextAsync();
if (!string.IsNullOrEmpty(cbstr))
{
cbstr = PromptCleaners.TrimWhitespaces(cbstr);
cbstr = PromptCleaners.TrimNewlines(cbstr);
prompt += " " + cbstr;
}
}
try
{
Logger.LogDebug("Deleting temporary voice file: " + file.Path);
await file.DeleteAsync();
}
catch (Exception e)
{
Logger.LogException("Error deleting temporary voice file: " + e.Message);
throw e;
}
string response = String.Empty;
using (var scope = Ioc.Default.CreateScope())
{
var openAIAPIService = scope.ServiceProvider.GetRequiredService<IOpenAIAPIService>();
try
{
windowingService.UpdateStatus("Waiting for GPT response...");
#if DEBUG
Logger.LogDebug("Sending prompt to OpenAI API: " + prompt);
#else
Logger.LogInfo("Waiting for GPT Response... (This can lag)");
#endif
var responseTask = openAIAPIService.GetResponse(prompt);
taskwatch = Stopwatch.StartNew();
while (!responseTask.IsCompleted)
{
await Task.Delay(50);
if (taskwatch.Elapsed.TotalSeconds >= 3)
{
taskwatch.Restart();
Logger.LogInfo(" Still waiting...");
}
}
response = await responseTask;
taskwatch.Stop();
windowingService.UpdateStatus("Response Received ...");
Logger.LogInfo("Received response from GPT...");
}
catch (Exception e)
{
Logger.LogException("Error sending prompt to OpenAI API: " + e.Message);
throw e;
}
}
await action(response);
}
catch (Exception e)
{
Logger.LogException("Error handling hotkey release: " + e.Message);
throw e;
}
return await Task.FromResult(true);
}
//private async Task<bool> Events_OnMainHotkey()
private async void Events_OnMainHotkey(object sender, EventArgs e)
{
// return
await HandleHotkey(async () =>
{
// In case hotkeys end up being snowflakes
return await Task.FromResult(true);
});
}
//private async Task<bool> Events_OnMainHotkeyRelease()
private async void Events_OnMainHotkeyRelease(object sender, EventArgs e)
{
// return
await HandleHotkeyRelease(async (response) =>
{
#if DEBUG
Logger.LogDebug("Returning");
#else
Logger.LogInfo("Sending response to STDOUT...");
#endif
windowingService.ForceStatusHide();
await stdInService.SendWithClipboardAsync(response);
return await Task.FromResult(true);
}, "MAIN_HOTKEY");
await MouseWait(false);
micQueueDebouncer.Restart();
isProcessing = false;
}
private async void Events_OnModalHotkey(object sender, EventArgs e)
{
await HandleHotkey(async () =>
{
// In case hotkeys end up being snowflakes
return await Task.FromResult(true);
});
}
//private async Task<bool> Events_OnModalHotkeyRelease()
private async void Events_OnModalHotkeyRelease(object sender, EventArgs e)
{
//return
await HandleHotkeyRelease(async (response) =>
{
Logger.LogInfo("Adding response to Clipboard...");
await ClipboardHelper.SetTextAsync(response);
#if DEBUG
Logger.LogDebug("Returning");
#else
Logger.LogInfo("Sending response via Modal...");
#endif
windowingService.ForceStatusHide();
await Task.Delay(100); // make sure focus changes are done
await windowingService.CreateModal(response);
return await Task.FromResult(true);
}, "MODAL_HOTKEY");
await MouseWait(false);
micQueueDebouncer.Restart();
isProcessing = false;
}
}
}
| Services/EventHandlerService.cs | dannyr-git-wingman-41103f3 | [
{
"filename": "ViewModels/MainPageViewModel.cs",
"retrieved_chunk": " private string _selectedStdInTarget;\n private string _preprompt;\n public MainPageViewModel(IEditorService editorService, IStdInService stdinService, ISettingsService settingsService, ILoggingService loggingService)\n {\n _editorService = editorService;\n _stdinService = stdinService;\n _loggingService = loggingService;\n InitializeStdInTargetOptions();\n _settingsService = settingsService;\n PrePrompt = _settingsService.Load<string>(WingmanSettings.System_Preprompt);",
"score": 0.8361021876335144
},
{
"filename": "App.xaml.cs",
"retrieved_chunk": " {\n _ = services\n // Services\n .AddSingleton<IGlobalHotkeyService, GlobalHotkeyService>()\n .AddSingleton<ILoggingService, LoggingService>()\n .AddSingleton<IEventHandlerService, EventHandlerService>()\n .AddSingleton<IWindowingService, WindowingService>()\n .AddSingleton<IMicrophoneDeviceService, MicrophoneDeviceService>()\n .AddSingleton<IEditorService, EditorService>()\n .AddSingleton<IStdInService, StdInService>()",
"score": 0.8271958827972412
},
{
"filename": "ViewModels/MainPageViewModel.cs",
"retrieved_chunk": "{\n public class MainPageViewModel : ObservableObject\n {\n private readonly IEditorService _editorService;\n private readonly IStdInService _stdinService;\n private readonly ISettingsService _settingsService;\n private readonly ILoggingService _loggingService;\n private List<string> _stdInTargetOptions = new List<string>();\n private List<Process> _runningProcesses;\n // Selected values",
"score": 0.8134238123893738
},
{
"filename": "Services/MicrophoneDeviceService.cs",
"retrieved_chunk": " private bool _disposing = false;\n private ulong _sampleRate;\n ILoggingService Logger;\n public MicrophoneDeviceService(ILoggingService logger)\n {\n Logger = logger;\n }\n public async Task<IReadOnlyList<MicrophoneDevice>> GetMicrophoneDevicesAsync()\n {\n List<MicrophoneDevice> result = new();",
"score": 0.8101537823677063
},
{
"filename": "Services/GlobalHotkeyService.cs",
"retrieved_chunk": " public class GlobalHotkeyService : IGlobalHotkeyService\n {\n private readonly IKeyboardMouseEvents _hook;\n private readonly Dictionary<WingmanSettings, EventHandler> _hotkeyUpHandlers;\n private readonly Dictionary<WingmanSettings, EventHandler> _hotkeyDownHandlers;\n private readonly ISettingsService _settingsService;\n private readonly Dictionary<HotkeyType, KeyCombination> _cachedValidHotkeys;\n private readonly HashSet<KeyCombination> _currentlyPressedCombinations;\n public GlobalHotkeyService(ISettingsService settingsService)\n {",
"score": 0.806808590888977
}
] | csharp | IWindowingService windowingService
)
{ |
using HarmonyLib;
using System.Collections.Generic;
using System.Reflection;
using System;
using System.Linq;
using System.Xml.Linq;
using UnityEngine;
namespace Ultrapain
{
public static class UnityUtils
{
public static LayerMask envLayer = new LayerMask() { value = (1 << 8) | (1 << 24) };
public static List<T> InsertFill<T>(this List<T> list, int index, T obj)
{
if (index > list.Count)
{
int itemsToAdd = index - list.Count;
for (int i = 0; i < itemsToAdd; i++)
list.Add(default(T));
list.Add(obj);
}
else
list.Insert(index, obj);
return list;
}
public static void PrintGameobject(GameObject o, int iters = 0)
{
string logMessage = "";
for (int i = 0; i < iters; i++)
logMessage += '|';
logMessage += o.name;
Debug.Log(logMessage);
foreach (Transform t in o.transform)
PrintGameobject(t.gameObject, iters + 1);
}
public static IEnumerable<T> GetComponentsInChildrenRecursively<T>(Transform obj)
{
T component;
foreach (Transform child in obj)
{
component = child.gameObject.GetComponent<T>();
if (component != null)
yield return component;
foreach (T childComp in GetComponentsInChildrenRecursively<T>(child))
yield return childComp;
}
yield break;
}
public static T GetComponentInChildrenRecursively<T>(Transform obj)
{
T component;
foreach (Transform child in obj)
{
component = child.gameObject.GetComponent<T>();
if (component != null)
return component;
component = GetComponentInChildrenRecursively<T>(child);
if (component != null)
return component;
}
return default(T);
}
public static | Transform GetChildByNameRecursively(Transform parent, string name)
{ |
foreach(Transform t in parent)
{
if (t.name == name)
return t;
Transform child = GetChildByNameRecursively(t, name);
if (child != null)
return child;
}
return null;
}
public static Transform GetChildByTagRecursively(Transform parent, string tag)
{
foreach (Transform t in parent)
{
if (t.tag == tag)
return t;
Transform child = GetChildByTagRecursively(t, tag);
if (child != null)
return child;
}
return null;
}
public const BindingFlags instanceFlag = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
public const BindingFlags staticFlag = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
public static readonly Func<Vector3, EnemyIdentifier, bool> doNotCollideWithPlayerValidator = (sourcePosition, enemy) => NewMovement.Instance.playerCollider.Raycast(new Ray(sourcePosition, enemy.transform.position - sourcePosition), out RaycastHit hit2, float.MaxValue);
public static List<Tuple<EnemyIdentifier, float>> GetClosestEnemies(Vector3 sourcePosition, int enemyCount, Func<Vector3, EnemyIdentifier, bool> validator)
{
List<Tuple<EnemyIdentifier, float>> targetEnemies = new List<Tuple<EnemyIdentifier, float>>();
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
float sqrMagnitude = (enemy.transform.position - sourcePosition).sqrMagnitude;
if (targetEnemies.Count < enemyCount || sqrMagnitude < targetEnemies.Last().Item2)
{
EnemyIdentifier eid = enemy.GetComponent<EnemyIdentifier>();
if (eid == null || eid.dead || eid.blessed)
continue;
if (Physics.Raycast(sourcePosition, enemy.transform.position - sourcePosition, out RaycastHit hit, Vector3.Distance(sourcePosition, enemy.transform.position) - 0.5f, envLayer))
continue;
if (!validator(sourcePosition, eid))
continue;
if (targetEnemies.Count == 0)
{
targetEnemies.Add(new Tuple<EnemyIdentifier, float>(eid, sqrMagnitude));
continue;
}
int insertionPoint = targetEnemies.Count;
while (insertionPoint != 0 && targetEnemies[insertionPoint - 1].Item2 > sqrMagnitude)
insertionPoint -= 1;
targetEnemies.Insert(insertionPoint, new Tuple<EnemyIdentifier, float>(eid, sqrMagnitude));
if (targetEnemies.Count > enemyCount)
targetEnemies.RemoveAt(enemyCount);
}
}
return targetEnemies;
}
public static T GetRandomIntWeightedItem<T>(IEnumerable<T> itemsEnumerable, Func<T, int> weightKey)
{
var items = itemsEnumerable.ToList();
var totalWeight = items.Sum(x => weightKey(x));
var randomWeightedIndex = UnityEngine.Random.RandomRangeInt(0, totalWeight);
var itemWeightedIndex = 0;
foreach (var item in items)
{
itemWeightedIndex += weightKey(item);
if (randomWeightedIndex < itemWeightedIndex)
return item;
}
throw new ArgumentException("Collection count and weights must be greater than 0");
}
public static T GetRandomFloatWeightedItem<T>(IEnumerable<T> itemsEnumerable, Func<T, float> weightKey)
{
var items = itemsEnumerable.ToList();
var totalWeight = items.Sum(x => weightKey(x));
var randomWeightedIndex = UnityEngine.Random.Range(0, totalWeight);
var itemWeightedIndex = 0f;
foreach (var item in items)
{
itemWeightedIndex += weightKey(item);
if (randomWeightedIndex < itemWeightedIndex)
return item;
}
throw new ArgumentException("Collection count and weights must be greater than 0");
}
}
}
| Ultrapain/UnityUtils.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " protected override void OnCreateUI(RectTransform fieldUI)\n {\n currentUI = fieldUI;\n fieldUI.sizeDelta = new Vector2(fieldUI.sizeDelta.x, space);\n }\n }\n public static class ConfigManager\n {\n public static PluginConfigurator config = null;\n public static void AddMissingPresets()",
"score": 0.7674334049224854
},
{
"filename": "Ultrapain/Patches/CommonComponents.cs",
"retrieved_chunk": " public Quaternion targetRotation;\n private void Awake()\n {\n transform.rotation = targetRotation;\n }\n }\n public class CommonActivator : MonoBehaviour\n {\n public int originalId;\n public Renderer rend;",
"score": 0.7607486248016357
},
{
"filename": "Ultrapain/Plugin.cs",
"retrieved_chunk": " public static void UpdateID(string id, string newName)\n {\n if (!registered || StyleHUD.Instance == null)\n return;\n (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName;\n }\n }\n public static Harmony harmonyTweaks;\n public static Harmony harmonyBase;\n private static MethodInfo GetMethod<T>(string name)",
"score": 0.7566819190979004
},
{
"filename": "Ultrapain/Patches/CommonComponents.cs",
"retrieved_chunk": " public MonoBehaviour activator;\n void Start()\n {\n if (gameObject.GetInstanceID() == originalInstanceID)\n return;\n activator?.Invoke(\"OnClone\", 0f);\n }\n }*/\n public class CommonLinearScaler : MonoBehaviour\n {",
"score": 0.7534738779067993
},
{
"filename": "Ultrapain/Patches/SwordsMachine.cs",
"retrieved_chunk": " sm.SendMessage(\"SetSpeed\");\n }\n private void Awake()\n {\n anim = GetComponent<Animator>();\n eid = GetComponent<EnemyIdentifier>();\n }\n public float speed = 1f;\n private void Update()\n {",
"score": 0.7500846982002258
}
] | csharp | Transform GetChildByNameRecursively(Transform parent, string name)
{ |
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using UnityEngine;
namespace QuestSystem.SaveSystem
{
public class QuestLogSaveDataSurrogate : ISerializationSurrogate
{
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
QuestLog ql = (QuestLog)obj;
info.AddValue("curentQuest", ql.curentQuests);
info.AddValue("doneQuest", ql.doneQuest);
info.AddValue("failedQuest", ql.failedQuest);
info.AddValue("businessDay", ql.businessDay);
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
QuestLog ql = (QuestLog)obj;
ql.curentQuests = (List<Quest>)info.GetValue("curentQuest", typeof(List<Quest>));
ql.doneQuest = (List<Quest>)info.GetValue("doneQuest", typeof(List<Quest>));
ql.failedQuest = (List<Quest>)info.GetValue("failedQuest", typeof(List<Quest>));
ql.businessDay = (int)info.GetValue("businessDay", typeof(int));
obj = ql;
return obj;
}
}
[System.Serializable]
public class QuestLogSaveData
{
public List< | QuestSaveData> currentQuestSave; |
public List<QuestSaveData> doneQuestSave;
public List<QuestSaveData> failedQuestSave;
public int dia;
public QuestLogSaveData(QuestLog ql)
{
//Manage current quest
currentQuestSave = new List<QuestSaveData>();
doneQuestSave = new List<QuestSaveData>();
failedQuestSave = new List<QuestSaveData>();
foreach (Quest q in ql.curentQuests)
{
QuestSaveData aux = new QuestSaveData();
aux.name = q.misionName;
aux.states = q.state;
aux.actualNodeData = new NodeQuestSaveData(q.nodeActual.nodeObjectives.Length);
for (int i = 0; i < q.nodeActual.nodeObjectives.Length; i++)
aux.actualNodeData.objectives[i] = q.nodeActual.nodeObjectives[i];
currentQuestSave.Add(aux);
}
foreach (Quest q in ql.doneQuest)
{
QuestSaveData aux = new QuestSaveData();
aux.name = q.misionName;
currentQuestSave.Add(aux);
}
foreach (Quest q in ql.failedQuest)
{
QuestSaveData aux = new QuestSaveData();
aux.name = q.misionName;
currentQuestSave.Add(aux);
}
dia = ql.businessDay;
}
}
} | Runtime/SaveData/QuestLogSaveDataSurrogate.cs | lluispalerm-QuestSystem-cd836cc | [
{
"filename": "Runtime/SaveData/NodeQuestSaveDataSurrogate.cs",
"retrieved_chunk": " obj = nq;\n return obj;\n }\n }\n [System.Serializable]\n public class NodeQuestSaveData\n {\n public QuestObjective[] objectives;\n public NodeQuestSaveData()\n {",
"score": 0.8853298425674438
},
{
"filename": "Runtime/SaveData/QuestSaveDataSurrogate.cs",
"retrieved_chunk": " return obj;\n }\n }\n [System.Serializable]\n public class QuestSaveData\n {\n public List<int> states;\n public string name;\n public NodeQuestSaveData actualNodeData;\n }",
"score": 0.8634192943572998
},
{
"filename": "Runtime/SaveData/NodeQuestSaveDataSurrogate.cs",
"retrieved_chunk": " objectives = new QuestObjective[1];\n }\n public NodeQuestSaveData(int i)\n {\n objectives = new QuestObjective[i];\n }\n }\n}",
"score": 0.8348289728164673
},
{
"filename": "Runtime/QuestOnObjectWorld.cs",
"retrieved_chunk": " public ActivationRowNode[] tableNodes;\n }\n [System.Serializable]\n public struct ActivationRowNode\n {\n public NodeQuest node;\n public bool activate;\n }\n public ObjectsForQuestTable[] objectsForQuestTable;\n public GameObject[] objectsToControlList;",
"score": 0.8191709518432617
},
{
"filename": "Runtime/QuestObjectiveUpdater.cs",
"retrieved_chunk": " returnList.Add(nodeToUpdate.nodeObjectives[i].keyName);\n }\n }\n }\n return returnList.ToArray();\n }\n public void Interact()\n {\n if (isAbleToUpdateQuest())\n {",
"score": 0.801263689994812
}
] | csharp | QuestSaveData> currentQuestSave; |
#nullable disable
using System;
using System.Text;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Logging;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Gengo.Cards;
using osu.Game.Graphics.Sprites;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Gengo.UI.Translation
{
/// <summary>
/// Container responsible for showing the two translation words
/// </summary>
public partial class TranslationContainer : GridContainer {
private List< | Card> translationsLine = new List<Card>(); |
private List<Card> fakesLine = new List<Card>();
public OsuSpriteText leftWordText;
public OsuSpriteText rightWordText;
[Resolved]
protected IBeatmap beatmap { get; set; }
private Random leftRightOrderRandom;
/// <summary>
/// Function to update the text of the two translation words (<see cref="leftWordText"/>, <see cref="rightWordText"/>)
/// </summary>
public void UpdateWordTexts() {
if (translationsLine.Count <= 0 || fakesLine.Count <= 0)
return;
// Randomly (seeded by the hash of the beatmap) decide whether the left or right word will be the bait/correct translation of the current HitObject
if (leftRightOrderRandom.NextDouble() > 0.5) {
leftWordText.Text = translationsLine[0].translatedText;
rightWordText.Text = fakesLine[0].translatedText;
} else {
leftWordText.Text = fakesLine[0].translatedText;
rightWordText.Text = translationsLine[0].translatedText;
}
}
/// <summary>
/// Function to add a new card to record. (function takes a fake card as well)
/// </summary>
public void AddCard(Card translationCard, Card fakeCard) {
translationsLine.Add(translationCard);
fakesLine.Add(fakeCard);
if (translationsLine.Count == 1)
UpdateWordTexts();
}
/// <summary>
/// Function to remove the first card (translation + fake) from their lines
/// </summary>
public void RemoveCard() {
if (translationsLine.Count <= 0)
return;
translationsLine.RemoveAt(0);
fakesLine.RemoveAt(0);
UpdateWordTexts();
}
[BackgroundDependencyLoader]
public void load() {
// convert from string -> bytes -> int32
int beatmapHash = BitConverter.ToInt32(Encoding.UTF8.GetBytes(beatmap.BeatmapInfo.Hash), 0);
leftRightOrderRandom = new Random(beatmapHash);
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Anchor = Anchor.TopCentre;
Origin = Anchor.TopCentre;
ColumnDimensions = new[] {
new Dimension(GridSizeMode.Distributed),
new Dimension(GridSizeMode.Distributed),
};
RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize) };
Content = new[] {
new[] {
new CircularContainer {
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Masking = true,
CornerRadius = Size.X / 2,
CornerExponent = 2,
BorderColour = Color4.Black,
BorderThickness = 4f,
Children = new Drawable[] {
new Box {
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = Color4.Red,
},
leftWordText = new OsuSpriteText {
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = Color4.Black,
Text = "-",
Font = new FontUsage(size: 20f),
Margin = new MarginPadding(8f),
},
},
},
new CircularContainer {
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Masking = true,
CornerRadius = Size.X / 2,
CornerExponent = 2,
BorderColour = Color4.Black,
BorderThickness = 4f,
Children = new Drawable[] {
new Box {
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = Color4.Red,
},
rightWordText = new OsuSpriteText {
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = Color4.Black,
Text = "-",
Font = new FontUsage(size: 20f),
Margin = new MarginPadding(8f),
},
},
}
}
};
}
}
} | osu.Game.Rulesets.Gengo/UI/Translation/TranslationContainer.cs | 0xdeadbeer-gengo-dd4f78d | [
{
"filename": "osu.Game.Rulesets.Gengo/Configuration/GengoRulesetConfigManager.cs",
"retrieved_chunk": "using osu.Game.Configuration; \nusing osu.Game.Rulesets.Configuration;\nusing osu.Game.Rulesets.UI; \nnamespace osu.Game.Rulesets.Gengo.Configuration \n{\n public class GengoRulesetConfigManager : RulesetConfigManager<GengoRulesetSetting> {\n public GengoRulesetConfigManager(SettingsStore? settings, RulesetInfo ruleset, int? variant = null)\n : base(settings, ruleset, variant) \n {\n }",
"score": 0.7962544560432434
},
{
"filename": "osu.Game.Rulesets.Gengo.Tests/TestSceneOsuPlayer.cs",
"retrieved_chunk": "// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.\n// See the LICENCE file in the repository root for full licence text.\nusing NUnit.Framework;\nusing osu.Game.Tests.Visual;\nnamespace osu.Game.Rulesets.Gengo.Tests\n{\n [TestFixture]\n public partial class TestSceneOsuPlayer : PlayerTestScene\n {\n protected override Ruleset CreatePlayerRuleset() => new GengoRuleset();",
"score": 0.7872374057769775
},
{
"filename": "osu.Game.Rulesets.Gengo/UI/Cursor/GengoCursorContainer.cs",
"retrieved_chunk": "using osu.Game.Screens.Play;\nusing osu.Game.Beatmaps;\nusing osuTK;\nnamespace osu.Game.Rulesets.Gengo.UI.Cursor\n{\n public partial class GengoCursorContainer : GameplayCursorContainer\n {\n public IBindable<float> CursorScale => cursorScale;\n private readonly Bindable<float> cursorScale = new BindableFloat(1);\n private Bindable<float> userCursorScale;",
"score": 0.7857856154441833
},
{
"filename": "osu.Game.Rulesets.Gengo/UI/Cursor/GengoCursor.cs",
"retrieved_chunk": "namespace osu.Game.Rulesets.Gengo.UI.Cursor\n{\n public partial class GengoCursor : SkinReloadableDrawable\n {\n private const float size = 45;\n private Sprite cursorSprite;\n public GengoCursor()\n {\n Origin = Anchor.Centre;\n Size = new Vector2(size);",
"score": 0.776375412940979
},
{
"filename": "osu.Game.Rulesets.Gengo/Cards/Card.cs",
"retrieved_chunk": "using System;\nnamespace osu.Game.Rulesets.Gengo.Cards \n{\n public class Card : IEquatable<Card> {\n public string foreignText { get; set; }\n public string translatedText { get; set; }\n public string cardID { get; set; }\n public Card(string foreignText, string translatedText, string cardID) {\n this.foreignText = foreignText;\n this.translatedText = translatedText;",
"score": 0.7748391032218933
}
] | csharp | Card> translationsLine = new List<Card>(); |
#nullable enable
using System.Collections.Generic;
using Mochineko.Relent.Result;
namespace Mochineko.RelentStateMachine
{
internal sealed class TransitionMap<TEvent, TContext>
: ITransitionMap<TEvent, TContext>
{
private readonly IState<TEvent, TContext> initialState;
private readonly IReadOnlyList<IState<TEvent, TContext>> states;
private readonly IReadOnlyDictionary<
IState<TEvent, TContext>,
IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>
transitionMap;
private readonly IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>
anyTransitionMap;
public TransitionMap(
IState<TEvent, TContext> initialState,
IReadOnlyList<IState<TEvent, TContext>> states,
IReadOnlyDictionary<
IState<TEvent, TContext>,
IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>
transitionMap,
IReadOnlyDictionary<TEvent, IState<TEvent, TContext>> anyTransitionMap)
{
this.initialState = initialState;
this.states = states;
this.transitionMap = transitionMap;
this.anyTransitionMap = anyTransitionMap;
}
IState<TEvent, TContext> ITransitionMap<TEvent, TContext>.InitialState
=> initialState;
IResult<IState<TEvent, TContext>> | ITransitionMap<TEvent, TContext>.AllowedToTransit(
IState<TEvent, TContext> currentState,
TEvent @event)
{ |
if (transitionMap.TryGetValue(currentState, out var candidates))
{
if (candidates.TryGetValue(@event, out var nextState))
{
return Results.Succeed(nextState);
}
}
if (anyTransitionMap.TryGetValue(@event, out var nextStateFromAny))
{
return Results.Succeed(nextStateFromAny);
}
return Results.Fail<IState<TEvent, TContext>>(
$"Not found transition from {currentState.GetType()} with event {@event}.");
}
public void Dispose()
{
foreach (var state in states)
{
state.Dispose();
}
}
}
} | Assets/Mochineko/RelentStateMachine/TransitionMap.cs | mochi-neko-RelentStateMachine-64762eb | [
{
"filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs",
"retrieved_chunk": " private readonly Dictionary<IState<TEvent, TContext>, Dictionary<TEvent, IState<TEvent, TContext>>>\n transitionMap = new();\n private readonly Dictionary<TEvent, IState<TEvent, TContext>>\n anyTransitionMap = new();\n private bool disposed = false;\n public static TransitionMapBuilder<TEvent, TContext> Create<TInitialState>()\n where TInitialState : IState<TEvent, TContext>, new()\n {\n var initialState = new TInitialState();\n return new TransitionMapBuilder<TEvent, TContext>(initialState);",
"score": 0.9183538556098938
},
{
"filename": "Assets/Mochineko/RelentStateMachine/ITransitionMap.cs",
"retrieved_chunk": "#nullable enable\nusing System;\nusing Mochineko.Relent.Result;\nnamespace Mochineko.RelentStateMachine\n{\n public interface ITransitionMap<TEvent, TContext> : IDisposable\n {\n internal IState<TEvent, TContext> InitialState { get; }\n internal IResult<IState<TEvent, TContext>> AllowedToTransit(IState<TEvent, TContext> currentState, TEvent @event);\n }",
"score": 0.913100004196167
},
{
"filename": "Assets/Mochineko/RelentStateMachine/ITransitionMapBuilder.cs",
"retrieved_chunk": "#nullable enable\nusing System;\nnamespace Mochineko.RelentStateMachine\n{\n public interface ITransitionMapBuilder<TEvent, TContext> : IDisposable\n {\n void RegisterTransition<TFromState, TToState>(TEvent @event)\n where TFromState : IState<TEvent, TContext>, new()\n where TToState : IState<TEvent, TContext>, new();\n void RegisterAnyTransition<TToState>(TEvent @event)",
"score": 0.8876045346260071
},
{
"filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs",
"retrieved_chunk": "#nullable enable\nusing System;\nusing System.Collections.Generic;\nnamespace Mochineko.RelentStateMachine\n{\n public sealed class TransitionMapBuilder<TEvent, TContext>\n : ITransitionMapBuilder<TEvent, TContext>\n {\n private readonly IState<TEvent, TContext> initialState;\n private readonly List<IState<TEvent, TContext>> states = new();",
"score": 0.8867391347885132
},
{
"filename": "Assets/Mochineko/RelentStateMachine/ITransitionMapBuilder.cs",
"retrieved_chunk": " where TToState : IState<TEvent, TContext>, new();\n ITransitionMap<TEvent, TContext> Build();\n }\n}",
"score": 0.8810023069381714
}
] | csharp | ITransitionMap<TEvent, TContext>.AllowedToTransit(
IState<TEvent, TContext> currentState,
TEvent @event)
{ |
using UnityEditor;
using UnityEditor.Timeline;
using UnityEngine;
using UnityEngine.Timeline;
namespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor
{
internal static class AbstractIntValueControlTrackEditorUtility
{
internal static Color PrimaryColor = new(1f, 1f, 0.5f);
}
[CustomTimelineEditor(typeof(AbstractIntValueControlTrack))]
public class AbstractIntValueControlTrackCustomEditor : TrackEditor
{
public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)
{
track.name = "CustomTrack";
var options = base.GetTrackOptions(track, binding);
options.trackColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor;
return options;
}
}
[CustomTimelineEditor(typeof( | AbstractIntValueControlClip))]
public class AbstractIntValueControlCustomEditor : ClipEditor
{ |
public override ClipDrawOptions GetClipOptions(TimelineClip clip)
{
var clipOptions = base.GetClipOptions(clip);
clipOptions.icons = null;
clipOptions.highlightColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor;
return clipOptions;
}
}
[CanEditMultipleObjects]
[CustomEditor(typeof(AbstractIntValueControlClip))]
public class AbstractIntValueControlClipEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
}
}
} | Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs | nmxi-Unity_AbstractTimelineExtention-b518049 | [
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractBoolValueControlTrack))]\n public class AbstractBoolValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractBoolValueControlTrackEditorUtility.PrimaryColor;\n // Debug.Log(binding.GetType());",
"score": 0.925287127494812
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractColorValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractColorValueControlTrack))]\n public class AbstractColorValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractColorValueControlTrackEditorUtility.PrimaryColor;\n return options;",
"score": 0.9242088794708252
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs",
"retrieved_chunk": " [CustomTimelineEditor(typeof(AbstractFloatValueControlTrack))]\n public class AbstractFloatValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor;\n return options;\n }",
"score": 0.9136970639228821
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractFloatValueControlClip))]\n public class AbstractFloatValueControlCustomEditor : ClipEditor\n {\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);\n clipOptions.icons = null;\n clipOptions.highlightColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor;\n return clipOptions;",
"score": 0.8897281885147095
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs",
"retrieved_chunk": " return options;\n }\n }\n [CustomTimelineEditor(typeof(AbstractBoolValueControlClip))]\n public class AbstractBoolValueControlCustomEditor : ClipEditor\n {\n Dictionary<AbstractBoolValueControlClip, Texture2D> textures = new();\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);",
"score": 0.8868575692176819
}
] | csharp | AbstractIntValueControlClip))]
public class AbstractIntValueControlCustomEditor : ClipEditor
{ |
using System;
using System.Diagnostics;
using System.Text;
namespace Gum.InnerThoughts
{
[DebuggerDisplay("{DebuggerDisplay(),nq}")]
public class Block
{
public readonly int Id = 0;
/// <summary>
/// Stop playing this dialog until this number.
/// If -1, this will play forever.
/// </summary>
public int PlayUntil = -1;
public readonly List<CriterionNode> Requirements = new();
public readonly List< | Line> Lines = new(); |
public List<DialogAction>? Actions = null;
/// <summary>
/// Go to another dialog with a specified id.
/// If this is -1, it will immediately exit the dialog interaction.
/// </summary>
public int? GoTo = null;
public bool NonLinearNode = false;
public bool IsChoice = false;
public bool Conditional = false;
public Block() { }
public Block(int id) { Id = id; }
public Block(int id, int playUntil) { (Id, PlayUntil) = (id, playUntil); }
public void AddLine(string? speaker, string? portrait, string text)
{
Lines.Add(new(speaker, portrait, text));
}
public void AddRequirement(CriterionNode node)
{
Requirements.Add(node);
}
public void AddAction(DialogAction action)
{
Actions ??= new();
Actions.Add(action);
}
public void Exit()
{
GoTo = -1;
}
public string DebuggerDisplay()
{
StringBuilder result = new();
_ = result.Append(
$"[{Id}, Requirements = {Requirements.Count}, Lines = {Lines.Count}, Actions = {Actions?.Count ?? 0}]");
return result.ToString();
}
}
}
| src/Gum/InnerThoughts/Block.cs | isadorasophia-gum-032cb2d | [
{
"filename": "src/Gum/InnerThoughts/Line.cs",
"retrieved_chunk": " public readonly string? Portrait = null;\n /// <summary>\n /// If the caption has a text, this will be the information.\n /// </summary>\n public readonly string? Text = null;\n /// <summary>\n /// Delay in seconds.\n /// </summary>\n public readonly float? Delay = null;\n public Line() { }",
"score": 0.9101094007492065
},
{
"filename": "src/Gum/InnerThoughts/Situation.cs",
"retrieved_chunk": " [JsonProperty]\n public readonly string Name = string.Empty;\n public int Root = 0;\n public readonly List<Block> Blocks = new();\n /// <summary>\n /// This points\n /// [ Node Id -> Edge ]\n /// </summary>\n public readonly Dictionary<int, Edge> Edges = new();\n /// <summary>",
"score": 0.8858363628387451
},
{
"filename": "src/Gum/InnerThoughts/Situation.cs",
"retrieved_chunk": " /// This points\n /// [ Node Id -> Parent ]\n /// If parent is empty, this is at the top.\n /// </summary>\n public readonly Dictionary<int, HashSet<int>> ParentOf = new();\n private readonly Stack<int> _lastBlocks = new();\n public Situation() { }\n public Situation(int id, string name)\n {\n Id = id;",
"score": 0.871511697769165
},
{
"filename": "src/Gum/Parser.cs",
"retrieved_chunk": " _random = false;\n return random;\n }\n /// <summary>\n /// The last directive '@' to play an amount of times.\n /// </summary>\n private int _playUntil = -1;\n private int ConsumePlayUntil()\n {\n int playUntil = _playUntil;",
"score": 0.8650462031364441
},
{
"filename": "src/Gum/Parser_Requirements.cs",
"retrieved_chunk": " }\n public partial class Parser\n {\n /// <summary>\n /// Read the next criterion.\n /// </summary>\n /// <param name=\"line\"></param>\n /// <param name=\"node\">\n /// The resulting node. Only valid if it was able to read a non-empty valid\n /// requirement syntax.",
"score": 0.8645638227462769
}
] | csharp | Line> Lines = new(); |
// -------------------------------------------------------------
// Copyright (c) - The Standard Community - All rights reserved.
// -------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Standard.REST.RESTFulSense.Models.Foundations.StatusDetails;
using Standard.REST.RESTFulSense.Models.Foundations.StatusDetails.Exceptions;
using Xeptions;
namespace Standard.REST.RESTFulSense.Services.Foundations.StatusDetails
{
internal partial class StatusDetailService
{
private delegate IQueryable<StatusDetail> ReturningStatusDetailsFunction();
private delegate StatusDetail ReturningStatusDetailFunction();
private IQueryable< | StatusDetail> TryCatch(ReturningStatusDetailsFunction returningStatusDetailsFunction)
{ |
try
{
return returningStatusDetailsFunction();
}
catch (JsonReaderException jsonReaderException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonReaderException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (JsonSerializationException jsonSerializationException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonSerializationException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (JsonException jsonException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (ArgumentNullException argumentNullException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(argumentNullException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (ArgumentException argumentException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(argumentException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (PathTooLongException pathTooLongException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(pathTooLongException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(directoryNotFoundException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (FileNotFoundException fileNotFoundException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(fileNotFoundException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(unauthorizedAccessException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (NotSupportedException notSupportedException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(notSupportedException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (IOException iOException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(iOException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (Exception exception)
{
var failedStatusDetailServiceException =
new FailedStatusDetailServiceException(exception);
throw CreateAndLogServiceException(failedStatusDetailServiceException);
}
}
private StatusDetail TryCatch(ReturningStatusDetailFunction returningStatusDetailFunction)
{
try
{
return returningStatusDetailFunction();
}
catch (NotFoundStatusDetailException notFoundStatusDetailException)
{
throw CreateAndLogValidationException(notFoundStatusDetailException);
}
catch (JsonReaderException jsonReaderException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonReaderException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (JsonSerializationException jsonSerializationException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonSerializationException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (JsonException jsonException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (ArgumentNullException argumentNullException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(argumentNullException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (ArgumentException argumentException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(argumentException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (PathTooLongException pathTooLongException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(pathTooLongException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(directoryNotFoundException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (FileNotFoundException fileNotFoundException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(fileNotFoundException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(unauthorizedAccessException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (NotSupportedException notSupportedException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(notSupportedException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (IOException iOException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(iOException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (Exception exception)
{
var failedStatusDetailServiceException =
new FailedStatusDetailServiceException(exception);
throw CreateAndLogServiceException(failedStatusDetailServiceException);
}
}
private StatusDetailDependencyException CreateAndLogDependencyException(Xeption exception)
{
var statusDetailDependencyException =
new StatusDetailDependencyException(exception);
return statusDetailDependencyException;
}
private StatusDetailValidationException CreateAndLogValidationException(Xeption exception)
{
var statusDetailValidationException =
new StatusDetailValidationException(exception);
return statusDetailValidationException;
}
private StatusDetailServiceException CreateAndLogServiceException(Xeption exception)
{
var statusDetailServiceException =
new StatusDetailServiceException(exception);
return statusDetailServiceException;
}
}
}
| Standard.REST.RESTFulSense/Services/Foundations/StatusDetails/StatusDetailService.Exceptions.cs | The-Standard-Organization-Standard.REST.RESTFulSense-7598bbe | [
{
"filename": "Standard.REST.RESTFulSense.Tests.Unit/Services/Foundations/StatusDetails/StatusDetailServiceTests.Logic.RetrieveStatusDetailByStatusCode.cs",
"retrieved_chunk": "namespace Standard.REST.RESTFulSense.Tests.Unit.Services.Foundations.StatusDetails\n{\n public partial class StatusDetailServiceTests\n {\n [Fact]\n public void ShouldReturnStatusDetailByStatusCode()\n {\n // given\n int randomNumber = GetRandomNumber();\n int randomStatusCode = 400 + randomNumber;",
"score": 0.8390504121780396
},
{
"filename": "Standard.REST.RESTFulSense.Tests.Unit/Services/Foundations/StatusDetails/StatusDetailServiceTests.Validations.RetrieveStatusDetailByStatusCode.cs",
"retrieved_chunk": "namespace Standard.REST.RESTFulSense.Tests.Unit.Services.Foundations.StatusDetails\n{\n public partial class StatusDetailServiceTests\n {\n [Fact]\n public void ShouldThrowNotFoundExceptionOnRetrieveByIdIfStatusDetailIsNotFound()\n {\n // given\n int randomNumber = GetRandomNumber();\n int randomStatusCode = randomNumber;",
"score": 0.8372673988342285
},
{
"filename": "Standard.REST.RESTFulSense/Services/Foundations/StatusDetails/StatusDetailService.cs",
"retrieved_chunk": " private readonly IStorageBroker storageBroker;\n public StatusDetailService(IStorageBroker storageBroker) =>\n this.storageBroker = storageBroker;\n public IQueryable<StatusDetail> RetrieveAllStatusDetails() =>\n TryCatch(() => this.storageBroker.SelectAllStatusDetails());\n public StatusDetail RetrieveStatusDetailByCode(int statusCode) =>\n TryCatch(() =>\n {\n StatusDetail maybeStatusDetail = this.storageBroker.SelectAllStatusDetails()\n .FirstOrDefault(statusDetail => statusDetail.Code == statusCode);",
"score": 0.8241531848907471
},
{
"filename": "Standard.REST.RESTFulSense/Services/Foundations/StatusDetails/IStatusDetailService.cs",
"retrieved_chunk": "// -------------------------------------------------------------\n// Copyright (c) - The Standard Community - All rights reserved.\n// -------------------------------------------------------------\nusing System.Linq;\nusing Standard.REST.RESTFulSense.Models.Foundations.StatusDetails;\ninternal interface IStatusDetailService\n{\n IQueryable<StatusDetail> RetrieveAllStatusDetails();\n StatusDetail RetrieveStatusDetailByCode(int statusCode);\n}",
"score": 0.8226488828659058
},
{
"filename": "Standard.REST.RESTFulSense/Models/Foundations/StatusDetails/Exceptions/FailedStatusDetailServiceException.cs",
"retrieved_chunk": "// -------------------------------------------------------------\n// Copyright (c) - The Standard Community - All rights reserved.\n// -------------------------------------------------------------\nusing System;\nusing Xeptions;\nnamespace Standard.REST.RESTFulSense.Models.Foundations.StatusDetails.Exceptions\n{\n public class FailedStatusDetailServiceException : Xeption\n {\n public FailedStatusDetailServiceException(Exception innerException)",
"score": 0.8176411390304565
}
] | csharp | StatusDetail> TryCatch(ReturningStatusDetailsFunction returningStatusDetailsFunction)
{ |
using NowPlaying.Models;
using NowPlaying.Utils;
using Playnite.SDK;
using System;
using System.Timers;
using System.Windows.Controls;
namespace NowPlaying.ViewModels
{
public class InstallProgressViewModel : ViewModelBase
{
private readonly NowPlaying plugin;
private readonly NowPlayingInstallController controller;
private readonly GameCacheManagerViewModel cacheManager;
private readonly GameCacheViewModel gameCache;
private readonly RoboStats jobStats;
private readonly Timer speedEtaRefreshTimer;
private readonly long speedEtaInterval = 500; // calc avg speed, Eta every 1/2 second
private long totalBytesCopied;
private long prevTotalBytesCopied;
private bool preparingToInstall;
public bool PreparingToInstall
{
get => preparingToInstall;
set
{
if (preparingToInstall != value)
{
preparingToInstall = value;
OnPropertyChanged();
OnPropertyChanged(nameof(CopiedFilesAndBytesProgress));
OnPropertyChanged(nameof(CurrentFile));
OnPropertyChanged(nameof(SpeedDurationEta));
OnPropertyChanged(nameof(ProgressBgBrush));
OnPropertyChanged(nameof(ProgressValue));
}
}
}
private int speedLimitIpg;
public int SpeedLimitIpg
{
get => speedLimitIpg;
set
{
if (speedLimitIpg != value)
{
speedLimitIpg = value;
OnPropertyChanged();
OnPropertyChanged(nameof(ProgressPanelTitle));
OnPropertyChanged(nameof(ProgressTitleBrush));
OnPropertyChanged(nameof(ProgressBarBrush));
}
}
}
public RelayCommand PauseInstallCommand { get; private set; }
public RelayCommand CancelInstallCommand { get; private set; }
public string GameTitle => gameCache.Title;
public string InstallSize => SmartUnits.Bytes(gameCache.InstallSize);
//
// Real-time GameCacheJob Statistics
//
private string formatStringCopyingFile;
private string formatStringCopyingFilePfr;
private string formatStringXofY;
private string formatStringFilesAndBytes;
private string formatStringSpeedDurationEta;
private double percentDone;
private long filesCopied;
private int bytesScale;
private string bytesCopied;
private string bytesToCopy;
private string copiedFilesOfFiles;
private string copiedBytesOfBytes;
private string currentFile;
private long currentFileSize;
private bool partialFileResume;
private string duration;
private string timeRemaining;
private string currentSpeed;
private string averageSpeed;
// . Transfer speed rolling averages
public RollingAvgLong currSpeedRollAvgBps;
public | RollingAvgLong averageSpeedRollAvgBps; |
private readonly int currSpeedRollAvgDepth = 32; // current speed → 16 second rolling average
private readonly int averageSpeedRollAvgDepth = 256; // average speed → approx 4 minute rolling average
public string ProgressPanelTitle =>
(
speedLimitIpg > 0 ? plugin.FormatResourceString("LOCNowPlayingProgressSpeedLimitTitleFmt2", speedLimitIpg, GameTitle) :
plugin.FormatResourceString("LOCNowPlayingProgressTitleFmt", GameTitle)
);
public string ProgressTitleBrush => speedLimitIpg > 0 ? "SlowInstallBrush" : "GlyphBrush";
public string ProgressValue => PreparingToInstall ? "" : $"{percentDone:n1}%";
public double PercentDone => percentDone;
public string ProgressBarBrush => speedLimitIpg > 0 ? "TopPanelSlowInstallFgBrush" : "TopPanelInstallFgBrush";
public string ProgressBgBrush => PreparingToInstall ? "TopPanelProcessingBgBrush" : "TransparentBgBrush";
public string CopiedFilesAndBytesProgress =>
(
PreparingToInstall
? plugin.GetResourceString("LOCNowPlayingPreparingToInstall")
: string.Format(formatStringFilesAndBytes, copiedFilesOfFiles, copiedBytesOfBytes)
);
public string CurrentFile =>
(
PreparingToInstall ? "" :
partialFileResume ? string.Format(formatStringCopyingFilePfr, currentFile, SmartUnits.Bytes(currentFileSize)) :
string.Format(formatStringCopyingFile, currentFile, SmartUnits.Bytes(currentFileSize))
);
public string SpeedDurationEta =>
(
PreparingToInstall ? "" : string.Format(formatStringSpeedDurationEta, currentSpeed, averageSpeed, duration, timeRemaining)
);
public InstallProgressViewModel(NowPlayingInstallController controller, int speedLimitIpg=0, bool partialFileResume=false)
{
this.plugin = controller.plugin;
this.controller = controller;
this.cacheManager = controller.cacheManager;
this.jobStats = controller.jobStats;
this.gameCache = controller.gameCache;
this.PauseInstallCommand = new RelayCommand(() => controller.RequestPauseInstall());
this.CancelInstallCommand = new RelayCommand(() => controller.RequestCancellInstall());
this.speedEtaRefreshTimer = new Timer() { Interval = speedEtaInterval };
this.formatStringCopyingFile = (plugin.GetResourceString("LOCNowPlayingTermsCopying") ?? "Copying") + " '{0}' ({1})...";
this.formatStringCopyingFilePfr = (plugin.GetResourceString("LOCNowPlayingTermsCopying") ?? "Copying") + " '{0}' ({1}) ";
this.formatStringCopyingFilePfr += (plugin.GetResourceString("LOCNowPlayingWithPartialFileResume") ?? "w/partial file resume") + "...";
this.formatStringXofY = plugin.GetResourceFormatString("LOCNowPlayingProgressXofYFmt2", 2) ?? "{0} of {1}";
this.formatStringFilesAndBytes = plugin.GetResourceFormatString("LOCNowPlayingProgressFilesAndBytesFmt2", 2) ?? "{0} files, {1} copied";
this.formatStringSpeedDurationEta = (plugin.GetResourceString("LOCNowPlayingTermsSpeed") ?? "Speed") + ": {0}, ";
this.formatStringSpeedDurationEta += (plugin.GetResourceString("LOCNowPlayingTermsAvgSpeed") ?? "Average speed") + ": {1}, ";
this.formatStringSpeedDurationEta += (plugin.GetResourceString("LOCNowPlayingTermsDuration") ?? "Duration") + ": {2}, ";
this.formatStringSpeedDurationEta += (plugin.GetResourceString("LOCNowPlayingTermsEta") ?? "ETA") + ": {3}";
PrepareToInstall(speedLimitIpg, partialFileResume);
}
public void PrepareToInstall(int speedLimitIpg=0, bool partialFileResume=false)
{
// . Start in "Preparing to install..." state; until job is underway & statistics are updated
this.PreparingToInstall = true;
this.SpeedLimitIpg = speedLimitIpg;
this.partialFileResume = partialFileResume;
cacheManager.gameCacheManager.eJobStatsUpdated += OnJobStatsUpdated;
cacheManager.gameCacheManager.eJobCancelled += OnJobDone;
cacheManager.gameCacheManager.eJobDone += OnJobDone;
speedEtaRefreshTimer.Elapsed += OnSpeedEtaRefreshTimerElapsed;
this.currentSpeed = "-";
// . initialize any rolling average stats
var avgBytesPerFile = gameCache.InstallSize / gameCache.InstallFiles;
var avgBps = cacheManager.GetInstallAverageBps(gameCache.InstallDir, avgBytesPerFile, speedLimitIpg);
this.currSpeedRollAvgBps = new RollingAvgLong(currSpeedRollAvgDepth, avgBps);
this.averageSpeedRollAvgBps = new RollingAvgLong(averageSpeedRollAvgDepth, avgBps);
this.filesCopied = 0;
this.bytesCopied = "-";
}
private void OnSpeedEtaRefreshTimerElapsed(object sender, ElapsedEventArgs e)
{
string sval = SmartUnits.Duration(jobStats.GetDuration());
bool durationUpdated = duration != sval;
if (durationUpdated)
{
duration = sval;
OnPropertyChanged(nameof(SpeedDurationEta));
}
// . current speed
long intervalBytesCopied = totalBytesCopied - prevTotalBytesCopied;
long currentBps = (long)((1000.0 * intervalBytesCopied) / speedEtaInterval);
currSpeedRollAvgBps.Push(currentBps);
prevTotalBytesCopied = totalBytesCopied;
sval = SmartUnits.Bytes(currSpeedRollAvgBps.GetAverage(), decimals: 1) + "/s";
if (currentSpeed != sval)
{
currentSpeed = sval;
OnPropertyChanged(nameof(SpeedDurationEta));
}
// . long term average speed, ETA
var currentAvgBps = jobStats.GetAvgBytesPerSecond();
averageSpeedRollAvgBps.Push(currentAvgBps);
var averageAvgBps = averageSpeedRollAvgBps.GetAverage();
var timeSpanRemaining = jobStats.GetTimeRemaining(averageAvgBps);
sval = SmartUnits.Duration(timeSpanRemaining);
if (timeRemaining != sval)
{
timeRemaining = sval;
OnPropertyChanged(nameof(SpeedDurationEta));
gameCache.UpdateInstallEta(timeSpanRemaining);
}
sval = SmartUnits.Bytes(averageAvgBps, decimals: 1) + "/s";
if (averageSpeed != sval)
{
averageSpeed = sval;
OnPropertyChanged(nameof(SpeedDurationEta));
}
}
/// <summary>
/// The Model's OnJobStatsUpdated event will notify us whenever stats
/// have been updated.
/// </summary>
private void OnJobStatsUpdated(object sender, string cacheId)
{
if (cacheId == gameCache.Id)
{
if (preparingToInstall)
{
PreparingToInstall = false;
OnSpeedEtaRefreshTimerElapsed(null, null); // initialize SpeedDurationEta
speedEtaRefreshTimer.Start(); // -> update every 1/2 second thereafter
// . First update only: get auto scale for and bake "OfBytes" to copy string.
bytesScale = SmartUnits.GetBytesAutoScale(jobStats.BytesToCopy);
bytesToCopy = SmartUnits.Bytes(jobStats.BytesToCopy, userScale: bytesScale);
// . Initiallize 'current speed' copied bytes trackers
totalBytesCopied = jobStats.GetTotalBytesCopied();
prevTotalBytesCopied = totalBytesCopied;
// . Initialize copied files of files and bytes of bytes progress.
filesCopied = jobStats.FilesCopied;
bytesCopied = SmartUnits.Bytes(totalBytesCopied, userScale: bytesScale, showUnits: false);
copiedFilesOfFiles = string.Format(formatStringXofY, jobStats.FilesCopied, jobStats.FilesToCopy);
copiedBytesOfBytes = string.Format(formatStringXofY, bytesCopied, bytesToCopy);
OnPropertyChanged(nameof(CopiedFilesAndBytesProgress));
OnPropertyChanged(nameof(ProgressPanelTitle));
OnPropertyChanged(nameof(ProgressTitleBrush));
OnPropertyChanged(nameof(ProgressBarBrush));
OnPropertyChanged(nameof(ProgressBgBrush));
OnPropertyChanged(nameof(ProgressValue));
}
// . update any real-time properties that have changed
double dval = jobStats.UpdatePercentDone();
if (percentDone != dval)
{
percentDone = dval;
OnPropertyChanged(nameof(PercentDone));
OnPropertyChanged(nameof(ProgressValue));
}
totalBytesCopied = jobStats.GetTotalBytesCopied();
string sval = SmartUnits.Bytes(totalBytesCopied, userScale: bytesScale, showUnits: false);
if (filesCopied != jobStats.FilesCopied || bytesCopied != sval)
{
if (filesCopied != jobStats.FilesCopied)
{
filesCopied = jobStats.FilesCopied;
copiedFilesOfFiles = string.Format(formatStringXofY, jobStats.FilesCopied, jobStats.FilesToCopy);
}
if (bytesCopied != sval)
{
bytesCopied = sval;
copiedBytesOfBytes = string.Format(formatStringXofY, bytesCopied, bytesToCopy);
}
OnPropertyChanged(nameof(CopiedFilesAndBytesProgress));
}
sval = jobStats.CurrFileName;
if (currentFile != sval || partialFileResume != jobStats.PartialFileResume)
{
currentFile = jobStats.CurrFileName;
currentFileSize = jobStats.CurrFileSize;
partialFileResume = jobStats.PartialFileResume;
OnPropertyChanged(nameof(CurrentFile));
}
gameCache.UpdateCacheSize();
}
}
private void OnJobDone(object sender, GameCacheJob job)
{
if (job.entry.Id == gameCache.Id)
{
gameCache.UpdateCacheSize();
gameCache.UpdateNowInstalling(false);
if (gameCache.State == GameCacheState.Populated || gameCache.State == GameCacheState.Played)
{
gameCache.UpdateInstallEta(TimeSpan.Zero);
}
else
{
gameCache.UpdateInstallEta();
}
// . all properties updated
OnPropertyChanged(null);
cacheManager.gameCacheManager.eJobStatsUpdated -= OnJobStatsUpdated;
cacheManager.gameCacheManager.eJobCancelled -= OnJobDone;
cacheManager.gameCacheManager.eJobDone -= OnJobDone;
speedEtaRefreshTimer.Stop();
speedEtaRefreshTimer.Elapsed -= OnSpeedEtaRefreshTimerElapsed;
}
}
}
}
| source/ViewModels/InstallProgressViewModel.cs | gittromney-Playnite-NowPlaying-23eec41 | [
{
"filename": "source/Models/RoboStats.cs",
"retrieved_chunk": " public long FilesCopied { get; set; }\n public long BytesCopied { get; set; }\n public long ResumeBytes { get; set; }\n public double PercentDone { get; set; }\n // Current File stats\n public string CurrFileName { get; set; }\n public long CurrFileSize { get; set; }\n public double CurrFilePct { get; set; }\n public bool PartialFileResume { get; set; }\n public void Reset(long filesToCopy, long bytesToCopy, bool partialFileResume = false)",
"score": 0.8634259104728699
},
{
"filename": "source/ViewModels/GameCacheManagerViewModel.cs",
"retrieved_chunk": " }\n }\n }\n public void UpdateInstallAverageBps\n (\n string installDir, \n long avgBytesPerFile,\n long averageBps,\n int speedLimitIpg = 0)\n {",
"score": 0.843161940574646
},
{
"filename": "source/ViewModels/TopPanelViewModel.cs",
"retrieved_chunk": " private string formatStringXofY;\n private int gamesToEnable;\n private int gamesEnabled;\n private int cachesToUninstall;\n private int cachesUninstalled;\n private GameCacheViewModel nowInstallingCache;\n private bool isSlowInstall;\n private int cachesToInstall;\n private int cachesInstalled;\n private long totalBytesToInstall;",
"score": 0.8413209915161133
},
{
"filename": "source/Models/RoboStats.cs",
"retrieved_chunk": "using NowPlaying.Utils;\nusing System;\nnamespace NowPlaying.Models\n{\n public class RoboStats\n {\n // Overall Job stats\n public DateTime StartTime { get; private set; }\n public long FilesToCopy { get; private set; }\n public long BytesToCopy { get; private set; }",
"score": 0.8388700485229492
},
{
"filename": "source/ViewModels/GameCacheViewModel.cs",
"retrieved_chunk": " private bool nowUninstalling;\n private string formatStringXofY;\n private int bytesScale;\n private string bytesToCopy;\n private string cacheInstalledSize;\n public string InstallQueueStatus => installQueueStatus;\n public string UninstallQueueStatus => uninstallQueueStatus;\n public bool NowInstalling => nowInstalling;\n public bool NowUninstalling => nowUninstalling;\n public string Status => GetStatus",
"score": 0.8383796215057373
}
] | csharp | RollingAvgLong averageSpeedRollAvgBps; |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Comfort.Common;
using EFT;
using EFT.InventoryLogic;
using LootingBots.Patch.Util;
using UnityEngine;
namespace LootingBots.Patch.Components
{
public class GearValue
{
public ValuePair Primary = new ValuePair("", 0);
public ValuePair Secondary = new ValuePair("", 0);
public ValuePair Holster = new ValuePair("", 0);
}
public class ValuePair
{
public string Id;
public float Value = 0;
public ValuePair(string id, float value)
{
Id = id;
Value = value;
}
}
public class BotStats
{
public float NetLootValue;
public int AvailableGridSpaces;
public int TotalGridSpaces;
public GearValue WeaponValues = new GearValue();
public void AddNetValue(float itemPrice)
{
NetLootValue += itemPrice;
}
public void SubtractNetValue(float itemPrice)
{
NetLootValue += itemPrice;
}
public void StatsDebugPanel(StringBuilder debugPanel)
{
Color freeSpaceColor =
AvailableGridSpaces == 0
? Color.red
: AvailableGridSpaces < TotalGridSpaces / 2
? Color.yellow
: Color.green;
debugPanel.AppendLabeledValue(
$"Total looted value",
$" {NetLootValue:n0}₽",
Color.white,
Color.white
);
debugPanel.AppendLabeledValue(
$"Available space",
$" {AvailableGridSpaces} slots",
Color.white,
freeSpaceColor
);
}
}
public class InventoryController
{
private readonly BotLog _log;
private readonly TransactionController _transactionController;
private readonly BotOwner _botOwner;
private readonly InventoryControllerClass _botInventoryController;
private readonly LootingBrain _lootingBrain;
private readonly ItemAppraiser _itemAppraiser;
private readonly bool _isBoss;
public BotStats Stats = new BotStats();
private static readonly GearValue GearValue = new GearValue();
// Represents the highest equipped armor class of the bot either from the armor vest or tac vest
public int CurrentBodyArmorClass = 0;
// Represents the value in roubles of the current item
public float CurrentItemPrice = 0f;
public bool ShouldSort = true;
public InventoryController(BotOwner botOwner, LootingBrain lootingBrain)
{
try
{
_log = new BotLog(LootingBots.LootLog, botOwner);
_lootingBrain = lootingBrain;
_isBoss = LootUtils.IsBoss(botOwner);
_itemAppraiser = LootingBots.ItemAppraiser;
// Initialize bot inventory controller
Type botOwnerType = botOwner.GetPlayer.GetType();
FieldInfo botInventory = botOwnerType.BaseType.GetField(
"_inventoryController",
BindingFlags.NonPublic
| BindingFlags.Static
| BindingFlags.Public
| BindingFlags.Instance
);
_botOwner = botOwner;
_botInventoryController = (InventoryControllerClass)
botInventory.GetValue(botOwner.GetPlayer);
_transactionController = new TransactionController(
_botOwner,
_botInventoryController,
_log
);
// Initialize current armor classs
Item chest = _botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.ArmorVest)
.ContainedItem;
SearchableItemClass tacVest = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.TacticalVest)
.ContainedItem;
ArmorComponent currentArmor = chest?.GetItemComponent<ArmorComponent>();
ArmorComponent currentVest = tacVest?.GetItemComponent<ArmorComponent>();
CurrentBodyArmorClass = currentArmor?.ArmorClass ?? currentVest?.ArmorClass ?? 0;
CalculateGearValue();
UpdateGridStats();
}
catch (Exception e)
{
_log.LogError(e);
}
}
/**
* Disable the tranaction controller to ensure transactions do not occur when the looting layer is interrupted
*/
public void DisableTransactions()
{
_transactionController.Enabled = false;
}
/**
* Used to enable the transaction controller when the looting layer is active
*/
public void EnableTransactions()
{
_transactionController.Enabled = true;
}
/**
* Calculates the value of the bot's current weapons to use in weapon swap comparison checks
*/
public void CalculateGearValue()
{
_log.LogDebug("Calculating gear value...");
Item primary = _botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.FirstPrimaryWeapon)
.ContainedItem;
Item secondary = _botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.SecondPrimaryWeapon)
.ContainedItem;
Item holster = _botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Holster)
.ContainedItem;
if (primary != null && GearValue.Primary.Id != primary.Id)
{
float value = _itemAppraiser.GetItemPrice(primary);
GearValue.Primary = new ValuePair(primary.Id, value);
}
if (secondary != null && GearValue.Secondary.Id != secondary.Id)
{
float value = _itemAppraiser.GetItemPrice(secondary);
GearValue.Secondary = new ValuePair(secondary.Id, value);
}
if (holster != null && GearValue.Holster.Id != holster.Id)
{
float value = _itemAppraiser.GetItemPrice(holster);
GearValue.Holster = new ValuePair(holster.Id, value);
}
}
/**
* Updates stats for AvailableGridSpaces and TotalGridSpaces based off the bots current gear
*/
public void UpdateGridStats()
{
SearchableItemClass tacVest = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.TacticalVest)
.ContainedItem;
SearchableItemClass backpack = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Backpack)
.ContainedItem;
SearchableItemClass pockets = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Pockets)
.ContainedItem;
int freePockets = LootUtils.GetAvailableGridSlots(pockets?.Grids);
int freeTacVest = LootUtils.GetAvailableGridSlots(tacVest?.Grids);
int freeBackpack = LootUtils.GetAvailableGridSlots(backpack?.Grids);
Stats.AvailableGridSpaces = freeBackpack + freePockets + freeTacVest;
Stats.TotalGridSpaces =
(tacVest?.Grids?.Length ?? 0)
+ (backpack?.Grids?.Length ?? 0)
+ (pockets?.Grids?.Length ?? 0);
}
/**
* Sorts the items in the tactical vest so that items prefer to be in slots that match their size. I.E a 1x1 item will be placed in a 1x1 slot instead of a 1x2 slot
*/
public async Task<IResult> SortTacVest()
{
SearchableItemClass tacVest = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.TacticalVest)
.ContainedItem;
ShouldSort = false;
if (tacVest != null)
{
var result = LootUtils.SortContainer(tacVest, _botInventoryController);
if (result.Succeeded)
{
return await _transactionController.TryRunNetworkTransaction(result);
}
}
return null;
}
/**
* Main driving method which kicks off the logic for what a bot will do with the loot found.
* If bots are looting something that is equippable and they have nothing equipped in that slot, they will always equip it.
* If the bot decides not to equip the item then it will attempt to put in an available container slot
*/
public async Task<bool> TryAddItemsToBot(Item[] items)
{
foreach (Item item in items)
{
if (_transactionController.IsLootingInterrupted())
{
UpdateKnownItems();
return false;
}
if (item != null && item.Name != null)
{
CurrentItemPrice = _itemAppraiser.GetItemPrice(item);
_log.LogInfo($"Loot found: {item.Name.Localized()} ({CurrentItemPrice}₽)");
if (item is MagazineClass mag && !CanUseMag(mag))
{
_log.LogDebug($"Cannot use mag: {item.Name.Localized()}. Skipping");
continue;
}
// Check to see if we need to swap gear
TransactionController.EquipAction action = GetEquipAction(item);
if (action.Swap != null)
{
await _transactionController.ThrowAndEquip(action.Swap);
continue;
}
else if (action.Move != null)
{
_log.LogDebug("Moving due to GetEquipAction");
if (await _transactionController.MoveItem(action.Move))
{
Stats.AddNetValue(CurrentItemPrice);
}
continue;
}
// Check to see if we can equip the item
bool ableToEquip =
AllowedToEquip(item) && await _transactionController.TryEquipItem(item);
if (ableToEquip)
{
Stats.AddNetValue(CurrentItemPrice);
continue;
}
// If the item we are trying to pickup is a weapon, we need to perform the "pickup" action before trying to strip the weapon of its mods. This is to
// prevent stripping the mods from a weapon and then picking up the weapon afterwards.
if (item is Weapon weapon)
{
bool ableToPickUp =
AllowedToPickup(weapon)
&& await _transactionController.TryPickupItem(weapon);
if (ableToPickUp)
{
Stats.AddNetValue(CurrentItemPrice);
continue;
}
if (LootingBots.CanStripAttachments.Value)
{
// Strip the weapon of its mods if we cannot pickup the weapon
bool success = await TryAddItemsToBot(
weapon.Mods.Where(mod => !mod.IsUnremovable).ToArray()
);
if (!success)
{
UpdateKnownItems();
return success;
}
}
}
else
{
// Try to pick up any nested items before trying to pick up the item. This helps when looting rigs to transfer ammo to the bots active rig
bool success = await LootNestedItems(item);
if (!success)
{
UpdateKnownItems();
return success;
}
// Check to see if we can pick up the item
bool ableToPickUp =
AllowedToPickup(item)
&& await _transactionController.TryPickupItem(item);
if (ableToPickUp)
{
Stats.AddNetValue(CurrentItemPrice);
continue;
}
}
}
else
{
_log.LogDebug("Item was null");
}
}
// Refresh bot's known items dictionary
UpdateKnownItems();
return true;
}
/**
* Method to make the bot change to its primary weapon. Useful for making sure bots have their weapon out after they have swapped weapons.
*/
public void ChangeToPrimary()
{
if (_botOwner != null && _botOwner.WeaponManager?.Selector != null)
{
_log.LogWarning($"Changing to primary");
_botOwner.WeaponManager.UpdateWeaponsList();
_botOwner.WeaponManager.Selector.ChangeToMain();
RefillAndReload();
}
}
/**
* Updates the bot's known weapon list and tells the bot to switch to its main weapon
*/
public void UpdateActiveWeapon()
{
if (_botOwner != null && _botOwner.WeaponManager?.Selector != null)
{
_log.LogWarning($"Updating weapons");
_botOwner.WeaponManager.UpdateWeaponsList();
_botOwner.WeaponManager.Selector.TakeMainWeapon();
RefillAndReload();
}
}
/**
* Method to refill magazines with ammo and also reload the current weapon with a new magazine
*/
private void RefillAndReload()
{
if (_botOwner != null && _botOwner.WeaponManager?.Selector != null)
{
_botOwner.WeaponManager.Reload.TryFillMagazines();
_botOwner.WeaponManager.Reload.TryReload();
}
}
/** Marks all items placed in rig/pockets/backpack as known items that they are able to use */
public void UpdateKnownItems()
{
// Protection against bot death interruption
if (_botOwner != null && _botInventoryController != null)
{
SearchableItemClass tacVest = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.TacticalVest)
.ContainedItem;
SearchableItemClass backpack = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Backpack)
.ContainedItem;
SearchableItemClass pockets = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Pockets)
.ContainedItem;
SearchableItemClass secureContainer = (SearchableItemClass)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.SecuredContainer)
.ContainedItem;
tacVest?.UncoverAll(_botOwner.ProfileId);
backpack?.UncoverAll(_botOwner.ProfileId);
pockets?.UncoverAll(_botOwner.ProfileId);
secureContainer?.UncoverAll(_botOwner.ProfileId);
}
}
/**
* Checks certain slots to see if the item we are looting is "better" than what is currently equipped. View shouldSwapGear for criteria.
* Gear is checked in a specific order so that bots will try to swap gear that is a "container" first like backpacks and tacVests to make sure
* they arent putting loot in an item they will ultimately decide to drop
*/
public | TransactionController.EquipAction GetEquipAction(Item lootItem)
{ |
Item helmet = _botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Headwear)
.ContainedItem;
Item chest = _botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.ArmorVest)
.ContainedItem;
Item tacVest = _botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.TacticalVest)
.ContainedItem;
Item backpack = _botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Backpack)
.ContainedItem;
string lootID = lootItem?.Parent?.Container?.ID;
TransactionController.EquipAction action = new TransactionController.EquipAction();
TransactionController.SwapAction swapAction = null;
if (!AllowedToEquip(lootItem))
{
return action;
}
if (lootItem.Template is WeaponTemplate && !_isBoss)
{
return GetWeaponEquipAction(lootItem as Weapon);
}
if (backpack?.Parent?.Container.ID == lootID && ShouldSwapGear(backpack, lootItem))
{
swapAction = GetSwapAction(backpack, lootItem, null, true);
}
else if (helmet?.Parent?.Container?.ID == lootID && ShouldSwapGear(helmet, lootItem))
{
swapAction = GetSwapAction(helmet, lootItem);
}
else if (chest?.Parent?.Container?.ID == lootID && ShouldSwapGear(chest, lootItem))
{
swapAction = GetSwapAction(chest, lootItem);
}
else if (tacVest?.Parent?.Container?.ID == lootID && ShouldSwapGear(tacVest, lootItem))
{
// If the tac vest we are looting is higher armor class and we have a chest equipped, make sure to drop the chest and pick up the armored rig
if (IsLootingBetterArmor(tacVest, lootItem) && chest != null)
{
_log.LogDebug("Looting armored rig and dropping chest");
swapAction = GetSwapAction(
chest,
null,
async () =>
await _transactionController.ThrowAndEquip(
GetSwapAction(tacVest, lootItem, null, true)
)
);
}
else
{
swapAction = GetSwapAction(tacVest, lootItem, null, true);
}
}
action.Swap = swapAction;
return action;
}
public bool CanUseMag(MagazineClass mag)
{
return _botInventoryController.Inventory.Equipment
.GetSlotsByName(
new EquipmentSlot[]
{
EquipmentSlot.FirstPrimaryWeapon,
EquipmentSlot.SecondPrimaryWeapon,
EquipmentSlot.Holster
}
)
.Where(
slot =>
slot.ContainedItem != null
&& ((Weapon)slot.ContainedItem).GetMagazineSlot() != null
&& ((Weapon)slot.ContainedItem).GetMagazineSlot().CanAccept(mag)
)
.ToArray()
.Length > 0;
}
/**
* Throws all magazines from the rig that are not able to be used by any of the weapons that the bot currently has equipped
*/
public async Task ThrowUselessMags(Weapon thrownWeapon)
{
Weapon primary = (Weapon)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.FirstPrimaryWeapon)
.ContainedItem;
Weapon secondary = (Weapon)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.SecondPrimaryWeapon)
.ContainedItem;
Weapon holster = (Weapon)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Holster)
.ContainedItem;
List<MagazineClass> mags = new List<MagazineClass>();
_botInventoryController.GetReachableItemsOfTypeNonAlloc(mags);
_log.LogDebug($"Cleaning up old mags...");
int reservedCount = 0;
foreach (MagazineClass mag in mags)
{
bool fitsInThrown =
thrownWeapon.GetMagazineSlot() != null
&& thrownWeapon.GetMagazineSlot().CanAccept(mag);
bool fitsInPrimary =
primary != null
&& primary.GetMagazineSlot() != null
&& primary.GetMagazineSlot().CanAccept(mag);
bool fitsInSecondary =
secondary != null
&& secondary.GetMagazineSlot() != null
&& secondary.GetMagazineSlot().CanAccept(mag);
bool fitsInHolster =
holster != null
&& holster.GetMagazineSlot() != null
&& holster.GetMagazineSlot().CanAccept(mag);
bool fitsInEquipped = fitsInPrimary || fitsInSecondary || fitsInHolster;
bool isSharedMag = fitsInThrown && fitsInEquipped;
if (reservedCount < 2 && fitsInThrown && fitsInEquipped)
{
_log.LogDebug($"Reserving shared mag {mag.Name.Localized()}");
reservedCount++;
}
else if ((reservedCount >= 2 && fitsInEquipped) || !fitsInEquipped)
{
_log.LogDebug($"Removing useless mag {mag.Name.Localized()}");
await _transactionController.ThrowAndEquip(
new TransactionController.SwapAction(mag)
);
}
}
}
/**
* Determines the kind of equip action the bot should take when encountering a weapon. Bots will always prefer to replace weapons that have lower value when encountering a higher value weapon.
*/
public TransactionController.EquipAction GetWeaponEquipAction(Weapon lootWeapon)
{
Weapon primary = (Weapon)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.FirstPrimaryWeapon)
.ContainedItem;
Weapon secondary = (Weapon)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.SecondPrimaryWeapon)
.ContainedItem;
Weapon holster = (Weapon)
_botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Holster)
.ContainedItem;
TransactionController.EquipAction action = new TransactionController.EquipAction();
bool isPistol = lootWeapon.WeapClass.Equals("pistol");
float lootValue = CurrentItemPrice;
if (isPistol)
{
if (holster == null)
{
var place = _botInventoryController.FindSlotToPickUp(lootWeapon);
if (place != null)
{
action.Move = new TransactionController.MoveAction(lootWeapon, place);
GearValue.Holster = new ValuePair(lootWeapon.Id, lootValue);
}
}
else if (holster != null && GearValue.Holster.Value < lootValue)
{
_log.LogDebug(
$"Trying to swap {holster.Name.Localized()} (₽{GearValue.Holster.Value}) with {lootWeapon.Name.Localized()} (₽{lootValue})"
);
action.Swap = GetSwapAction(holster, lootWeapon);
GearValue.Holster = new ValuePair(lootWeapon.Id, lootValue);
}
}
else
{
// If we have no primary, just equip the weapon to primary
if (primary == null)
{
var place = _botInventoryController.FindSlotToPickUp(lootWeapon);
if (place != null)
{
action.Move = new TransactionController.MoveAction(
lootWeapon,
place,
null,
async () =>
{
ChangeToPrimary();
Stats.AddNetValue(lootValue);
await TransactionController.SimulatePlayerDelay(1000);
}
);
GearValue.Primary = new ValuePair(lootWeapon.Id, lootValue);
}
}
else if (GearValue.Primary.Value < lootValue)
{
// If the loot weapon is worth more than the primary, by nature its also worth more than the secondary. Try to move the primary weapon to the secondary slot and equip the new weapon as the primary
if (secondary == null)
{
ItemAddress place = _botInventoryController.FindSlotToPickUp(primary);
if (place != null)
{
_log.LogDebug(
$"Moving {primary.Name.Localized()} (₽{GearValue.Primary.Value}) to secondary and equipping {lootWeapon.Name.Localized()} (₽{lootValue})"
);
action.Move = new TransactionController.MoveAction(
primary,
place,
null,
async () =>
{
await _transactionController.TryEquipItem(lootWeapon);
await TransactionController.SimulatePlayerDelay(1500);
ChangeToPrimary();
}
);
GearValue.Secondary = GearValue.Primary;
GearValue.Primary = new ValuePair(lootWeapon.Id, lootValue);
}
}
// In the case where we have a secondary, throw it, move the primary to secondary, and equip the loot weapon as primary
else
{
_log.LogDebug(
$"Trying to swap {secondary.Name.Localized()} (₽{GearValue.Secondary.Value}) with {primary.Name.Localized()} (₽{GearValue.Primary.Value}) and equip {lootWeapon.Name.Localized()} (₽{lootValue})"
);
action.Swap = GetSwapAction(
secondary,
primary,
null,
false,
async () =>
{
await ThrowUselessMags(secondary);
await _transactionController.TryEquipItem(lootWeapon);
Stats.AddNetValue(lootValue);
await TransactionController.SimulatePlayerDelay(1500);
ChangeToPrimary();
}
);
GearValue.Secondary = GearValue.Primary;
GearValue.Primary = new ValuePair(lootWeapon.Id, lootValue);
}
}
// If there is no secondary weapon, equip to secondary
else if (secondary == null)
{
var place = _botInventoryController.FindSlotToPickUp(lootWeapon);
if (place != null)
{
action.Move = new TransactionController.MoveAction(
lootWeapon,
_botInventoryController.FindSlotToPickUp(lootWeapon)
);
GearValue.Secondary = new ValuePair(lootWeapon.Id, lootValue);
}
}
// If the loot weapon is worth more than the secondary, swap it
else if (GearValue.Secondary.Value < lootValue)
{
_log.LogDebug(
$"Trying to swap {secondary.Name.Localized()} (₽{GearValue.Secondary.Value}) with {lootWeapon.Name.Localized()} (₽{lootValue})"
);
action.Swap = GetSwapAction(secondary, lootWeapon);
GearValue.Secondary = new ValuePair(secondary.Id, lootValue);
}
}
return action;
}
/**
* Checks to see if the bot should swap its currently equipped gear with the item to loot. Bot will swap under the following criteria:
* 1. The item is a container and its larger than what is equipped.
* - Tactical rigs have an additional check, will not switch out if the rig we are looting is lower armor class than what is equipped
* 2. The item has an armor rating, and its higher than what is currently equipped.
*/
public bool ShouldSwapGear(Item equipped, Item itemToLoot)
{
// Bosses cannot swap gear as many bosses have custom logic tailored to their loadouts
if (_isBoss)
{
return false;
}
bool foundBiggerContainer = false;
// If the item is a container, calculate the size and see if its bigger than what is equipped
if (equipped.IsContainer)
{
int equippedSize = LootUtils.GetContainerSize(equipped as SearchableItemClass);
int itemToLootSize = LootUtils.GetContainerSize(itemToLoot as SearchableItemClass);
foundBiggerContainer = equippedSize < itemToLootSize;
}
bool foundBetterArmor = IsLootingBetterArmor(equipped, itemToLoot);
ArmorComponent lootArmor = itemToLoot.GetItemComponent<ArmorComponent>();
ArmorComponent equippedArmor = equipped.GetItemComponent<ArmorComponent>();
// Equip if we found item with a better armor class.
// Equip if we found an item with more slots only if what we have equipped is the same or worse armor class
return foundBetterArmor
|| (
foundBiggerContainer
&& (equippedArmor == null || equippedArmor.ArmorClass <= lootArmor?.ArmorClass)
);
}
/**
* Checks to see if the item we are looting has higher armor value than what is currently equipped. For chests/vests, make sure we compare against the
* currentBodyArmorClass and update the value if a higher armor class is found.
*/
public bool IsLootingBetterArmor(Item equipped, Item itemToLoot)
{
ArmorComponent lootArmor = itemToLoot.GetItemComponent<ArmorComponent>();
HelmetComponent lootHelmet = itemToLoot.GetItemComponent<HelmetComponent>();
ArmorComponent equippedArmor = equipped.GetItemComponent<ArmorComponent>();
bool foundBetterArmor = false;
// If we are looting a helmet, check to see if it has a better armor class than what is equipped
if (lootArmor != null && lootHelmet != null)
{
// If the equipped item is not an ArmorComponent then assume the lootArmor item is higher class
if (equippedArmor == null)
{
return lootArmor != null;
}
foundBetterArmor = equippedArmor.ArmorClass <= lootArmor.ArmorClass;
}
else if (lootArmor != null)
{
// If we are looting chest/rig with armor, check to see if it has a better armor class than what is equipped
foundBetterArmor = CurrentBodyArmorClass <= lootArmor.ArmorClass;
if (foundBetterArmor)
{
CurrentBodyArmorClass = lootArmor.ArmorClass;
}
}
return foundBetterArmor;
}
/** Searches throught the child items of a container and attempts to loot them */
public async Task<bool> LootNestedItems(Item parentItem)
{
if (_transactionController.IsLootingInterrupted())
{
return false;
}
Item[] nestedItems = parentItem.GetAllItems().ToArray();
if (nestedItems.Length > 1)
{
// Filter out the parent item from the list, filter out any items that are children of another container like a magazine, backpack, rig
Item[] containerItems = nestedItems
.Where(
nestedItem =>
nestedItem.Id != parentItem.Id
&& nestedItem.Id == nestedItem.GetRootItem().Id
&& !nestedItem.QuestItem
&& !LootUtils.IsSingleUseKey(nestedItem)
)
.ToArray();
if (containerItems.Length > 0)
{
_log.LogDebug(
$"Looting {containerItems.Length} items from {parentItem.Name.Localized()}"
);
await TransactionController.SimulatePlayerDelay(1000);
return await TryAddItemsToBot(containerItems);
}
}
else
{
_log.LogDebug($"No nested items found in {parentItem.Name}");
}
return true;
}
/**
Check if the item being looted meets the loot value threshold specified in the mod settings and saves its value in CurrentItemPrice.
PMC bots use the PMC loot threshold, all other bots such as scavs, bosses, and raiders will use the scav threshold
*/
public bool IsValuableEnough(float itemPrice)
{
WildSpawnType botType = _botOwner.Profile.Info.Settings.Role;
bool isPMC = BotTypeUtils.IsPMC(botType);
// If the bot is a PMC, compare the price against the PMC loot threshold. For all other bot types use the scav threshold
return isPMC && itemPrice >= LootingBots.PMCLootThreshold.Value
|| !isPMC && itemPrice >= LootingBots.ScavLootThreshold.Value;
}
public bool AllowedToEquip(Item lootItem)
{
WildSpawnType botType = _botOwner.Profile.Info.Settings.Role;
bool isPMC = BotTypeUtils.IsPMC(botType);
bool allowedToEquip = isPMC
? LootingBots.PMCGearToEquip.Value.IsItemEligible(lootItem)
: LootingBots.ScavGearToEquip.Value.IsItemEligible(lootItem);
return allowedToEquip && IsValuableEnough(CurrentItemPrice);
}
public bool AllowedToPickup(Item lootItem)
{
WildSpawnType botType = _botOwner.Profile.Info.Settings.Role;
bool isPMC = BotTypeUtils.IsPMC(botType);
bool allowedToPickup = isPMC
? LootingBots.PMCGearToPickup.Value.IsItemEligible(lootItem)
: LootingBots.ScavGearToPickup.Value.IsItemEligible(lootItem);
return allowedToPickup && IsValuableEnough(CurrentItemPrice);
}
/**
* Returns the list of slots to loot from a corpse in priority order. When a bot already has a backpack/rig, they will attempt to loot the weapons off the bot first. Otherwise they will loot the equipement first and loot the weapons afterwards.
*/
public EquipmentSlot[] GetPrioritySlots()
{
InventoryControllerClass botInventoryController = _botInventoryController;
bool hasBackpack =
botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.Backpack)
.ContainedItem != null;
bool hasTacVest =
botInventoryController.Inventory.Equipment
.GetSlot(EquipmentSlot.TacticalVest)
.ContainedItem != null;
EquipmentSlot[] prioritySlots = new EquipmentSlot[0];
EquipmentSlot[] weaponSlots = new EquipmentSlot[]
{
EquipmentSlot.Holster,
EquipmentSlot.FirstPrimaryWeapon,
EquipmentSlot.SecondPrimaryWeapon
};
EquipmentSlot[] storageSlots = new EquipmentSlot[]
{
EquipmentSlot.Backpack,
EquipmentSlot.ArmorVest,
EquipmentSlot.TacticalVest,
EquipmentSlot.Pockets
};
if (hasBackpack || hasTacVest)
{
_log.LogDebug($"Has backpack/rig and is looting weapons first!");
prioritySlots = prioritySlots.Concat(weaponSlots).Concat(storageSlots).ToArray();
}
else
{
prioritySlots = prioritySlots.Concat(storageSlots).Concat(weaponSlots).ToArray();
}
return prioritySlots
.Concat(
new EquipmentSlot[]
{
EquipmentSlot.Headwear,
EquipmentSlot.Earpiece,
EquipmentSlot.Dogtag,
EquipmentSlot.Scabbard,
EquipmentSlot.FaceCover
}
)
.ToArray();
}
/** Generates a SwapAction to send to the transaction controller*/
public TransactionController.SwapAction GetSwapAction(
Item toThrow,
Item toEquip,
TransactionController.ActionCallback callback = null,
bool tranferItems = false,
TransactionController.ActionCallback onComplete = null
)
{
TransactionController.ActionCallback onSwapComplete = null;
// If we want to transfer items after the throw and equip fully completes, call the lootNestedItems method
// on the item that was just thrown
if (tranferItems)
{
onSwapComplete = async () =>
{
await TransactionController.SimulatePlayerDelay();
await LootNestedItems(toThrow);
};
}
return new TransactionController.SwapAction(
toThrow,
toEquip,
callback
?? (
async () =>
{
Stats.SubtractNetValue(_itemAppraiser.GetItemPrice(toThrow));
_lootingBrain.IgnoreLoot(toThrow.Id);
await TransactionController.SimulatePlayerDelay(1000);
if (toThrow is Weapon weapon)
{
await ThrowUselessMags(weapon);
}
bool isMovingOwnedItem = _botInventoryController.IsItemEquipped(
toEquip
);
// Try to equip the item after throwing
if (
await _transactionController.TryEquipItem(toEquip)
&& !isMovingOwnedItem
)
{
Stats.AddNetValue(CurrentItemPrice);
}
}
),
onComplete ?? onSwapComplete
);
}
}
}
| LootingBots/components/InventoryController.cs | Skwizzy-SPT-LootingBots-76279a3 | [
{
"filename": "LootingBots/components/TransactionController.cs",
"retrieved_chunk": " }\n _log.LogDebug($\"Cannot equip: {item.Name.Localized()}\");\n }\n catch (Exception e)\n {\n _log.LogError(e);\n }\n return false;\n }\n /** Tries to find a valid grid for the item being looted. Checks all containers currently equipped to the bot. If there is a valid grid to place the item inside of, issue a move action to pick up the item */",
"score": 0.8905873894691467
},
{
"filename": "LootingBots/logics/LootingLogic.cs",
"retrieved_chunk": " }\n }\n return true;\n }\n /**\n * Makes the bot look towards the target destination and begin moving towards it. Navigation will be cancelled if the bot has not moved in more than 2 navigation calls, if the destination cannot be snapped to a mesh,\n * or if the NavPathStatus is anything other than Completed\n */\n public bool TryMoveToLoot()\n {",
"score": 0.885291576385498
},
{
"filename": "LootingBots/logics/LootingLogic.cs",
"retrieved_chunk": " {\n _log.LogError(e);\n }\n return canMove;\n }\n /**\n * Check to see if the bot is close enough to the destination so that they can stop moving and start looting\n */\n private bool IsCloseEnough()\n {",
"score": 0.8837993741035461
},
{
"filename": "LootingBots/components/TransactionController.cs",
"retrieved_chunk": " catch (Exception e)\n {\n _log.LogError(e);\n }\n return false;\n }\n /** Tries to find an open Slot to equip the current item to. If a slot is found, issue a move action to equip the item */\n public async Task<bool> TryEquipItem(Item item)\n {\n try",
"score": 0.8794772624969482
},
{
"filename": "LootingBots/utils/LootUtils.cs",
"retrieved_chunk": " container.Interact(result);\n }\n /**\n * Sorts the items in a container and places them in grid spaces that match their exact size before moving on to a bigger slot size. This helps make more room in the container for items to be placed in\n */\n public static SortResultStruct SortContainer(\n SearchableItemClass container,\n InventoryControllerClass controller\n )\n {",
"score": 0.878218412399292
}
] | csharp | TransactionController.EquipAction GetEquipAction(Item lootItem)
{ |
using LibreDteDotNet.RestRequest.Interfaces;
namespace LibreDteDotNet.RestRequest.Extensions
{
public static class BoletaExtension
{
public static IBoleta Conectar(this | IBoleta folioService)
{ |
IBoleta instance = folioService;
return instance.SetCookieCertificado().Result;
}
}
}
| LibreDteDotNet.RestRequest/Extensions/BoletaExtension.cs | sergiokml-LibreDteDotNet.RestRequest-6843109 | [
{
"filename": "LibreDteDotNet.RestRequest/Extensions/FolioCafExtension.cs",
"retrieved_chunk": "using System.Xml.Linq;\nusing LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class FolioCafExtension\n {\n private static CancellationToken CancellationToken { get; set; }\n public static IFolioCaf Conectar(this IFolioCaf instance)\n {\n return instance.SetCookieCertificado().Result;",
"score": 0.8999269604682922
},
{
"filename": "LibreDteDotNet.RestRequest/Extensions/DTEExtension.cs",
"retrieved_chunk": "using LibreDteDotNet.Common.Models;\nusing LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class DTEExtension\n {\n public static IDTE Conectar(this IDTE folioService)\n {\n IDTE instance = folioService;\n return instance.SetCookieCertificado().ConfigureAwait(false).GetAwaiter().GetResult();",
"score": 0.8924716711044312
},
{
"filename": "LibreDteDotNet.RestRequest/Infraestructure/RestRequest.cs",
"retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Infraestructure\n{\n public class RestRequest\n {\n public ILibro Libro { get; }\n public IContribuyente Contribuyente { get; }\n public IFolioCaf FolioCaf { get; }\n public IBoleta Boleta { get; }\n public IDTE DocumentoTributario { get; }",
"score": 0.8818084001541138
},
{
"filename": "LibreDteDotNet.RestRequest/Extensions/ContribuyenteExtension.cs",
"retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class ContribuyenteExtension\n {\n public static IContribuyente Conectar(this IContribuyente folioService)\n {\n IContribuyente instance = folioService;\n return instance.SetCookieCertificado().Result;\n }",
"score": 0.8811386823654175
},
{
"filename": "LibreDteDotNet.RestRequest/Services/BoletaService.cs",
"retrieved_chunk": "using System.Net;\nusing LibreDteDotNet.Common;\nusing LibreDteDotNet.RestRequest.Infraestructure;\nusing LibreDteDotNet.RestRequest.Interfaces;\nusing Microsoft.Extensions.Configuration;\nnamespace LibreDteDotNet.RestRequest.Services\n{\n internal class BoletaService : ComunEnum, IBoleta\n {\n private readonly IConfiguration configuration;",
"score": 0.8477474451065063
}
] | csharp | IBoleta folioService)
{ |
using JWLSLMerge.Data.Attributes;
namespace JWLSLMerge.Data.Models
{
public class UserMark
{
[ | Ignore]
public int UserMarkId { | get; set; }
public int ColorIndex { get; set; }
public int LocationId { get; set; }
public int StyleIndex { get; set; }
public string UserMarkGuid { get; set; } = null!;
public int Version { get; set; }
[Ignore]
public int NewUserMarkId { get; set; }
}
}
| JWLSLMerge.Data/Models/UserMark.cs | pliniobrunelli-JWLSLMerge-7fe66dc | [
{
"filename": "JWLSLMerge.Data/Attributes/Ignore.cs",
"retrieved_chunk": "namespace JWLSLMerge.Data.Attributes\n{\n [AttributeUsage(AttributeTargets.Property)]\n public class IgnoreAttribute : Attribute { }\n}",
"score": 0.8608590364456177
},
{
"filename": "JWLSLMerge.Data/Models/Tag.cs",
"retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class Tag\n {\n [Ignore]\n public int TagId { get; set; }\n public int Type { get; set; }\n public string Name { get; set; } = null!;\n [Ignore]",
"score": 0.8205559849739075
},
{
"filename": "JWLSLMerge.Data/JWDal.cs",
"retrieved_chunk": "using Dapper;\nusing JWLSLMerge.Data.Attributes;\nusing System.Data;\nusing System.Data.SQLite;\nnamespace JWLSLMerge.Data\n{\n public class JWDal\n {\n private string connectionString;\n public JWDal(string dbPath)",
"score": 0.8194923400878906
},
{
"filename": "JWLSLMerge.Data/Models/Note.cs",
"retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [Ignore]\n public int NoteId { get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }",
"score": 0.8038144111633301
},
{
"filename": "JWLSLMerge.Data/Models/BlockRange.cs",
"retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class BlockRange\n {\n [Ignore]\n public int BlockRangeId { get; set; }\n public int BlockType { get; set; }\n public int Identifier { get; set; }\n public int? StartToken { get; set; }",
"score": 0.8036028146743774
}
] | csharp | Ignore]
public int UserMarkId { |
using System;
using System.Diagnostics;
using wingman.Interfaces;
using wingman.Views;
namespace wingman.Services
{
public class AppActivationService : IAppActivationService, IDisposable
{
private readonly | MainWindow _mainWindow; |
private readonly ISettingsService _settingsService;
public AppActivationService(
MainWindow mainWindow,
ISettingsService settingsService)
{
_mainWindow = mainWindow;
_settingsService = settingsService;
}
public void Activate(object activationArgs)
{
InitializeServices();
_mainWindow.Activate();
}
public void Dispose()
{
Debug.WriteLine("Appactivate Disposed");
// _app.Dispose();
}
private void InitializeServices()
{
}
}
} | Services/AppActivationService.cs | dannyr-git-wingman-41103f3 | [
{
"filename": "Services/LoggingService.cs",
"retrieved_chunk": "using System;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing wingman.Interfaces;\nusing wingman.Services;\nnamespace wingman.Interfaces\n{\n public interface ILoggingService\n {\n event EventHandler<string> UIOutputHandler;",
"score": 0.9004632234573364
},
{
"filename": "Services/WindowingService.cs",
"retrieved_chunk": "using Microsoft.UI.Xaml;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing wingman.Views;\nnamespace wingman.Interfaces\n{\n public class WindowingService : IWindowingService, IDisposable\n {",
"score": 0.8914462327957153
},
{
"filename": "App.xaml.cs",
"retrieved_chunk": "using wingman.ViewModels;\nusing wingman.Views;\nnamespace wingman\n{\n public partial class App : Application, IDisposable\n {\n private readonly IHost _host;\n private readonly AppUpdater _appUpdater;\n public App()\n {",
"score": 0.8747022151947021
},
{
"filename": "Views/MainPage.xaml.cs",
"retrieved_chunk": "using CommunityToolkit.Mvvm.DependencyInjection;\nusing Microsoft.UI.Xaml.Controls;\nusing wingman.ViewModels;\nnamespace wingman.Views\n{\n public sealed partial class MainPage : Page\n {\n public MainPage()\n {\n InitializeComponent();",
"score": 0.8740206360816956
},
{
"filename": "Views/Controls/ModalControl.xaml.cs",
"retrieved_chunk": "using CommunityToolkit.Mvvm.DependencyInjection;\nusing Microsoft.UI.Xaml.Controls;\nusing wingman.ViewModels;\nnamespace wingman.Views\n{\n public sealed partial class ModalControl : UserControl\n {\n public ModalControl()\n {\n InitializeComponent();",
"score": 0.8701128959655762
}
] | csharp | MainWindow _mainWindow; |
using HarmonyLib;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using ULTRAKILL.Cheats;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Ultrapain.Patches
{
public class V2SecondFlag : MonoBehaviour
{
public V2RocketLauncher rocketLauncher;
public V2MaliciousCannon maliciousCannon;
public Collider v2collider;
public Transform targetGrenade;
}
public class V2RocketLauncher : MonoBehaviour
{
public Transform shootPoint;
public Collider v2collider;
AudioSource aud;
float altFireCharge = 0f;
bool altFireCharging = false;
void Awake()
{
aud = GetComponent<AudioSource>();
if (aud == null)
aud = gameObject.AddComponent<AudioSource>();
aud.playOnAwake = false;
aud.clip = Plugin.cannonBallChargeAudio;
}
void Update()
{
if (altFireCharging)
{
if (!aud.isPlaying)
{
aud.pitch = Mathf.Min(1f, altFireCharge) + 0.5f;
aud.Play();
}
altFireCharge += Time.deltaTime;
}
}
void OnDisable()
{
altFireCharging = false;
}
void PrepareFire()
{
Instantiate<GameObject>(Plugin.v2flashUnparryable, this.shootPoint.position, this.shootPoint.rotation).transform.localScale *= 4f;
}
void SetRocketRotation(Transform rocket)
{
// OLD PREDICTION
/*Rigidbody rb = rocket.GetComponent<Rigidbody>();
Grenade grn = rocket.GetComponent<Grenade>();
float magnitude = grn.rocketSpeed;
//float distance = Vector3.Distance(MonoSingleton<PlayerTracker>.Instance.gameObject.transform.position, __0.transform.position);
float distance = Vector3.Distance(MonoSingleton<PlayerTracker>.Instance.GetTarget().position, rocket.transform.position);
Vector3 predictedPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(1.0f);
float velocity = Mathf.Clamp(distance, Mathf.Max(magnitude - 5.0f, 0), magnitude + 5);
rocket.transform.LookAt(predictedPosition);
rocket.GetComponent<Grenade>().rocketSpeed = velocity;
rb.maxAngularVelocity = velocity;
rb.velocity = Vector3.zero;
rb.AddRelativeForce(Vector3.forward * magnitude * rb.mass, ForceMode.VelocityChange);
// rb.velocity = rocket.transform.forward * velocity;
*/
// NEW PREDICTION
Vector3 playerPos = Tools.PredictPlayerPosition(0.5f);
rocket.LookAt(playerPos);
Rigidbody rb = rocket.GetComponent<Rigidbody>();
rb.velocity = Vector3.zero;
rb.AddForce(rocket.transform.forward * 10000f);
}
void Fire()
{
GameObject rocket = Instantiate<GameObject>(Plugin.rocket, shootPoint.transform.position, shootPoint.transform.rotation);
rocket.transform.position = new Vector3(rocket.transform.position.x, v2collider.bounds.center.y, rocket.transform.position.z);
rocket.transform.LookAt(PlayerTracker.Instance.GetTarget());
rocket.transform.position += rocket.transform.forward * 2f;
SetRocketRotation(rocket.transform);
Grenade component = rocket.GetComponent<Grenade>();
if (component)
{
component.harmlessExplosion = component.explosion;
component.enemy = true;
component.CanCollideWithPlayer(true);
}
//Physics.IgnoreCollision(rocket.GetComponent<Collider>(), v2collider);
}
void PrepareAltFire()
{
altFireCharging = true;
}
void AltFire()
{
altFireCharging = false;
altFireCharge = 0;
GameObject cannonBall = Instantiate(Plugin.cannonBall, shootPoint.transform.position, shootPoint.transform.rotation);
cannonBall.transform.position = new Vector3(cannonBall.transform.position.x, v2collider.bounds.center.y, cannonBall.transform.position.z);
cannonBall.transform.LookAt(PlayerTracker.Instance.GetTarget());
cannonBall.transform.position += cannonBall.transform.forward * 2f;
if(cannonBall.TryGetComponent<Cannonball>(out Cannonball comp))
{
comp.sourceWeapon = this.gameObject;
}
if(cannonBall.TryGetComponent<Rigidbody>(out Rigidbody rb))
{
rb.velocity = rb.transform.forward * 150f;
}
}
static MethodInfo bounce = typeof(Cannonball).GetMethod("Bounce", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
public static bool CannonBallTriggerPrefix(Cannonball __instance, Collider __0)
{
if(__instance.sourceWeapon != null && __instance.sourceWeapon.GetComponent<V2RocketLauncher>() != null)
{
if (__0.gameObject.tag == "Player")
{
if (!__instance.hasBounced)
{
bounce.Invoke(__instance, new object[0]);
NewMovement.Instance.GetHurt((int)__instance.damage, true, 1, false, false);
return false;
}
}
else
{
EnemyIdentifierIdentifier eii = __0.gameObject.GetComponent<EnemyIdentifierIdentifier>();
if (!__instance.launched && eii != null && (eii.eid.enemyType == EnemyType.V2 || eii.eid.enemyType == EnemyType.V2Second))
return false;
}
return true;
}
return true;
}
}
public class V2MaliciousCannon : MonoBehaviour
{
//readonly static FieldInfo maliciousIgnorePlayer = typeof(RevolverBeam).GetField("maliciousIgnorePlayer", BindingFlags.NonPublic | BindingFlags.Instance);
Transform shootPoint;
public Transform v2trans;
public float cooldown = 0f;
static readonly string debugTag = "[V2][MalCannonShoot]";
void Awake()
{
shootPoint = UnityUtils.GetChildByNameRecursively(transform, "Shootpoint");
}
void PrepareFire()
{
Instantiate<GameObject>(Plugin.v2flashUnparryable, this.shootPoint.position, this.shootPoint.rotation).transform.localScale *= 4f;
}
void Fire()
{
cooldown = ConfigManager.v2SecondMalCannonSnipeCooldown.value;
Transform target = V2Utils.GetClosestGrenade();
Vector3 targetPosition = Vector3.zero;
if (target != null)
{
Debug.Log($"{debugTag} Targeted grenade");
targetPosition = target.position;
}
else
{
Transform playerTarget = PlayerTracker.Instance.GetTarget();
/*if (Physics.Raycast(new Ray(playerTarget.position, Vector3.down), out RaycastHit hit, 100f, new LayerMask() { value = (1 << 8 | 1 << 24) }, QueryTriggerInteraction.Ignore))
{
Debug.Log($"{debugTag} Targeted ground below player");
targetPosition = hit.point;
}
else
{*/
Debug.Log($"{debugTag} Targeted player with random spread");
targetPosition = playerTarget.transform.position + UnityEngine.Random.onUnitSphere * 2f;
//}
}
GameObject beam = Instantiate(Plugin.maliciousCannonBeam, v2trans.position, Quaternion.identity);
beam.transform.position = new Vector3(beam.transform.position.x, v2trans.GetComponent<Collider>().bounds.center.y, beam.transform.position.z);
beam.transform.LookAt(targetPosition);
beam.transform.position += beam.transform.forward * 2f;
if (beam.TryGetComponent<RevolverBeam>(out RevolverBeam comp))
{
comp.alternateStartPoint = shootPoint.transform.position;
comp.ignoreEnemyType = EnemyType.V2Second;
comp.sourceWeapon = gameObject;
//comp.beamType = BeamType.Enemy;
//maliciousIgnorePlayer.SetValue(comp, false);
}
}
void PrepareAltFire()
{
}
void AltFire()
{
}
}
class V2SecondUpdate
{
static bool Prefix(V2 __instance, ref int ___currentWeapon, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb, ref float ___shootCooldown,
ref bool ___aboutToShoot, ref EnemyIdentifier ___eid, bool ___escaping)
{
if (!__instance.secondEncounter)
return true;
if (!__instance.active || ___escaping || BlindEnemies.Blind)
return true;
V2SecondFlag flag = __instance.GetComponent<V2SecondFlag>();
if (flag == null)
return true;
if (flag.maliciousCannon.cooldown > 0)
flag.maliciousCannon.cooldown = Mathf.MoveTowards(flag.maliciousCannon.cooldown, 0, Time.deltaTime);
if (flag.targetGrenade == null)
{
Transform target = V2Utils.GetClosestGrenade();
//if (ConfigManager.v2SecondMalCannonSnipeToggle.value && target != null
// && ___shootCooldown <= 0.9f && !___aboutToShoot && flag.maliciousCannon.cooldown == 0f)
if(target != null)
{
float distanceToPlayer = Vector3.Distance(target.position, PlayerTracker.Instance.GetTarget().transform.position);
float distanceToV2 = Vector3.Distance(target.position, flag.v2collider.bounds.center);
if (ConfigManager.v2SecondMalCannonSnipeToggle.value && flag.maliciousCannon.cooldown == 0 && distanceToPlayer <= ConfigManager.v2SecondMalCannonSnipeMaxDistanceToPlayer.value && distanceToV2 >= ConfigManager.v2SecondMalCannonSnipeMinDistanceToV2.value)
{
flag.targetGrenade = target;
___shootCooldown = 1f;
___aboutToShoot = true;
__instance.weapons[___currentWeapon].transform.GetChild(0).SendMessage("CancelAltCharge", SendMessageOptions.DontRequireReceiver);
__instance.CancelInvoke("ShootWeapon");
__instance.CancelInvoke("AltShootWeapon");
__instance.Invoke("ShootWeapon", ConfigManager.v2SecondMalCannonSnipeReactTime.value / ___eid.totalSpeedModifier);
V2SecondSwitchWeapon.SwitchWeapon.Invoke(__instance, new object[1] { 4 });
}
else if(ConfigManager.v2SecondCoreSnipeToggle.value && distanceToPlayer <= ConfigManager.v2SecondCoreSnipeMaxDistanceToPlayer.value && distanceToV2 >= ConfigManager.v2SecondCoreSnipeMinDistanceToV2.value)
{
flag.targetGrenade = target;
__instance.weapons[___currentWeapon].transform.GetChild(0).SendMessage("CancelAltCharge", SendMessageOptions.DontRequireReceiver);
__instance.CancelInvoke("ShootWeapon");
__instance.CancelInvoke("AltShootWeapon");
__instance.Invoke("ShootWeapon", ConfigManager.v2SecondCoreSnipeReactionTime.value / ___eid.totalSpeedModifier);
___shootCooldown = 1f;
___aboutToShoot = true;
V2SecondSwitchWeapon.SwitchWeapon.Invoke(__instance, new object[1] { 0 });
Debug.Log("Preparing to fire for grenade");
}
}
}
return true;
}
}
class V2SecondShootWeapon
{
static bool Prefix(V2 __instance, ref int ___currentWeapon)
{
if (!__instance.secondEncounter)
return true;
V2SecondFlag flag = __instance.GetComponent<V2SecondFlag>();
if (flag == null)
return true;
if (___currentWeapon == 0)
{
//Transform closestGrenade = V2Utils.GetClosestGrenade();
Transform closestGrenade = flag.targetGrenade;
if (closestGrenade != null && ConfigManager.v2SecondCoreSnipeToggle.value)
{
float distanceToPlayer = Vector3.Distance(closestGrenade.position, PlayerTracker.Instance.GetTarget().position);
float distanceToV2 = Vector3.Distance(closestGrenade.position, flag.v2collider.bounds.center);
if (distanceToPlayer <= ConfigManager.v2SecondCoreSnipeMaxDistanceToPlayer.value && distanceToV2 >= ConfigManager.v2SecondCoreSnipeMinDistanceToV2.value)
{
Debug.Log("Attempting to shoot the grenade");
GameObject revolverBeam = GameObject.Instantiate(Plugin.revolverBeam, __instance.transform.position + __instance.transform.forward, Quaternion.identity);
revolverBeam.transform.LookAt(closestGrenade.position);
if (revolverBeam.TryGetComponent<RevolverBeam>(out RevolverBeam comp))
{
comp.beamType = BeamType.Enemy;
comp.sourceWeapon = __instance.weapons[0];
}
__instance.ForceDodge(V2Utils.GetDirectionAwayFromTarget(flag.v2collider.bounds.center, closestGrenade.transform.position));
return false;
}
}
}
else if(___currentWeapon == 4)
{
__instance.ForceDodge(V2Utils.GetDirectionAwayFromTarget(flag.v2collider.bounds.center, PlayerTracker.Instance.GetTarget().position));
}
return true;
}
static void Postfix(V2 __instance, ref int ___currentWeapon)
{
if (!__instance.secondEncounter)
return;
if (___currentWeapon == 4)
{
V2SecondSwitchWeapon.SwitchWeapon.Invoke(__instance, new object[] { 0 });
}
}
}
class V2SecondSwitchWeapon
{
public static MethodInfo SwitchWeapon = typeof(V2).GetMethod("SwitchWeapon", BindingFlags.Instance | BindingFlags.NonPublic);
static bool Prefix(V2 __instance, ref int __0)
{
if (!__instance.secondEncounter || !ConfigManager.v2SecondRocketLauncherToggle.value)
return true;
if (__0 != 1 && __0 != 2)
return true;
int[] weapons = new int[] { 1, 2, 3 };
int weapon = weapons[UnityEngine.Random.RandomRangeInt(0, weapons.Length)];
__0 = weapon;
return true;
}
}
class V2SecondFastCoin
{
static MethodInfo switchWeapon = typeof(V2).GetMethod("SwitchWeapon", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
static bool Prefix(V2 __instance, ref int ___coinsToThrow, ref bool ___aboutToShoot, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb,
ref Transform ___target, Animator ___anim, ref bool ___shootingForCoin, ref int ___currentWeapon, ref float ___shootCooldown, ref bool ___aiming)
{
if (___coinsToThrow == 0)
{
return false;
}
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.coin, __instance.transform.position, __instance.transform.rotation);
Rigidbody rigidbody;
if (gameObject.TryGetComponent<Rigidbody>(out rigidbody))
{
rigidbody.AddForce((___target.transform.position - ___anim.transform.position).normalized * 20f + Vector3.up * 30f, ForceMode.VelocityChange);
}
Coin coin;
if (gameObject.TryGetComponent<Coin>(out coin))
{
GameObject gameObject2 = GameObject.Instantiate<GameObject>(coin.flash, coin.transform.position, MonoSingleton<CameraController>.Instance.transform.rotation);
gameObject2.transform.localScale *= 2f;
gameObject2.transform.SetParent(gameObject.transform, true);
}
___coinsToThrow--;
___aboutToShoot = true;
___shootingForCoin = true;
switchWeapon.Invoke(__instance, new object[1] { 0 });
__instance.CancelInvoke("ShootWeapon");
__instance.Invoke("ShootWeapon", ConfigManager.v2SecondFastCoinShootDelay.value);
___overrideTarget = coin.transform;
___overrideTargetRb = coin.GetComponent<Rigidbody>();
__instance.CancelInvoke("AltShootWeapon");
__instance.weapons[___currentWeapon].transform.GetChild(0).SendMessage("CancelAltCharge", SendMessageOptions.DontRequireReceiver);
___shootCooldown = 1f;
__instance.CancelInvoke("ThrowCoins");
__instance.Invoke("ThrowCoins", ConfigManager.v2SecondFastCoinThrowDelay.value);
return false;
}
}
class V2SecondEnrage
{
static void Postfix(BossHealthBar __instance, ref EnemyIdentifier ___eid, ref int ___currentHpSlider)
{
V2 v2 = __instance.GetComponent<V2>();
if (v2 != null && v2.secondEncounter && ___currentHpSlider == 1)
v2.Invoke("Enrage", 0.01f);
}
}
class V2SecondStart
{
static void RemoveAlwaysOnTop(Transform t)
{
foreach (Transform child in UnityUtils.GetComponentsInChildrenRecursively<Transform>(t))
{
child.gameObject.layer = Physics.IgnoreRaycastLayer;
}
t.gameObject.layer = Physics.IgnoreRaycastLayer;
}
static FieldInfo machineV2 = typeof(Machine).GetField("v2", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
static void Postfix( | V2 __instance, EnemyIdentifier ___eid)
{ |
if (!__instance.secondEncounter)
return;
V2SecondFlag flag = __instance.gameObject.AddComponent<V2SecondFlag>();
flag.v2collider = __instance.GetComponent<Collider>();
/*___eid.enemyType = EnemyType.V2Second;
___eid.UpdateBuffs();
machineV2.SetValue(__instance.GetComponent<Machine>(), __instance);*/
GameObject player = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Player").FirstOrDefault();
if (player == null)
return;
Transform v2WeaponTrans = __instance.weapons[0].transform.parent;
GameObject v2rocketLauncher = GameObject.Instantiate(Plugin.rocketLauncherAlt, v2WeaponTrans);
v2rocketLauncher.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
v2rocketLauncher.transform.localPosition = new Vector3(0.1f, -0.2f, -0.1f);
v2rocketLauncher.transform.localRotation = Quaternion.Euler(new Vector3(10.2682f, 12.6638f, 198.834f));
v2rocketLauncher.transform.GetChild(0).localPosition = Vector3.zero;
v2rocketLauncher.transform.GetChild(0).localRotation = Quaternion.Euler(Vector3.zero);
GameObject.DestroyImmediate(v2rocketLauncher.GetComponent<RocketLauncher>());
GameObject.DestroyImmediate(v2rocketLauncher.GetComponent<WeaponIcon>());
GameObject.DestroyImmediate(v2rocketLauncher.GetComponent<WeaponIdentifier>());
GameObject.DestroyImmediate(v2rocketLauncher.GetComponent<WeaponPos>());
GameObject.DestroyImmediate(v2rocketLauncher.GetComponent<Animator>());
V2RocketLauncher rocketComp = v2rocketLauncher.transform.GetChild(0).gameObject.AddComponent<V2RocketLauncher>();
rocketComp.v2collider = __instance.GetComponent<Collider>();
rocketComp.shootPoint = __instance.transform;
RemoveAlwaysOnTop(v2rocketLauncher.transform);
flag.rocketLauncher = rocketComp;
GameObject v2maliciousCannon = GameObject.Instantiate(Plugin.maliciousRailcannon, v2WeaponTrans);
GameObject.DestroyImmediate(v2maliciousCannon.GetComponent<Railcannon>());
GameObject.DestroyImmediate(v2maliciousCannon.GetComponent<WeaponIcon>());
GameObject.DestroyImmediate(v2maliciousCannon.GetComponent<WeaponIdentifier>());
GameObject.DestroyImmediate(v2maliciousCannon.GetComponent<WeaponIcon>());
GameObject.DestroyImmediate(v2maliciousCannon.GetComponent<WeaponPos>());
foreach (RailCannonPip pip in UnityUtils.GetComponentsInChildrenRecursively<RailCannonPip>(v2maliciousCannon.transform))
GameObject.DestroyImmediate(pip);
//GameObject.Destroy(v2maliciousCannon.GetComponent<Animator>());
v2maliciousCannon.transform.localScale = new Vector3(0.25f, 0.25f, 0.25f);
v2maliciousCannon.transform.localRotation = Quaternion.Euler(270, 90, 0);
v2maliciousCannon.transform.localPosition = Vector3.zero;
v2maliciousCannon.transform.GetChild(0).localPosition = Vector3.zero;
V2MaliciousCannon cannonComp = v2maliciousCannon.transform.GetChild(0).gameObject.AddComponent<V2MaliciousCannon>();
cannonComp.v2trans = __instance.transform;
RemoveAlwaysOnTop(v2maliciousCannon.transform);
flag.maliciousCannon = cannonComp;
EnemyRevolver rev = UnityUtils.GetComponentInChildrenRecursively<EnemyRevolver>(__instance.weapons[0].transform);
V2CommonRevolverComp revComp;
if (ConfigManager.v2SecondSharpshooterToggle.value)
{
revComp = rev.gameObject.AddComponent<V2CommonRevolverComp>();
revComp.secondPhase = __instance.secondEncounter;
}
__instance.weapons = new GameObject[] { __instance.weapons[0], __instance.weapons[1], __instance.weapons[2], v2rocketLauncher, v2maliciousCannon };
}
}
}
| Ultrapain/Patches/V2Second.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Mindflayer.cs",
"retrieved_chunk": " static FieldInfo goForward = typeof(Mindflayer).GetField(\"goForward\", BindingFlags.NonPublic | BindingFlags.Instance);\n static MethodInfo meleeAttack = typeof(Mindflayer).GetMethod(\"MeleeAttack\", BindingFlags.NonPublic | BindingFlags.Instance);\n static bool Prefix(Collider __0, out int __state)\n {\n __state = __0.gameObject.layer;\n return true;\n }\n static void Postfix(SwingCheck2 __instance, Collider __0, int __state)\n {\n if (__0.tag == \"Player\")",
"score": 0.8180396556854248
},
{
"filename": "Ultrapain/Patches/Drone.cs",
"retrieved_chunk": " public ParticleSystem particleSystem;\n public LineRenderer lr;\n public Firemode currentMode = Firemode.Projectile;\n private static Firemode[] allModes = Enum.GetValues(typeof(Firemode)) as Firemode[];\n static FieldInfo turretAimLine = typeof(Turret).GetField(\"aimLine\", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);\n static Material whiteMat;\n public void Awake()\n {\n lr = gameObject.AddComponent<LineRenderer>();\n lr.enabled = false;",
"score": 0.8149981498718262
},
{
"filename": "Ultrapain/Patches/Panopticon.cs",
"retrieved_chunk": " }\n class Panopticon_SpawnBlackHole\n {\n static void Postfix(FleshPrison __instance, EnemyIdentifier ___eid)\n {\n if (!__instance.altVersion)\n return;\n Vector3 vector = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.5f / ___eid.totalSpeedModifier);\n GameObject gameObject = GameObject.Instantiate(Plugin.sisyphusDestroyExplosion, vector, Quaternion.identity);\n GoreZone gz = __instance.GetComponentInParent<GoreZone>();",
"score": 0.7979024648666382
},
{
"filename": "Ultrapain/Patches/Solider.cs",
"retrieved_chunk": " /*___projectile = Plugin.soliderBullet;\n if (Plugin.decorativeProjectile2.gameObject != null)\n ___decProjectile = Plugin.decorativeProjectile2.gameObject;*/\n __instance.gameObject.AddComponent<SoliderShootCounter>();\n }\n }\n class Solider_SpawnProjectile_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP)\n {",
"score": 0.7875930666923523
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " {\n __state.canPostStyle = true;\n // REVOLVER NORMAL\n if (Coin_ReflectRevolver.shootingAltBeam == null)\n {\n if(ConfigManager.orbStrikeRevolverExplosion.value)\n {\n GameObject explosion = GameObject.Instantiate(Plugin.explosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity);\n foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>())\n {",
"score": 0.7854104042053223
}
] | csharp | V2 __instance, EnemyIdentifier ___eid)
{ |
using EleCho.GoCqHttpSdk;
using EleCho.GoCqHttpSdk.Message;
using EleCho.GoCqHttpSdk.Post;
using NodeBot.Classes;
using NodeBot.Command;
using NodeBot.Event;
using NodeBot.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
namespace NodeBot
{
public class NodeBot
{
public Dictionary<long, int> Permissions = new();
public int OpPermission = 5;
public CqWsSession session;
public event EventHandler<ConsoleInputEvent>? ConsoleInputEvent;
public event EventHandler<ReceiveMessageEvent>? ReceiveMessageEvent;
public List<ICommand> Commands = new List<ICommand>();
public List<IService> Services = new List<IService>();
public Queue<Task> ToDoQueue = new Queue<Task>();
public NodeBot(string ip)
{
session = new(new()
{
BaseUri = new Uri("ws://" + ip),
UseApiEndPoint = true,
UseEventEndPoint = true,
});
session.PostPipeline.Use(async (context, next) =>
{
if (ReceiveMessageEvent != null)
{
ReceiveMessageEvent(this, new(context));
}
await next();
});
ConsoleInputEvent += (sender, e) =>
{
ExecuteCommand(new ConsoleCommandSender(session, this), e.Text);
};
ReceiveMessageEvent += (sender, e) =>
{
if (e.Context is CqPrivateMessagePostContext cqPrivateMessage)
{
ExecuteCommand(new UserQQSender(session, this, cqPrivateMessage.UserId), cqPrivateMessage.Message);
}
if (e.Context is CqGroupMessagePostContext cqGroupMessage)
{
ExecuteCommand(new GroupQQSender(session ,this, cqGroupMessage.GroupId, cqGroupMessage.UserId), cqGroupMessage.Message);
}
};
}
/// <summary>
/// 保存权限数据
/// </summary>
public void SavePermission()
{
if (!File.Exists("Permission.json"))
{
File.Create("Permission.json").Close();
}
File.WriteAllText("Permission.json", Newtonsoft.Json.JsonConvert.SerializeObject(Permissions));
}
/// <summary>
/// 加载权限数据
/// </summary>
public void LoadPermission()
{
if (File.Exists("Permission.json"))
{
string json = File.ReadAllText("Permission.json");
Permissions = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<long, int>>(json)!;
}
}
public void RegisterCommand(ICommand command)
{
Commands.Add(command);
}
public void RegisterService(IService service)
{
Services.Add(service);
}
public void Start()
{
session.Start();
foreach (IService service in Services)
{
service.OnStart(this);
}
Task.Run(() =>
{
while (true)
{
Thread.Sleep(1000);
if (ToDoQueue.Count > 0)
{
Task task;
lock (ToDoQueue)
{
task = ToDoQueue.Dequeue();
}
task.Start();
}
}
});
}
public void CallConsoleInputEvent(string text)
{
if (ConsoleInputEvent != null)
{
ConsoleInputEvent(this, new(text));
}
}
public void ExecuteCommand(ICommandSender sender, string commandLine)
{
ICommand? command = GetCommandByCommandLine(commandLine);
if (command == null)
{
return;
}
if (sender is ConsoleCommandSender console)
{
if (command.IsConsoleCommand())
{
command.Execute(sender, commandLine);
}
}
}
public void ExecuteCommand(IQQSender sender, CqMessage commandLine)
{
if (commandLine[0] is CqTextMsg cqTextMsg)
{
ICommand? command = GetCommandByCommandLine(cqTextMsg.Text);
if (command == null)
{
return;
}
if (HasPermission(command, sender))
{
if (sender is UserQQSender userQQSender && command.IsUserCommand())
{
command.Execute(sender, commandLine);
}
if (sender is GroupQQSender groupQQSender && command.IsGroupCommand())
{
command.Execute(sender, commandLine);
}
}
else
{
sender.SendMessage("你没有权限");
}
}
}
public ICommand? GetCommandByCommandLine(string command)
{
string[] tmp = command.Split(' ');
foreach (string s in tmp)
{
if (s != string.Empty)
{
return FindCommand(s);
}
}
return null;
}
public ICommand? FindCommand(string commandName)
{
foreach (ICommand command in Commands)
{
if (command.GetName().ToLower() == commandName.ToLower())
{
return command;
}
}
return null;
}
public bool HasPermission(ICommand command, long QQNumber)
{
int permission = 0;
if (Permissions.ContainsKey(QQNumber))
{
permission = Permissions[QQNumber];
}
return permission >= command.GetDefaultPermission();
}
public bool HasPermission(ICommand command, | ICommandSender sender)
{ |
if (sender is IQQSender QQSender)
{
return HasPermission(command, QQSender.GetNumber());
}
if (sender is ConsoleCommandSender)
{
return true;
}
return false;
}
public void RunTask(Task task)
{
lock (ToDoQueue)
{
ToDoQueue.Enqueue(task);
}
}
public void RunAction(Action action)
{
Task task = new(action);
RunTask(task);
}
public void SendGroupMessage(long GroupNumber, CqMessage msgs)
{
RunAction(() =>
{
session.SendGroupMessage(GroupNumber, msgs);
});
}
public void SendPrivateMessage(long QQNumber, CqMessage msgs)
{
RunAction(() =>
{
session.SendPrivateMessage(QQNumber, msgs);
});
}
public void SendMessage(long Number, CqMessage msgs, UserType type)
{
if(type == UserType.User)
{
SendPrivateMessage(Number, msgs);
}
else if(type == UserType.Group)
{
SendGroupMessage(Number, msgs);
}
}
}
}
| NodeBot/NodeBot.cs | Blessing-Studio-NodeBot-ca9921f | [
{
"filename": "NodeBot/Command/Op.cs",
"retrieved_chunk": " catch { }\n }\n QQSender.GetNodeBot().SavePermission();\n return true;\n }\n public int GetDefaultPermission()\n {\n return 5;\n }\n public string GetName()",
"score": 0.8120681643486023
},
{
"filename": "NodeBot/Classes/IQQSender.cs",
"retrieved_chunk": " {\n this.Session = session;\n this.QQNumber = QQNumber;\n this.Bot = bot;\n }\n public long? GetGroupNumber()\n {\n return null;\n }\n public NodeBot GetNodeBot()",
"score": 0.7967137694358826
},
{
"filename": "NodeBot/Command/AtAll.cs",
"retrieved_chunk": " {\n return false;\n }\n public bool IsGroupCommand()\n {\n return true;\n }\n public bool IsUserCommand()\n {\n return false;",
"score": 0.7928538918495178
},
{
"filename": "NodeBot/github/GithubCommand.cs",
"retrieved_chunk": " public class GithubCommand : ICommand\n {\n public GithubCommand()\n {\n }\n public bool Execute(ICommandSender sender, string commandLine)\n {\n return true;\n }\n public bool Execute(IQQSender QQSender, CqMessage msgs)",
"score": 0.7921684980392456
},
{
"filename": "NodeBot/Command/Echo.cs",
"retrieved_chunk": " {\n public bool Execute(ICommandSender sender, string commandLine)\n {\n sender.SendMessage(commandLine.TrimStart().Substring(5));\n return true;\n }\n public bool Execute(IQQSender QQSender, CqMessage msgs)\n {\n if (msgs[0] is CqTextMsg msg)\n {",
"score": 0.7907370924949646
}
] | csharp | ICommandSender sender)
{ |
using HarmonyLib;
using MonoMod.Utils;
using System.Collections.Generic;
using UnityEngine;
namespace Ultrapain.Patches
{
/*public class SisyphusInstructionistFlag : MonoBehaviour
{
}
[HarmonyPatch(typeof(Sisyphus), nameof(Sisyphus.Knockdown))]
public class SisyphusInstructionist_Knockdown_Patch
{
static void Postfix(Sisyphus __instance, ref EnemyIdentifier ___eid)
{
SisyphusInstructionistFlag flag = __instance.GetComponent<SisyphusInstructionistFlag>();
if (flag != null)
return;
__instance.gameObject.AddComponent<SisyphusInstructionistFlag>();
foreach(EnemySimplifier esi in UnityUtils.GetComponentsInChildrenRecursively<EnemySimplifier>(__instance.transform))
{
esi.enraged = true;
}
GameObject effect = GameObject.Instantiate(Plugin.enrageEffect, __instance.transform);
effect.transform.localScale = Vector3.one * 0.2f;
}
}*/
public class SisyphusInstructionist_Start
{
public static GameObject _shockwave;
public static | GameObject shockwave
{ |
get {
if(_shockwave == null && Plugin.shockwave != null)
{
_shockwave = GameObject.Instantiate(Plugin.shockwave);
CommonActivator activator = _shockwave.AddComponent<CommonActivator>();
//ObjectActivator objectActivator = _shockwave.AddComponent<ObjectActivator>();
//objectActivator.originalInstanceID = _shockwave.GetInstanceID();
//objectActivator.activator = activator;
activator.originalId = _shockwave.GetInstanceID();
foreach (Transform t in _shockwave.transform)
t.gameObject.SetActive(false);
/*Renderer rend = _shockwave.GetComponent<Renderer>();
activator.rend = rend;
rend.enabled = false;*/
Rigidbody rb = _shockwave.GetComponent<Rigidbody>();
activator.rb = rb;
activator.kinematic = rb.isKinematic;
activator.colDetect = rb.detectCollisions;
rb.detectCollisions = false;
rb.isKinematic = true;
AudioSource aud = _shockwave.GetComponent<AudioSource>();
activator.aud = aud;
aud.enabled = false;
/*Collider col = _shockwave.GetComponent<Collider>();
activator.col = col;
col.enabled = false;*/
foreach(Component comp in _shockwave.GetComponents<Component>())
{
if (comp == null || comp is Transform)
continue;
if (comp is MonoBehaviour behaviour)
{
if (behaviour is not CommonActivator && behaviour is not ObjectActivator)
{
behaviour.enabled = false;
activator.comps.Add(behaviour);
}
}
}
PhysicalShockwave shockComp = _shockwave.GetComponent<PhysicalShockwave>();
shockComp.maxSize = 100f;
shockComp.speed = ConfigManager.sisyInstJumpShockwaveSpeed.value;
shockComp.damage = ConfigManager.sisyInstJumpShockwaveDamage.value;
shockComp.enemy = true;
shockComp.enemyType = EnemyType.Sisyphus;
_shockwave.transform.localScale = new Vector3(_shockwave.transform.localScale.x, _shockwave.transform.localScale.y * ConfigManager.sisyInstJumpShockwaveSize.value, _shockwave.transform.localScale.z);
}
return _shockwave;
}
}
static void Postfix(Sisyphus __instance, ref GameObject ___explosion, ref PhysicalShockwave ___m_ShockwavePrefab)
{
//___explosion = shockwave/*___m_ShockwavePrefab.gameObject*/;
___m_ShockwavePrefab = shockwave.GetComponent<PhysicalShockwave>();
}
}
/*
* A bug occurs where if the player respawns, the shockwave prefab gets deleted
*
* Check existence of the prefab on update
*/
public class SisyphusInstructionist_Update
{
static void Postfix(Sisyphus __instance, ref PhysicalShockwave ___m_ShockwavePrefab)
{
//___explosion = shockwave/*___m_ShockwavePrefab.gameObject*/;
if(___m_ShockwavePrefab == null)
___m_ShockwavePrefab = SisyphusInstructionist_Start.shockwave.GetComponent<PhysicalShockwave>();
}
}
public class SisyphusInstructionist_SetupExplosion
{
static void Postfix(Sisyphus __instance, ref GameObject __0, EnemyIdentifier ___eid)
{
GameObject shockwave = GameObject.Instantiate(Plugin.shockwave, __0.transform.position, __0.transform.rotation);
PhysicalShockwave comp = shockwave.GetComponent<PhysicalShockwave>();
comp.enemy = true;
comp.enemyType = EnemyType.Sisyphus;
comp.maxSize = 100f;
comp.speed = ConfigManager.sisyInstBoulderShockwaveSpeed.value * ___eid.totalSpeedModifier;
comp.damage = (int)(ConfigManager.sisyInstBoulderShockwaveDamage.value * ___eid.totalDamageModifier);
shockwave.transform.localScale = new Vector3(shockwave.transform.localScale.x, shockwave.transform.localScale.y * ConfigManager.sisyInstBoulderShockwaveSize.value, shockwave.transform.localScale.z);
}
/*static bool Prefix(Sisyphus __instance, ref GameObject __0, ref Animator ___anim)
{
string clipName = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name;
Debug.Log($"Clip name: {clipName}");
PhysicalShockwave comp = __0.GetComponent<PhysicalShockwave>();
if (comp == null)
return true;
comp.enemy = true;
comp.enemyType = EnemyType.Sisyphus;
comp.maxSize = 100f;
comp.speed = 35f;
comp.damage = 20;
__0.transform.localScale = new Vector3(__0.transform.localScale.x, __0.transform.localScale.y / 2, __0.transform.localScale.z);
GameObject explosion = GameObject.Instantiate(Plugin.sisyphiusExplosion, __0.transform.position, Quaternion.identity);
__0 = explosion;
return true;
}*/
}
public class SisyphusInstructionist_StompExplosion
{
static bool Prefix(Sisyphus __instance, Transform ___target, EnemyIdentifier ___eid)
{
Vector3 vector = __instance.transform.position + Vector3.up;
if (Physics.Raycast(vector, ___target.position - vector, Vector3.Distance(___target.position, vector), LayerMaskDefaults.Get(LMD.Environment)))
{
vector = __instance.transform.position + Vector3.up * 5f;
}
GameObject explosion = Object.Instantiate<GameObject>(Plugin.sisyphiusPrimeExplosion, vector, Quaternion.identity);
foreach(Explosion exp in explosion.GetComponentsInChildren<Explosion>())
{
exp.enemy = true;
exp.toIgnore.Add(EnemyType.Sisyphus);
exp.maxSize *= ConfigManager.sisyInstStrongerExplosionSizeMulti.value;
exp.speed *= ConfigManager.sisyInstStrongerExplosionSizeMulti.value * ___eid.totalSpeedModifier;
exp.damage = (int)(exp.damage * ConfigManager.sisyInstStrongerExplosionDamageMulti.value * ___eid.totalDamageModifier);
}
return false;
}
}
}
| Ultrapain/Patches/SisyphusInstructionist.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Panopticon.cs",
"retrieved_chunk": " explosion.damage = Mathf.RoundToInt((float)explosion.damage * ___eid.totalDamageModifier);\n explosion.maxSize *= ___eid.totalDamageModifier;\n }\n }\n }\n class Panopticon_SpawnFleshDrones\n {\n struct StateInfo\n {\n public GameObject template;",
"score": 0.8343368768692017
},
{
"filename": "Ultrapain/Patches/MinosPrime.cs",
"retrieved_chunk": " __instance.Teleport(vector + Vector3.up * 25f, __instance.transform.position);\n __instance.SendMessage(\"DropAttack\");\n return false;\n }\n }\n // End of PREPARE THYSELF\n class MinosPrime_ProjectileCharge\n {\n static bool Prefix(MinosPrime __instance, Animator ___anim)\n {",
"score": 0.829330325126648
},
{
"filename": "Ultrapain/Patches/MinosPrime.cs",
"retrieved_chunk": " }\n class MinosPrimeFlag : MonoBehaviour\n {\n void Start()\n {\n }\n public void ComboExplosion()\n {\n GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity);\n foreach(Explosion e in explosion.GetComponentsInChildren<Explosion>())",
"score": 0.8253916501998901
},
{
"filename": "Ultrapain/Patches/Stalker.cs",
"retrieved_chunk": " }\n }\n __instance.gameObject.SetActive(false);\n Object.Destroy(__instance.gameObject);\n return false;\n }\n }\n public class SandificationZone_Enter_Patch\n {\n static void Postfix(SandificationZone __instance, Collider __0)",
"score": 0.8249263763427734
},
{
"filename": "Ultrapain/Patches/DruidKnight.cs",
"retrieved_chunk": " public static float offset = 0.205f;\n class StateInfo\n {\n public GameObject oldProj;\n public GameObject tempProj;\n }\n static bool Prefix(Mandalore __instance, out StateInfo __state)\n {\n __state = new StateInfo() { oldProj = __instance.fullAutoProjectile };\n GameObject obj = new GameObject();",
"score": 0.8244726657867432
}
] | csharp | GameObject shockwave
{ |
using LegendaryLibraryNS.Enums;
using LegendaryLibraryNS.Services;
using Playnite;
using Playnite.Commands;
using Playnite.SDK;
using Playnite.SDK.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace LegendaryLibraryNS
{
public class LegendaryLibrarySettings
{
public bool ImportInstalledGames { get; set; } = LegendaryLauncher.IsInstalled;
public bool ConnectAccount { get; set; } = false;
public bool ImportUninstalledGames { get; set; } = false;
public string SelectedLauncherPath { get; set; } = "";
public bool UseCustomLauncherPath { get; set; } = false;
public string GamesInstallationPath { get; set; } = LegendaryLauncher.DefaultGamesInstallationPath;
public bool LaunchOffline { get; set; } = false;
public List<string> OnlineList { get; set; } = new List<string>();
public string PreferredCDN { get; set; } = LegendaryLauncher.DefaultPreferredCDN;
public bool NoHttps { get; set; } = LegendaryLauncher.DefaultNoHttps;
public int DoActionAfterDownloadComplete { get; set; } = (int)DownloadCompleteAction.Nothing;
public bool SyncGameSaves { get; set; } = false;
public int MaxWorkers { get; set; } = LegendaryLauncher.DefaultMaxWorkers;
public int MaxSharedMemory { get; set; } = LegendaryLauncher.DefaultMaxSharedMemory;
public bool EnableReordering { get; set; } = false;
public int AutoClearCache { get; set; } = (int)ClearCacheTime.Never;
}
public class LegendaryLibrarySettingsViewModel : PluginSettingsViewModel<LegendaryLibrarySettings, | LegendaryLibrary>
{ |
public bool IsUserLoggedIn
{
get
{
return new EpicAccountClient(PlayniteApi, LegendaryLauncher.TokensPath).GetIsUserLoggedIn();
}
}
public RelayCommand<object> LoginCommand
{
get => new RelayCommand<object>(async (a) =>
{
await Login();
});
}
public LegendaryLibrarySettingsViewModel(LegendaryLibrary library, IPlayniteAPI api) : base(library, api)
{
Settings = LoadSavedSettings() ?? new LegendaryLibrarySettings();
}
private async Task Login()
{
try
{
var clientApi = new EpicAccountClient(PlayniteApi, LegendaryLauncher.TokensPath);
await clientApi.Login();
OnPropertyChanged(nameof(IsUserLoggedIn));
}
catch (Exception e) when (!Debugger.IsAttached)
{
PlayniteApi.Dialogs.ShowErrorMessage(PlayniteApi.Resources.GetString(LOC.EpicNotLoggedInError), "");
Logger.Error(e, "Failed to authenticate user.");
}
}
}
}
| src/LegendaryLibrarySettingsViewModel.cs | hawkeye116477-playnite-legendary-plugin-d7af6b2 | [
{
"filename": "src/Models/DownloadManagerData.cs",
"retrieved_chunk": " public string installPath { get; set; } = \"\";\n public int downloadAction { get; set; }\n public bool enableReordering { get; set; }\n public int maxWorkers { get; set; }\n public int maxSharedMemory { get; set; }\n public List<string> extraContent { get; set; } = default;\n }\n}",
"score": 0.8941290974617004
},
{
"filename": "src/LegendaryLibrary.cs",
"retrieved_chunk": "using System.Windows.Controls;\nnamespace LegendaryLibraryNS\n{\n [LoadPlugin]\n public class LegendaryLibrary : LibraryPluginBase<LegendaryLibrarySettingsViewModel>\n {\n private static readonly ILogger logger = LogManager.GetLogger();\n public static LegendaryLibrary Instance { get; set; }\n public static bool LegendaryGameInstaller { get; internal set; }\n public LegendaryDownloadManager LegendaryDownloadManager { get; set; }",
"score": 0.8768853545188904
},
{
"filename": "src/Models/LegendaryGameInfo.cs",
"retrieved_chunk": " public bool Is_dlc { get; set; }\n }\n public class Manifest\n {\n public double Disk_size { get; set; }\n public double Download_size { get; set; }\n public string Launch_exe { get; set; }\n public string[] Install_tags { get; set; }\n public Tag_Disk_Size[] Tag_disk_size { get; set; }\n public Tag_Download_Size[] Tag_download_size { get; set; }",
"score": 0.8631578683853149
},
{
"filename": "src/LegendaryClient.cs",
"retrieved_chunk": " public class LegendaryClient : LibraryClient\n {\n private static readonly ILogger logger = LogManager.GetLogger();\n public override string Icon => LegendaryLauncher.Icon;\n public override bool IsInstalled => LegendaryLauncher.IsInstalled;\n public override void Open()\n {\n LegendaryLauncher.StartClient();\n }\n public override void Shutdown()",
"score": 0.859559178352356
},
{
"filename": "src/LegendaryMessagesSettings.cs",
"retrieved_chunk": " public class LegendaryMessagesSettingsModel\n {\n public bool DontShowDownloadManagerWhatsUpMsg { get; set; } = false;\n }\n public class LegendaryMessagesSettings\n {\n public static LegendaryMessagesSettingsModel LoadSettings()\n {\n LegendaryMessagesSettingsModel messagesSettings = null;\n var dataDir = LegendaryLibrary.Instance.GetPluginUserDataPath();",
"score": 0.8588293194770813
}
] | csharp | LegendaryLibrary>
{ |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SQLServerCoverage.Gateway;
using SQLServerCoverage.Objects;
using SQLServerCoverage.Parsers;
namespace SQLServerCoverage.Source
{
public class DatabaseSourceGateway : SourceGateway
{
private readonly DatabaseGateway _databaseGateway;
public DatabaseSourceGateway(DatabaseGateway databaseGateway)
{
_databaseGateway = databaseGateway;
}
public | SqlServerVersion GetVersion()
{ |
var compatibilityString = _databaseGateway.GetString("select compatibility_level from sys.databases where database_id = db_id();");
SqlServerVersion res;
if (Enum.TryParse(string.Format("Sql{0}", compatibilityString), out res))
{
return res;
}
return SqlServerVersion.Sql130;
}
public bool IsAzure()
{
var versionString = _databaseGateway.GetString("select @@version");
return versionString.Contains("Azure");
}
public IEnumerable<Batch> GetBatches(List<string> objectFilter)
{
var table =
_databaseGateway.GetRecords(
"SELECT sm.object_id, ISNULL('[' + OBJECT_SCHEMA_NAME(sm.object_id) + '].[' + OBJECT_NAME(sm.object_id) + ']', '[' + st.name + ']') object_name, sm.definition, sm.uses_quoted_identifier FROM sys.sql_modules sm LEFT JOIN sys.triggers st ON st.object_id = sm.object_id WHERE sm.object_id NOT IN(SELECT object_id FROM sys.objects WHERE type = 'IF'); ");
var batches = new List<Batch>();
var version = GetVersion();
var excludedObjects = GetExcludedObjects();
if(objectFilter == null)
objectFilter = new List<string>();
objectFilter.Add(".*tSQLt.*");
foreach (DataRow row in table.Rows)
{
var quoted = (bool) row["uses_quoted_identifier"];
var name = row["object_name"] as string;
if (name != null && row["object_id"] as int? != null && ShouldIncludeObject(name, objectFilter, excludedObjects))
{
batches.Add(
new Batch(new StatementParser(version), quoted, EndDefinitionWithNewLine(GetDefinition(row)), name, name, (int) row["object_id"]));
}
}
table.Dispose();
foreach (var batch in batches)
{
batch.StatementCount = batch.Statements.Count(p => p.IsCoverable);
batch.BranchesCount = batch.Statements.SelectMany(x => x.Branches).Count();
}
return batches.Where(p=>p.StatementCount > 0);
}
private static string GetDefinition(DataRow row)
{
if (row["definition"] != null && row["definition"] is string)
{
var definition = row["definition"] as string;
if (!String.IsNullOrEmpty(definition))
return definition;
}
return String.Empty;
}
public string GetWarnings()
{
var warnings = new StringBuilder();
var table =
_databaseGateway.GetRecords(
"select \'[\' + object_schema_name(object_id) + \'].[\' + object_name(object_id) + \']\' as object_name from sys.sql_modules where object_id not in (select object_id from sys.objects where type = 'IF') and definition is null");
foreach (DataRow row in table.Rows)
{
if(row["object_name"] == null || row["object_name"] as string == null)
{
warnings.AppendFormat("An object_name was not found, unable to provide code coverage results, I don't even know the name to tell you what it was - check sys.sql_modules where definition is null and the object is not an inline function");
}
else
{
var name = (string)row["object_name"];
warnings.AppendFormat("The object definition for {0} was not found, unable to provide code coverage results", name);
}
}
return warnings.ToString();
}
private static string EndDefinitionWithNewLine(string definition)
{
if (definition.EndsWith("\r\n\r\n"))
return definition;
return definition + "\r\n\r\n";
}
private List<string> GetExcludedObjects()
{
var tSQLtObjects =
_databaseGateway.GetRecords(
@"select '[' + object_schema_name(object_id) + '].[' + object_name(object_id) + ']' as object_name from sys.procedures
where schema_id in (
select major_id from sys.extended_properties ep
where class_desc = 'SCHEMA' and name = 'tSQLt.TestClass' )");
var excludedObjects = new List<string>();
foreach (DataRow row in tSQLtObjects.Rows)
{
excludedObjects.Add(row[0].ToString().ToLowerInvariant());
}
return excludedObjects;
}
private bool ShouldIncludeObject(string name, List<string> customExcludedObjects, List<string> excludedObjects)
{
var lowerName = name.ToLowerInvariant();
foreach (var filter in customExcludedObjects)
{
if (Regex.IsMatch(name, (string) (filter ?? ".*")))
return false;
}
foreach (var filter in excludedObjects)
{
if (filter == lowerName)
return false;
}
return true;
}
}
} | src/SQLServerCoverageLib/Gateway/DatabaseSourceGateway.cs | sayantandey-SQLServerCoverage-aea57e3 | [
{
"filename": "src/SQLServerCoverageLib/Gateway/DatabaseGateway.cs",
"retrieved_chunk": " private readonly string _databaseName;\n private readonly SqlConnectionStringBuilder _connectionStringBuilder;\n public string DataSource { get { return _connectionStringBuilder.DataSource; } }\n public int TimeOut { get; set; }\n public DatabaseGateway()\n {\n //for mocking.\n }\n public DatabaseGateway(string connectionString, string databaseName)\n {",
"score": 0.8769092559814453
},
{
"filename": "src/SQLServerCoverageLib/CodeCoverage.cs",
"retrieved_chunk": " private readonly SourceGateway _source;\n private CoverageResult _result;\n public const short TIMEOUT_EXPIRED = -2; //From TdsEnums\n public SQLServerCoverageException Exception { get; private set; } = null;\n public bool IsStarted { get; private set; } = false;\n private TraceController _trace;\n //This is to better support powershell and optional parameters\n public CodeCoverage(string connectionString, string databaseName) : this(connectionString, databaseName, null, false, false, TraceControllerType.Default)\n {\n }",
"score": 0.8473955988883972
},
{
"filename": "src/SQLServerCoverageLib/Trace/AzureTraceController.cs",
"retrieved_chunk": " private readonly List<string> _events = new List<string>();\n private bool _stop;\n private bool _stopped;\n private bool _stopping;\n public AzureTraceController(DatabaseGateway gateway, string databaseName) : base(gateway, databaseName)\n {\n }\n private void Create()\n {\n RunScript(CreateTrace, \"Error creating the extended events trace, error: {0}\");",
"score": 0.8423277735710144
},
{
"filename": "src/SQLServerCoverageLib/Trace/SqlLocalDbTraceController.cs",
"retrieved_chunk": "using SQLServerCoverage.Gateway;\nusing System.IO;\nnamespace SQLServerCoverage.Trace\n{\n class SqlLocalDbTraceController : SqlTraceController\n {\n public SqlLocalDbTraceController(DatabaseGateway gateway, string databaseName) : base(gateway, databaseName)\n {\n }\n protected override void Create()",
"score": 0.8407686948776245
},
{
"filename": "src/SQLServerCoverageLib/Trace/TraceController.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing SQLServerCoverage.Gateway;\nnamespace SQLServerCoverage.Trace\n{\n abstract class TraceController\n {\n protected readonly string DatabaseId;\n protected readonly DatabaseGateway Gateway;\n protected string FileName;",
"score": 0.8306131958961487
}
] | csharp | SqlServerVersion GetVersion()
{ |
using HarmonyLib;
using UnityEngine;
namespace Ultrapain.Patches
{
class Virtue_Start_Patch
{
static void Postfix(Drone __instance, ref EnemyIdentifier ___eid)
{
VirtueFlag flag = __instance.gameObject.AddComponent<VirtueFlag>();
flag.virtue = __instance;
}
}
class Virtue_Death_Patch
{
static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid)
{
if(___eid.enemyType != EnemyType.Virtue)
return true;
__instance.GetComponent<VirtueFlag>().DestroyProjectiles();
return true;
}
}
class VirtueFlag : MonoBehaviour
{
public AudioSource lighningBoltSFX;
public GameObject ligtningBoltAud;
public Transform windupObj;
private EnemyIdentifier eid;
public | Drone virtue; |
public void Awake()
{
eid = GetComponent<EnemyIdentifier>();
ligtningBoltAud = Instantiate(Plugin.lighningBoltSFX, transform);
lighningBoltSFX = ligtningBoltAud.GetComponent<AudioSource>();
}
public void SpawnLightningBolt()
{
LightningStrikeExplosive lightningStrikeExplosive = Instantiate(Plugin.lightningStrikeExplosiveSetup.gameObject, windupObj.transform.position, Quaternion.identity).GetComponent<LightningStrikeExplosive>();
lightningStrikeExplosive.safeForPlayer = false;
lightningStrikeExplosive.damageMultiplier = eid.totalDamageModifier * ((virtue.enraged)? ConfigManager.virtueEnragedLightningDamage.value : ConfigManager.virtueNormalLightningDamage.value);
if(windupObj != null)
Destroy(windupObj.gameObject);
}
public void DestroyProjectiles()
{
CancelInvoke("SpawnLightningBolt");
if (windupObj != null)
Destroy(windupObj.gameObject);
}
}
class Virtue_SpawnInsignia_Patch
{
static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, ref int ___usedAttacks)
{
if (___eid.enemyType != EnemyType.Virtue)
return true;
GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, int damage, float lastMultiplier)
{
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity);
VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>();
component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer();
component.parentDrone = __instance;
component.hadParent = true;
component.damage = damage;
component.explosionLength *= lastMultiplier;
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
if (__instance.enraged)
{
component.predictive = true;
}
/*if (___difficulty == 1)
{
component.windUpSpeedMultiplier = 0.875f;
}
else if (___difficulty == 0)
{
component.windUpSpeedMultiplier = 0.75f;
}*/
if (MonoSingleton<PlayerTracker>.Instance.playerType == PlayerType.Platformer)
{
gameObject.transform.localScale *= 0.75f;
component.windUpSpeedMultiplier *= 0.875f;
}
component.windUpSpeedMultiplier *= ___eid.totalSpeedModifier;
component.damage = Mathf.RoundToInt((float)component.damage * ___eid.totalDamageModifier);
return gameObject;
}
if (__instance.enraged && !ConfigManager.virtueTweakEnragedAttackToggle.value)
return true;
if (!__instance.enraged && !ConfigManager.virtueTweakNormalAttackToggle.value)
return true;
bool insignia = (__instance.enraged) ? ConfigManager.virtueEnragedAttackType.value == ConfigManager.VirtueAttackType.Insignia
: ConfigManager.virtueNormalAttackType.value == ConfigManager.VirtueAttackType.Insignia;
if (insignia)
{
bool xAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXtoggle.value : ConfigManager.virtueNormalInsigniaXtoggle.value;
bool yAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYtoggle.value : ConfigManager.virtueNormalInsigniaYtoggle.value;
bool zAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZtoggle.value : ConfigManager.virtueNormalInsigniaZtoggle.value;
if (xAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXdamage.value : ConfigManager.virtueNormalInsigniaXdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXsize.value : ConfigManager.virtueNormalInsigniaXsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
obj.transform.Rotate(new Vector3(90f, 0, 0));
}
if (yAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYdamage.value : ConfigManager.virtueNormalInsigniaYdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYsize.value : ConfigManager.virtueNormalInsigniaYsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
}
if (zAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZdamage.value : ConfigManager.virtueNormalInsigniaZdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZsize.value : ConfigManager.virtueNormalInsigniaZsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
obj.transform.Rotate(new Vector3(0, 0, 90f));
}
}
else
{
Vector3 predictedPos;
if (___difficulty <= 1)
predictedPos = MonoSingleton<PlayerTracker>.Instance.GetPlayer().position;
else
{
Vector3 vector = new Vector3(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().x, 0f, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().z);
predictedPos = MonoSingleton<PlayerTracker>.Instance.GetPlayer().position + vector.normalized * Mathf.Min(vector.magnitude, 5.0f);
}
GameObject currentWindup = GameObject.Instantiate<GameObject>(Plugin.lighningStrikeWindup.gameObject, predictedPos, Quaternion.identity);
foreach (Follow follow in currentWindup.GetComponents<Follow>())
{
if (follow.speed != 0f)
{
if (___difficulty >= 2)
{
follow.speed *= (float)___difficulty;
}
else if (___difficulty == 1)
{
follow.speed /= 2f;
}
else
{
follow.enabled = false;
}
follow.speed *= ___eid.totalSpeedModifier;
}
}
VirtueFlag flag = __instance.GetComponent<VirtueFlag>();
flag.lighningBoltSFX.Play();
flag.windupObj = currentWindup.transform;
flag.Invoke("SpawnLightningBolt", (__instance.enraged)? ConfigManager.virtueEnragedLightningDelay.value : ConfigManager.virtueNormalLightningDelay.value);
}
___usedAttacks += 1;
if(___usedAttacks == 3)
{
__instance.Invoke("Enrage", 3f / ___eid.totalSpeedModifier);
}
return false;
}
/*static void Postfix(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, bool __state)
{
if (!__state)
return;
GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target)
{
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity);
VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>();
component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer();
component.parentDrone = __instance;
component.hadParent = true;
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
if (__instance.enraged)
{
component.predictive = true;
}
if (___difficulty == 1)
{
component.windUpSpeedMultiplier = 0.875f;
}
else if (___difficulty == 0)
{
component.windUpSpeedMultiplier = 0.75f;
}
if (MonoSingleton<PlayerTracker>.Instance.playerType == PlayerType.Platformer)
{
gameObject.transform.localScale *= 0.75f;
component.windUpSpeedMultiplier *= 0.875f;
}
component.windUpSpeedMultiplier *= ___eid.totalSpeedModifier;
component.damage = Mathf.RoundToInt((float)component.damage * ___eid.totalDamageModifier);
return gameObject;
}
GameObject xAxisInsignia = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target);
xAxisInsignia.transform.Rotate(new Vector3(90, 0, 0));
xAxisInsignia.transform.localScale = new Vector3(xAxisInsignia.transform.localScale.x * horizontalInsigniaScale, xAxisInsignia.transform.localScale.y, xAxisInsignia.transform.localScale.z * horizontalInsigniaScale);
GameObject zAxisInsignia = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target);
zAxisInsignia.transform.Rotate(new Vector3(0, 0, 90));
zAxisInsignia.transform.localScale = new Vector3(zAxisInsignia.transform.localScale.x * horizontalInsigniaScale, zAxisInsignia.transform.localScale.y, zAxisInsignia.transform.localScale.z * horizontalInsigniaScale);
}*/
}
}
| Ultrapain/Patches/Virtue.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " {\n private LeviathanHead comp;\n private Animator anim;\n //private Collider col;\n private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };\n public float playerRocketRideTracker = 0;\n private GameObject currentProjectileEffect;\n private AudioSource currentProjectileAud;\n private Transform shootPoint;\n public float currentProjectileSize = 0;",
"score": 0.8644540905952454
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " }\n class OrbitalExplosionInfo : MonoBehaviour\n {\n public bool active = true;\n public string id;\n public int points;\n }\n class Grenade_Explode\n {\n class StateInfo",
"score": 0.8539417386054993
},
{
"filename": "Ultrapain/Patches/V2Second.cs",
"retrieved_chunk": " public class V2SecondFlag : MonoBehaviour\n {\n public V2RocketLauncher rocketLauncher;\n public V2MaliciousCannon maliciousCannon;\n public Collider v2collider;\n public Transform targetGrenade;\n }\n public class V2RocketLauncher : MonoBehaviour\n {\n public Transform shootPoint;",
"score": 0.8525964021682739
},
{
"filename": "Ultrapain/Patches/V2Common.cs",
"retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;",
"score": 0.8475018739700317
},
{
"filename": "Ultrapain/Patches/Cerberus.cs",
"retrieved_chunk": "using UnityEngine;\nnamespace Ultrapain.Patches\n{\n class CerberusFlag : MonoBehaviour\n {\n public int extraDashesRemaining = ConfigManager.cerberusTotalDashCount.value - 1;\n public Transform head;\n public float lastParryTime;\n private EnemyIdentifier eid;\n private void Awake()",
"score": 0.846580982208252
}
] | csharp | Drone virtue; |
#nullable enable
using Newtonsoft.Json;
namespace Mochineko.YouTubeLiveStreamingClient.Responses
{
[JsonObject]
public sealed class LiveChatMessageItem
{
[JsonProperty("kind"), JsonRequired]
public string Kind { get; private set; } = string.Empty;
[JsonProperty("etag"), JsonRequired]
public string Etag { get; private set; } = string.Empty;
[JsonProperty("id"), JsonRequired]
public string Id { get; private set; } = string.Empty;
[JsonProperty("snippet"), JsonRequired]
public LiveChatMessageSnippet Snippet { get; private set; } = new();
[JsonProperty("authorDetails"), JsonRequired]
public | AuthorDetails AuthorDetails { | get; private set; } = new();
}
} | Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessageItem.cs | mochi-neko-youtube-live-streaming-client-unity-b712d77 | [
{
"filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/VideoItem.cs",
"retrieved_chunk": " public string Etag { get; private set; } = string.Empty;\n [JsonProperty(\"id\"), JsonRequired]\n public string Id { get; private set; } = string.Empty;\n [JsonProperty(\"snippet\"), JsonRequired]\n public VideoSnippet Snippet { get; private set; } = new();\n [JsonProperty(\"liveStreamingDetails\"), JsonRequired]\n public LiveStreamingDetails LiveStreamingDetails { get; private set; } = new();\n }\n}",
"score": 0.9499595165252686
},
{
"filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessagesAPIResponse.cs",
"retrieved_chunk": " [JsonProperty(\"etag\"), JsonRequired]\n public string Etag { get; private set; } = string.Empty;\n [JsonProperty(\"nextPageToken\"), JsonRequired]\n public string NextPageToken { get; private set; } = string.Empty;\n [JsonProperty(\"pollingIntervalMillis\"), JsonRequired]\n public uint PollingIntervalMillis { get; private set; }\n [JsonProperty(\"pageInfo\"), JsonRequired]\n public PageInfo PageInfo { get; private set; } = new();\n [JsonProperty(\"items\"), JsonRequired]\n public List<LiveChatMessageItem> Items { get; private set; } = new();",
"score": 0.9472273588180542
},
{
"filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessageSnippet.cs",
"retrieved_chunk": " public LiveChatMessageType Type { get; private set; }\n [JsonProperty(\"liveChatId\"), JsonRequired]\n public string LiveChatId { get; private set; } = string.Empty;\n [JsonProperty(\"authorChannelId\"), JsonRequired]\n public string AuthorChannelId { get; private set; } = string.Empty;\n [JsonProperty(\"publishedAt\"), JsonRequired]\n public DateTime PublishedAt { get; private set; }\n [JsonProperty(\"hasDisplayContent\"), JsonRequired]\n public bool HasDisplayContent { get; private set; }\n [JsonProperty(\"displayMessage\"), JsonRequired]",
"score": 0.9460216760635376
},
{
"filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/VideoSnippet.cs",
"retrieved_chunk": " [JsonProperty(\"tags\")]\n public string[]? Tags { get; private set; }\n [JsonProperty(\"categoryId\"), JsonRequired]\n public string CategoryId { get; private set; } = string.Empty;\n [JsonProperty(\"liveBroadcastContent\"), JsonRequired]\n public string LiveBroadcastContent { get; private set; } = string.Empty;\n [JsonProperty(\"defaultLanguage\")]\n public string? DefaultLanguage { get; private set; }\n [JsonProperty(\"localized\"), JsonRequired]\n public Localized Localized { get; private set; } = new();",
"score": 0.9457679390907288
},
{
"filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/VideoSnippet.cs",
"retrieved_chunk": " [JsonProperty(\"channelId\"), JsonRequired]\n public string ChannelId { get; private set; } = string.Empty;\n [JsonProperty(\"title\"), JsonRequired]\n public string Title { get; private set; } = string.Empty;\n [JsonProperty(\"description\"), JsonRequired]\n public string Description { get; private set; } = string.Empty;\n [JsonProperty(\"thumbnails\"), JsonRequired]\n public VideoThumbnails Thumbnails { get; private set; } = new();\n [JsonProperty(\"channelTitle\"), JsonRequired]\n public string ChannelTitle { get; private set; } = string.Empty;",
"score": 0.9356287121772766
}
] | csharp | AuthorDetails AuthorDetails { |
/*
Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox')
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
namespace Kingdox.UniFlux.Core.Internal
{
internal static class FluxState<T,T2>
{
internal static readonly | IFluxParam<T, T2, Action<T2>> flux_action_param = new StateFlux<T,T2>(); |
internal static void Store(in T key, in Action<T2> action, in bool condition) => flux_action_param.Store(in condition, key, action);
internal static void Dispatch(in T key,in T2 @param) => flux_action_param.Dispatch(key, @param);
internal static bool Get(in T key, out T2 _state)
{
//TODO TEMP
if((flux_action_param as StateFlux<T,T2>).dictionary.TryGetValue(key, out var state))
{
return state.Get(out _state);
}
else
{
_state = default;
return false;
}
}
}
} | Runtime/Core/Internal/FluxState.cs | xavierarpa-UniFlux-a2d46de | [
{
"filename": "Runtime/Core/Internal/FluxParam_T_T2.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux<T> Action<T2>\n ///</summary>\n internal static class FluxParam<T,T2> // (T, Action<T2>)\n {\n ///<summary>\n /// Defines a static instance of ActionFluxParam<T, T2>\n ///</summary>\n internal static readonly IFluxParam<T, T2, Action<T2>> flux_action_param = new ActionFluxParam<T,T2>();",
"score": 0.849619448184967
},
{
"filename": "Runtime/Core/Internal/Flux_T.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux Action\n ///</summary>\n internal static class Flux<T> //(T, Action)\n {\n ///<summary>\n /// Defines a static instance of ActionFlux<T>\n ///</summary>\n internal static readonly IFlux<T, Action> flux_action = new ActionFlux<T>();",
"score": 0.8195815086364746
},
{
"filename": "Runtime/Core/Internal/FluxReturn_T_T2.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux<T> Func<out T2>\n ///</summary>\n internal static class FluxReturn<T,T2> // (T, Func<out T2>)\n {\n ///<summary>\n /// Defines a static instance of FuncFlux<T,T2>\n ///</summary>\n internal static readonly IFluxReturn<T, T2, Func<T2>> flux_func = new FuncFlux<T,T2>();",
"score": 0.8187838196754456
},
{
"filename": "Runtime/Core/Internal/FluxParamReturn_T_T2_T3.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux<T> Func<T2, out T3>\n ///</summary>\n internal static class FluxParamReturn<T,T2,T3> // (T, Func<T2, out T3>)\n {\n ///<summary>\n /// Defines a static instance of FuncFluxParam<T, T2, T3>\n ///</summary>\n internal static readonly IFluxParamReturn<T, T2, T3, Func<T2,T3>> flux_func_param = new FuncFluxParam<T, T2, T3>();",
"score": 0.8098372220993042
},
{
"filename": "Runtime/Core/Flux.cs",
"retrieved_chunk": "using System;\nnamespace Kingdox.UniFlux.Core\n{\n public static class Flux \n {\n#region // Flux\n public static void Store<T>(in T key, in Action callback, in bool condition) => Internal.Flux<T>.Store(in key, in callback, in condition);\n public static void Dispatch<T>(in T key) => Internal.Flux<T>.Dispatch(in key);\n#endregion\n#region // FluxParam",
"score": 0.8065253496170044
}
] | csharp | IFluxParam<T, T2, Action<T2>> flux_action_param = new StateFlux<T,T2>(); |
using TreeifyTask;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace TreeifyTask.Sample
{
public class TaskNodeViewModel : INotifyPropertyChanged
{
private readonly ITaskNode baseTaskNode;
private ObservableCollection<TaskNodeViewModel> _childTasks;
private | TaskStatus _taskStatus; |
public TaskNodeViewModel(ITaskNode baseTaskNode)
{
this.baseTaskNode = baseTaskNode;
PopulateChild(baseTaskNode);
baseTaskNode.Reporting += BaseTaskNode_Reporting;
}
private void PopulateChild(ITaskNode baseTaskNode)
{
this._childTasks = new ObservableCollection<TaskNodeViewModel>();
foreach (var ct in baseTaskNode.ChildTasks)
{
this._childTasks.Add(new TaskNodeViewModel(ct));
}
}
private void BaseTaskNode_Reporting(object sender, ProgressReportingEventArgs eventArgs)
{
this.TaskStatus = eventArgs.TaskStatus;
}
public ObservableCollection<TaskNodeViewModel> ChildTasks =>
_childTasks;
public string Id
{
get => baseTaskNode.Id;
}
public TaskStatus TaskStatus
{
get => _taskStatus;
set
{
_taskStatus = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TaskStatus)));
}
}
public ITaskNode BaseTaskNode => baseTaskNode;
public event PropertyChangedEventHandler PropertyChanged;
}
}
| Source/TreeifyTask.WpfSample/TaskNodeViewModel.cs | intuit-TreeifyTask-4b124d4 | [
{
"filename": "Source/TreeifyTask/TaskTree/ITaskNode.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nnamespace TreeifyTask\n{\n public interface ITaskNode : IProgressReporter\n {\n string Id { get; set; }\n double ProgressValue { get; }",
"score": 0.8342591524124146
},
{
"filename": "Source/TreeifyTask/TaskTree/TaskNodeCycleDetectedException.cs",
"retrieved_chunk": "using System;\nusing System.Runtime.Serialization;\nnamespace TreeifyTask\n{\n [Serializable]\n public class TaskNodeCycleDetectedException : Exception\n {\n public ITaskNode NewTask { get; }\n public ITaskNode ParentTask { get; }\n public string MessageStr { get; private set; }",
"score": 0.8317035436630249
},
{
"filename": "Source/TreeifyTask.BlazorSample/TaskDataModel/code.cs",
"retrieved_chunk": "using System;\nusing System.Threading.Tasks;\nnamespace TreeifyTask.BlazorSample\n{\n delegate Task CancellableAsyncActionDelegate(Pr reporter, Tk token);\n class Pr\n {\n public void report() { }\n }\n struct Tk",
"score": 0.7938569784164429
},
{
"filename": "Source/TreeifyTask/TaskTree/IProgressReporter.cs",
"retrieved_chunk": "namespace TreeifyTask\n{\n public interface IProgressReporter\n {\n void Report(TaskStatus taskStatus, double progressValue, object progressState = default);\n event ProgressReportingEventHandler Reporting;\n }\n}",
"score": 0.7929442524909973
},
{
"filename": "Source/TreeifyTask/TaskTree/TaskNode.cs",
"retrieved_chunk": " private static Random rnd = new Random();\n private readonly List<Task> taskObjects = new();\n private readonly List<ITaskNode> childTasks = new();\n private bool hasCustomAction;\n private Func<IProgressReporter, CancellationToken, Task> action =\n async (rep, tok) => await Task.Yield();\n public event ProgressReportingEventHandler Reporting;\n private bool seriesRunnerIsBusy;\n private bool concurrentRunnerIsBusy;\n public TaskNode()",
"score": 0.7854089736938477
}
] | csharp | TaskStatus _taskStatus; |
//#define PRINT_DEBUG
using System;
using System.IO;
using Godot;
using Mono.Unix;
using Directory = System.IO.Directory;
using Environment = System.Environment;
using File = System.IO.File;
using Path = System.IO.Path;
namespace GodotLauncher
{
public class DataPaths
{
static string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
static string BasePath => Path.Combine(AppDataPath, "ReadyToLaunch");
public static string platformOverride;
public static string SanitizeProjectPath(string path)
{
if (File.Exists(path))
{
path = new FileInfo(path).DirectoryName;
}
return path;
}
public static void EnsureProjectExists(string path)
{
var filePath = Path.Combine(path, "project.godot");
if (!File.Exists(filePath)) File.WriteAllText(filePath, "");
}
public static string GetExecutablePath(InstallerEntryData installerEntryData)
{
string platformName = GetPlatformName();
string path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);
path = Path.Combine(path, installerEntryData.ExecutableName);
return path;
}
public static string GetPlatformName()
{
if (!string.IsNullOrEmpty(platformOverride)) return platformOverride;
return OS.GetName();
}
public static void WriteFile(string fileName, byte[] data)
{
var path = Path.Combine(BasePath, fileName);
#if PRINT_DEBUG
GD.Print("Writing: " + path);
#endif
File.WriteAllBytes(path, data);
}
public static void WriteFile(string fileName, string data)
{
var path = Path.Combine(BasePath, fileName);
#if PRINT_DEBUG
GD.Print("Writing: " + path);
#endif
File.WriteAllText(path, data);
}
public static string ReadFile(string fileName, string defaultData = null)
{
var path = Path.Combine(BasePath, fileName);
if (File.Exists(path))
{
#if PRINT_DEBUG
GD.Print("Reading: " + path);
#endif
return File.ReadAllText(path);
}
#if PRINT_DEBUG
GD.Print("File not found: " + path);
#endif
return defaultData;
}
public static bool ExecutableExists(InstallerEntryData installerEntryData)
{
string path = GetExecutablePath(installerEntryData);
bool exists = File.Exists(path);
#if PRINT_DEBUG
GD.Print("Checking if path exists: " + path + " exists=" + exists);
#endif
return exists;
}
public static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)
{
string source = Path.Combine(BasePath, fileName);
string dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);
if (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);
File.Delete(source);
}
public static void DeleteVersion(string version, string buildType)
{
Directory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);
}
public static void LaunchGodot( | InstallerEntryData installerEntryData, string arguments = "")
{ |
string path = GetExecutablePath(installerEntryData);
#if PRINT_DEBUG
GD.Print("Launching: " + path);
#endif
if (!OS.GetName().Equals("Windows"))
{
var unixFile = new UnixFileInfo(path);
unixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute
| FileAccessPermissions.GroupExecute
| FileAccessPermissions.OtherExecute;
}
using var process = new System.Diagnostics.Process();
process.StartInfo.FileName = path;
process.StartInfo.WorkingDirectory = BasePath;
process.StartInfo.Arguments = arguments;
process.Start();
}
public static void CreateInstallationDirectory()
{
MoveOldInstallationDirectory("ReadyForLaunch");
MoveOldInstallationDirectory("GodotLauncher");
Directory.CreateDirectory(BasePath);
}
static void MoveOldInstallationDirectory(string oldName)
{
var oldPath = Path.Combine(AppDataPath, oldName);
if (!Directory.Exists(oldPath) || Directory.Exists(BasePath))
return;
Directory.Move(oldPath, BasePath);
}
public static void ShowInFolder(string filePath)
{
filePath = "\"" + filePath + "\"";
switch (OS.GetName())
{
case "Linux":
System.Diagnostics.Process.Start("xdg-open", filePath);
break;
case "Windows":
string argument = "/select, " + filePath;
System.Diagnostics.Process.Start("explorer.exe", argument);
break;
case "macOS":
System.Diagnostics.Process.Start("open", filePath);
break;
default:
throw new Exception("OS not defined! " + OS.GetName());
}
}
}
}
| godot-project/Scripts/DataManagement/DataPaths.cs | NathanWarden-ready-to-launch-58eba6d | [
{
"filename": "godot-project/Scripts/DataManagement/LauncherManager.cs",
"retrieved_chunk": "\t\t\tbool installerExists = DataPaths.ExecutableExists(installerEntry);\n\t\t\tif (installerExists)\n\t\t\t{\n\t\t\t\tDataPaths.LaunchGodot(installerEntry);\n\t\t\t\t//OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tvoid _onInstallerDeletePressed(string version, string buildType)",
"score": 0.7988647222518921
},
{
"filename": "godot-project/Scripts/DataManagement/FileHelper.cs",
"retrieved_chunk": "\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}",
"score": 0.7842212915420532
},
{
"filename": "godot-project/Scripts/DataManagement/LauncherManager.cs",
"retrieved_chunk": "\t\tvoid _onRunProject(string path)\n\t\t{\n\t\t\tLaunchProject(path, true);\n\t\t}\n\t\tvoid LaunchProject(string path, bool run)\n\t\t{\n\t\t\tfor (int i = 0; i < projectEntries.Count; i++)\n\t\t\t{\n\t\t\t\tif (projectEntries[i].path.Equals(path) && installerEntries.TryGetValue(projectEntries[i].versionKey, out var entry))\n\t\t\t\t{",
"score": 0.7828500270843506
},
{
"filename": "godot-project/Scripts/DataManagement/FileHelper.cs",
"retrieved_chunk": "\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)",
"score": 0.781445324420929
},
{
"filename": "godot-project/Scripts/DataManagement/FileHelper.cs",
"retrieved_chunk": "\t\tfile.StoreString(json);\n\t\tfile.Close();\n\t}\n\tpublic static bool FileExists(string path)\n\t{\n\t\treturn FileAccess.FileExists(path);\n\t}\n\tpublic static string ReadUserText(string path)\n\t{\n\t\treturn ReadAllText(PathCombine(BasePath, path));",
"score": 0.7788196802139282
}
] | csharp | InstallerEntryData installerEntryData, string arguments = "")
{ |
using HarmonyLib;
using UnityEngine;
namespace Ultrapain.Patches
{
class Virtue_Start_Patch
{
static void Postfix(Drone __instance, ref EnemyIdentifier ___eid)
{
VirtueFlag flag = __instance.gameObject.AddComponent<VirtueFlag>();
flag.virtue = __instance;
}
}
class Virtue_Death_Patch
{
static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid)
{
if(___eid.enemyType != EnemyType.Virtue)
return true;
__instance.GetComponent<VirtueFlag>().DestroyProjectiles();
return true;
}
}
class VirtueFlag : MonoBehaviour
{
public AudioSource lighningBoltSFX;
public GameObject ligtningBoltAud;
public Transform windupObj;
private EnemyIdentifier eid;
public Drone virtue;
public void Awake()
{
eid = GetComponent<EnemyIdentifier>();
ligtningBoltAud = Instantiate(Plugin.lighningBoltSFX, transform);
lighningBoltSFX = ligtningBoltAud.GetComponent<AudioSource>();
}
public void SpawnLightningBolt()
{
LightningStrikeExplosive lightningStrikeExplosive = Instantiate(Plugin.lightningStrikeExplosiveSetup.gameObject, windupObj.transform.position, Quaternion.identity).GetComponent<LightningStrikeExplosive>();
lightningStrikeExplosive.safeForPlayer = false;
lightningStrikeExplosive.damageMultiplier = eid.totalDamageModifier * ((virtue.enraged)? ConfigManager.virtueEnragedLightningDamage.value : ConfigManager.virtueNormalLightningDamage.value);
if(windupObj != null)
Destroy(windupObj.gameObject);
}
public void DestroyProjectiles()
{
CancelInvoke("SpawnLightningBolt");
if (windupObj != null)
Destroy(windupObj.gameObject);
}
}
class Virtue_SpawnInsignia_Patch
{
static bool Prefix( | Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, ref int ___usedAttacks)
{ |
if (___eid.enemyType != EnemyType.Virtue)
return true;
GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, int damage, float lastMultiplier)
{
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity);
VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>();
component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer();
component.parentDrone = __instance;
component.hadParent = true;
component.damage = damage;
component.explosionLength *= lastMultiplier;
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
if (__instance.enraged)
{
component.predictive = true;
}
/*if (___difficulty == 1)
{
component.windUpSpeedMultiplier = 0.875f;
}
else if (___difficulty == 0)
{
component.windUpSpeedMultiplier = 0.75f;
}*/
if (MonoSingleton<PlayerTracker>.Instance.playerType == PlayerType.Platformer)
{
gameObject.transform.localScale *= 0.75f;
component.windUpSpeedMultiplier *= 0.875f;
}
component.windUpSpeedMultiplier *= ___eid.totalSpeedModifier;
component.damage = Mathf.RoundToInt((float)component.damage * ___eid.totalDamageModifier);
return gameObject;
}
if (__instance.enraged && !ConfigManager.virtueTweakEnragedAttackToggle.value)
return true;
if (!__instance.enraged && !ConfigManager.virtueTweakNormalAttackToggle.value)
return true;
bool insignia = (__instance.enraged) ? ConfigManager.virtueEnragedAttackType.value == ConfigManager.VirtueAttackType.Insignia
: ConfigManager.virtueNormalAttackType.value == ConfigManager.VirtueAttackType.Insignia;
if (insignia)
{
bool xAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXtoggle.value : ConfigManager.virtueNormalInsigniaXtoggle.value;
bool yAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYtoggle.value : ConfigManager.virtueNormalInsigniaYtoggle.value;
bool zAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZtoggle.value : ConfigManager.virtueNormalInsigniaZtoggle.value;
if (xAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXdamage.value : ConfigManager.virtueNormalInsigniaXdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXsize.value : ConfigManager.virtueNormalInsigniaXsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
obj.transform.Rotate(new Vector3(90f, 0, 0));
}
if (yAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYdamage.value : ConfigManager.virtueNormalInsigniaYdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYsize.value : ConfigManager.virtueNormalInsigniaYsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
}
if (zAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZdamage.value : ConfigManager.virtueNormalInsigniaZdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZsize.value : ConfigManager.virtueNormalInsigniaZsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
obj.transform.Rotate(new Vector3(0, 0, 90f));
}
}
else
{
Vector3 predictedPos;
if (___difficulty <= 1)
predictedPos = MonoSingleton<PlayerTracker>.Instance.GetPlayer().position;
else
{
Vector3 vector = new Vector3(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().x, 0f, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().z);
predictedPos = MonoSingleton<PlayerTracker>.Instance.GetPlayer().position + vector.normalized * Mathf.Min(vector.magnitude, 5.0f);
}
GameObject currentWindup = GameObject.Instantiate<GameObject>(Plugin.lighningStrikeWindup.gameObject, predictedPos, Quaternion.identity);
foreach (Follow follow in currentWindup.GetComponents<Follow>())
{
if (follow.speed != 0f)
{
if (___difficulty >= 2)
{
follow.speed *= (float)___difficulty;
}
else if (___difficulty == 1)
{
follow.speed /= 2f;
}
else
{
follow.enabled = false;
}
follow.speed *= ___eid.totalSpeedModifier;
}
}
VirtueFlag flag = __instance.GetComponent<VirtueFlag>();
flag.lighningBoltSFX.Play();
flag.windupObj = currentWindup.transform;
flag.Invoke("SpawnLightningBolt", (__instance.enraged)? ConfigManager.virtueEnragedLightningDelay.value : ConfigManager.virtueNormalLightningDelay.value);
}
___usedAttacks += 1;
if(___usedAttacks == 3)
{
__instance.Invoke("Enrage", 3f / ___eid.totalSpeedModifier);
}
return false;
}
/*static void Postfix(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, bool __state)
{
if (!__state)
return;
GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target)
{
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity);
VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>();
component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer();
component.parentDrone = __instance;
component.hadParent = true;
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
if (__instance.enraged)
{
component.predictive = true;
}
if (___difficulty == 1)
{
component.windUpSpeedMultiplier = 0.875f;
}
else if (___difficulty == 0)
{
component.windUpSpeedMultiplier = 0.75f;
}
if (MonoSingleton<PlayerTracker>.Instance.playerType == PlayerType.Platformer)
{
gameObject.transform.localScale *= 0.75f;
component.windUpSpeedMultiplier *= 0.875f;
}
component.windUpSpeedMultiplier *= ___eid.totalSpeedModifier;
component.damage = Mathf.RoundToInt((float)component.damage * ___eid.totalDamageModifier);
return gameObject;
}
GameObject xAxisInsignia = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target);
xAxisInsignia.transform.Rotate(new Vector3(90, 0, 0));
xAxisInsignia.transform.localScale = new Vector3(xAxisInsignia.transform.localScale.x * horizontalInsigniaScale, xAxisInsignia.transform.localScale.y, xAxisInsignia.transform.localScale.z * horizontalInsigniaScale);
GameObject zAxisInsignia = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target);
zAxisInsignia.transform.Rotate(new Vector3(0, 0, 90));
zAxisInsignia.transform.localScale = new Vector3(zAxisInsignia.transform.localScale.x * horizontalInsigniaScale, zAxisInsignia.transform.localScale.y, zAxisInsignia.transform.localScale.z * horizontalInsigniaScale);
}*/
}
}
| Ultrapain/Patches/Virtue.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " public static int projectileDamage = 10;\n public static int explosionDamage = 20;\n public static float coreSpeed = 110f;\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref Animator ___anim, ref GameObject ___currentProjectile\n , ref NavMeshAgent ___nma, ref Zombie ___zmb)\n {\n if (___eid.enemyType != EnemyType.Stray)\n return;\n StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>();\n if (flag == null)",
"score": 0.8819984197616577
},
{
"filename": "Ultrapain/Patches/Turret.cs",
"retrieved_chunk": " static void Postfix(Turret __instance)\n {\n __instance.gameObject.AddComponent<TurretFlag>();\n }\n }\n class TurretShoot\n {\n static bool Prefix(Turret __instance, ref EnemyIdentifier ___eid, ref RevolverBeam ___beam, ref Transform ___shootPoint,\n ref float ___aimTime, ref float ___maxAimTime, ref float ___nextBeepTime, ref float ___flashTime)\n {",
"score": 0.8811304569244385
},
{
"filename": "Ultrapain/Patches/Solider.cs",
"retrieved_chunk": " /*___projectile = Plugin.soliderBullet;\n if (Plugin.decorativeProjectile2.gameObject != null)\n ___decProjectile = Plugin.decorativeProjectile2.gameObject;*/\n __instance.gameObject.AddComponent<SoliderShootCounter>();\n }\n }\n class Solider_SpawnProjectile_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP)\n {",
"score": 0.8716228008270264
},
{
"filename": "Ultrapain/Patches/Mindflayer.cs",
"retrieved_chunk": " componentInChildren.sourceWeapon = __instance.gameObject;\n counter.shotsLeft -= 1;\n __instance.Invoke(\"ShootProjectiles\", ConfigManager.mindflayerShootDelay.value / ___eid.totalSpeedModifier);\n return false;\n }\n }\n class EnemyIdentifier_DeliverDamage_MF\n {\n static bool Prefix(EnemyIdentifier __instance, ref float __3, GameObject __6)\n {",
"score": 0.8699069619178772
},
{
"filename": "Ultrapain/Patches/Drone.cs",
"retrieved_chunk": " lr.SetPosition(1, transform.position + transform.forward * 1000);\n }\n }\n }\n class Drone_Death_Patch\n {\n static bool Prefix(Drone __instance, EnemyIdentifier ___eid)\n {\n if (___eid.enemyType != EnemyType.Drone || __instance.crashing)\n return true;",
"score": 0.8681532144546509
}
] | csharp | Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, ref int ___usedAttacks)
{ |
/*
Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox')
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using UnityEngine;
namespace Kingdox.UniFlux.Sample
{
public sealed class Sample_4 : MonoFlux
{
[SerializeField] private int _shots;
private void Update()
{
Kingdox.UniFlux.Core.Flux.Dispatch(_shots < 10);
}
[Flux(true)]private void CanShot()
{
if(Time.frameCount % 60 == 0)
{
"Shot".Dispatch(Time.frameCount);
}
}
[ | Flux("Shot")] private void Shot(int frameCount)
{ |
_shots++;
"LogShot".Dispatch((frameCount, _shots));
}
[Flux("LogShot")] private void LogShot((int frameCount, int shots) data)
{
Debug.Log(data);
}
}
} | Samples/UniFlux.Sample.4/Sample_4.cs | xavierarpa-UniFlux-a2d46de | [
{
"filename": "Samples/UniFlux.Sample.3/Sample_3.cs",
"retrieved_chunk": " \"OnChange_Life\".Dispatch(value);\n }\n }\n private void Start() \n {\n \"Set_Life\".Dispatch(10);\n }\n private void Update()\n {\n (Time.frameCount % 60).Dispatch();",
"score": 0.8599971532821655
},
{
"filename": "Samples/UniFlux.Sample.3/Sample_3.cs",
"retrieved_chunk": " if(life == 0)\n {\n \"OnDeath\".Dispatch();\n } \n }\n [Flux(\"OnDeath\")] private void OnDeath()\n {\n Debug.Log(\"You're Dead !\");\n }\n }",
"score": 0.8045224547386169
},
{
"filename": "Samples/UniFlux.Sample.3/Sample_3.cs",
"retrieved_chunk": " }\n [Flux(0)] private void OnUpdate() \n {\n if(\"Get_Life\".Dispatch<int>() > 0)\n {\n \"Set_Life\".Dispatch(\"Get_Life\".Dispatch<int>()-1);\n }\n }\n [Flux(\"OnChange_Life\")] private void OnChange_Life(int life) \n {",
"score": 0.7892417907714844
},
{
"filename": "Tests/EditMode/EditMode_Test_1.cs",
"retrieved_chunk": " [Test] public void SubscribeFuncParam()\n {\n Flux.Store<string,float,float>(\"OnTest\", OnTest_FuncPatam, true);\n }\n [Test] public void DispatchAction()\n {\n Flux.Dispatch(\"OnTest\");\n }\n [Test] public void DispatchActionParam()\n {",
"score": 0.7794970273971558
},
{
"filename": "Benchmark/Nest/Benchmark_Nest_UniFlux.cs",
"retrieved_chunk": " private void Store_1() => \"2\".Dispatch();\n private void Store_2() => \"3\".Dispatch();\n private void Store_3() => \"4\".Dispatch();\n private void Store_4() => \"5\".Dispatch();\n private void Store_5() {}\n private void Sample()\n {\n if (_mark_fluxAttribute.Execute)\n {\n _mark_fluxAttribute.iteration = iteration;",
"score": 0.7780473828315735
}
] | csharp | Flux("Shot")] private void Shot(int frameCount)
{ |
#nullable enable
using System.Collections.Generic;
using Mochineko.FacialExpressions.Blink;
using UniVRM10;
namespace Mochineko.FacialExpressions.Extensions.VRM
{
/// <summary>
/// An eyelid morpher for VRM models.
/// </summary>
// ReSharper disable once InconsistentNaming
public sealed class VRMEyelidMorpher : IEyelidMorpher
{
private readonly Vrm10RuntimeExpression expression;
private static readonly IReadOnlyDictionary< | Eyelid, ExpressionKey> KeyMap
= new Dictionary<Eyelid, ExpressionKey>
{ |
[Eyelid.Both] = ExpressionKey.Blink,
[Eyelid.Left] = ExpressionKey.BlinkLeft,
[Eyelid.Right] = ExpressionKey.BlinkRight,
};
/// <summary>
/// Create an eyelid morpher for VRM models.
/// </summary>
/// <param name="expression">Target expression of VRM instance.</param>
public VRMEyelidMorpher(Vrm10RuntimeExpression expression)
{
this.expression = expression;
}
public void MorphInto(EyelidSample sample)
{
if (KeyMap.TryGetValue(sample.eyelid, out var key))
{
expression.SetWeight(key, sample.weight);
}
}
public float GetWeightOf(Eyelid eyelid)
{
if (KeyMap.TryGetValue(eyelid, out var key))
{
return expression.GetWeight(key);
}
else
{
return 0f;
}
}
public void Reset()
{
expression.SetWeight(ExpressionKey.BlinkLeft, 0f);
expression.SetWeight(ExpressionKey.BlinkRight, 0f);
expression.SetWeight(ExpressionKey.Blink, 0f);
}
}
}
| Assets/Mochineko/FacialExpressions.Extensions/VRM/VRMEyelidMorpher.cs | mochi-neko-facial-expressions-unity-ab0d020 | [
{
"filename": "Assets/Mochineko/FacialExpressions.Extensions/VRM/VRMEmotionMorpher.cs",
"retrieved_chunk": " // ReSharper disable once InconsistentNaming\n public sealed class VRMEmotionMorpher<TEmotion> :\n IEmotionMorpher<TEmotion>\n where TEmotion: Enum\n {\n private readonly Vrm10RuntimeExpression expression;\n private readonly IReadOnlyDictionary<TEmotion, ExpressionKey> keyMap;\n /// <summary>\n /// Creates a new instance of <see cref=\"VRMEmotionMorpher\"/>.\n /// </summary>",
"score": 0.8856122493743896
},
{
"filename": "Assets/Mochineko/FacialExpressions/Blink/SequentialEyelidAnimator.cs",
"retrieved_chunk": " /// </summary>\n public sealed class SequentialEyelidAnimator : ISequentialEyelidAnimator\n {\n private readonly IEyelidMorpher morpher;\n /// <summary>\n /// Creates a new instance of <see cref=\"SequentialEyelidAnimator\"/>.\n /// </summary>\n /// <param name=\"morpher\">Target morpher.</param>\n public SequentialEyelidAnimator(IEyelidMorpher morpher)\n {",
"score": 0.8207457065582275
},
{
"filename": "Assets/Mochineko/FacialExpressions.Extensions/VRM/VRMEmotionMorpher.cs",
"retrieved_chunk": " /// <param name=\"expression\">Target expression of VRM instance.</param>\n /// <param name=\"keyMap\">Map of emotion to expression key.</param>\n public VRMEmotionMorpher(\n Vrm10RuntimeExpression expression,\n IReadOnlyDictionary<TEmotion, ExpressionKey> keyMap)\n {\n this.expression = expression;\n this.keyMap = keyMap;\n }\n public void MorphInto(EmotionSample<TEmotion> sample)",
"score": 0.8203776478767395
},
{
"filename": "Assets/Mochineko/FacialExpressions.Extensions/VRM/VRMLipMorpher.cs",
"retrieved_chunk": " [Viseme.oh] = ExpressionKey.Ou,\n };\n /// <summary>\n /// Create a lip morpher for VRM models.\n /// </summary>\n /// <param name=\"expression\">Target expression of VRM instance.</param>\n public VRMLipMorpher(Vrm10RuntimeExpression expression)\n {\n this.expression = expression;\n }",
"score": 0.8166788816452026
},
{
"filename": "Assets/Mochineko/FacialExpressions/LipSync/FollowingLipAnimator.cs",
"retrieved_chunk": " /// A framewise lip animator that animates lip by following target weights.\n /// </summary>\n public sealed class FollowingLipAnimator : IFramewiseLipAnimator\n {\n private readonly ILipMorpher morpher;\n private readonly float dt;\n private readonly float initialFollowingVelocity;\n private readonly float followingTime;\n private readonly Dictionary<Viseme, float> targetWeights = new ();\n private readonly Dictionary<Viseme, float> followingVelocities = new();",
"score": 0.8161032199859619
}
] | csharp | Eyelid, ExpressionKey> KeyMap
= new Dictionary<Eyelid, ExpressionKey>
{ |
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Ultrapain.Patches
{
/*public class ObjectActivator : MonoBehaviour
{
public int originalInstanceID = 0;
public MonoBehaviour activator;
void Start()
{
if (gameObject.GetInstanceID() == originalInstanceID)
return;
activator?.Invoke("OnClone", 0f);
}
}*/
public class CommonLinearScaler : MonoBehaviour
{
public Transform targetTransform;
public float scaleSpeed = 1f;
void Update()
{
float deltaSize = Time.deltaTime * scaleSpeed;
targetTransform.localScale = new Vector3(targetTransform.localScale.x + deltaSize, targetTransform.localScale.y + deltaSize, targetTransform.localScale.y + deltaSize);
}
}
public class CommonAudioPitchScaler : MonoBehaviour
{
public AudioSource targetAud;
public float scaleSpeed = 1f;
void Update()
{
float deltaPitch = Time.deltaTime * scaleSpeed;
targetAud.pitch += deltaPitch;
}
}
public class RotateOnSpawn : MonoBehaviour
{
public Quaternion targetRotation;
private void Awake()
{
transform.rotation = targetRotation;
}
}
public class CommonActivator : MonoBehaviour
{
public int originalId;
public Renderer rend;
public Rigidbody rb;
public bool kinematic;
public bool colDetect;
public Collider col;
public AudioSource aud;
public List<MonoBehaviour> comps = new List<MonoBehaviour>();
void Awake()
{
if (originalId == gameObject.GetInstanceID())
return;
if (rend != null)
rend.enabled = true;
if (rb != null)
{
rb.isKinematic = kinematic;
rb.detectCollisions = colDetect;
}
if (col != null)
col.enabled = true;
if (aud != null)
aud.enabled = true;
foreach (MonoBehaviour comp in comps)
comp.enabled = true;
foreach (Transform child in gameObject.transform)
child.gameObject.SetActive(true);
}
}
public class GrenadeExplosionOverride : MonoBehaviour
{
public bool harmlessMod = false;
public float harmlessSize = 1f;
public float harmlessSpeed = 1f;
public float harmlessDamage = 1f;
public int harmlessPlayerDamageOverride = -1;
public bool normalMod = false;
public float normalSize = 1f;
public float normalSpeed = 1f;
public float normalDamage = 1f;
public int normalPlayerDamageOverride = -1;
public bool superMod = false;
public float superSize = 1f;
public float superSpeed = 1f;
public float superDamage = 1f;
public int superPlayerDamageOverride = -1;
struct StateInfo
{
public GameObject tempHarmless;
public GameObject tempNormal;
public GameObject tempSuper;
public | StateInfo()
{ |
tempHarmless = tempNormal = tempSuper = null;
}
}
[HarmonyBefore]
static bool Prefix(Grenade __instance, out StateInfo __state)
{
__state = new StateInfo();
GrenadeExplosionOverride flag = __instance.GetComponent<GrenadeExplosionOverride>();
if (flag == null)
return true;
if (flag.harmlessMod)
{
__state.tempHarmless = __instance.harmlessExplosion = GameObject.Instantiate(__instance.harmlessExplosion);
foreach (Explosion exp in __instance.harmlessExplosion.GetComponentsInChildren<Explosion>())
{
exp.damage = (int)(exp.damage * flag.harmlessDamage);
exp.maxSize *= flag.harmlessSize;
exp.speed *= flag.harmlessSize * flag.harmlessSpeed;
exp.playerDamageOverride = flag.harmlessPlayerDamageOverride;
}
}
if (flag.normalMod)
{
__state.tempNormal = __instance.explosion = GameObject.Instantiate(__instance.explosion);
foreach (Explosion exp in __instance.explosion.GetComponentsInChildren<Explosion>())
{
exp.damage = (int)(exp.damage * flag.normalDamage);
exp.maxSize *= flag.normalSize;
exp.speed *= flag.normalSize * flag.normalSpeed;
exp.playerDamageOverride = flag.normalPlayerDamageOverride;
}
}
if (flag.superMod)
{
__state.tempSuper = __instance.superExplosion = GameObject.Instantiate(__instance.superExplosion);
foreach (Explosion exp in __instance.superExplosion.GetComponentsInChildren<Explosion>())
{
exp.damage = (int)(exp.damage * flag.superDamage);
exp.maxSize *= flag.superSize;
exp.speed *= flag.superSize * flag.superSpeed;
exp.playerDamageOverride = flag.superPlayerDamageOverride;
}
}
return true;
}
static void Postfix(StateInfo __state)
{
if (__state.tempHarmless != null)
GameObject.Destroy(__state.tempHarmless);
if (__state.tempNormal != null)
GameObject.Destroy(__state.tempNormal);
if (__state.tempSuper != null)
GameObject.Destroy(__state.tempSuper);
}
}
}
| Ultrapain/Patches/CommonComponents.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " // ENEMY STAT CONFIG\n public static char resistanceSeparator = (char)1;\n public struct EidStatContainer\n {\n public FloatField health;\n public FloatField damage;\n public FloatField speed;\n public StringField resistanceStr;\n public Dictionary<string, float> resistanceDict;\n public void SetHidden(bool hidden)",
"score": 0.8871333599090576
},
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " public GameObject standardProjectile;\n public GameObject standardDecorativeProjectile;\n public int comboRemaining = ConfigManager.strayShootCount.value;\n public bool inCombo = false;\n public float lastSpeed = 1f;\n public enum AttackMode\n {\n ProjectileCombo,\n FastHoming\n }",
"score": 0.8862030506134033
},
{
"filename": "Ultrapain/Patches/Parry.cs",
"retrieved_chunk": " public GameObject temporaryBigExplosion;\n public GameObject weapon;\n public enum GrenadeType\n {\n Core,\n Rocket,\n }\n public GrenadeType grenadeType;\n }\n class Punch_CheckForProjectile_Patch",
"score": 0.8777657747268677
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " }\n class OrbitalExplosionInfo : MonoBehaviour\n {\n public bool active = true;\n public string id;\n public int points;\n }\n class Grenade_Explode\n {\n class StateInfo",
"score": 0.8703979253768921
},
{
"filename": "Ultrapain/Patches/SomethingWicked.cs",
"retrieved_chunk": " public MassSpear spearComp;\n public EnemyIdentifier eid;\n public Transform spearOrigin;\n public Rigidbody spearRb;\n public static float SpearTriggerDistance = 80f;\n public static LayerMask envMask = new LayerMask() { value = (1 << 8) | (1 << 24) };\n void Awake()\n {\n if (eid == null)\n eid = GetComponent<EnemyIdentifier>();",
"score": 0.8703426122665405
}
] | csharp | StateInfo()
{ |
using NowPlaying.Models;
using NowPlaying.ViewModels;
using Playnite.SDK;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using static NowPlaying.Models.GameCacheManager;
namespace NowPlaying
{
public class NowPlayingUninstallController : UninstallController
{
private readonly ILogger logger = NowPlaying.logger;
private readonly NowPlaying plugin;
private readonly NowPlayingSettings settings;
private readonly IPlayniteAPI PlayniteApi;
private readonly GameCacheManagerViewModel cacheManager;
private readonly Game nowPlayingGame;
private readonly string cacheDir;
private readonly string installDir;
public readonly GameCacheViewModel gameCache;
public NowPlayingUninstallController(NowPlaying plugin, Game nowPlayingGame, | GameCacheViewModel gameCache)
: base(nowPlayingGame)
{ |
this.plugin = plugin;
this.settings = plugin.Settings;
this.PlayniteApi = plugin.PlayniteApi;
this.cacheManager = plugin.cacheManager;
this.nowPlayingGame = nowPlayingGame;
this.gameCache = gameCache;
this.cacheDir = gameCache.CacheDir;
this.installDir = gameCache.InstallDir;
}
public override void Uninstall(UninstallActionArgs args)
{
// . enqueue our controller (but don't add more than once)
if (plugin.EnqueueCacheUninstallerIfUnique(this))
{
// . Proceed only if uninstaller is first -- in the "active install" spot...
// . Otherwise, when the active install controller finishes it will
// automatically invoke NowPlayingUninstall on the next controller in the queue.
//
if (plugin.cacheUninstallQueue.First() == this)
{
Task.Run(() => NowPlayingUninstallAsync());
}
else
{
plugin.UpdateUninstallQueueStatuses();
logger.Info($"NowPlaying uninstall of '{gameCache.Title}' game cache queued ({gameCache.UninstallQueueStatus}).");
}
}
}
public async Task NowPlayingUninstallAsync()
{
bool cacheWriteBackOption = settings.SyncDirtyCache_DoWhen == DoWhen.Always;
bool cancelUninstall = false;
string gameTitle = nowPlayingGame.Name;
gameCache.UpdateNowUninstalling(true);
if (settings.ConfirmUninstall)
{
string message = plugin.FormatResourceString("LOCNowPlayingUninstallConfirmMsgFmt", gameTitle);
MessageBoxResult userChoice = PlayniteApi.Dialogs.ShowMessage(message, string.Empty, MessageBoxButton.YesNo);
cancelUninstall = userChoice == MessageBoxResult.No;
}
if (!cancelUninstall && settings.SyncDirtyCache_DoWhen != DoWhen.Never)
{
// . Sync on uninstall Always | Ask selected.
if (!await plugin.CheckIfGameInstallDirIsAccessibleAsync(gameTitle, installDir, silentMode: true))
{
// Game's install dir not readable:
// . See if user wants to continue uninstall without Syncing
string nl = System.Environment.NewLine;
string message = plugin.FormatResourceString("LOCNowPlayingGameInstallDirNotFoundFmt2", gameTitle, installDir);
message += nl + nl + plugin.FormatResourceString("LOCNowPlayingUnistallWithoutSyncFmt", gameTitle);
MessageBoxResult userChoice = PlayniteApi.Dialogs.ShowMessage(message, "NowPlaying Error:", MessageBoxButton.YesNo);
if (userChoice == MessageBoxResult.Yes)
{
cacheWriteBackOption = false;
}
else
{
cancelUninstall = true;
}
}
}
if (!cancelUninstall && settings.SyncDirtyCache_DoWhen == DoWhen.Ask)
{
DirtyCheckResult result = cacheManager.CheckCacheDirty(gameCache.Id);
if (result.isDirty)
{
string nl = System.Environment.NewLine;
string caption = plugin.GetResourceString("LOCNowPlayingSyncOnUninstallCaption");
string message = plugin.FormatResourceString("LOCNowPlayingSyncOnUninstallDiffHeadingFmt3", gameTitle, cacheDir, installDir) + nl + nl;
message += result.summary;
message += plugin.GetResourceString("LOCNowPlayingSyncOnUninstallPrompt");
MessageBoxResult userChoice = PlayniteApi.Dialogs.ShowMessage(message, caption, MessageBoxButton.YesNoCancel);
cacheWriteBackOption = userChoice == MessageBoxResult.Yes;
cancelUninstall = userChoice == MessageBoxResult.Cancel;
}
}
if (!cancelUninstall)
{
// . Workaround: prevent (accidental) play while uninstall in progress
// -> Note, real solution requires a Playnite fix => Play CanExecute=false while IsUnistalling=true
// -> Also, while we're at it: Playnite's Install CanExecute=false while IsInstalling=true
//
nowPlayingGame.IsInstalled = false;
PlayniteApi.Database.Games.Update(nowPlayingGame);
cacheManager.UninstallGameCache(gameCache, cacheWriteBackOption, OnUninstallDone, OnUninstallCancelled);
}
// . Uninstall cancelled during confirmation (above)...
else
{
// . exit uninstalling state
InvokeOnUninstalled(new GameUninstalledEventArgs());
// Restore some items that Playnite's uninstall flow may have changed automatically.
// . NowPlaying Game's InstallDirectory
//
nowPlayingGame.InstallDirectory = cacheDir;
nowPlayingGame.IsUninstalling = false; // needed if invoked from Panel View
nowPlayingGame.IsInstalled = true;
PlayniteApi.Database.Games.Update(nowPlayingGame);
gameCache.UpdateNowUninstalling(false);
plugin.DequeueUninstallerAndInvokeNextAsync(gameCache.Id);
}
}
private void OnUninstallDone(GameCacheJob job)
{
plugin.NotifyInfo(plugin.FormatResourceString("LOCNowPlayingUninstallNotifyFmt", gameCache.Title));
// . exit uninstalling state
InvokeOnUninstalled(new GameUninstalledEventArgs());
// Restore some items that Playnite's uninstall flow may have changed automatically.
// . NowPlaying Game's InstallDirectory
//
nowPlayingGame.InstallDirectory = cacheDir;
nowPlayingGame.IsUninstalling = false; // needed if invoked from Panel View
nowPlayingGame.IsInstalled = false;
PlayniteApi.Database.Games.Update(nowPlayingGame);
gameCache.UpdateCacheSize();
gameCache.UpdateNowUninstalling(false);
gameCache.UpdateInstallEta();
gameCache.cacheRoot.UpdateGameCaches();
// . update state to JSON file
cacheManager.SaveGameCacheEntriesToJson();
plugin.DequeueUninstallerAndInvokeNextAsync(gameCache.Id);
}
private void OnUninstallCancelled(GameCacheJob job)
{
// . exit uninstalling state
InvokeOnUninstalled(new GameUninstalledEventArgs());
nowPlayingGame.IsUninstalling = false; // needed if invoked from Panel View
PlayniteApi.Database.Games.Update(nowPlayingGame);
gameCache.UpdateNowUninstalling(false);
if (job.cancelledOnError)
{
string seeLogFile = plugin.SaveJobErrorLogAndGetMessage(job, ".uninstall.txt");
plugin.PopupError(plugin.FormatResourceString("LOCNowPlayingUninstallCancelledOnErrorFmt", gameCache.Title) + seeLogFile);
}
// . update state in JSON file
cacheManager.SaveGameCacheEntriesToJson();
plugin.DequeueUninstallerAndInvokeNextAsync(gameCache.Id);
}
}
}
| source/NowPlayingUninstallController.cs | gittromney-Playnite-NowPlaying-23eec41 | [
{
"filename": "source/NowPlayingInstallController.cs",
"retrieved_chunk": " public readonly RoboStats jobStats;\n public readonly GameCacheViewModel gameCache;\n public readonly GameCacheManagerViewModel cacheManager;\n public readonly InstallProgressViewModel progressViewModel;\n public readonly InstallProgressView progressView;\n private Action onPausedAction;\n public int speedLimitIpg;\n private bool deleteCacheOnJobCancelled { get; set; } = false;\n private bool pauseOnPlayniteExit { get; set; } = false;\n public NowPlayingInstallController(NowPlaying plugin, Game nowPlayingGame, GameCacheViewModel gameCache, int speedLimitIpg = 0) ",
"score": 0.9160509705543518
},
{
"filename": "source/NowPlayingGameEnabler.cs",
"retrieved_chunk": "{\n public class NowPlayingGameEnabler\n {\n private readonly ILogger logger = NowPlaying.logger;\n private readonly NowPlaying plugin;\n private readonly IPlayniteAPI PlayniteApi;\n private readonly GameCacheManagerViewModel cacheManager;\n private readonly Game game;\n private readonly string cacheRootDir;\n public string Id => game.Id.ToString();",
"score": 0.9078165292739868
},
{
"filename": "source/ViewModels/GameCacheManagerViewModel.cs",
"retrieved_chunk": " private readonly string gameCacheEntriesJsonPath;\n private readonly string installAverageBpsJsonPath;\n public readonly GameCacheManager gameCacheManager;\n public ObservableCollection<CacheRootViewModel> CacheRoots { get; private set; }\n public ObservableCollection<GameCacheViewModel> GameCaches { get; private set; }\n public SortedDictionary<string, long> InstallAverageBps { get; private set; }\n public GameCacheManagerViewModel(NowPlaying plugin, ILogger logger)\n {\n this.plugin = plugin;\n this.logger = logger;",
"score": 0.8978350162506104
},
{
"filename": "source/ViewModels/GameCacheManagerViewModel.cs",
"retrieved_chunk": "using static NowPlaying.Models.GameCacheManager;\nusing Playnite.SDK;\nnamespace NowPlaying.ViewModels\n{\n public class GameCacheManagerViewModel : ViewModelBase\n {\n public readonly NowPlaying plugin;\n public readonly ILogger logger;\n private readonly string pluginUserDataPath;\n private readonly string cacheRootsJsonPath;",
"score": 0.8977779746055603
},
{
"filename": "source/NowPlayingInstallController.cs",
"retrieved_chunk": "using System.Threading;\nnamespace NowPlaying\n{\n public class NowPlayingInstallController : InstallController\n {\n private readonly ILogger logger = NowPlaying.logger;\n private readonly NowPlayingSettings settings;\n private readonly IPlayniteAPI PlayniteApi;\n private readonly Game nowPlayingGame;\n public readonly NowPlaying plugin;",
"score": 0.8953936100006104
}
] | csharp | GameCacheViewModel gameCache)
: base(nowPlayingGame)
{ |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace QuestSystem
{
public class QuestGiver : MonoBehaviour , IQuestInteraction
{
public | Quest questToGive; |
public TextAsset extraText;
private bool ableToGive = false;
private bool questAlreadyGiven;
private QuestManager questManagerRef;
// Start is called before the first frame update
void Start()
{
questManagerRef = QuestManager.GetInstance();
questAlreadyGiven = questManagerRef.IsMisionInLog(questToGive);
}
public void giveQuest()
{
showDialogue();
questManagerRef.AddMisionToCurrent(questToGive);
questAlreadyGiven = true;
QuestManager.GetInstance().Save();
}
public void showDialogue()
{
//if (conversation != null) FindObjectOfType<DialogueWindow>().StartDialogue(conversation, null);
//else return;
}
//Delete the ones you don't want to use
private void OnTriggerEnter(Collider other)
{
resultOfEnter(true, other.tag);
}
private void OnTriggerExit(Collider other)
{
resultOfEnter(false, other.tag);
}
private void OnTriggerEnter2D(Collider2D other)
{
resultOfEnter(true, other.tag);
}
private void OnTriggerExit2D(Collider2D other)
{
resultOfEnter(false, other.tag);
}
private void resultOfEnter(bool ableToGiveResult, string tag)
{
if (tag == "Player") ableToGive = ableToGiveResult;
}
public void Interact()
{
if(ableToGive && !questAlreadyGiven)
{
giveQuest();
}
}
}
} | Runtime/QuestGiver.cs | lluispalerm-QuestSystem-cd836cc | [
{
"filename": "Runtime/QuestObjectiveUpdater.cs",
"retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.Events;\nnamespace QuestSystem\n{\n public class QuestObjectiveUpdater : MonoBehaviour, IQuestInteraction\n {\n public Quest questToUpdate;\n [HideInInspector] public NodeQuest nodeToUpdate;",
"score": 0.9309672117233276
},
{
"filename": "Runtime/IQuestInteraction.cs",
"retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace QuestSystem\n{\n public interface IQuestInteraction\n {\n void Interact(); \n }\n}",
"score": 0.9078704714775085
},
{
"filename": "Runtime/QuestObjective.cs",
"retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace QuestSystem\n{\n [System.Serializable]\n public class QuestObjective\n {\n public string keyName;\n public bool isCompleted;",
"score": 0.8914298415184021
},
{
"filename": "Runtime/QuestManager.cs",
"retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\nusing QuestSystem.SaveSystem;\nnamespace QuestSystem\n{\n public class QuestManager\n {\n public QuestLog misionLog;",
"score": 0.8819186687469482
},
{
"filename": "Runtime/QuestOnObjectWorld.cs",
"retrieved_chunk": "using UnityEngine;\nnamespace QuestSystem\n{\n public class QuestOnObjectWorld : MonoBehaviour\n {\n //Structs in order to show on editor\n [System.Serializable]\n public struct ObjectsForQuestTable\n {\n public Quest quest;",
"score": 0.8784404993057251
}
] | csharp | Quest questToGive; |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using ForceConnect.Interfaces;
namespace ForceConnect.Services
{
internal class NetworkInformation
{
public static | NetworkInterfaceInfo GetActiveNetworkInterfaceInfo()
{ |
NetworkInterface activeInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
a => a.OperationalStatus == OperationalStatus.Up &&
(a.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || a.NetworkInterfaceType == NetworkInterfaceType.Ethernet) &&
a.GetIPProperties().GatewayAddresses.Any(g => g.Address.AddressFamily == AddressFamily.InterNetwork));
if (activeInterface != null)
{
IPInterfaceProperties ipProperties = activeInterface.GetIPProperties();
IPAddress ipAddress = ipProperties.UnicastAddresses.FirstOrDefault(a => a.Address.AddressFamily == AddressFamily.InterNetwork)?.Address;
IPAddress subnetMask = ipProperties.UnicastAddresses.FirstOrDefault(a => a.Address.AddressFamily == AddressFamily.InterNetwork)?.IPv4Mask;
string hostName = Dns.GetHostName();
IPAddress[] dnsIPAddresses = ipProperties.DnsAddresses.Where(a => a.AddressFamily == AddressFamily.InterNetwork).ToArray();
return new NetworkInterfaceInfo
{
ActiveInterfaceName = activeInterface.Name,
Description = activeInterface.Description,
Status = activeInterface.OperationalStatus,
MACAddress = activeInterface.GetPhysicalAddress().ToString(),
Speed = activeInterface.Speed,
IPAddress = ipAddress,
SubnetMask = subnetMask,
HostName = hostName,
DNSIPAddress = dnsIPAddresses
};
}
else
{
return null;
}
}
public static double ConvertBytesToMbps(long bytes)
{
double bits = bytes * 8; // Convert bytes to bits
double mbps = bits / 1000000; // Convert bits to megabits
return Math.Round(mbps, 2);
}
}
}
| ForceConnect/Services/NetworkInformation.cs | Mxqius-ForceConnect-059bd9e | [
{
"filename": "ForceConnect/frm_network.cs",
"retrieved_chunk": "using ForceConnect.Interfaces;\nusing ForceConnect.Services;\nusing System;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\nnamespace ForceConnect\n{\n public partial class frm_network : Form\n {\n public frm_network()",
"score": 0.8904656171798706
},
{
"filename": "ForceConnect/API/Latency.cs",
"retrieved_chunk": "using System.Net.NetworkInformation;\nnamespace ForceConnect.API\n{\n public class Latency\n {\n public static long MeasureLatency(string ipAddress)\n {\n try\n {\n Ping pingSender = new Ping();",
"score": 0.8503124713897705
},
{
"filename": "ForceConnect/frm_service.cs",
"retrieved_chunk": "using System.Threading.Tasks;\nusing System.Windows.Forms;\nnamespace ForceConnect\n{\n public partial class frm_service : Form\n {\n public frm_service()\n {\n InitializeComponent();\n }",
"score": 0.8481971621513367
},
{
"filename": "ForceConnect/Services/Service.cs",
"retrieved_chunk": "using System;\nusing System.IO;\nnamespace ForceConnect.Services\n{\n internal class Service\n {\n private static readonly string pathServices = Environment.CurrentDirectory + \"\\\\Services\\\\services.txt\";\n private static readonly string directory = Environment.CurrentDirectory + \"\\\\Services\";\n public static void AddService(string name, string address1, string address2 = \"\")\n {",
"score": 0.8439019322395325
},
{
"filename": "ForceConnect/frm_explore.cs",
"retrieved_chunk": "using ForceConnect.API;\nusing ForceConnect.Services;\nusing System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\nnamespace ForceConnect\n{\n public partial class frm_explore : Form\n {",
"score": 0.8313256502151489
}
] | csharp | NetworkInterfaceInfo GetActiveNetworkInterfaceInfo()
{ |
using Iced.Intel;
using System.Collections;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace OGXbdmDumper
{
public static class Extensions
{
#region Misc
/// <summary>
/// Converts an Int32 into a Version.
/// </summary>
/// <param name="version"></param>
/// <returns></returns>
public static Version ToVersion(this int version)
{
return new Version(version & 0xFF, (version >> 8) & 0xFF,
(version >> 16) & 0xFF, version >> 24);
}
#endregion
#region String
/// <summary>
/// Extracts name/value pairs from an Xbox response line.
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
public static Dictionary<string, object> ParseXboxResponseLine(this string line)
{
Dictionary<string, object> values = new Dictionary<string, object>();
var items = Regex.Matches(line, @"(\S+)\s*=\s*(""(?:[^""]|"""")*""|\S+)");
foreach (Match item in items)
{
string name = item.Groups[1].Value;
string value = item.Groups[2].Value;
long longValue;
if (value.StartsWith("\""))
{
// string
values[name] = value.Trim('"');
}
else if (value.StartsWith("0x"))
{
// hexidecimal integer
values[name] = Convert.ToInt64(value, 16);
}
else if (long.TryParse(value, out longValue))
{
// decimal integer
values[name] = longValue;
}
else
{
throw new InvalidCastException("Unknown data type");
}
}
return values;
}
#endregion
#region Arrays
/// <summary>
/// Fills the specified byte array with random data.
/// </summary>
/// <param name="data"></param>
/// <returns>Returns a reference of itself.</returns>
public static byte[] FillRandom(this byte[] data)
{
for (int i = 0; i < data.Length; i++)
{
data[i] = (byte)Utility.Random.Next(byte.MaxValue);
}
return data;
}
/// <summary>
/// Fills the specified byte array with random data.
/// </summary>
/// <param name="data"></param>
/// <returns>Returns a reference of itself.</returns>
public static Span<byte> FillRandom(this Span<byte> data)
{
for (int i = 0; i < data.Length; i++)
{
data[i] = (byte)Utility.Random.Next(byte.MaxValue);
}
return data;
}
/// <summary>
/// Checks if the underlying data is equal.
/// </summary>
/// <param name="sourceData"></param>
/// <param name="data"></param>
/// <returns></returns>
public static bool IsEqual(this byte[] sourceData, byte[] data)
{
return StructuralComparisons.StructuralEqualityComparer.Equals(sourceData, data);
}
/// <summary>
/// Checks if the underlying data is equal.
/// </summary>
/// <param name="sourceData"></param>
/// <param name="data"></param>
/// <returns></returns>
public static bool IsEqual(this Span<byte> sourceData, Span<byte> data)
{
return MemoryExtensions.SequenceEqual(sourceData, data);
}
/// <summary>
/// TODO: description
/// </summary>
/// <param name="data"></param>
/// <param name="pattern"></param>
/// <param name="startIndex"></param>
/// <returns></returns>
public static int IndexOfArray(this byte[] data, byte[] pattern, int startIndex = 0)
{
for (int i = startIndex; i < data.Length; i++)
{
for (int j = 0; j < pattern.Length; j++)
{
if (data[i + j] != pattern[j])
break;
if (j == pattern.Length - 1)
return i;
}
}
return -1;
}
#endregion
#region Assembler
/// <summary>
/// Assembles the instructions.
/// </summary>
/// <param name="asm"></param>
/// <param name="baseAddress"></param>
/// <returns>Returns the assembled bytes.</returns>
public static byte[] AssembleBytes(this Assembler asm, uint baseAddress)
{
using var ms = new MemoryStream();
asm.Assemble(new StreamCodeWriter(ms), baseAddress);
return ms.ToArray();
}
/// <summary>
/// Hooks the specified Xbox target address redirecting to the specified cave address.
/// Caller must recreate any instructions clobbered by the hook in the cave.
/// The hook is 6 bytes long consisting of a push followed by a ret.
/// </summary>
/// <param name="asm">The assembler.</param>
/// <param name="target">The xbox target.</param>
/// <param name="hookAddress">The hook address.</param>
/// <param name="caveAddress">The cave address.</param>
public static void Hook(this Assembler asm, | Xbox target, long hookAaddress, long caveAddress)
{ |
// store the pushret hook to the cave
// TODO: combine writes!
target.Memory.Position = hookAaddress;
target.Memory.Write((byte)0x68); // push
target.Memory.Write(caveAddress); // cave address
target.Memory.Write((byte)0xC3); // ret
}
#endregion
#region Stream
/// <summary>
/// Copies the specified amount of data from the source to desination streams.
/// Useful when at least one stream doesn't support the Length property.
/// </summary>
/// <param name="source">The source stream.</param>
/// <param name="destination">The destination stream.</param>
/// <param name="count">The amount of data to copy.</param>
public static void CopyToCount(this Stream source, Stream destination, long count)
{
Span<byte> buffer = stackalloc byte[1024 * 80];
while (count > 0)
{
var slice = buffer.Slice(0, (int)Math.Min(buffer.Length, count));
// TODO: optimize via async queuing of reads/writes
source.Read(slice);
destination.Write(slice);
count -= slice.Length;
}
}
/// <summary>
/// Writes a value to a stream.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream"></param>
/// <param name="value"></param>
/// <returns>Returns the number of bytes written.</returns>
public static int Write<T>(this Stream stream, T value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
long origStreamPosition = stream.Position;
using var writer = new BinaryWriter(stream);
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Boolean:
writer.Write((bool)(object)value);
break;
case TypeCode.Char:
writer.Write((char)(object)value);
break;
case TypeCode.SByte:
writer.Write((sbyte)(object)value);
break;
case TypeCode.Byte:
writer.Write((byte)(object)value);
break;
case TypeCode.Int16:
writer.Write((short)(object)value);
break;
case TypeCode.UInt16:
writer.Write((ushort)(object)value);
break;
case TypeCode.Int32:
writer.Write((int)(object)value);
break;
case TypeCode.UInt32:
writer.Write((uint)(object)value);
break;
case TypeCode.Int64:
writer.Write((long)(object)value);
break;
case TypeCode.UInt64:
writer.Write((ulong)(object)value);
break;
case TypeCode.Single:
writer.Write((float)(object)value);
break;
case TypeCode.Double:
writer.Write((double)(object)value);
break;
case TypeCode.String:
writer.Write(Encoding.ASCII.GetBytes((string)(object)value));
break;
default:
if (value is byte[])
{
writer.Write(value as byte[]);
break;
}
throw new InvalidCastException();
}
return (int)(stream.Position - origStreamPosition);
}
#endregion
#region Hex Conversion
/// <summary>
/// TODO: description
/// </summary>
/// <param name="value"></param>
/// <param name="padWidth"></param>
/// <returns></returns>
public static string ToHexString(this uint value, int padWidth = 0)
{
// TODO: cleanup
return "0x" + value.ToString("X" + (padWidth > 0 ? padWidth.ToString() : string.Empty));
}
/// <summary>
/// TODO: description
/// </summary>
/// <param name="value"></param>
/// <param name="padWidth"></param>
/// <returns></returns>
public static string ToHexString(this int value, int padWidth = 0)
{
// TODO: cleanup
return "0x" + value.ToString("X" + (padWidth > 0 ? padWidth.ToString() : string.Empty));
}
/// <summary>
/// TODO: description
/// </summary>
/// <param name="value"></param>
/// <param name="padWidth"></param>
/// <returns></returns>
public static string ToHexString(this long value, int padWidth = 0)
{
// TODO: cleanup
return "0x" + value.ToString("X" + (padWidth > 0 ? padWidth.ToString() : string.Empty));
}
/// <summary>
/// Converts an span array of bytes to a hexidecimal string representation.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string ToHexString(this byte[] data)
{
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
hexString.Append(Convert.ToString(data[i], 16).ToUpperInvariant().PadLeft(2, '0'));
}
return hexString.ToString();
}
/// <summary>
/// Converts an span array of bytes to a hexidecimal string representation.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string ToHexString(this Span<byte> data)
{
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
hexString.Append(Convert.ToString(data[i], 16).ToUpperInvariant().PadLeft(2, '0'));
}
return hexString.ToString();
}
/// <summary>
/// Converts an span array of bytes to a hexidecimal string representation.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string ToHexString(this ReadOnlySpan<byte> data)
{
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
hexString.Append(Convert.ToString(data[i], 16).ToUpperInvariant().PadLeft(2, '0'));
}
return hexString.ToString();
}
/// <summary>
/// Converts a hexidecimal string into byte format in the destination.
/// </summary>
/// <param name="str"></param>
/// <param name="destination"></param>
public static void FromHexString(this Span<byte> destination, string str)
{
if (str.Length == 0 || str.Length % 2 != 0)
throw new ArgumentException("Invalid hexidecimal string length.");
if (destination.Length != str.Length / 2)
throw new ArgumentException("Invalid size.", nameof(destination));
for (int i = 0; i < str.Length / 2; i++)
{
destination[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
}
}
#endregion
#region Reflection
/// <summary>
/// Gets the value of the specified member field or property.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="member"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static T GetValue<T>(this MemberInfo member, object obj)
{
return member.MemberType switch
{
MemberTypes.Field => (T)((FieldInfo)member).GetValue(obj),
MemberTypes.Property => (T)((PropertyInfo)member).GetValue(obj),
_ => throw new NotImplementedException(),
};
}
/// <summary>
/// Sets the value of the specified member field or property.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="member"></param>
/// <param name="obj"></param>
/// <param name="value"></param>
public static void SetValue<T>(this MemberInfo member, object obj, T value)
{
switch (member.MemberType)
{
case MemberTypes.Field:
((FieldInfo)member).SetValue(obj, value);
break;
case MemberTypes.Property:
((PropertyInfo)member).SetValue(obj, value);
break;
default:
throw new NotImplementedException();
}
}
#endregion
}
}
| src/OGXbdmDumper/Extensions.cs | Ernegien-OGXbdmDumper-07a1e82 | [
{
"filename": "src/OGXbdmDumper/Xbox.cs",
"retrieved_chunk": " /// <param name=\"address\">The function address.</param>\n /// <param name=\"args\">The function arguments.</param>\n /// <returns>Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.</returns>\n public uint Call(long address, params object[] args)\n {\n // TODO: call context (~4039+ which requires qwordparam)\n // injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);",
"score": 0.8313210606575012
},
{
"filename": "src/OGXbdmDumper/Connection.cs",
"retrieved_chunk": " /// </summary>\n public void ClearReceiveBuffer()\n {\n ClearReceiveBuffer(_client.Available);\n }\n /// <summary>\n /// Sends a command to the xbox without waiting for a response.\n /// </summary>\n /// <param name=\"command\">Command to be sent</param>\n /// <param name=\"args\">Arguments</param>",
"score": 0.8229362964630127
},
{
"filename": "src/OGXbdmDumper/SodmaSignature.cs",
"retrieved_chunk": " /// </summary>\n public readonly ReadOnlyMemory<byte> Data;\n /// <summary>\n /// Initializes a new offset data mask pattern.\n /// </summary>\n /// <param name=\"offset\">The offset from the presumed function start upon match. Negative offsets are allowed.</param>\n /// <param name=\"data\">The data to match.</param>\n /// <param name=\"mask\">The bitwise mask applied to the data when evaluating a match.</param>\n public OdmPattern(int offset, ReadOnlyMemory<byte> data, ReadOnlyMemory<byte> mask)\n {",
"score": 0.8227927088737488
},
{
"filename": "src/OGXbdmDumper/Xbox.cs",
"retrieved_chunk": " /// </summary>\n /// <param name=\"target\"></param>\n private void PatchXbdm(Xbox target)\n {\n // the spin routine to be patched in after the signature patterns\n // spin:\n // jmp spin\n // int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n // prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)",
"score": 0.8217822909355164
},
{
"filename": "src/OGXbdmDumper/Module.cs",
"retrieved_chunk": " /// Name of the module that was loaded.\n /// </summary>\n public string? Name;\n /// <summary>\n /// Address that the module was loaded to.\n /// </summary>\n public uint BaseAddress;\n /// <summary>\n /// Size of the module.\n /// </summary>",
"score": 0.8204823136329651
}
] | csharp | Xbox target, long hookAaddress, long caveAddress)
{ |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using System.Threading.Tasks;
using Magic.IndexedDb.Helpers;
using Magic.IndexedDb.Models;
using Magic.IndexedDb.SchemaAnnotations;
using Microsoft.JSInterop;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using static System.Collections.Specialized.BitVector32;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Magic.IndexedDb
{
/// <summary>
/// Provides functionality for accessing IndexedDB from Blazor application
/// </summary>
public class IndexedDbManager
{
readonly DbStore _dbStore;
readonly IJSRuntime _jsRuntime;
const string InteropPrefix = "window.magicBlazorDB";
DotNetObjectReference<IndexedDbManager> _objReference;
IDictionary<Guid, WeakReference<Action<BlazorDbEvent>>> _transactions = new Dictionary<Guid, WeakReference<Action<BlazorDbEvent>>>();
IDictionary<Guid, TaskCompletionSource< | BlazorDbEvent>> _taskTransactions = new Dictionary<Guid, TaskCompletionSource<BlazorDbEvent>>(); |
private IJSObjectReference? _module { get; set; }
/// <summary>
/// A notification event that is raised when an action is completed
/// </summary>
public event EventHandler<BlazorDbEvent> ActionCompleted;
/// <summary>
/// Ctor
/// </summary>
/// <param name="dbStore"></param>
/// <param name="jsRuntime"></param>
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
internal IndexedDbManager(DbStore dbStore, IJSRuntime jsRuntime)
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
{
_objReference = DotNetObjectReference.Create(this);
_dbStore = dbStore;
_jsRuntime = jsRuntime;
}
public async Task<IJSObjectReference> GetModule(IJSRuntime jsRuntime)
{
if (_module == null)
{
_module = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/Magic.IndexedDb/magicDB.js");
}
return _module;
}
public List<StoreSchema> Stores => _dbStore.StoreSchemas;
public string CurrentVersion => _dbStore.Version;
public string DbName => _dbStore.Name;
/// <summary>
/// Opens the IndexedDB defined in the DbStore. Under the covers will create the database if it does not exist
/// and create the stores defined in DbStore.
/// </summary>
/// <returns></returns>
public async Task<Guid> OpenDb(Action<BlazorDbEvent>? action = null)
{
var trans = GenerateTransaction(action);
await CallJavascriptVoid(IndexedDbFunctions.CREATE_DB, trans, _dbStore);
return trans;
}
/// <summary>
/// Deletes the database corresponding to the dbName passed in
/// </summary>
/// <param name="dbName">The name of database to delete</param>
/// <returns></returns>
public async Task<Guid> DeleteDb(string dbName, Action<BlazorDbEvent>? action = null)
{
if (string.IsNullOrEmpty(dbName))
{
throw new ArgumentException("dbName cannot be null or empty", nameof(dbName));
}
var trans = GenerateTransaction(action);
await CallJavascriptVoid(IndexedDbFunctions.DELETE_DB, trans, dbName);
return trans;
}
/// <summary>
/// Deletes the database corresponding to the dbName passed in
/// Waits for response
/// </summary>
/// <param name="dbName">The name of database to delete</param>
/// <returns></returns>
public async Task<BlazorDbEvent> DeleteDbAsync(string dbName)
{
if (string.IsNullOrEmpty(dbName))
{
throw new ArgumentException("dbName cannot be null or empty", nameof(dbName));
}
var trans = GenerateTransaction();
await CallJavascriptVoid(IndexedDbFunctions.DELETE_DB, trans.trans, dbName);
return await trans.task;
}
/// <summary>
/// Adds a new record/object to the specified store
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="recordToAdd">An instance of StoreRecord that provides the store name and the data to add</param>
/// <returns></returns>
private async Task<Guid> AddRecord<T>(StoreRecord<T> recordToAdd, Action<BlazorDbEvent>? action = null)
{
var trans = GenerateTransaction(action);
try
{
recordToAdd.DbName = DbName;
await CallJavascriptVoid(IndexedDbFunctions.ADD_ITEM, trans, recordToAdd);
}
catch (JSException e)
{
RaiseEvent(trans, true, e.Message);
}
return trans;
}
public async Task<Guid> Add<T>(T record, Action<BlazorDbEvent>? action = null) where T : class
{
string schemaName = SchemaHelper.GetSchemaName<T>();
T? myClass = null;
object? processedRecord = await ProcessRecord(record);
if (processedRecord is ExpandoObject)
myClass = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(processedRecord));
else
myClass = (T?)processedRecord;
var trans = GenerateTransaction(action);
try
{
Dictionary<string, object?>? convertedRecord = null;
if (processedRecord is ExpandoObject)
{
var result = ((ExpandoObject)processedRecord)?.ToDictionary(kv => kv.Key, kv => (object?)kv.Value);
if (result != null)
{
convertedRecord = result;
}
}
else
{
convertedRecord = ManagerHelper.ConvertRecordToDictionary(myClass);
}
var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
// Convert the property names in the convertedRecord dictionary
if (convertedRecord != null)
{
var updatedRecord = ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings);
if (updatedRecord != null)
{
StoreRecord<Dictionary<string, object?>> RecordToSend = new StoreRecord<Dictionary<string, object?>>()
{
DbName = this.DbName,
StoreName = schemaName,
Record = updatedRecord
};
await CallJavascriptVoid(IndexedDbFunctions.ADD_ITEM, trans, RecordToSend);
}
}
}
catch (JSException e)
{
RaiseEvent(trans, true, e.Message);
}
return trans;
}
public async Task<string> Decrypt(string EncryptedValue)
{
EncryptionFactory encryptionFactory = new EncryptionFactory(_jsRuntime, this);
string decryptedValue = await encryptionFactory.Decrypt(EncryptedValue, _dbStore.EncryptionKey);
return decryptedValue;
}
private async Task<object?> ProcessRecord<T>(T record) where T : class
{
string schemaName = SchemaHelper.GetSchemaName<T>();
StoreSchema? storeSchema = Stores.FirstOrDefault(s => s.Name == schemaName);
if (storeSchema == null)
{
throw new InvalidOperationException($"StoreSchema not found for '{schemaName}'");
}
// Encrypt properties with EncryptDb attribute
var propertiesToEncrypt = typeof(T).GetProperties()
.Where(p => p.GetCustomAttributes(typeof(MagicEncryptAttribute), false).Length > 0);
EncryptionFactory encryptionFactory = new EncryptionFactory(_jsRuntime, this);
foreach (var property in propertiesToEncrypt)
{
if (property.PropertyType != typeof(string))
{
throw new InvalidOperationException("EncryptDb attribute can only be used on string properties.");
}
string? originalValue = property.GetValue(record) as string;
if (!string.IsNullOrWhiteSpace(originalValue))
{
string encryptedValue = await encryptionFactory.Encrypt(originalValue, _dbStore.EncryptionKey);
property.SetValue(record, encryptedValue);
}
else
{
property.SetValue(record, originalValue);
}
}
// Proceed with adding the record
if (storeSchema.PrimaryKeyAuto)
{
var primaryKeyProperty = typeof(T)
.GetProperties()
.FirstOrDefault(p => p.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length > 0);
if (primaryKeyProperty != null)
{
Dictionary<string, object?> recordAsDict;
var primaryKeyValue = primaryKeyProperty.GetValue(record);
if (primaryKeyValue == null || primaryKeyValue.Equals(GetDefaultValue(primaryKeyValue.GetType())))
{
recordAsDict = typeof(T).GetProperties()
.Where(p => p.Name != primaryKeyProperty.Name && p.GetCustomAttributes(typeof(MagicNotMappedAttribute), false).Length == 0)
.ToDictionary(p => p.Name, p => p.GetValue(record));
}
else
{
recordAsDict = typeof(T).GetProperties()
.Where(p => p.GetCustomAttributes(typeof(MagicNotMappedAttribute), false).Length == 0)
.ToDictionary(p => p.Name, p => p.GetValue(record));
}
// Create a new ExpandoObject and copy the key-value pairs from the dictionary
var expandoRecord = new ExpandoObject() as IDictionary<string, object?>;
foreach (var kvp in recordAsDict)
{
expandoRecord.Add(kvp);
}
return expandoRecord as ExpandoObject;
}
}
return record;
}
// Returns the default value for the given type
private static object? GetDefaultValue(Type type)
{
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
/// <summary>
/// Adds records/objects to the specified store in bulk
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="recordsToBulkAdd">The data to add</param>
/// <returns></returns>
private async Task<Guid> BulkAddRecord<T>(string storeName, IEnumerable<T> recordsToBulkAdd, Action<BlazorDbEvent>? action = null)
{
var trans = GenerateTransaction(action);
try
{
await CallJavascriptVoid(IndexedDbFunctions.BULKADD_ITEM, trans, DbName, storeName, recordsToBulkAdd);
}
catch (JSException e)
{
RaiseEvent(trans, true, e.Message);
}
return trans;
}
//public async Task<Guid> AddRange<T>(IEnumerable<T> records, Action<BlazorDbEvent> action = null) where T : class
//{
// string schemaName = SchemaHelper.GetSchemaName<T>();
// var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
// List<object> processedRecords = new List<object>();
// foreach (var record in records)
// {
// object processedRecord = await ProcessRecord(record);
// if (processedRecord is ExpandoObject)
// {
// var convertedRecord = ((ExpandoObject)processedRecord).ToDictionary(kv => kv.Key, kv => (object)kv.Value);
// processedRecords.Add(ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings));
// }
// else
// {
// var convertedRecord = ManagerHelper.ConvertRecordToDictionary((T)processedRecord);
// processedRecords.Add(ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings));
// }
// }
// return await BulkAddRecord(schemaName, processedRecords, action);
//}
/// <summary>
/// Adds records/objects to the specified store in bulk
/// Waits for response
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="recordsToBulkAdd">An instance of StoreRecord that provides the store name and the data to add</param>
/// <returns></returns>
private async Task<BlazorDbEvent> BulkAddRecordAsync<T>(string storeName, IEnumerable<T> recordsToBulkAdd)
{
var trans = GenerateTransaction();
try
{
await CallJavascriptVoid(IndexedDbFunctions.BULKADD_ITEM, trans.trans, DbName, storeName, recordsToBulkAdd);
}
catch (JSException e)
{
RaiseEvent(trans.trans, true, e.Message);
}
return await trans.task;
}
public async Task AddRange<T>(IEnumerable<T> records) where T : class
{
string schemaName = SchemaHelper.GetSchemaName<T>();
//var trans = GenerateTransaction(null);
//var TableCount = await CallJavascript<int>(IndexedDbFunctions.COUNT_TABLE, trans, DbName, schemaName);
List<Dictionary<string, object?>> processedRecords = new List<Dictionary<string, object?>>();
foreach (var record in records)
{
bool IsExpando = false;
T? myClass = null;
object? processedRecord = await ProcessRecord(record);
if (processedRecord is ExpandoObject)
{
myClass = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(processedRecord));
IsExpando = true;
}
else
myClass = (T?)processedRecord;
Dictionary<string, object?>? convertedRecord = null;
if (processedRecord is ExpandoObject)
{
var result = ((ExpandoObject)processedRecord)?.ToDictionary(kv => kv.Key, kv => (object?)kv.Value);
if (result != null)
convertedRecord = result;
}
else
{
convertedRecord = ManagerHelper.ConvertRecordToDictionary(myClass);
}
var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
// Convert the property names in the convertedRecord dictionary
if (convertedRecord != null)
{
var updatedRecord = ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings);
if (updatedRecord != null)
{
if (IsExpando)
{
//var test = updatedRecord.Cast<Dictionary<string, object>();
var dictionary = updatedRecord as Dictionary<string, object?>;
processedRecords.Add(dictionary);
}
else
{
processedRecords.Add(updatedRecord);
}
}
}
}
await BulkAddRecordAsync(schemaName, processedRecords);
}
public async Task<Guid> Update<T>(T item, Action<BlazorDbEvent>? action = null) where T : class
{
var trans = GenerateTransaction(action);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute)));
if (primaryKeyProperty != null)
{
object? primaryKeyValue = primaryKeyProperty.GetValue(item);
var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item);
if (primaryKeyValue != null)
{
UpdateRecord<Dictionary<string, object?>> record = new UpdateRecord<Dictionary<string, object?>>()
{
Key = primaryKeyValue,
DbName = this.DbName,
StoreName = schemaName,
Record = convertedRecord
};
// Get the primary key value of the item
await CallJavascriptVoid(IndexedDbFunctions.UPDATE_ITEM, trans, record);
}
else
{
throw new ArgumentException("Item being updated must have a key.");
}
}
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
public async Task<Guid> UpdateRange<T>(IEnumerable<T> items, Action<BlazorDbEvent>? action = null) where T : class
{
var trans = GenerateTransaction(action);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute)));
if (primaryKeyProperty != null)
{
List<UpdateRecord<Dictionary<string, object?>>> recordsToUpdate = new List<UpdateRecord<Dictionary<string, object?>>>();
foreach (var item in items)
{
object? primaryKeyValue = primaryKeyProperty.GetValue(item);
var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item);
if (primaryKeyValue != null)
{
recordsToUpdate.Add(new UpdateRecord<Dictionary<string, object?>>()
{
Key = primaryKeyValue,
DbName = this.DbName,
StoreName = schemaName,
Record = convertedRecord
});
}
await CallJavascriptVoid(IndexedDbFunctions.BULKADD_UPDATE, trans, recordsToUpdate);
}
}
else
{
throw new ArgumentException("Item being update range item must have a key.");
}
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
public async Task<TResult?> GetById<TResult>(object key) where TResult : class
{
string schemaName = SchemaHelper.GetSchemaName<TResult>();
// Find the primary key property
var primaryKeyProperty = typeof(TResult)
.GetProperties()
.FirstOrDefault(p => p.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length > 0);
if (primaryKeyProperty == null)
{
throw new InvalidOperationException("No primary key property found with PrimaryKeyDbAttribute.");
}
// Check if the key is of the correct type
if (!primaryKeyProperty.PropertyType.IsInstanceOfType(key))
{
throw new ArgumentException($"Invalid key type. Expected: {primaryKeyProperty.PropertyType}, received: {key.GetType()}");
}
var trans = GenerateTransaction(null);
string columnName = primaryKeyProperty.GetPropertyColumnName<MagicPrimaryKeyAttribute>();
var data = new { DbName = DbName, StoreName = schemaName, Key = columnName, KeyValue = key };
try
{
var propertyMappings = ManagerHelper.GeneratePropertyMapping<TResult>();
var RecordToConvert = await CallJavascript<Dictionary<string, object>>(IndexedDbFunctions.FIND_ITEMV2, trans, data.DbName, data.StoreName, data.KeyValue);
if (RecordToConvert != null)
{
var ConvertedResult = ConvertIndexedDbRecordToCRecord<TResult>(RecordToConvert, propertyMappings);
return ConvertedResult;
}
else
{
return default(TResult);
}
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return default(TResult);
}
public MagicQuery<T> Where<T>(Expression<Func<T, bool>> predicate) where T : class
{
string schemaName = SchemaHelper.GetSchemaName<T>();
MagicQuery<T> query = new MagicQuery<T>(schemaName, this);
// Preprocess the predicate to break down Any and All expressions
var preprocessedPredicate = PreprocessPredicate(predicate);
var asdf = preprocessedPredicate.ToString();
CollectBinaryExpressions(preprocessedPredicate.Body, preprocessedPredicate, query.JsonQueries);
return query;
}
private Expression<Func<T, bool>> PreprocessPredicate<T>(Expression<Func<T, bool>> predicate)
{
var visitor = new PredicateVisitor<T>();
var newExpression = visitor.Visit(predicate.Body);
return Expression.Lambda<Func<T, bool>>(newExpression, predicate.Parameters);
}
internal async Task<IList<T>?> WhereV2<T>(string storeName, List<string> jsonQuery, MagicQuery<T> query) where T : class
{
var trans = GenerateTransaction(null);
try
{
string? jsonQueryAdditions = null;
if (query != null && query.storedMagicQueries != null && query.storedMagicQueries.Count > 0)
{
jsonQueryAdditions = Newtonsoft.Json.JsonConvert.SerializeObject(query.storedMagicQueries.ToArray());
}
var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
IList<Dictionary<string, object>>? ListToConvert =
await CallJavascript<IList<Dictionary<string, object>>>
(IndexedDbFunctions.WHEREV2, trans, DbName, storeName, jsonQuery.ToArray(), jsonQueryAdditions!, query?.ResultsUnique!);
var resultList = ConvertListToRecords<T>(ListToConvert, propertyMappings);
return resultList;
}
catch (Exception jse)
{
RaiseEvent(trans, true, jse.Message);
}
return default;
}
private void CollectBinaryExpressions<T>(Expression expression, Expression<Func<T, bool>> predicate, List<string> jsonQueries) where T : class
{
var binaryExpr = expression as BinaryExpression;
if (binaryExpr != null && binaryExpr.NodeType == ExpressionType.OrElse)
{
// Split the OR condition into separate expressions
var left = binaryExpr.Left;
var right = binaryExpr.Right;
// Process left and right expressions recursively
CollectBinaryExpressions(left, predicate, jsonQueries);
CollectBinaryExpressions(right, predicate, jsonQueries);
}
else
{
// If the expression is a single condition, create a query for it
var test = expression.ToString();
var tes2t = predicate.ToString();
string jsonQuery = GetJsonQueryFromExpression(Expression.Lambda<Func<T, bool>>(expression, predicate.Parameters));
jsonQueries.Add(jsonQuery);
}
}
private object ConvertValueToType(object value, Type targetType)
{
if (targetType == typeof(Guid) && value is string stringValue)
{
return Guid.Parse(stringValue);
}
return Convert.ChangeType(value, targetType);
}
private IList<TRecord> ConvertListToRecords<TRecord>(IList<Dictionary<string, object>> listToConvert, Dictionary<string, string> propertyMappings)
{
var records = new List<TRecord>();
var recordType = typeof(TRecord);
foreach (var item in listToConvert)
{
var record = Activator.CreateInstance<TRecord>();
foreach (var kvp in item)
{
if (propertyMappings.TryGetValue(kvp.Key, out var propertyName))
{
var property = recordType.GetProperty(propertyName);
var value = ManagerHelper.GetValueFromValueKind(kvp.Value);
if (property != null)
{
property.SetValue(record, ConvertValueToType(value!, property.PropertyType));
}
}
}
records.Add(record);
}
return records;
}
private TRecord ConvertIndexedDbRecordToCRecord<TRecord>(Dictionary<string, object> item, Dictionary<string, string> propertyMappings)
{
var recordType = typeof(TRecord);
var record = Activator.CreateInstance<TRecord>();
foreach (var kvp in item)
{
if (propertyMappings.TryGetValue(kvp.Key, out var propertyName))
{
var property = recordType.GetProperty(propertyName);
var value = ManagerHelper.GetValueFromValueKind(kvp.Value);
if (property != null)
{
property.SetValue(record, ConvertValueToType(value!, property.PropertyType));
}
}
}
return record;
}
private string GetJsonQueryFromExpression<T>(Expression<Func<T, bool>> predicate) where T : class
{
var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var conditions = new List<JObject>();
var orConditions = new List<List<JObject>>();
void TraverseExpression(Expression expression, bool inOrBranch = false)
{
if (expression is BinaryExpression binaryExpression)
{
if (binaryExpression.NodeType == ExpressionType.AndAlso)
{
TraverseExpression(binaryExpression.Left, inOrBranch);
TraverseExpression(binaryExpression.Right, inOrBranch);
}
else if (binaryExpression.NodeType == ExpressionType.OrElse)
{
if (inOrBranch)
{
throw new InvalidOperationException("Nested OR conditions are not supported.");
}
TraverseExpression(binaryExpression.Left, !inOrBranch);
TraverseExpression(binaryExpression.Right, !inOrBranch);
}
else
{
AddCondition(binaryExpression, inOrBranch);
}
}
else if (expression is MethodCallExpression methodCallExpression)
{
AddCondition(methodCallExpression, inOrBranch);
}
}
void AddCondition(Expression expression, bool inOrBranch)
{
if (expression is BinaryExpression binaryExpression)
{
var leftMember = binaryExpression.Left as MemberExpression;
var rightMember = binaryExpression.Right as MemberExpression;
var leftConstant = binaryExpression.Left as ConstantExpression;
var rightConstant = binaryExpression.Right as ConstantExpression;
var operation = binaryExpression.NodeType.ToString();
if (leftMember != null && rightConstant != null)
{
AddConditionInternal(leftMember, rightConstant, operation, inOrBranch);
}
else if (leftConstant != null && rightMember != null)
{
// Swap the order of the left and right expressions and the operation
if (operation == "GreaterThan")
{
operation = "LessThan";
}
else if (operation == "LessThan")
{
operation = "GreaterThan";
}
else if (operation == "GreaterThanOrEqual")
{
operation = "LessThanOrEqual";
}
else if (operation == "LessThanOrEqual")
{
operation = "GreaterThanOrEqual";
}
AddConditionInternal(rightMember, leftConstant, operation, inOrBranch);
}
}
else if (expression is MethodCallExpression methodCallExpression)
{
if (methodCallExpression.Method.DeclaringType == typeof(string) &&
(methodCallExpression.Method.Name == "Equals" || methodCallExpression.Method.Name == "Contains" || methodCallExpression.Method.Name == "StartsWith"))
{
var left = methodCallExpression.Object as MemberExpression;
var right = methodCallExpression.Arguments[0] as ConstantExpression;
var operation = methodCallExpression.Method.Name;
var caseSensitive = true;
if (methodCallExpression.Arguments.Count > 1)
{
var stringComparison = methodCallExpression.Arguments[1] as ConstantExpression;
if (stringComparison != null && stringComparison.Value is StringComparison comparisonValue)
{
caseSensitive = comparisonValue == StringComparison.Ordinal || comparisonValue == StringComparison.CurrentCulture;
}
}
AddConditionInternal(left, right, operation == "Equals" ? "StringEquals" : operation, inOrBranch, caseSensitive);
}
}
}
void AddConditionInternal(MemberExpression? left, ConstantExpression? right, string operation, bool inOrBranch, bool caseSensitive = false)
{
if (left != null && right != null)
{
var propertyInfo = typeof(T).GetProperty(left.Member.Name);
if (propertyInfo != null)
{
bool index = propertyInfo.GetCustomAttributes(typeof(MagicIndexAttribute), false).Length == 0;
bool unique = propertyInfo.GetCustomAttributes(typeof(MagicUniqueIndexAttribute), false).Length == 0;
bool primary = propertyInfo.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length == 0;
if (index == true && unique == true && primary == true)
{
throw new InvalidOperationException($"Property '{propertyInfo.Name}' does not have the IndexDbAttribute.");
}
string? columnName = null;
if (index == false)
columnName = propertyInfo.GetPropertyColumnName<MagicIndexAttribute>();
else if (unique == false)
columnName = propertyInfo.GetPropertyColumnName<MagicUniqueIndexAttribute>();
else if (primary == false)
columnName = propertyInfo.GetPropertyColumnName<MagicPrimaryKeyAttribute>();
bool _isString = false;
JToken? valSend = null;
if (right != null && right.Value != null)
{
valSend = JToken.FromObject(right.Value);
_isString = right.Value is string;
}
var jsonCondition = new JObject
{
{ "property", columnName },
{ "operation", operation },
{ "value", valSend },
{ "isString", _isString },
{ "caseSensitive", caseSensitive }
};
if (inOrBranch)
{
var currentOrConditions = orConditions.LastOrDefault();
if (currentOrConditions == null)
{
currentOrConditions = new List<JObject>();
orConditions.Add(currentOrConditions);
}
currentOrConditions.Add(jsonCondition);
}
else
{
conditions.Add(jsonCondition);
}
}
}
}
TraverseExpression(predicate.Body);
if (conditions.Any())
{
orConditions.Add(conditions);
}
return JsonConvert.SerializeObject(orConditions, serializerSettings);
}
public class QuotaUsage
{
public long quota { get; set; }
public long usage { get; set; }
}
/// <summary>
/// Returns Mb
/// </summary>
/// <returns></returns>
public async Task<(double quota, double usage)> GetStorageEstimateAsync()
{
var storageInfo = await CallJavascriptNoTransaction<QuotaUsage>(IndexedDbFunctions.GET_STORAGE_ESTIMATE);
double quotaInMB = ConvertBytesToMegabytes(storageInfo.quota);
double usageInMB = ConvertBytesToMegabytes(storageInfo.usage);
return (quotaInMB, usageInMB);
}
private static double ConvertBytesToMegabytes(long bytes)
{
return (double)bytes / (1024 * 1024);
}
public async Task<IEnumerable<T>> GetAll<T>() where T : class
{
var trans = GenerateTransaction(null);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
IList<Dictionary<string, object>>? ListToConvert = await CallJavascript<IList<Dictionary<string, object>>>(IndexedDbFunctions.TOARRAY, trans, DbName, schemaName);
var resultList = ConvertListToRecords<T>(ListToConvert, propertyMappings);
return resultList;
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return Enumerable.Empty<T>();
}
public async Task<Guid> Delete<T>(T item, Action<BlazorDbEvent>? action = null) where T : class
{
var trans = GenerateTransaction(action);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute)));
if (primaryKeyProperty != null)
{
object? primaryKeyValue = primaryKeyProperty.GetValue(item);
var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item);
if (primaryKeyValue != null)
{
UpdateRecord<Dictionary<string, object?>> record = new UpdateRecord<Dictionary<string, object?>>()
{
Key = primaryKeyValue,
DbName = this.DbName,
StoreName = schemaName,
Record = convertedRecord
};
// Get the primary key value of the item
await CallJavascriptVoid(IndexedDbFunctions.DELETE_ITEM, trans, record);
}
else
{
throw new ArgumentException("Item being Deleted must have a key.");
}
}
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
public async Task<int> DeleteRange<TResult>(IEnumerable<TResult> items) where TResult : class
{
List<object> keys = new List<object>();
foreach (var item in items)
{
PropertyInfo? primaryKeyProperty = typeof(TResult).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute)));
if (primaryKeyProperty == null)
{
throw new InvalidOperationException("No primary key property found with PrimaryKeyDbAttribute.");
}
object? primaryKeyValue = primaryKeyProperty.GetValue(item);
if (primaryKeyValue != null)
keys.Add(primaryKeyValue);
}
string schemaName = SchemaHelper.GetSchemaName<TResult>();
var trans = GenerateTransaction(null);
var data = new { DbName = DbName, StoreName = schemaName, Keys = keys };
try
{
var deletedCount = await CallJavascript<int>(IndexedDbFunctions.BULK_DELETE, trans, data.DbName, data.StoreName, data.Keys);
return deletedCount;
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return 0;
}
/// <summary>
/// Clears all data from a Table but keeps the table
/// </summary>
/// <param name="storeName"></param>
/// <param name="action"></param>
/// <returns></returns>
public async Task<Guid> ClearTable(string storeName, Action<BlazorDbEvent>? action = null)
{
var trans = GenerateTransaction(action);
try
{
await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans, DbName, storeName);
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
public async Task<Guid> ClearTable<T>(Action<BlazorDbEvent>? action = null) where T : class
{
var trans = GenerateTransaction(action);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans, DbName, schemaName);
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
/// <summary>
/// Clears all data from a Table but keeps the table
/// Wait for response
/// </summary>
/// <param name="storeName"></param>
/// <returns></returns>
public async Task<BlazorDbEvent> ClearTableAsync(string storeName)
{
var trans = GenerateTransaction();
try
{
await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans.trans, DbName, storeName);
}
catch (JSException jse)
{
RaiseEvent(trans.trans, true, jse.Message);
}
return await trans.task;
}
[JSInvokable("BlazorDBCallback")]
public void CalledFromJS(Guid transaction, bool failed, string message)
{
if (transaction != Guid.Empty)
{
WeakReference<Action<BlazorDbEvent>>? r = null;
_transactions.TryGetValue(transaction, out r);
TaskCompletionSource<BlazorDbEvent>? t = null;
_taskTransactions.TryGetValue(transaction, out t);
if (r != null && r.TryGetTarget(out Action<BlazorDbEvent>? action))
{
action?.Invoke(new BlazorDbEvent()
{
Transaction = transaction,
Message = message,
Failed = failed
});
_transactions.Remove(transaction);
}
else if (t != null)
{
t.TrySetResult(new BlazorDbEvent()
{
Transaction = transaction,
Message = message,
Failed = failed
});
_taskTransactions.Remove(transaction);
}
else
RaiseEvent(transaction, failed, message);
}
}
//async Task<TResult> CallJavascriptNoTransaction<TResult>(string functionName, params object[] args)
//{
// return await _jsRuntime.InvokeAsync<TResult>($"{InteropPrefix}.{functionName}", args);
//}
async Task<TResult> CallJavascriptNoTransaction<TResult>(string functionName, params object[] args)
{
var mod = await GetModule(_jsRuntime);
return await mod.InvokeAsync<TResult>($"{functionName}", args);
}
private const string dynamicJsCaller = "DynamicJsCaller";
/// <summary>
///
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="functionName"></param>
/// <param name="transaction"></param>
/// <param name="timeout">in ms</param>
/// <param name="args"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public async Task<TResult> CallJS<TResult>(string functionName, double Timeout, params object[] args)
{
List<object> modifiedArgs = new List<object>(args);
modifiedArgs.Insert(0, $"{InteropPrefix}.{functionName}");
Task<JsResponse<TResult>> task = _jsRuntime.InvokeAsync<JsResponse<TResult>>(dynamicJsCaller, modifiedArgs.ToArray()).AsTask();
Task delay = Task.Delay(TimeSpan.FromMilliseconds(Timeout));
if (await Task.WhenAny(task, delay) == task)
{
JsResponse<TResult> response = await task;
if (response.Success)
return response.Data;
else
throw new ArgumentException(response.Message);
}
else
{
throw new ArgumentException("Timed out after 1 minute");
}
}
//public async Task<TResult> CallJS<TResult>(string functionName, JsSettings Settings, params object[] args)
//{
// var newArgs = GetNewArgs(Settings.Transaction, args);
// Task<JsResponse<TResult>> task = _jsRuntime.InvokeAsync<JsResponse<TResult>>($"{InteropPrefix}.{functionName}", newArgs).AsTask();
// Task delay = Task.Delay(TimeSpan.FromMilliseconds(Settings.Timeout));
// if (await Task.WhenAny(task, delay) == task)
// {
// JsResponse<TResult> response = await task;
// if (response.Success)
// return response.Data;
// else
// throw new ArgumentException(response.Message);
// }
// else
// {
// throw new ArgumentException("Timed out after 1 minute");
// }
//}
//async Task<TResult> CallJavascript<TResult>(string functionName, Guid transaction, params object[] args)
//{
// var newArgs = GetNewArgs(transaction, args);
// return await _jsRuntime.InvokeAsync<TResult>($"{InteropPrefix}.{functionName}", newArgs);
//}
//async Task CallJavascriptVoid(string functionName, Guid transaction, params object[] args)
//{
// var newArgs = GetNewArgs(transaction, args);
// await _jsRuntime.InvokeVoidAsync($"{InteropPrefix}.{functionName}", newArgs);
//}
async Task<TResult> CallJavascript<TResult>(string functionName, Guid transaction, params object[] args)
{
var mod = await GetModule(_jsRuntime);
var newArgs = GetNewArgs(transaction, args);
return await mod.InvokeAsync<TResult>($"{functionName}", newArgs);
}
async Task CallJavascriptVoid(string functionName, Guid transaction, params object[] args)
{
var mod = await GetModule(_jsRuntime);
var newArgs = GetNewArgs(transaction, args);
await mod.InvokeVoidAsync($"{functionName}", newArgs);
}
object[] GetNewArgs(Guid transaction, params object[] args)
{
var newArgs = new object[args.Length + 2];
newArgs[0] = _objReference;
newArgs[1] = transaction;
for (var i = 0; i < args.Length; i++)
newArgs[i + 2] = args[i];
return newArgs;
}
(Guid trans, Task<BlazorDbEvent> task) GenerateTransaction()
{
bool generated = false;
var transaction = Guid.Empty;
TaskCompletionSource<BlazorDbEvent> tcs = new TaskCompletionSource<BlazorDbEvent>();
do
{
transaction = Guid.NewGuid();
if (!_taskTransactions.ContainsKey(transaction))
{
generated = true;
_taskTransactions.Add(transaction, tcs);
}
} while (!generated);
return (transaction, tcs.Task);
}
Guid GenerateTransaction(Action<BlazorDbEvent>? action)
{
bool generated = false;
Guid transaction = Guid.Empty;
do
{
transaction = Guid.NewGuid();
if (!_transactions.ContainsKey(transaction))
{
generated = true;
_transactions.Add(transaction, new WeakReference<Action<BlazorDbEvent>>(action!));
}
} while (!generated);
return transaction;
}
void RaiseEvent(Guid transaction, bool failed, string message)
=> ActionCompleted?.Invoke(this, new BlazorDbEvent { Transaction = transaction, Failed = failed, Message = message });
}
}
| Magic.IndexedDb/IndexDbManager.cs | magiccodingman-Magic.IndexedDb-a279d6d | [
{
"filename": "Magic.IndexedDb/Factories/MagicDbFactory.cs",
"retrieved_chunk": " readonly IJSRuntime _jsRuntime;\n readonly IServiceProvider _serviceProvider;\n readonly IDictionary<string, IndexedDbManager> _dbs = new Dictionary<string, IndexedDbManager>();\n //private IJSObjectReference _module;\n public MagicDbFactory(IServiceProvider serviceProvider, IJSRuntime jSRuntime)\n {\n _serviceProvider = serviceProvider;\n _jsRuntime = jSRuntime;\n }\n //public async Task<IndexedDbManager> CreateAsync(DbStore dbStore)",
"score": 0.8046919107437134
},
{
"filename": "Magic.IndexedDb/Factories/IMagicDbFactory.cs",
"retrieved_chunk": "using System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public interface IMagicDbFactory\n {\n Task<IndexedDbManager> GetDbManager(string dbName);\n Task<IndexedDbManager> GetDbManager(DbStore dbStore);\n }\n}",
"score": 0.7950105667114258
},
{
"filename": "Magic.IndexedDb/Extensions/ServiceCollectionExtensions.cs",
"retrieved_chunk": " {\n public static IServiceCollection AddBlazorDB(this IServiceCollection services, Action<DbStore> options)\n {\n var dbStore = new DbStore();\n options(dbStore);\n services.AddTransient<DbStore>((_) => dbStore);\n services.TryAddSingleton<IMagicDbFactory, MagicDbFactory>();\n return services;\n }\n public static IServiceCollection AddEncryptionFactory(this IServiceCollection services)",
"score": 0.7502363920211792
},
{
"filename": "Magic.IndexedDb/Factories/MagicDbFactory.cs",
"retrieved_chunk": " //{\n // var manager = new IndexedDbManager(dbStore, _jsRuntime);\n // var importedManager = await _jsRuntime.InvokeAsync<IJSObjectReference>(\"import\", \"./_content/Magic.IndexedDb/magicDB.js\");\n // return manager;\n //}\n public async Task<IndexedDbManager> GetDbManager(string dbName)\n {\n if (!_dbs.Any())\n await BuildFromServices();\n if (_dbs.ContainsKey(dbName))",
"score": 0.7373659610748291
},
{
"filename": "Magic.IndexedDb/Factories/EncryptionFactory.cs",
"retrieved_chunk": " public class EncryptionFactory: IEncryptionFactory\n {\n readonly IJSRuntime _jsRuntime;\n readonly IndexedDbManager _indexDbManager;\n public EncryptionFactory(IJSRuntime jsRuntime, IndexedDbManager indexDbManager)\n {\n _jsRuntime = jsRuntime;\n _indexDbManager = indexDbManager;\n }\n public async Task<string> Encrypt(string data, string key)",
"score": 0.7314003705978394
}
] | csharp | BlazorDbEvent>> _taskTransactions = new Dictionary<Guid, TaskCompletionSource<BlazorDbEvent>>(); |
using HarmonyLib;
using UnityEngine;
namespace Ultrapain.Patches
{
class Virtue_Start_Patch
{
static void Postfix(Drone __instance, ref EnemyIdentifier ___eid)
{
VirtueFlag flag = __instance.gameObject.AddComponent<VirtueFlag>();
flag.virtue = __instance;
}
}
class Virtue_Death_Patch
{
static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid)
{
if(___eid.enemyType != EnemyType.Virtue)
return true;
__instance.GetComponent<VirtueFlag>().DestroyProjectiles();
return true;
}
}
class VirtueFlag : MonoBehaviour
{
public AudioSource lighningBoltSFX;
public GameObject ligtningBoltAud;
public Transform windupObj;
private EnemyIdentifier eid;
public Drone virtue;
public void Awake()
{
eid = GetComponent<EnemyIdentifier>();
ligtningBoltAud = Instantiate(Plugin.lighningBoltSFX, transform);
lighningBoltSFX = ligtningBoltAud.GetComponent<AudioSource>();
}
public void SpawnLightningBolt()
{
LightningStrikeExplosive lightningStrikeExplosive = Instantiate(Plugin.lightningStrikeExplosiveSetup.gameObject, windupObj.transform.position, Quaternion.identity).GetComponent<LightningStrikeExplosive>();
lightningStrikeExplosive.safeForPlayer = false;
lightningStrikeExplosive.damageMultiplier = eid.totalDamageModifier * ((virtue.enraged)? ConfigManager.virtueEnragedLightningDamage.value : ConfigManager.virtueNormalLightningDamage.value);
if(windupObj != null)
Destroy(windupObj.gameObject);
}
public void DestroyProjectiles()
{
CancelInvoke("SpawnLightningBolt");
if (windupObj != null)
Destroy(windupObj.gameObject);
}
}
class Virtue_SpawnInsignia_Patch
{
static bool Prefix(Drone __instance, ref | EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, ref int ___usedAttacks)
{ |
if (___eid.enemyType != EnemyType.Virtue)
return true;
GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, int damage, float lastMultiplier)
{
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity);
VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>();
component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer();
component.parentDrone = __instance;
component.hadParent = true;
component.damage = damage;
component.explosionLength *= lastMultiplier;
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
if (__instance.enraged)
{
component.predictive = true;
}
/*if (___difficulty == 1)
{
component.windUpSpeedMultiplier = 0.875f;
}
else if (___difficulty == 0)
{
component.windUpSpeedMultiplier = 0.75f;
}*/
if (MonoSingleton<PlayerTracker>.Instance.playerType == PlayerType.Platformer)
{
gameObject.transform.localScale *= 0.75f;
component.windUpSpeedMultiplier *= 0.875f;
}
component.windUpSpeedMultiplier *= ___eid.totalSpeedModifier;
component.damage = Mathf.RoundToInt((float)component.damage * ___eid.totalDamageModifier);
return gameObject;
}
if (__instance.enraged && !ConfigManager.virtueTweakEnragedAttackToggle.value)
return true;
if (!__instance.enraged && !ConfigManager.virtueTweakNormalAttackToggle.value)
return true;
bool insignia = (__instance.enraged) ? ConfigManager.virtueEnragedAttackType.value == ConfigManager.VirtueAttackType.Insignia
: ConfigManager.virtueNormalAttackType.value == ConfigManager.VirtueAttackType.Insignia;
if (insignia)
{
bool xAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXtoggle.value : ConfigManager.virtueNormalInsigniaXtoggle.value;
bool yAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYtoggle.value : ConfigManager.virtueNormalInsigniaYtoggle.value;
bool zAxis = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZtoggle.value : ConfigManager.virtueNormalInsigniaZtoggle.value;
if (xAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXdamage.value : ConfigManager.virtueNormalInsigniaXdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaXsize.value : ConfigManager.virtueNormalInsigniaXsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
obj.transform.Rotate(new Vector3(90f, 0, 0));
}
if (yAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYdamage.value : ConfigManager.virtueNormalInsigniaYdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaYsize.value : ConfigManager.virtueNormalInsigniaYsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
}
if (zAxis)
{
GameObject obj = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZdamage.value : ConfigManager.virtueNormalInsigniaZdamage.value,
(__instance.enraged) ? ConfigManager.virtueEnragedInsigniaLastMulti.value : ConfigManager.virtueNormalInsigniaLastMulti.value);
float size = (__instance.enraged) ? ConfigManager.virtueEnragedInsigniaZsize.value : ConfigManager.virtueNormalInsigniaZsize.value;
obj.transform.localScale = new Vector3(size, obj.transform.localScale.y, size);
obj.transform.Rotate(new Vector3(0, 0, 90f));
}
}
else
{
Vector3 predictedPos;
if (___difficulty <= 1)
predictedPos = MonoSingleton<PlayerTracker>.Instance.GetPlayer().position;
else
{
Vector3 vector = new Vector3(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().x, 0f, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().z);
predictedPos = MonoSingleton<PlayerTracker>.Instance.GetPlayer().position + vector.normalized * Mathf.Min(vector.magnitude, 5.0f);
}
GameObject currentWindup = GameObject.Instantiate<GameObject>(Plugin.lighningStrikeWindup.gameObject, predictedPos, Quaternion.identity);
foreach (Follow follow in currentWindup.GetComponents<Follow>())
{
if (follow.speed != 0f)
{
if (___difficulty >= 2)
{
follow.speed *= (float)___difficulty;
}
else if (___difficulty == 1)
{
follow.speed /= 2f;
}
else
{
follow.enabled = false;
}
follow.speed *= ___eid.totalSpeedModifier;
}
}
VirtueFlag flag = __instance.GetComponent<VirtueFlag>();
flag.lighningBoltSFX.Play();
flag.windupObj = currentWindup.transform;
flag.Invoke("SpawnLightningBolt", (__instance.enraged)? ConfigManager.virtueEnragedLightningDelay.value : ConfigManager.virtueNormalLightningDelay.value);
}
___usedAttacks += 1;
if(___usedAttacks == 3)
{
__instance.Invoke("Enrage", 3f / ___eid.totalSpeedModifier);
}
return false;
}
/*static void Postfix(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, bool __state)
{
if (!__state)
return;
GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target)
{
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity);
VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>();
component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer();
component.parentDrone = __instance;
component.hadParent = true;
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
if (__instance.enraged)
{
component.predictive = true;
}
if (___difficulty == 1)
{
component.windUpSpeedMultiplier = 0.875f;
}
else if (___difficulty == 0)
{
component.windUpSpeedMultiplier = 0.75f;
}
if (MonoSingleton<PlayerTracker>.Instance.playerType == PlayerType.Platformer)
{
gameObject.transform.localScale *= 0.75f;
component.windUpSpeedMultiplier *= 0.875f;
}
component.windUpSpeedMultiplier *= ___eid.totalSpeedModifier;
component.damage = Mathf.RoundToInt((float)component.damage * ___eid.totalDamageModifier);
return gameObject;
}
GameObject xAxisInsignia = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target);
xAxisInsignia.transform.Rotate(new Vector3(90, 0, 0));
xAxisInsignia.transform.localScale = new Vector3(xAxisInsignia.transform.localScale.x * horizontalInsigniaScale, xAxisInsignia.transform.localScale.y, xAxisInsignia.transform.localScale.z * horizontalInsigniaScale);
GameObject zAxisInsignia = createInsignia(__instance, ref ___eid, ref ___difficulty, ref ___target);
zAxisInsignia.transform.Rotate(new Vector3(0, 0, 90));
zAxisInsignia.transform.localScale = new Vector3(zAxisInsignia.transform.localScale.x * horizontalInsigniaScale, zAxisInsignia.transform.localScale.y, zAxisInsignia.transform.localScale.z * horizontalInsigniaScale);
}*/
}
}
| Ultrapain/Patches/Virtue.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Mindflayer.cs",
"retrieved_chunk": " componentInChildren.sourceWeapon = __instance.gameObject;\n counter.shotsLeft -= 1;\n __instance.Invoke(\"ShootProjectiles\", ConfigManager.mindflayerShootDelay.value / ___eid.totalSpeedModifier);\n return false;\n }\n }\n class EnemyIdentifier_DeliverDamage_MF\n {\n static bool Prefix(EnemyIdentifier __instance, ref float __3, GameObject __6)\n {",
"score": 0.8782979249954224
},
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " public static int projectileDamage = 10;\n public static int explosionDamage = 20;\n public static float coreSpeed = 110f;\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref Animator ___anim, ref GameObject ___currentProjectile\n , ref NavMeshAgent ___nma, ref Zombie ___zmb)\n {\n if (___eid.enemyType != EnemyType.Stray)\n return;\n StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>();\n if (flag == null)",
"score": 0.8774985074996948
},
{
"filename": "Ultrapain/Patches/Turret.cs",
"retrieved_chunk": " static void Postfix(Turret __instance)\n {\n __instance.gameObject.AddComponent<TurretFlag>();\n }\n }\n class TurretShoot\n {\n static bool Prefix(Turret __instance, ref EnemyIdentifier ___eid, ref RevolverBeam ___beam, ref Transform ___shootPoint,\n ref float ___aimTime, ref float ___maxAimTime, ref float ___nextBeepTime, ref float ___flashTime)\n {",
"score": 0.8714028000831604
},
{
"filename": "Ultrapain/Patches/Solider.cs",
"retrieved_chunk": " /*___projectile = Plugin.soliderBullet;\n if (Plugin.decorativeProjectile2.gameObject != null)\n ___decProjectile = Plugin.decorativeProjectile2.gameObject;*/\n __instance.gameObject.AddComponent<SoliderShootCounter>();\n }\n }\n class Solider_SpawnProjectile_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP)\n {",
"score": 0.8708095550537109
},
{
"filename": "Ultrapain/Patches/Drone.cs",
"retrieved_chunk": " {\n static void Postfix(Drone __instance, ref EnemyIdentifier ___eid)\n {\n if (___eid.enemyType != EnemyType.Drone)\n return;\n __instance.gameObject.AddComponent<DroneFlag>();\n }\n }\n class Drone_PlaySound_Patch\n {",
"score": 0.862517774105072
}
] | csharp | EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, ref int ___usedAttacks)
{ |
using HarmonyLib;
using UnityEngine;
namespace Ultrapain.Patches
{
public class HideousMassProjectile : MonoBehaviour
{
public float damageBuf = 1f;
public float speedBuf = 1f;
}
public class Projectile_Explode_Patch
{
static void Postfix( | Projectile __instance)
{ |
HideousMassProjectile flag = __instance.gameObject.GetComponent<HideousMassProjectile>();
if (flag == null)
return;
GameObject createInsignia(float size, int damage)
{
GameObject insignia = GameObject.Instantiate(Plugin.virtueInsignia, __instance.transform.position, Quaternion.identity);
insignia.transform.localScale = new Vector3(size, 1f, size);
VirtueInsignia comp = insignia.GetComponent<VirtueInsignia>();
comp.windUpSpeedMultiplier = ConfigManager.hideousMassInsigniaSpeed.value * flag.speedBuf;
comp.damage = (int)(damage * flag.damageBuf);
comp.predictive = false;
comp.hadParent = false;
comp.noTracking = true;
return insignia;
}
if (ConfigManager.hideousMassInsigniaXtoggle.value)
{
GameObject insignia = createInsignia(ConfigManager.hideousMassInsigniaXsize.value, ConfigManager.hideousMassInsigniaXdamage.value);
insignia.transform.Rotate(new Vector3(0, 0, 90f));
}
if (ConfigManager.hideousMassInsigniaYtoggle.value)
{
GameObject insignia = createInsignia(ConfigManager.hideousMassInsigniaYsize.value, ConfigManager.hideousMassInsigniaYdamage.value);
}
if (ConfigManager.hideousMassInsigniaZtoggle.value)
{
GameObject insignia = createInsignia(ConfigManager.hideousMassInsigniaZsize.value, ConfigManager.hideousMassInsigniaZdamage.value);
insignia.transform.Rotate(new Vector3(90f, 0, 0));
}
}
}
public class HideousMassHoming
{
static bool Prefix(Mass __instance, EnemyIdentifier ___eid)
{
__instance.explosiveProjectile = GameObject.Instantiate(Plugin.hideousMassProjectile);
HideousMassProjectile flag = __instance.explosiveProjectile.AddComponent<HideousMassProjectile>();
flag.damageBuf = ___eid.totalDamageModifier;
flag.speedBuf = ___eid.totalSpeedModifier;
return true;
}
static void Postfix(Mass __instance)
{
GameObject.Destroy(__instance.explosiveProjectile);
__instance.explosiveProjectile = Plugin.hideousMassProjectile;
}
}
}
| Ultrapain/Patches/HideousMass.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " /*__instance.projectile = Plugin.homingProjectile;\n __instance.decProjectile = Plugin.decorativeProjectile2;*/\n }\n }\n public class ZombieProjectile_ThrowProjectile_Patch\n {\n public static float normalizedTime = 0f;\n public static float animSpeed = 20f;\n public static float projectileSpeed = 75;\n public static float turnSpeedMultiplier = 0.45f;",
"score": 0.897728443145752
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " }\n class OrbitalExplosionInfo : MonoBehaviour\n {\n public bool active = true;\n public string id;\n public int points;\n }\n class Grenade_Explode\n {\n class StateInfo",
"score": 0.8963792324066162
},
{
"filename": "Ultrapain/Patches/CommonComponents.cs",
"retrieved_chunk": " public float superSize = 1f;\n public float superSpeed = 1f;\n public float superDamage = 1f;\n public int superPlayerDamageOverride = -1;\n struct StateInfo\n {\n public GameObject tempHarmless;\n public GameObject tempNormal;\n public GameObject tempSuper;\n public StateInfo()",
"score": 0.8961182832717896
},
{
"filename": "Ultrapain/Patches/V2Common.cs",
"retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;",
"score": 0.895707368850708
},
{
"filename": "Ultrapain/Patches/Mindflayer.cs",
"retrieved_chunk": " //___eid.SpeedBuff();\n }\n }\n class Mindflayer_ShootProjectiles_Patch\n {\n public static float maxProjDistance = 5;\n public static float initialProjectileDistance = -1f;\n public static float distancePerProjShot = 0.2f;\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)\n {",
"score": 0.8934637308120728
}
] | csharp | Projectile __instance)
{ |
using System.IO;
using UnityEditor;
using UnityEngine;
using VRC.PackageManagement.PackageMaker;
public class PackageMakerWindowData : ScriptableObject
{
public static string defaultAssetPath = Path.Combine("Assets", "PackageMakerWindowData.asset");
public string targetAssetFolder;
public string packageID;
public | PackageMakerWindow.VRCPackageEnum relatedPackage; |
public static PackageMakerWindowData GetOrCreate()
{
var existingData = AssetDatabase.AssetPathToGUID(defaultAssetPath);
if (string.IsNullOrWhiteSpace(existingData))
{
return Create();
}
else
{
var saveData = AssetDatabase.LoadAssetAtPath<PackageMakerWindowData>(defaultAssetPath);
if (saveData == null)
{
Debug.LogError($"Could not load saved data but the save file exists. Resetting.");
return Create();
}
return saveData;
}
}
public static PackageMakerWindowData Create()
{
var saveData = CreateInstance<PackageMakerWindowData>();
AssetDatabase.CreateAsset(saveData, defaultAssetPath);
AssetDatabase.SaveAssets();
return saveData;
}
public void Save()
{
AssetDatabase.SaveAssets();
}
}
| Packages/com.vrchat.core.vpm-resolver/Editor/PackageMaker/PackageMakerWindowData.cs | koyashiro-generic-data-container-1aef372 | [
{
"filename": "Packages/com.vrchat.core.vpm-resolver/Editor/PackageMaker/PackageMakerWindow.cs",
"retrieved_chunk": "using UnityEngine;\nusing UnityEngine.UIElements;\nusing VRC.PackageManagement.Core.Types.Packages;\nusing YamlDotNet.Serialization.NodeTypeResolvers;\nnamespace VRC.PackageManagement.PackageMaker\n{\n public class PackageMakerWindow : EditorWindow\n {\n // VisualElements\n private VisualElement _rootView;",
"score": 0.8491805195808411
},
{
"filename": "Packages/com.vrchat.core.vpm-resolver/Editor/Resolver/ResolverWindow.cs",
"retrieved_chunk": "using Version = VRC.PackageManagement.Core.Types.VPMVersion.Version;\nnamespace VRC.PackageManagement.Resolver\n{\n public class ResolverWindow : EditorWindow\n {\n // VisualElements\n private static VisualElement _rootView;\n private static Button _refreshButton;\n private static Button _createButton;\n private static Button _resolveButton;",
"score": 0.8041022419929504
},
{
"filename": "Packages/com.vrchat.core.vpm-resolver/Editor/Resolver/Resolver.cs",
"retrieved_chunk": "using VRC.PackageManagement.Core;\nusing VRC.PackageManagement.Core.Types;\nusing VRC.PackageManagement.Core.Types.Packages;\nusing Version = VRC.PackageManagement.Core.Types.VPMVersion.Version;\nnamespace VRC.PackageManagement.Resolver\n{\n [InitializeOnLoad]\n public class Resolver\n {\n private const string _projectLoadedKey = \"PROJECT_LOADED\";",
"score": 0.7964259386062622
},
{
"filename": "Packages/com.vrchat.core.vpm-resolver/Editor/PackageMaker/PackageMakerWindow.cs",
"retrieved_chunk": " \t\tprivate TextField _targetAssetFolderField;\n private TextField _packageIDField;\n private Button _actionButton;\n private EnumField _targetVRCPackageField;\n private static string _projectDir;\n private PackageMakerWindowData _windowData;\n private void LoadDataFromSave()\n {\n if (!string.IsNullOrWhiteSpace(_windowData.targetAssetFolder))\n {",
"score": 0.7707488536834717
},
{
"filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionary.cs",
"retrieved_chunk": "using UnityEngine;\nusing VRC.SDK3.Data;\nusing UdonSharp;\nnamespace Koyashiro.GenericDataContainer\n{\n [AddComponentMenu(\"\")]\n public class DataDictionary<TKey, TValue> : UdonSharpBehaviour\n {\n public static DataDictionary<TKey, TValue> New()\n {",
"score": 0.7680927515029907
}
] | csharp | PackageMakerWindow.VRCPackageEnum relatedPackage; |
using Moadian.Dto;
using Moadian.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Moadian.API
{
public class Api
{
private TokenModel? token = null;
private readonly string username;
private readonly HttpClientService httpClient;
public Api(string username, HttpClientService httpClient)
{
this.username = username;
this.httpClient = httpClient;
}
public async Task<TokenModel> GetToken()
{
var getTokenDto = new GetTokenDto() { username = this.username };
var packet = new Packet(Constants.PacketType.GET_TOKEN, getTokenDto);
packet.retry = false;
packet.fiscalId = this.username;
var headers = GetEssentialHeaders();
var response = await this.httpClient.SendPacket("req/api/self-tsp/sync/GET_TOKEN", packet, headers);
return null;
//var tokenData = response["result"]["data"];
//return new TokenModel(tokenData["token"], tokenData["expiresIn"]);
}
public async Task<dynamic> InquiryByReferenceNumberAsync(string referenceNumber)
{
var inquiryByReferenceNumberDto = new InquiryByReferenceNumberDto();
inquiryByReferenceNumberDto.SetReferenceNumber(referenceNumber);
var packet = new Packet(Constants.PacketType.PACKET_TYPE_INQUIRY_BY_REFERENCE_NUMBER, inquiryByReferenceNumberDto);
packet.retry = false;
packet.fiscalId = this.username;
var headers = GetEssentialHeaders();
headers["Authorization"] = "Bearer " + this.token?.Token;
var path = "req/api/self-tsp/sync/" + Constants.PacketType.PACKET_TYPE_INQUIRY_BY_REFERENCE_NUMBER;
return await this.httpClient.SendPacket(path, packet, headers);
}
public async Task<dynamic> GetEconomicCodeInformationAsync(string taxID)
{
RequireToken();
var packet = new Packet(Constants.PacketType.GET_ECONOMIC_CODE_INFORMATION, JsonConvert.SerializeObject(new { economicCode = taxID }));
packet.retry = false;
packet.fiscalId = this.username;
var headers = GetEssentialHeaders();
headers["Authorization"] = "Bearer " + this.token?.Token;
var path = "req/api/self-tsp/sync/" + Constants.PacketType.GET_ECONOMIC_CODE_INFORMATION;
return await this.httpClient.SendPacket(path, packet, headers);
}
public async Task<dynamic> SendInvoicesAsync(List<object> invoiceDtos)
{
var packets = new List<Packet>();
foreach (var invoiceDto in invoiceDtos)
{
var packet = new Packet(Constants.PacketType.INVOICE_V01, invoiceDto);
packet.uid = "AAA";
packets.Add(packet);
}
var headers = GetEssentialHeaders();
headers[Constants.TransferConstants.AUTHORIZATION_HEADER] = this.token?.Token;
dynamic res = null;
try
{
res = await this.httpClient.SendPackets("req/api/self-tsp/async/normal-enqueue", packets, headers, true, true);
}
catch (Exception e)
{
}
return res?.GetBody().GetContents();
}
public async Task<dynamic> GetFiscalInfoAsync()
{
RequireToken();
var packet = new Packet(Constants.PacketType.GET_FISCAL_INFORMATION, this.username);
var headers = GetEssentialHeaders();
headers["Authorization"] = "Bearer " + this.token?.Token;
return await this.httpClient.SendPacket("req/api/self-tsp/sync/GET_FISCAL_INFORMATION", packet, headers);
}
public Api SetToken( | TokenModel? token)
{ |
this.token = token;
return this;
}
public dynamic InquiryByReferenceNumber(string referenceNumber)
{
var inquiryByReferenceNumberDto = new InquiryByReferenceNumberDto();
inquiryByReferenceNumberDto.SetReferenceNumber(referenceNumber);
var packet = new Packet(Constants.PacketType.PACKET_TYPE_INQUIRY_BY_REFERENCE_NUMBER, inquiryByReferenceNumberDto);
packet.retry = false;
packet.fiscalId = this.username;
var headers = GetEssentialHeaders();
headers["Authorization"] = "Bearer " + this.token.Token;
var path = "req/api/self-tsp/sync/" + Constants.PacketType.PACKET_TYPE_INQUIRY_BY_REFERENCE_NUMBER;
return this.httpClient.SendPacket(path, packet, headers);
}
public dynamic GetEconomicCodeInformation(string taxId)
{
RequireToken();
var packet = new Packet(Constants.PacketType.GET_ECONOMIC_CODE_INFORMATION, JsonConvert.SerializeObject(new { EconomicCode = taxId }));
packet.retry = false;
packet.fiscalId = this.username;
var headers = GetEssentialHeaders();
headers["Authorization"] = "Bearer " + this.token.Token;
var path = "req/api/self-tsp/sync/" + Constants.PacketType.GET_ECONOMIC_CODE_INFORMATION;
return this.httpClient.SendPacket(path, packet, headers);
}
public dynamic SendInvoices(List<InvoiceDto> invoiceDtos)
{
var packets = new List<Packet>();
foreach (var invoiceDto in invoiceDtos)
{
var packet = new Packet(Constants.PacketType.INVOICE_V01, invoiceDto);
packet.uid = "AAA";
packets.Add(packet);
}
var headers = GetEssentialHeaders();
headers[Constants.TransferConstants.AUTHORIZATION_HEADER] = this.token.Token;
dynamic res = null;
try
{
res = this.httpClient.SendPackets(
"req/api/self-tsp/async/normal-enqueue",
packets,
headers,
true,
true
);
}
catch (Exception e)
{
}
return res?.GetBody()?.GetContents();
}
public dynamic GetFiscalInfo()
{
RequireToken();
var packet = new Packet(Constants.PacketType.GET_FISCAL_INFORMATION, this.username);
var headers = GetEssentialHeaders();
headers["Authorization"] = "Bearer " + this.token.Token;
return this.httpClient.SendPacket("req/api/self-tsp/sync/GET_FISCAL_INFORMATION", packet, headers);
}
private Dictionary<string, string> GetEssentialHeaders()
{
return new Dictionary<string, string>
{
{ Constants.TransferConstants.TIMESTAMP_HEADER, DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString() },
{ Constants.TransferConstants.REQUEST_TRACE_ID_HEADER, Guid.NewGuid().ToString() }
};
}
private async void RequireToken()
{
if (this.token == null || this.token.IsExpired())
{
this.token = await this.GetToken();
}
}
}
}
| API/API.cs | Torabi-srh-Moadian-482c806 | [
{
"filename": "Moadian.cs",
"retrieved_chunk": " throw new ArgumentException(\"Set token before sending invoice!\");\n }\n var headers = new Dictionary<string, string>\n {\n { \"Authorization\", \"Bearer \" + this.token.Token },\n { \"requestTraceId\", Guid.NewGuid().ToString() },\n { \"timestamp\", DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString() },\n };\n var path = \"req/api/self-tsp/async/normal-enqueue\";\n var response = await httpClient.SendPackets(path, new List<Packet>() { packet }, headers, true, true);",
"score": 0.7936124801635742
},
{
"filename": "Services/HttpClientService.cs",
"retrieved_chunk": " {\n BaseAddress = new Uri(baseUri)\n };\n client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n this.signatureService = signatureService;\n this.encryptionService = encryptionService;\n }\n public async Task<object?> SendPacket(string path, Packet packet, Dictionary<string, string> headers)\n {\n var cloneHeader = new Dictionary<string, string>(headers);",
"score": 0.7471011877059937
},
{
"filename": "Services/HttpClientService.cs",
"retrieved_chunk": " packet.data = (Encoding.UTF8.GetBytes(encryptionService.Encrypt(JsonConvert.SerializeObject(packet.data is string ? packet.data : ((PacketDataInterface)packet.data)?.ToArray()), hex2bin(aesHex), hex2bin(iv))));\n }\n return packets;\n }\n private async Task<HttpResponseMessage> Post(string path, string content, Dictionary<string, string> headers = null)\n {\n var request = new HttpRequestMessage(HttpMethod.Post, path);\n request.Content = new StringContent(content, Encoding.UTF8, \"application/json\");\n if (headers != null)\n {",
"score": 0.7190343141555786
},
{
"filename": "Moadian.cs",
"retrieved_chunk": " public async Task<dynamic> GetEconomicCodeInformation(string taxID)\n {\n var api = new Api(this.Username, httpClient);\n api.SetToken(this.token);\n var response = await api.GetEconomicCodeInformation(taxID);\n return response;\n }\n public object GetFiscalInfo()\n {\n var api = new Api(this.username, httpClient);",
"score": 0.718726634979248
},
{
"filename": "Services/HttpClientService.cs",
"retrieved_chunk": " return await Post(path, JsonConvert.SerializeObject(content), headers);\n }\n private void SignPacket(Packet packet)\n {\n var normalized = Normalizer.NormalizeArray(packet.data is string ? null : ((PacketDataInterface)packet.data)?.ToArray());\n var signature = signatureService.Sign(normalized);\n packet.dataSignature = signature;\n // TODO: Not sure?\n // packet.SetSignatureKeyId(signatureService.GetKeyId());\n }",
"score": 0.6949940919876099
}
] | csharp | TokenModel? token)
{ |
using ABI.CCK.Scripts;
using NAK.AASEmulator.Runtime.SubSystems;
using System.Collections.Generic;
using UnityEngine;
using static ABI.CCK.Scripts.CVRAdvancedSettingsEntry;
namespace NAK.AASEmulator.Runtime
{
[AddComponentMenu("")]
public class AASMenu : EditorOnlyMonoBehaviour
{
#region Static Initialization
[RuntimeInitializeOnLoadMethod]
private static void Initialize()
{
AASEmulator.runtimeInitializedDelegate = runtime =>
{
if (AASEmulator.Instance != null && !AASEmulator.Instance.EmulateAASMenu)
return;
AASMenu menu = runtime.gameObject.AddComponent<AASMenu>();
menu.isInitializedExternally = true;
menu.runtime = runtime;
AASEmulator.addTopComponentDelegate?.Invoke(menu);
};
}
#endregion Static Initialization
#region Variables
public List<AASMenuEntry> entries = new List<AASMenuEntry>();
public | AnimatorManager AnimatorManager => runtime.AnimatorManager; |
private AASEmulatorRuntime runtime;
#endregion Variables
#region Menu Setup
private void Start() => SetupAASMenus();
private void SetupAASMenus()
{
entries.Clear();
if (runtime == null)
{
SimpleLogger.LogError("Unable to setup AAS Menus: AASEmulatorRuntime is missing", this);
return;
}
if (runtime.m_avatar == null)
{
SimpleLogger.LogError("Unable to setup AAS Menus: CVRAvatar is missing", this);
return;
}
if (runtime.m_avatar.avatarSettings?.settings == null)
{
SimpleLogger.LogError("Unable to setup AAS Menus: AvatarAdvancedSettings is missing", this);
return;
}
var avatarSettings = runtime.m_avatar.avatarSettings.settings;
foreach (CVRAdvancedSettingsEntry setting in avatarSettings)
{
string[] postfixes;
switch (setting.type)
{
case SettingsType.Joystick2D:
case SettingsType.InputVector2:
postfixes = new[] { "-x", "-y" };
break;
case SettingsType.Joystick3D:
case SettingsType.InputVector3:
postfixes = new[] { "-x", "-y", "-z" };
break;
case SettingsType.MaterialColor:
postfixes = new[] { "-r", "-g", "-b" };
break;
case SettingsType.GameObjectDropdown:
case SettingsType.GameObjectToggle:
case SettingsType.Slider:
case SettingsType.InputSingle:
default:
postfixes = new[] { "" };
break;
}
AASMenuEntry menuEntry = new AASMenuEntry
{
menuName = setting.name,
machineName = setting.machineName,
settingType = setting.type,
};
if (setting.setting is CVRAdvancesAvatarSettingGameObjectDropdown dropdown)
menuEntry.menuOptions = dropdown.getOptionsList();
for (int i = 0; i < postfixes.Length; i++)
{
if (AnimatorManager.Parameters.TryGetValue(setting.machineName + postfixes[i],
out AnimatorManager.BaseParam param))
{
float value;
switch (param)
{
case AnimatorManager.FloatParam floatParam:
value = floatParam.defaultValue;
break;
case AnimatorManager.IntParam intParam:
value = intParam.defaultValue;
break;
case AnimatorManager.BoolParam boolParam:
value = boolParam.defaultValue ? 1f : 0f;
break;
default:
value = 0f;
break;
}
switch (i)
{
case 0:
menuEntry.valueX = value;
break;
case 1:
menuEntry.valueY = value;
break;
case 2:
menuEntry.valueZ = value;
break;
}
}
}
entries.Add(menuEntry);
}
SimpleLogger.Log($"Successfully created {entries.Count} menu entries for {runtime.m_avatar.name}!", this);
}
#endregion Menu Setup
#region Menu Entry Class
public class AASMenuEntry
{
public string menuName;
public string machineName;
public SettingsType settingType;
public float valueX, valueY, valueZ;
public string[] menuOptions;
}
#endregion Menu Entry Class
}
} | Runtime/Scripts/AASMenu.cs | NotAKidOnSteam-AASEmulator-aacd289 | [
{
"filename": "Runtime/Scripts/AASEmulator.cs",
"retrieved_chunk": " public delegate void AddTopComponent(Component component);\n public static AddTopComponent addTopComponentDelegate;\n public delegate void RuntimeInitialized(AASEmulatorRuntime runtime);\n public static RuntimeInitialized runtimeInitializedDelegate;\n #endregion Support Delegates\n public static AASEmulator Instance;\n private readonly List<AASEmulatorRuntime> m_runtimes = new List<AASEmulatorRuntime>();\n private readonly HashSet<CVRAvatar> m_scannedAvatars = new HashSet<CVRAvatar>();\n public bool OnlyInitializeOnSelect = false;\n public bool EmulateAASMenu = false;",
"score": 0.8279843926429749
},
{
"filename": "Runtime/Scripts/SubSystems/AnimatorManager.cs",
"retrieved_chunk": " : base(name, nameHash, isLocal, isControlledByCurve)\n {\n this.value = value;\n this.defaultValue = value;\n }\n }\n #endregion Parameter Definitions\n #region Animator Info\n public Animator animator;\n public readonly Dictionary<string, CoreParam> CoreParameters = new Dictionary<string, CoreParam>();",
"score": 0.8015743494033813
},
{
"filename": "Runtime/Scripts/Helpers/EditorOnlyMonoBehaviour.cs",
"retrieved_chunk": "using UnityEngine;\nnamespace NAK.AASEmulator.Runtime\n{\n [AddComponentMenu(\"\")] // Hide from Inspector search\n public class EditorOnlyMonoBehaviour : MonoBehaviour\n {\n [HideInInspector]\n public bool isInitializedExternally = false;\n // Created via Inspector in Edit Mode\n internal virtual void Reset() => SetHideFlags();",
"score": 0.7950087785720825
},
{
"filename": "Editor/AASMenuEditor.cs",
"retrieved_chunk": " {\n #region Variables\n private AASMenu _targetScript;\n #endregion\n #region Unity / GUI Methods\n private void OnEnable()\n {\n OnRequestRepaint -= Repaint;\n OnRequestRepaint += Repaint;\n _targetScript = (AASMenu)target;",
"score": 0.7860966324806213
},
{
"filename": "Runtime/Scripts/AASEmulator.cs",
"retrieved_chunk": " runtime.isInitializedExternally = true;\n m_runtimes.Add(runtime);\n }\n m_scannedAvatars.Add(avatar);\n }\n if (newAvatars.Count > 0)\n SimpleLogger.Log(\"Setting up AASEmulator on \" + newAvatars.Count + \" new avatars.\", gameObject);\n }\n private void OnSceneLoaded(Scene scene, LoadSceneMode mode) => ScanForAvatars(scene);\n #endregion Private Methods",
"score": 0.7758572697639465
}
] | csharp | AnimatorManager AnimatorManager => runtime.AnimatorManager; |
/*
Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox')
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Kingdox.UniFlux
{
///<summary>
/// static class that ensure to handle the FluxAttribute
///</summary>
internal static class MonoFluxExtension
{
internal static readonly BindingFlags m_bindingflag_all = (BindingFlags)(-1);
//
internal static readonly Type m_type_monoflux = typeof(MonoFlux);
//
internal static readonly Type m_type_flux = typeof(Core.Internal.Flux<>);
internal static readonly Type m_type_flux_delegate = typeof(Action);
internal static readonly string m_type_flux_method = nameof(Core.Internal.Flux<object>.Store);
//
internal static readonly Type m_type_fluxparam = typeof(Core.Internal.FluxParam<,>);
internal static readonly Type m_type_fluxparam_delegate = typeof(Action<>);
internal static readonly string m_type_fluxparam_method = nameof(Core.Internal.FluxParam<object,object>.Store);
//
internal static readonly Type m_type_fluxreturn = typeof(Core.Internal.FluxReturn<,>);
internal static readonly Type m_type_fluxreturn_delegate = typeof(Func<>);
internal static readonly string m_type_fluxreturn_method = nameof(Core.Internal.FluxReturn<object,object>.Store);
//
internal static readonly Type m_type_fluxparamreturn = typeof(Core.Internal.FluxParamReturn<,,>);
internal static readonly Type m_type_fluxparamreturn_delegate = typeof(Func<,>);
internal static readonly string m_type_fluxparamreturn_method = nameof(Core.Internal.FluxParamReturn<object,object,object>.Store);
//
///<summary>
/// typeof(void)
///</summary>
internal static readonly Type m_type_void = typeof(void);
///<summary>
/// Dictionary to cache each MonoFlux instance's methods
///</summary>
internal static readonly Dictionary<MonoFlux, List<MethodInfo>> m_monofluxes = new Dictionary<MonoFlux, List<MethodInfo>>();
///<summary>
/// Dictionary to cache the FluxAttribute of each MethodInfo
///</summary>
internal static readonly Dictionary<MethodInfo, FluxAttribute> m_methods = new Dictionary<MethodInfo, FluxAttribute>();
///<summary>
/// Allows subscribe methods using `FluxAttribute` by reflection
/// ~ where magic happens ~
///</summary>
internal static void Subscribe(this | MonoFlux monoflux, in bool condition)
{ |
if (!m_monofluxes.ContainsKey(monoflux))
{
m_monofluxes.Add(
monoflux,
monoflux.gameObject.GetComponent(m_type_monoflux).GetType().GetMethods(m_bindingflag_all).Where(method =>
{
if(System.Attribute.GetCustomAttributes(method).FirstOrDefault((_att) => _att is FluxAttribute) is FluxAttribute _attribute)
{
if(!m_methods.ContainsKey(method)) m_methods.Add(method, _attribute); // ADD <Method, Attribute>!
return true;
}
else return false;
}).ToList()
);
}
//
List<MethodInfo> methods = m_monofluxes[monoflux];
//
for (int i = 0; i < methods.Count; i++)
{
var _Parameters = methods[i].GetParameters();
#if UNITY_EDITOR
if(_Parameters.Length > 1) // Auth Params is 0 or 1
{
throw new System.Exception($"Error '{methods[i].Name}' : Theres more than one parameter, please set 1 or 0 parameter. (if you need to add more than 1 argument use Tuples or create a struct, record o class...)");
}
#endif
switch ((_Parameters.Length.Equals(1), !methods[i].ReturnType.Equals(m_type_void)))
{
case (false, false): // Flux
m_type_flux
.MakeGenericType(m_methods[methods[i]].key.GetType())
.GetMethod(m_type_flux_method, m_bindingflag_all)
.Invoke( null, new object[]{ m_methods[methods[i]].key, methods[i].CreateDelegate(m_type_flux_delegate, monoflux), condition})
;
break;
case (true, false): // FluxParam
m_type_fluxparam
.MakeGenericType(m_methods[methods[i]].key.GetType(), _Parameters[0].ParameterType)
.GetMethod(m_type_fluxparam_method, m_bindingflag_all)
.Invoke( null, new object[]{ m_methods[methods[i]].key, methods[i].CreateDelegate(m_type_fluxparam_delegate.MakeGenericType(_Parameters[0].ParameterType), monoflux), condition})
;
break;
case (false, true): //FluxReturn
m_type_fluxreturn
.MakeGenericType(m_methods[methods[i]].key.GetType(), methods[i].ReturnType)
.GetMethod(m_type_fluxreturn_method, m_bindingflag_all)
.Invoke( null, new object[]{ m_methods[methods[i]].key, methods[i].CreateDelegate(m_type_fluxreturn_delegate.MakeGenericType(methods[i].ReturnType), monoflux), condition})
;
break;
case (true, true): //FluxParamReturn
m_type_fluxparamreturn
.MakeGenericType(m_methods[methods[i]].key.GetType(), _Parameters[0].ParameterType, methods[i].ReturnType)
.GetMethod(m_type_fluxparamreturn_method, m_bindingflag_all)
.Invoke( null, new object[]{ m_methods[methods[i]].key, methods[i].CreateDelegate(m_type_fluxparamreturn_delegate.MakeGenericType(_Parameters[0].ParameterType, methods[i].ReturnType), monoflux), condition})
;
break;
}
}
}
// internal static void Subscribe_v2(this MonoFlux monoflux, in bool condition)
// {
// var methods = new List<(MethodInfo Method, FluxAttribute Attribute)>();
// var methods_raw = monoflux.GetType().GetMethods(m_bindingflag_all);
// foreach (var method in methods_raw)
// {
// var attribute = method.GetCustomAttribute<FluxAttribute>();
// if (attribute != null)
// {
// #if UNITY_EDITOR
// if (method.GetParameters().Length > 1)
// {
// throw new System.Exception($"Error '{method.Name}' : Theres more than one parameter, please set 1 or 0 parameter. (if you need to add more than 1 argument use Tuples or create a struct, record o class...)");
// }
// #endif
// methods.Add((method, attribute));
// }
// }
// foreach (var (method, attribute) in methods)
// {
// var parameters = method.GetParameters();
// var returnType = method.ReturnType;
// switch ((parameters.Length == 1, returnType != m_type_void))
// {
// case (false, false):
// m_type_flux.MakeGenericType(attribute.key.GetType())
// .GetMethod(m_type_flux_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_flux_delegate, monoflux, method), condition });
// break;
// case (true, false):
// m_type_fluxparam.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType)
// .GetMethod(m_type_fluxparam_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxparam_delegate.MakeGenericType(parameters[0].ParameterType), monoflux, method), condition });
// break;
// case (false, true):
// m_type_fluxreturn.MakeGenericType(attribute.key.GetType(), returnType)
// .GetMethod(m_type_fluxreturn_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxreturn_delegate.MakeGenericType(returnType), monoflux, method), condition });
// break;
// case (true, true):
// m_type_fluxparamreturn.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType, returnType)
// .GetMethod(m_type_fluxparamreturn_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxparamreturn_delegate.MakeGenericType(parameters[0].ParameterType, returnType), monoflux, method), condition });
// break;
// }
// }
// }
// internal static void Subscribe_v3(this MonoFlux monoflux, in bool condition)
// {
// var methods_raw = monoflux.GetType().GetMethods(m_bindingflag_all);
// var methods = new (MethodInfo Method, FluxAttribute Attribute)[methods_raw.Length];
// var method_count = 0;
// for (int i = 0; i < methods_raw.Length; i++)
// {
// var attribute = methods_raw[i].GetCustomAttribute<FluxAttribute>();
// if (attribute != null)
// {
// #if UNITY_EDITOR
// if (methods_raw[i].GetParameters().Length > 1) throw new System.Exception($"Error '{methods_raw[i].Name}' : Theres more than one parameter, please set 1 or 0 parameter. (if you need to add more than 1 argument use Tuples or create a struct, record o class...)");
// #endif
// methods[method_count++] = (methods_raw[i], attribute);
// }
// }
// for (int i = 0; i < method_count; i++)
// {
// var method = methods[i].Method;
// var attribute = methods[i].Attribute;
// var parameters = method.GetParameters();
// var returnType = method.ReturnType;
// switch ((parameters.Length == 1, returnType != m_type_void))
// {
// case (false, false):
// m_type_flux.MakeGenericType(attribute.key.GetType())
// .GetMethod(m_type_flux_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_flux_delegate, monoflux, method), condition }.ToArray());
// break;
// case (true, false):
// m_type_fluxparam.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType)
// .GetMethod(m_type_fluxparam_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxparam_delegate.MakeGenericType(parameters[0].ParameterType), monoflux, method), condition }.ToArray());
// break;
// case (false, true):
// m_type_fluxreturn.MakeGenericType(attribute.key.GetType(), returnType)
// .GetMethod(m_type_fluxreturn_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxreturn_delegate.MakeGenericType(returnType), monoflux, method), condition }.ToArray());
// break;
// case (true, true):
// m_type_fluxparamreturn.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType, returnType)
// .GetMethod(m_type_fluxparamreturn_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxparamreturn_delegate.MakeGenericType(parameters[0].ParameterType, returnType), monoflux, method), condition }.ToArray());
// break;
// }
// }
// }
// internal static void Subscribe_v4(this MonoFlux monoflux, in bool condition)
// {
// var methods_raw = monoflux.GetType().GetMethods(m_bindingflag_all);
// var methods = new (MethodInfo Method, FluxAttribute Attribute)[methods_raw.Length];
// var method_count = 0;
// for (int i = 0; i < methods_raw.Length; i++)
// {
// var attribute = methods_raw[i].GetCustomAttribute<FluxAttribute>();
// if (attribute != null)
// {
// methods[method_count++] = (methods_raw[i], attribute);
// }
// }
// for (int i = 0; i < method_count; i++)
// {
// var method = methods[i].Method;
// var attribute = methods[i].Attribute;
// var parameters = method.GetParameters();
// var returnType = method.ReturnType;
// switch ((parameters.Length == 1, returnType != m_type_void))
// {
// case (false, false):
// var genericType = m_type_flux.MakeGenericType(attribute.key.GetType());
// var methodInfo = genericType.GetMethod(m_type_flux_method, m_bindingflag_all);
// var delegateType = m_type_flux_delegate;
// var delegateMethod = Delegate.CreateDelegate(delegateType, monoflux, method);
// var arguments = new object[] { attribute.key, delegateMethod, condition };
// methodInfo.Invoke(null, arguments);
// break;
// case (true, false):
// genericType = m_type_fluxparam.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType);
// methodInfo = genericType.GetMethod(m_type_fluxparam_method, m_bindingflag_all);
// delegateType = m_type_fluxparam_delegate.MakeGenericType(parameters[0].ParameterType);
// delegateMethod = Delegate.CreateDelegate(delegateType, monoflux, method);
// arguments = new object[] { attribute.key, delegateMethod, condition };
// methodInfo.Invoke(null, arguments);
// break;
// case (false, true):
// genericType = m_type_fluxreturn.MakeGenericType(attribute.key.GetType(), returnType);
// methodInfo = genericType.GetMethod(m_type_fluxreturn_method, m_bindingflag_all);
// delegateType = m_type_fluxreturn_delegate.MakeGenericType(returnType);
// delegateMethod = Delegate.CreateDelegate(delegateType, monoflux, method);
// arguments = new object[] { attribute.key, delegateMethod, condition };
// methodInfo.Invoke(null, arguments);
// break;
// case (true, true):
// genericType = m_type_fluxparamreturn.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType, returnType);
// methodInfo = genericType.GetMethod(m_type_fluxparamreturn_method, m_bindingflag_all);
// delegateType = m_type_fluxparamreturn_delegate.MakeGenericType(parameters[0].ParameterType, returnType);
// delegateMethod = Delegate.CreateDelegate(delegateType, monoflux, method);
// arguments = new object[] { attribute.key, delegateMethod, condition };
// methodInfo.Invoke(null, arguments);
// break;
// }
// }
// }
}
} | Runtime/MonoFluxExtension.cs | xavierarpa-UniFlux-a2d46de | [
{
"filename": "Runtime/Core/Internal/Flux_T.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux Action\n ///</summary>\n internal static class Flux<T> //(T, Action)\n {\n ///<summary>\n /// Defines a static instance of ActionFlux<T>\n ///</summary>\n internal static readonly IFlux<T, Action> flux_action = new ActionFlux<T>();",
"score": 0.8727073073387146
},
{
"filename": "Runtime/FluxAttribute.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Class FluxAttribute, a custom attribute that mark a method to be subscribed in a flux.\n /// AllowMultiple is false to keep legibility\n ///</summary>\n [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)]\n public class FluxAttribute : System.Attribute\n {\n ///<summary>\n /// Key provided to the attribute's constructor.",
"score": 0.8593930006027222
},
{
"filename": "Runtime/FluxAttribute.cs",
"retrieved_chunk": " ///</summary>\n public readonly object key;\n ///<summary>\n /// Constructor of the FluxAttribute class that takes a key as a parameter.\n ///</summary>\n public FluxAttribute(object key)\n {\n this.key = key;\n }\n }",
"score": 0.8568518757820129
},
{
"filename": "Runtime/MonoFlux.cs",
"retrieved_chunk": " private void OnEnable() => OnSubscription(true);\n /// <summary>\n /// Called when the script instance is being disabled.\n /// </summary>\n private void OnDisable() => OnSubscription(false);\n /// <summary>\n /// Helper method to subscribe or unsubscribe from the flux state updates.\n /// </summary>\n /// <param name=\"condition\">Whether to subscribe or unsubscribe.</param>\n private void OnSubscription(bool condition)",
"score": 0.840951144695282
},
{
"filename": "Runtime/Core/Internal/Flux_T.cs",
"retrieved_chunk": " ///<summary>\n /// Defines a static method that subscribes an action to a key with a condition\n ///</summary>\n internal static void Store(in T key, in Action action, in bool condition) => flux_action.Store(in condition, key, action);\n ///<summary>\n /// Defines a static method that triggers an action with a key\n ///</summary>\n internal static void Dispatch(in T key) => flux_action.Dispatch(key);\n }\n}",
"score": 0.8387156128883362
}
] | csharp | MonoFlux monoflux, in bool condition)
{ |
namespace Library.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Library.Consts;
using Library.Tests.TestCases;
using QAPortalAPI.Models.ReportingModels;
using Skyline.DataMiner.Automation;
using Skyline.DataMiner.Net.Messages;
internal class Test : ITest
{
private readonly string name;
private readonly string description;
private readonly List<ITestCase> testCases;
private TestReport report;
public Test(string name, string description)
{
this.name = name;
this.description = description;
this.testCases = new List<ITestCase>();
}
public void AddTestCase(params | ITestCase[] newTestCases)
{ |
foreach (var testCase in newTestCases)
{
if (testCase == null || String.IsNullOrWhiteSpace(testCase.Name))
{
// We should not do anything
}
else if (this.testCases.FirstOrDefault(x => x.Name.Equals(testCase.Name)) != null)
{
// Name has to be unique
testCase.Name += " - copy";
AddTestCase(testCase);
}
else
{
this.testCases.Add(testCase);
}
}
}
public TestReport Execute(IEngine engine)
{
this.report = new TestReport(
new TestInfo(name, TestInfoConsts.Contact, TestInfoConsts.ProjectIds, description),
new TestSystemInfo(GetAgentWhereScriptIsRunning(engine)));
foreach (var testCase in testCases)
{
try
{
testCase.Execute(engine);
if (testCase.TestCaseReport != null && !this.report.TryAddTestCase(testCase.TestCaseReport, out string errorMessage))
{
engine.ExitFail(errorMessage);
}
if (testCase.PerformanceTestCaseReport != null)
{
if (!testCase.PerformanceTestCaseReport.IsValid(out string validationInfo))
{
engine.ExitFail(validationInfo);
}
else
{
this.report.PerformanceTestCases.Add(testCase.PerformanceTestCaseReport);
}
}
}
catch (Exception e)
{
engine.ExitFail(e.ToString());
}
}
return this.report;
}
public void PublishResults(IEngine engine)
{
try
{
var portal = new QAPortal.QAPortal(engine);
portal.PublishReport(report);
}
catch (Exception e)
{
engine.Log($"Reporting results for {report.TestInfo.TestName} to QAPortal failed: {e}");
}
var isSuccessful = report.TestResult == QAPortalAPI.Enums.Result.Success;
var reason = GenerateReason();
engine.Log($"{report.TestInfo.TestName} {report.TestResult}: {reason}");
engine.AddScriptOutput("Success", isSuccessful.ToString());
engine.AddScriptOutput("Reason", reason);
}
private string GetAgentWhereScriptIsRunning(IEngine engine)
{
string agentName = null;
try
{
var message = new GetInfoMessage(-1, InfoType.LocalDataMinerInfo);
var response = (GetDataMinerInfoResponseMessage)engine.SendSLNetSingleResponseMessage(message);
agentName = response?.AgentName ?? throw new NullReferenceException("No valid agent name was returned by SLNET.");
}
catch (Exception e)
{
engine.ExitFail("RT Exception - Could not retrieve local agent name: " + e);
}
return agentName;
}
private string GenerateReason()
{
var reason = new StringBuilder();
reason.AppendLine(report.TestInfo.TestDescription);
foreach (var testCaseReport in report.TestCases)
{
reason.AppendLine($"{testCaseReport.TestCaseName}|{testCaseReport.TestCaseResult}|{testCaseReport.TestCaseResultInfo}");
}
return reason.ToString();
}
}
} | Library/Tests/Test.cs | SkylineCommunications-Skyline.DataMiner.GithubTemplate.RegressionTest-bb57db1 | [
{
"filename": "RT_Customer_MyFirstRegressionTest_1/TestCases/TestCaseExample.cs",
"retrieved_chunk": "\tpublic class TestCaseExample : ITestCase\n\t{\n\t\tpublic TestCaseExample(string name)\n\t\t{\n\t\t\tif (String.IsNullOrWhiteSpace(name))\n\t\t\t{\n\t\t\t\tthrow new ArgumentNullException(\"name\");\n\t\t\t}\n\t\t\tName = name;\n\t\t}",
"score": 0.8069857358932495
},
{
"filename": "RT_Customer_MyFirstRegressionTest_1Tests/TestCases/TestCaseExampleTests.cs",
"retrieved_chunk": "\t[TestClass]\n\tpublic class TestCaseExampleTests\n\t{\n\t\t[TestMethod]\n\t\tpublic void TestCaseExampleNameNull()\n\t\t{\n\t\t\tAssert.ThrowsException<ArgumentNullException>(() => new TestCaseExample(null));\n\t\t}\n\t\t[TestMethod]\n\t\tpublic void TestCaseExampleNameEmpty()",
"score": 0.7962022423744202
},
{
"filename": "RT_Customer_MyFirstRegressionTest_1Tests/TestCases/TestCaseExampleTests.cs",
"retrieved_chunk": "\t\t{\n\t\t\tAssert.ThrowsException<ArgumentNullException>(() => new TestCaseExample(String.Empty));\n\t\t}\n\t\t[TestMethod]\n\t\tpublic void ExecuteTest()\n\t\t{\n\t\t\t// Arrange\n\t\t\tTestCaseExample tce = new TestCaseExample(\"example\");\n\t\t\tMock<IEngine> engine = new Mock<IEngine>();\n\t\t\t// Act",
"score": 0.7649219036102295
},
{
"filename": "RT_Customer_MyFirstRegressionTest_1/RT_Customer_MyFirstRegressionTest_1.cs",
"retrieved_chunk": "\t\t\tTest myTest = new Test(TestName, TestDescription);\n\t\t\tmyTest.AddTestCase(\n\t\t\t\tnew TestCaseExample(\"Test 1\"),\n\t\t\t\tnew TestCaseExample(\"Test 2\"));\n\t\t\tmyTest.Execute(engine);\n\t\t\tmyTest.PublishResults(engine);\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tengine.Log($\"{TestName} failed: {e}\");",
"score": 0.7631595134735107
},
{
"filename": "Library/QAPortal/QAPortal.cs",
"retrieved_chunk": "\t\tpublic QAPortal(IEngine engine)\n\t\t{\n\t\t\tthis.engine = engine;\n\t\t\tconfiguration = QaPortalConfiguration.GetConfiguration(out var e);\n\t\t\tif (e != null)\n\t\t\t{\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tpublic void PublishReport(TestReport report)",
"score": 0.7337627410888672
}
] | csharp | ITestCase[] newTestCases)
{ |
using Newtonsoft.Json;
namespace DotNetDevBadgeWeb.Model
{
public class UserSummary
{
[JsonProperty("likes_given")]
public int LikesGiven { get; set; }
[JsonProperty("likes_received")]
public int LikesReceived { get; set; }
[JsonProperty("topics_entered")]
public int TopicsEntered { get; set; }
[JsonProperty("posts_read_count")]
public int PostsReadCount { get; set; }
[JsonProperty("days_visited")]
public int DaysVisited { get; set; }
[JsonProperty("topic_count")]
public int TopicCount { get; set; }
[JsonProperty("post_count")]
public int PostCount { get; set; }
[ | JsonProperty("time_read")]
public int TimeRead { | get; set; }
[JsonProperty("recent_time_read")]
public int RecentTimeRead { get; set; }
[JsonProperty("bookmark_count")]
public int BookmarkCount { get; set; }
[JsonProperty("can_see_summary_stats")]
public bool CanSeeSummaryStats { get; set; }
[JsonProperty("solved_count")]
public int SolvedCount { get; set; }
}
}
| src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs | chanos-dev-dotnetdev-badge-5740a40 | [
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs",
"retrieved_chunk": " public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]",
"score": 0.8448970913887024
},
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs",
"retrieved_chunk": " public bool? Admin { get; set; }\n [JsonProperty(\"moderator\")]\n public bool? Moderator { get; set; }\n public ELevel Level => TrustLevel switch\n {\n 3 => ELevel.Silver,\n 4 => ELevel.Gold,\n _ => ELevel.Bronze,\n };\n public string AvatarEndPoint => AvatarTemplate?.Replace(\"{size}\", AVATAR_SIZE.ToString()) ?? string.Empty;",
"score": 0.7439476251602173
},
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs",
"retrieved_chunk": "using DotNetDevBadgeWeb.Common;\nusing Newtonsoft.Json;\nnamespace DotNetDevBadgeWeb.Model\n{\n public class User\n {\n private const int AVATAR_SIZE = 128;\n [JsonProperty(\"id\")]\n public int Id { get; set; }\n [JsonProperty(\"username\")]",
"score": 0.7337879538536072
},
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Common/Palette.cs",
"retrieved_chunk": " _ => \"CD7F32\",\n };\n }\n internal class ColorSet\n {\n internal string FontColor { get; private set; }\n internal string BackgroundColor { get; private set; }\n internal ColorSet(string fontColor, string backgroundColor)\n {\n FontColor = fontColor;",
"score": 0.7301567792892456
},
{
"filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs",
"retrieved_chunk": "using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}",
"score": 0.6881143450737
}
] | csharp | JsonProperty("time_read")]
public int TimeRead { |
#nullable enable
using System.Collections.Generic;
namespace Mochineko.FacialExpressions.Blink
{
/// <summary>
/// Composition of some <see cref="IEyelidMorpher"/>s.
/// </summary>
public sealed class CompositeEyelidMorpher : IEyelidMorpher
{
private readonly IReadOnlyList<IEyelidMorpher> morphers;
/// <summary>
/// Creates a new instance of <see cref="CompositeEyelidMorpher"/>.
/// </summary>
/// <param name="morphers">Composited morphers.</param>
public CompositeEyelidMorpher(IReadOnlyList<IEyelidMorpher> morphers)
{
this.morphers = morphers;
}
void IEyelidMorpher.MorphInto(EyelidSample sample)
{
foreach (var morpher in morphers)
{
morpher.MorphInto(sample);
}
}
float IEyelidMorpher.GetWeightOf(Eyelid eyelid)
{
return morphers[0].GetWeightOf(eyelid);
}
void | IEyelidMorpher.Reset()
{ |
foreach (var morpher in morphers)
{
morpher.Reset();
}
}
}
}
| Assets/Mochineko/FacialExpressions/Blink/CompositeEyelidMorpher.cs | mochi-neko-facial-expressions-unity-ab0d020 | [
{
"filename": "Assets/Mochineko/FacialExpressions/LipSync/CompositeLipMorpher.cs",
"retrieved_chunk": " foreach (var morpher in morphers)\n {\n morpher.MorphInto(sample);\n }\n }\n float ILipMorpher.GetWeightOf(Viseme viseme)\n {\n return morphers[0].GetWeightOf(viseme);\n }\n void ILipMorpher.Reset()",
"score": 0.8717089891433716
},
{
"filename": "Assets/Mochineko/FacialExpressions/Emotion/CompositeEmotionMorpher.cs",
"retrieved_chunk": " this.morphers = morphers;\n }\n void IEmotionMorpher<TEmotion>.MorphInto(EmotionSample<TEmotion> sample)\n {\n foreach (var morpher in morphers)\n {\n morpher.MorphInto(sample);\n }\n }\n float IEmotionMorpher<TEmotion>.GetWeightOf(TEmotion emotion)",
"score": 0.8266891241073608
},
{
"filename": "Assets/Mochineko/FacialExpressions/Emotion/CompositeEmotionMorpher.cs",
"retrieved_chunk": " {\n return morphers[0].GetWeightOf(emotion);\n }\n void IEmotionMorpher<TEmotion>.Reset()\n {\n foreach (var morpher in morphers)\n {\n morpher.Reset();\n }\n }",
"score": 0.8127202391624451
},
{
"filename": "Assets/Mochineko/FacialExpressions/Blink/SkinnedMeshEyelidMorpher.cs",
"retrieved_chunk": " }\n else if (indexMap.TryGetValue(sample.eyelid, out var index))\n {\n skinnedMeshRenderer.SetBlendShapeWeight(index, sample.weight * 100f);\n }\n }\n public float GetWeightOf(Eyelid eyelid)\n {\n if (indexMap.TryGetValue(eyelid, out var index))\n {",
"score": 0.7837307453155518
},
{
"filename": "Assets/Mochineko/FacialExpressions/Emotion/ExclusiveFollowingEmotionAnimator.cs",
"retrieved_chunk": " velocities[target.Key] = velocity;\n morpher.MorphInto(new EmotionSample<TEmotion>(target.Key, smoothedWeight));\n }\n }\n public void Reset()\n {\n morpher.Reset();\n }\n }\n}",
"score": 0.7755498886108398
}
] | csharp | IEyelidMorpher.Reset()
{ |
using NowPlaying.Utils;
using NowPlaying.Views;
using Playnite.SDK;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Input;
using static NowPlaying.ViewModels.CacheRootsViewModel;
namespace NowPlaying.ViewModels
{
public class CacheRootsViewModel : ViewModelBase
{
public readonly NowPlaying plugin;
public ICommand RefreshRootsCommand { get; private set; }
public ICommand AddCacheRootCommand { get; private set; }
public ICommand EditMaxFillCommand { get; private set; }
public ICommand RemoveCacheRootCommand { get; private set; }
public ObservableCollection<CacheRootViewModel> CacheRoots => plugin.cacheManager.CacheRoots;
public | CacheRootViewModel SelectedCacheRoot { | get; set; }
public string EmptyRootsVisible => CacheRoots.Count > 0 ? "Collapsed" : "Visible";
public string NonEmptyRootsVisible => CacheRoots.Count > 0 ? "Visible" : "Collapsed";
public CacheRootsViewModel(NowPlaying plugin)
{
this.plugin = plugin;
this.CustomSpaceAvailableSort = new CustomSpaceAvailableSorter();
this.CustomCachesInstalledSort = new CustomCachesInstalledSorter();
this.CustomMaxFillReservedSort = new CustomMaxFillReservedSorter();
AddCacheRootCommand = new RelayCommand(() =>
{
var appWindow = plugin.PlayniteApi.Dialogs.GetCurrentAppWindow();
var popup = plugin.PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions()
{
ShowCloseButton = false,
ShowMaximizeButton = false,
ShowMinimizeButton = false
});
var viewModel = new AddCacheRootViewModel(plugin, popup, isFirstAdded: CacheRoots.Count == 0);
var view = new AddCacheRootView(viewModel);
popup.Content = view;
// setup up popup and center within the current application window
popup.Width = view.MinWidth;
popup.MinWidth = view.MinWidth;
popup.Height = view.MinHeight + SystemParameters.WindowCaptionHeight;
popup.MinHeight = view.MinHeight + SystemParameters.WindowCaptionHeight;
popup.Left = appWindow.Left + (appWindow.Width - popup.Width) / 2;
popup.Top = appWindow.Top + (appWindow.Height - popup.Height) / 2;
popup.ShowDialog();
});
EditMaxFillCommand = new RelayCommand(
() => {
var appWindow = plugin.PlayniteApi.Dialogs.GetCurrentAppWindow();
var popup = plugin.PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions()
{
ShowCloseButton = false,
ShowMaximizeButton = false,
ShowMinimizeButton = false
});
var viewModel = new EditMaxFillViewModel(plugin, popup, SelectedCacheRoot);
var view = new EditMaxFillView(viewModel);
popup.Content = view;
// setup up popup and center within the current application window
popup.Width = view.MinWidth;
popup.MinWidth = view.MinWidth;
popup.Height = view.MinHeight + SystemParameters.WindowCaptionHeight;
popup.MinHeight = view.MinHeight + SystemParameters.WindowCaptionHeight;
popup.Left = appWindow.Left + (appWindow.Width - popup.Width) / 2;
popup.Top = appWindow.Top + (appWindow.Height - popup.Height) / 2;
popup.ShowDialog();
},
// CanExecute
() => SelectedCacheRoot != null
);
RemoveCacheRootCommand = new RelayCommand(
() => {
plugin.cacheManager.RemoveCacheRoot(SelectedCacheRoot.Directory);
RefreshCacheRoots();
},
// canExecute
() => SelectedCacheRoot?.GameCaches.Count == 0
);
RefreshRootsCommand = new RelayCommand(() => RefreshCacheRoots());
// . track cache roots list changes, in order to auto-adjust directory column width
this.CacheRoots.CollectionChanged += CacheRoots_CollectionChanged;
}
private void CacheRoots_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
plugin.cacheRootsView.UnselectCacheRoots();
GridViewUtils.ColumnResize(plugin.cacheRootsView.CacheRoots);
}
public void RefreshCacheRoots()
{
foreach (var root in CacheRoots)
{
root.UpdateGameCaches();
}
OnPropertyChanged(nameof(CacheRoots));
OnPropertyChanged(nameof(EmptyRootsVisible));
OnPropertyChanged(nameof(NonEmptyRootsVisible));
plugin.cacheRootsView.UnselectCacheRoots();
plugin.panelViewModel.UpdateCacheRoots();
}
public class CustomSpaceAvailableSorter : IComparer
{
public int Compare(object x, object y)
{
long spaceX = ((CacheRootViewModel)x).BytesAvailableForCaches;
long spaceY = ((CacheRootViewModel)y).BytesAvailableForCaches;
return spaceX.CompareTo(spaceY);
}
}
public CustomSpaceAvailableSorter CustomSpaceAvailableSort { get; private set; }
public class CustomCachesInstalledSorter : IComparer
{
public int Compare(object x, object y)
{
// . sort by installed number of caches 1st, and installed cache bytes 2nd
int countX = ((CacheRootViewModel)x).CachesInstalled;
int countY = ((CacheRootViewModel)y).CachesInstalled;
long bytesX = ((CacheRootViewModel)x).cachesAggregateSizeOnDisk;
long bytesY = ((CacheRootViewModel)y).cachesAggregateSizeOnDisk;
return countX != countY ? countX.CompareTo(countY) : bytesX.CompareTo(bytesY);
}
}
public CustomCachesInstalledSorter CustomCachesInstalledSort { get; private set; }
public class CustomMaxFillReservedSorter : IComparer
{
public int Compare(object x, object y)
{
// . sort by max fill level 1st, and reserved bytes (reverse direction) 2nd
double fillX = ((CacheRootViewModel)x).MaxFillLevel;
double fillY = ((CacheRootViewModel)y).MaxFillLevel;
long bytesX = ((CacheRootViewModel)x).bytesReservedOnDevice;
long bytesY = ((CacheRootViewModel)y).bytesReservedOnDevice;
return fillX != fillY ? fillX.CompareTo(fillY) : bytesY.CompareTo(bytesX);
}
}
public CustomMaxFillReservedSorter CustomMaxFillReservedSort { get; private set; }
}
}
| source/ViewModels/CacheRootsViewModel.cs | gittromney-Playnite-NowPlaying-23eec41 | [
{
"filename": "source/ViewModels/NowPlayingPanelViewModel.cs",
"retrieved_chunk": " public ICommand AddGameCachesCommand { get; private set; }\n public ICommand InstallCachesCommand { get; private set; }\n public ICommand UninstallCachesCommand { get; private set; }\n public ICommand DisableCachesCommand { get; private set; }\n public ICommand RerootClickCanExecute { get; private set; }\n public ICommand CancelQueuedInstallsCommand { get; private set; }\n public ICommand PauseInstallCommand { get; private set; }\n public ICommand CancelInstallCommand { get; private set; }\n public ObservableCollection<GameCacheViewModel> GameCaches => plugin.cacheManager.GameCaches;\n public bool AreCacheRootsNonEmpty => plugin.cacheManager.CacheRoots.Count > 0;",
"score": 0.9376179575920105
},
{
"filename": "source/ViewModels/AddCacheRootViewModel.cs",
"retrieved_chunk": " public string SpaceAvailableForCaches { get; private set; }\n public ICommand MakeDirCommand { get; private set; }\n public ICommand SelectFolderCommand { get; private set; }\n public ICommand AddCommand { get; private set; }\n public ICommand CancelCommand { get; private set; }\n public bool MakeDirCanExecute { get; private set; }\n public string MakeDirCommandVisibility => MakeDirCanExecute ? \"Visible\" : \"Collapsed\";\n public bool AddCommandCanExecute { get; private set; }\n public AddCacheRootViewModel(NowPlaying plugin, Window popup, bool isFirstAdded = false)\n {",
"score": 0.924042820930481
},
{
"filename": "source/ViewModels/NowPlayingPanelViewModel.cs",
"retrieved_chunk": " long spaceY = ((GameCacheViewModel)y).cacheRoot.BytesAvailableForCaches;\n return spaceX.CompareTo(spaceY);\n }\n }\n public CustomSpaceAvailableSorter CustomSpaceAvailableSort { get; private set; }\n public ICommand ToggleShowCacheRoots { get; private set; }\n public ICommand ToggleShowSettings { get; private set; }\n public ICommand SaveSettingsCommand { get; private set; }\n public ICommand CancelSettingsCommand { get; private set; }\n public ICommand RefreshCachesCommand { get; private set; }",
"score": 0.9218745827674866
},
{
"filename": "source/ViewModels/AddGameCachesViewModel.cs",
"retrieved_chunk": " return sizeX.CompareTo(sizeY);\n }\n }\n public CustomInstallSizeSorter CustomInstallSizeSort { get; private set; }\n public ICommand ClearSearchTextCommand { get; private set; }\n public ICommand SelectAllCommand { get; private set; }\n public ICommand SelectNoneCommand { get; private set; }\n public ICommand CloseCommand { get; private set; }\n public ICommand EnableSelectedGamesCommand { get; private set; }\n public List<string> CacheRoots => cacheRoots.Select(r => r.Directory).ToList();",
"score": 0.9206982851028442
},
{
"filename": "source/ViewModels/AddCacheRootViewModel.cs",
"retrieved_chunk": "{\n public class AddCacheRootViewModel : ViewModelBase\n {\n private readonly NowPlaying plugin;\n private readonly GameCacheManagerViewModel cacheManager;\n private Dictionary<string, string> rootDevices;\n private List<string> existingRoots;\n public Window popup { get; set; }\n public bool DeviceIsValid { get; private set; }\n public bool RootIsValid { get; private set; }",
"score": 0.9035478830337524
}
] | csharp | CacheRootViewModel SelectedCacheRoot { |
using CliWrap;
using CliWrap.EventStream;
using LegendaryLibraryNS.Enums;
using LegendaryLibraryNS.Models;
using LegendaryLibraryNS.Services;
using Playnite.Common;
using Playnite.SDK;
using Playnite.SDK.Data;
using Playnite.SDK.Events;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace LegendaryLibraryNS
{
[LoadPlugin]
public class LegendaryLibrary : LibraryPluginBase<LegendaryLibrarySettingsViewModel>
{
private static readonly ILogger logger = LogManager.GetLogger();
public static LegendaryLibrary Instance { get; set; }
public static bool LegendaryGameInstaller { get; internal set; }
public | LegendaryDownloadManager LegendaryDownloadManager { | get; set; }
public LegendaryLibrary(IPlayniteAPI api) : base(
"Legendary (Epic)",
Guid.Parse("EAD65C3B-2F8F-4E37-B4E6-B3DE6BE540C6"),
new LibraryPluginProperties { CanShutdownClient = true, HasSettings = true },
new LegendaryClient(),
LegendaryLauncher.Icon,
(_) => new LegendaryLibrarySettingsView(),
api)
{
Instance = this;
SettingsViewModel = new LegendaryLibrarySettingsViewModel(this, api);
LoadEpicLocalization();
}
public static LegendaryLibrarySettings GetSettings()
{
return Instance.SettingsViewModel?.Settings ?? null;
}
public static LegendaryDownloadManager GetLegendaryDownloadManager()
{
if (Instance.LegendaryDownloadManager == null)
{
Instance.LegendaryDownloadManager = new LegendaryDownloadManager();
}
return Instance.LegendaryDownloadManager;
}
internal Dictionary<string, GameMetadata> GetInstalledGames()
{
var games = new Dictionary<string, GameMetadata>();
var appList = LegendaryLauncher.GetInstalledAppList();
foreach (KeyValuePair<string, Installed> d in appList)
{
var app = d.Value;
if (app.App_name.StartsWith("UE_"))
{
continue;
}
// DLC
if (app.Is_dlc)
{
continue;
}
var installLocation = app.Install_path;
var gameName = app?.Title ?? Path.GetFileName(installLocation);
if (installLocation.IsNullOrEmpty())
{
continue;
}
installLocation = Paths.FixSeparators(installLocation);
if (!Directory.Exists(installLocation))
{
logger.Error($"Epic game {gameName} installation directory {installLocation} not detected.");
continue;
}
var game = new GameMetadata()
{
Source = new MetadataNameProperty("Epic"),
GameId = app.App_name,
Name = gameName,
Version = app.Version,
InstallDirectory = installLocation,
IsInstalled = true,
Platforms = new HashSet<MetadataProperty> { new MetadataSpecProperty("pc_windows") }
};
game.Name = game.Name.RemoveTrademarks();
games.Add(game.GameId, game);
}
return games;
}
internal List<GameMetadata> GetLibraryGames(CancellationToken cancelToken)
{
var cacheDir = GetCachePath("catalogcache");
var games = new List<GameMetadata>();
var accountApi = new EpicAccountClient(PlayniteApi, LegendaryLauncher.TokensPath);
var assets = accountApi.GetAssets();
if (!assets?.Any() == true)
{
Logger.Warn("Found no assets on Epic accounts.");
}
var playtimeItems = accountApi.GetPlaytimeItems();
foreach (var gameAsset in assets.Where(a => a.@namespace != "ue"))
{
if (cancelToken.IsCancellationRequested)
{
break;
}
var cacheFile = Paths.GetSafePathName($"{gameAsset.@namespace}_{gameAsset.catalogItemId}_{gameAsset.buildVersion}.json");
cacheFile = Path.Combine(cacheDir, cacheFile);
var catalogItem = accountApi.GetCatalogItem(gameAsset.@namespace, gameAsset.catalogItemId, cacheFile);
if (catalogItem?.categories?.Any(a => a.path == "applications") != true)
{
continue;
}
if (catalogItem?.categories?.Any(a => a.path == "dlc") == true)
{
continue;
}
var newGame = new GameMetadata
{
Source = new MetadataNameProperty("Epic"),
GameId = gameAsset.appName,
Name = catalogItem.title.RemoveTrademarks(),
Platforms = new HashSet<MetadataProperty> { new MetadataSpecProperty("pc_windows") }
};
var playtimeItem = playtimeItems?.FirstOrDefault(x => x.artifactId == gameAsset.appName);
if (playtimeItem != null)
{
newGame.Playtime = playtimeItem.totalTime;
}
games.Add(newGame);
}
return games;
}
public override IEnumerable<GameMetadata> GetGames(LibraryGetGamesArgs args)
{
var allGames = new List<GameMetadata>();
var installedGames = new Dictionary<string, GameMetadata>();
Exception importError = null;
if (SettingsViewModel.Settings.ImportInstalledGames)
{
try
{
installedGames = GetInstalledGames();
Logger.Debug($"Found {installedGames.Count} installed Epic games.");
allGames.AddRange(installedGames.Values.ToList());
}
catch (Exception e)
{
Logger.Error(e, "Failed to import installed Epic games.");
importError = e;
}
}
if (SettingsViewModel.Settings.ConnectAccount)
{
try
{
var libraryGames = GetLibraryGames(args.CancelToken);
Logger.Debug($"Found {libraryGames.Count} library Epic games.");
if (!SettingsViewModel.Settings.ImportUninstalledGames)
{
libraryGames = libraryGames.Where(lg => installedGames.ContainsKey(lg.GameId)).ToList();
}
foreach (var game in libraryGames)
{
if (installedGames.TryGetValue(game.GameId, out var installed))
{
installed.Playtime = game.Playtime;
installed.LastActivity = game.LastActivity;
installed.Name = game.Name;
}
else
{
allGames.Add(game);
}
}
}
catch (Exception e)
{
Logger.Error(e, "Failed to import linked account Epic games details.");
importError = e;
}
}
if (importError != null)
{
PlayniteApi.Notifications.Add(new NotificationMessage(
ImportErrorMessageId,
string.Format(PlayniteApi.Resources.GetString("LOCLibraryImportError"), Name) +
Environment.NewLine + importError.Message,
NotificationType.Error,
() => OpenSettingsView()));
}
else
{
PlayniteApi.Notifications.Remove(ImportErrorMessageId);
}
return allGames;
}
public string GetCachePath(string dirName)
{
return Path.Combine(GetPluginUserDataPath(), dirName);
}
public override IEnumerable<InstallController> GetInstallActions(GetInstallActionsArgs args)
{
if (args.Game.PluginId != Id)
{
yield break;
}
yield return new LegendaryInstallController(args.Game);
}
public override IEnumerable<UninstallController> GetUninstallActions(GetUninstallActionsArgs args)
{
if (args.Game.PluginId != Id)
{
yield break;
}
yield return new LegendaryUninstallController(args.Game);
}
public override IEnumerable<PlayController> GetPlayActions(GetPlayActionsArgs args)
{
if (args.Game.PluginId != Id)
{
yield break;
}
yield return new LegendaryPlayController(args.Game);
}
public override LibraryMetadataProvider GetMetadataDownloader()
{
return new EpicMetadataProvider(PlayniteApi);
}
public void LoadEpicLocalization()
{
var currentLanguage = PlayniteApi.ApplicationSettings.Language;
var dictionaries = Application.Current.Resources.MergedDictionaries;
void loadString(string xamlPath)
{
ResourceDictionary res = null;
try
{
res = Xaml.FromFile<ResourceDictionary>(xamlPath);
res.Source = new Uri(xamlPath, UriKind.Absolute);
foreach (var key in res.Keys)
{
if (res[key] is string locString)
{
if (locString.IsNullOrEmpty())
{
res.Remove(key);
}
}
else
{
res.Remove(key);
}
}
}
catch (Exception e)
{
logger.Error(e, $"Failed to parse localization file {xamlPath}");
return;
}
dictionaries.Add(res);
}
var extraLocDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Localization\Epic");
if (!Directory.Exists(extraLocDir))
{
return;
}
var enXaml = Path.Combine(extraLocDir, "en_US.xaml");
if (!File.Exists(enXaml))
{
return;
}
loadString(enXaml);
if (currentLanguage != "en_US")
{
var langXaml = Path.Combine(extraLocDir, $"{currentLanguage}.xaml");
if (File.Exists(langXaml))
{
loadString(langXaml);
}
}
}
public void SyncGameSaves(string gameName, string gameID, string gameInstallDir, bool download)
{
if (GetSettings().SyncGameSaves)
{
var metadataFile = Path.Combine(LegendaryLauncher.ConfigPath, "metadata", gameID + ".json");
if (File.Exists(metadataFile))
{
bool correctJson = false;
LegendaryMetadata.Rootobject metadata = null;
if (Serialization.TryFromJson(FileSystem.ReadFileAsStringSafe(Path.Combine(LegendaryLauncher.ConfigPath, "metadata", gameID + ".json")), out metadata))
{
if (metadata != null && metadata.metadata != null)
{
correctJson = true;
}
}
if (!correctJson)
{
GlobalProgressOptions metadataProgressOptions = new GlobalProgressOptions(ResourceProvider.GetString("LOCProgressMetadata"), false);
PlayniteApi.Dialogs.ActivateGlobalProgress(async (a) =>
{
a.ProgressMaxValue = 100;
a.CurrentProgressValue = 0;
var cmd = Cli.Wrap(LegendaryLauncher.ClientExecPath).WithArguments(new[] { "info", gameID });
await foreach (var cmdEvent in cmd.ListenAsync())
{
switch (cmdEvent)
{
case StartedCommandEvent started:
a.CurrentProgressValue = 1;
break;
case StandardErrorCommandEvent stdErr:
logger.Debug("[Legendary] " + stdErr.ToString());
break;
case ExitedCommandEvent exited:
if (exited.ExitCode != 0)
{
logger.Error("[Legendary] exit code: " + exited.ExitCode);
PlayniteApi.Dialogs.ShowErrorMessage(PlayniteApi.Resources.GetString("LOCMetadataDownloadError").Format(gameName));
return;
}
else
{
metadata = Serialization.FromJson<LegendaryMetadata.Rootobject>(FileSystem.ReadFileAsStringSafe(Path.Combine(LegendaryLauncher.ConfigPath, "metadata", gameID + ".json")));
}
a.CurrentProgressValue = 100;
break;
default:
break;
}
}
}, metadataProgressOptions);
}
var cloudSaveFolder = metadata.metadata.customAttributes.CloudSaveFolder.value;
if (cloudSaveFolder != null)
{
var userData = Serialization.FromJson<OauthResponse>(FileSystem.ReadFileAsStringSafe(LegendaryLauncher.TokensPath));
var pathVariables = new Dictionary<string, string>
{
{ "{installdir}", gameInstallDir },
{ "{epicid}", userData.account_id },
{ "{appdata}", Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) },
{ "{userdir}", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) },
{ "{userprofile}", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) },
{ "{usersavedgames}", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Saved Games") }
};
foreach (var pathVar in pathVariables)
{
if (cloudSaveFolder.Contains(pathVar.Key, StringComparison.OrdinalIgnoreCase))
{
cloudSaveFolder = cloudSaveFolder.Replace(pathVar.Key, pathVar.Value, StringComparison.OrdinalIgnoreCase);
}
}
cloudSaveFolder = Path.GetFullPath(cloudSaveFolder);
if (Directory.Exists(cloudSaveFolder))
{
GlobalProgressOptions globalProgressOptions = new GlobalProgressOptions(ResourceProvider.GetString(LOC.LegendarySyncing).Format(gameName), false);
PlayniteApi.Dialogs.ActivateGlobalProgress(async (a) =>
{
a.ProgressMaxValue = 100;
a.CurrentProgressValue = 0;
var skippedActivity = "--skip-upload";
if (download == false)
{
skippedActivity = "--skip-download";
}
var cmd = Cli.Wrap(LegendaryLauncher.ClientExecPath)
.WithArguments(new[] { "-y", "sync-saves", gameID, skippedActivity, "--save-path", cloudSaveFolder });
await foreach (var cmdEvent in cmd.ListenAsync())
{
switch (cmdEvent)
{
case StartedCommandEvent started:
a.CurrentProgressValue = 1;
break;
case StandardErrorCommandEvent stdErr:
logger.Debug("[Legendary] " + stdErr.ToString());
break;
case ExitedCommandEvent exited:
a.CurrentProgressValue = 100;
if (exited.ExitCode != 0)
{
logger.Error("[Legendary] exit code: " + exited.ExitCode);
PlayniteApi.Dialogs.ShowErrorMessage(PlayniteApi.Resources.GetString(LOC.LegendarySyncError).Format(gameName));
}
break;
default:
break;
}
}
}, globalProgressOptions);
}
}
}
}
}
public override void OnGameStarting(OnGameStartingEventArgs args)
{
SyncGameSaves(args.Game.Name, args.Game.GameId, args.Game.InstallDirectory, true);
}
public override void OnGameStopped(OnGameStoppedEventArgs args)
{
SyncGameSaves(args.Game.Name, args.Game.GameId, args.Game.InstallDirectory, false);
}
public override IEnumerable<SidebarItem> GetSidebarItems()
{
yield return new SidebarItem
{
Title = ResourceProvider.GetString(LOC.LegendaryPanel),
Icon = LegendaryLauncher.Icon,
Type = SiderbarItemType.View,
Opened = () => GetLegendaryDownloadManager()
};
}
public override void OnApplicationStopped(OnApplicationStoppedEventArgs args)
{
LegendaryDownloadManager downloadManager = GetLegendaryDownloadManager();
var runningAndQueuedDownloads = downloadManager.downloadManagerData.downloads.Where(i => i.status == (int)DownloadStatus.Running
|| i.status == (int)DownloadStatus.Queued).ToList();
if (runningAndQueuedDownloads.Count > 0)
{
foreach (var download in runningAndQueuedDownloads)
{
if (download.status == (int)DownloadStatus.Running)
{
downloadManager.gracefulInstallerCTS?.Cancel();
downloadManager.gracefulInstallerCTS?.Dispose();
downloadManager.forcefulInstallerCTS?.Dispose();
}
download.status = (int)DownloadStatus.Paused;
}
downloadManager.SaveData();
}
if (GetSettings().AutoClearCache != (int)ClearCacheTime.Never)
{
var clearingTime = DateTime.Now;
switch (GetSettings().AutoClearCache)
{
case (int)ClearCacheTime.Day:
clearingTime = DateTime.Now.AddDays(-1);
break;
case (int)ClearCacheTime.Week:
clearingTime = DateTime.Now.AddDays(-7);
break;
case (int)ClearCacheTime.Month:
clearingTime = DateTime.Now.AddMonths(-1);
break;
case (int)ClearCacheTime.ThreeMonths:
clearingTime = DateTime.Now.AddMonths(-3);
break;
case (int)ClearCacheTime.SixMonths:
clearingTime = DateTime.Now.AddMonths(-6);
break;
default:
break;
}
var cacheDirs = new List<string>()
{
GetCachePath("catalogcache"),
GetCachePath("infocache"),
GetCachePath("sdlcache")
};
foreach (var cacheDir in cacheDirs)
{
if (Directory.Exists(cacheDir))
{
if (Directory.GetCreationTime(cacheDir) < clearingTime)
{
Directory.Delete(cacheDir, true);
}
}
}
}
}
public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args)
{
foreach (var game in args.Games)
{
if (game.PluginId == Id && game.IsInstalled)
{
yield return new GameMenuItem
{
Description = ResourceProvider.GetString(LOC.LegendaryRepair),
Action = (args) =>
{
Window window = null;
if (PlayniteApi.ApplicationInfo.Mode == ApplicationMode.Desktop)
{
window = PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions
{
ShowMaximizeButton = false,
});
}
else
{
window = new Window
{
Background = System.Windows.Media.Brushes.DodgerBlue
};
}
window.Title = game.Name;
var installProperties = new DownloadProperties { downloadAction = (int)DownloadAction.Repair };
var installData = new DownloadManagerData.Download { gameID = game.GameId, downloadProperties = installProperties };
window.DataContext = installData;
window.Content = new LegendaryGameInstaller();
window.Owner = PlayniteApi.Dialogs.GetCurrentAppWindow();
window.SizeToContent = SizeToContent.WidthAndHeight;
window.MinWidth = 600;
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
window.ShowDialog();
}
};
}
}
}
}
}
| src/LegendaryLibrary.cs | hawkeye116477-playnite-legendary-plugin-d7af6b2 | [
{
"filename": "src/LegendaryGameInstaller.xaml.cs",
"retrieved_chunk": "namespace LegendaryLibraryNS\n{\n /// <summary>\n /// Interaction logic for LegendaryGameInstaller.xaml\n /// </summary>\n public partial class LegendaryGameInstaller : UserControl\n {\n private ILogger logger = LogManager.GetLogger();\n private IPlayniteAPI playniteAPI = API.Instance;\n public string installCommand;",
"score": 0.8960248231887817
},
{
"filename": "src/LegendaryClient.cs",
"retrieved_chunk": " public class LegendaryClient : LibraryClient\n {\n private static readonly ILogger logger = LogManager.GetLogger();\n public override string Icon => LegendaryLauncher.Icon;\n public override bool IsInstalled => LegendaryLauncher.IsInstalled;\n public override void Open()\n {\n LegendaryLauncher.StartClient();\n }\n public override void Shutdown()",
"score": 0.8920646905899048
},
{
"filename": "src/LegendaryMessagesSettings.cs",
"retrieved_chunk": " public class LegendaryMessagesSettingsModel\n {\n public bool DontShowDownloadManagerWhatsUpMsg { get; set; } = false;\n }\n public class LegendaryMessagesSettings\n {\n public static LegendaryMessagesSettingsModel LoadSettings()\n {\n LegendaryMessagesSettingsModel messagesSettings = null;\n var dataDir = LegendaryLibrary.Instance.GetPluginUserDataPath();",
"score": 0.8847208023071289
},
{
"filename": "src/LegendaryGameController.cs",
"retrieved_chunk": " }\n }));\n }\n }\n }\n public class LegendaryUninstallController : UninstallController\n {\n private IPlayniteAPI playniteAPI = API.Instance;\n private static readonly ILogger logger = LogManager.GetLogger();\n public LegendaryUninstallController(Game game) : base(game)",
"score": 0.8727404475212097
},
{
"filename": "src/LegendaryLibrarySettingsViewModel.cs",
"retrieved_chunk": " public bool NoHttps { get; set; } = LegendaryLauncher.DefaultNoHttps;\n public int DoActionAfterDownloadComplete { get; set; } = (int)DownloadCompleteAction.Nothing;\n public bool SyncGameSaves { get; set; } = false;\n public int MaxWorkers { get; set; } = LegendaryLauncher.DefaultMaxWorkers;\n public int MaxSharedMemory { get; set; } = LegendaryLauncher.DefaultMaxSharedMemory;\n public bool EnableReordering { get; set; } = false;\n public int AutoClearCache { get; set; } = (int)ClearCacheTime.Never;\n }\n public class LegendaryLibrarySettingsViewModel : PluginSettingsViewModel<LegendaryLibrarySettings, LegendaryLibrary>\n {",
"score": 0.8691310882568359
}
] | csharp | LegendaryDownloadManager LegendaryDownloadManager { |
using Microsoft.VisualStudio.Shell;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.VisualStudio.Shell.Interop;
using System.Diagnostics;
using Task = System.Threading.Tasks.Task;
using Microsoft;
namespace VSIntelliSenseTweaks
{
/// <summary>
/// This is the class that implements the package exposed by this assembly.
/// </summary>
/// <remarks>
/// <para>
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell. These attributes tell the pkgdef creation
/// utility what data to put into .pkgdef file.
/// </para>
/// <para>
/// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file.
/// </para>
/// </remarks>
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSIntelliSenseTweaksPackage.PackageGuidString)]
[ProvideOptionPage(pageType: typeof(GeneralSettings), categoryName: PackageDisplayName, pageName: GeneralSettings.PageName, 0, 0, true)]
public sealed class VSIntelliSenseTweaksPackage : AsyncPackage
{
/// <summary>
/// VSIntelliSenseTweaksPackage GUID string.
/// </summary>
public const string PackageGuidString = "8e0ec3d8-0561-477a-ade4-77d8826fc290";
public const string PackageDisplayName = "IntelliSense Tweaks";
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
/// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
/// <param name="progress">A provider for progress updates.</param>
/// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
Instance = this;
// When initialized asynchronously, the current thread may be a background thread at this point.
// Do any initialization that requires the UI thread after switching to the UI thread.
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
}
public static VSIntelliSenseTweaksPackage Instance;
public static | GeneralSettings Settings
{ |
get
{
Debug.Assert(Instance != null);
return (GeneralSettings)Instance.GetDialogPage(typeof(GeneralSettings));
}
}
public static void EnsurePackageLoaded()
{
ThreadHelper.ThrowIfNotOnUIThread();
if (Instance == null)
{
var vsShell = (IVsShell)ServiceProvider.GlobalProvider.GetService(typeof(IVsShell));
Assumes.Present(vsShell);
var guid = new Guid(VSIntelliSenseTweaksPackage.PackageGuidString);
vsShell.LoadPackage(ref guid, out var package);
Debug.Assert(Instance != null);
}
}
#endregion
}
}
| VSIntelliSenseTweaks/VSIntelliSenseTweaksPackage.cs | cfognom-VSIntelliSenseTweaks-4099741 | [
{
"filename": "VSIntelliSenseTweaks/MultiSelectionCompletionHandler.cs",
"retrieved_chunk": " var trigger = new CompletionTrigger(CompletionTriggerReason.InvokeAndCommitIfUnique, textBuffer.CurrentSnapshot);\n for (int i = 0; i < n_selections; i++)\n {\n var selection = selections[i];\n // Triggering a completion session only works when there is one selection.\n // So we have to make a hack where try each selection one at a time and then\n // patch up all other selections once an item was committed.\n selectionBroker.SetSelection(selection);\n var triggerPoint = selection.InsertionPoint.Position;\n var potentialSession = completionBroker.TriggerCompletion(textView, trigger, triggerPoint, CancellationToken.None);",
"score": 0.8197135925292969
},
{
"filename": "VSIntelliSenseTweaks/MultiSelectionCompletionHandler.cs",
"retrieved_chunk": " if (potentialSession == null)\n continue;\n potentialSession.OpenOrUpdate(trigger, triggerPoint, CancellationToken.None);\n var completionItems = potentialSession.GetComputedItems(CancellationToken.None); // This call dismisses the session if it is started in a bad location (in a string for example).\n if (textBuffer.CurrentSnapshot.Version != textVersion)\n {\n // For some reason the text version changed due to starting a session.\n // We have to get the updated selections.\n selections = selectionBroker.AllSelections;\n selection = selections[i];",
"score": 0.8137916326522827
},
{
"filename": "VSIntelliSenseTweaks/MultiSelectionCompletionHandler.cs",
"retrieved_chunk": " Debug.Assert(sender == selectionBroker);\n if (!selectionBroker.HasMultipleSelections)\n {\n // If we dont have multiSelections anymore it is likely the user committed an item and a bug set the selections to one.\n return;\n }\n currentSelections = selectionBroker.AllSelections;\n currentPrimarySelection = selectionBroker.PrimarySelection;\n }\n private void AfterTextBufferChanged(object sender, TextContentChangedEventArgs e)",
"score": 0.8109451532363892
},
{
"filename": "VSIntelliSenseTweaks/CompletionItemManager.cs",
"retrieved_chunk": " filters: filterStates,\n selectionHint: selectionKind,\n centerSelection: false,\n uniqueItem: null\n );\n Debug.Assert(!cancellationToken.IsCancellationRequested);\n return result;\n bool ShouldDismiss()\n {\n // Dismisses if first char in pattern is a number and not after a '.'.",
"score": 0.809931218624115
},
{
"filename": "VSIntelliSenseTweaks/CompletionItemManager.cs",
"retrieved_chunk": " whitelist.SetBit(i);\n break;\n default: throw new Exception();\n }\n }\n CompletionFilterKind GetFilterKind(int index, CompletionFilter filter)\n {\n // Is there a safer rule to determine what kind of filter it is?\n return index == 0 ? CompletionFilterKind.Blacklist : CompletionFilterKind.Whitelist;\n }",
"score": 0.8025509119033813
}
] | csharp | GeneralSettings Settings
{ |
/*
Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox')
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Kingdox.UniFlux
{
///<summary>
/// static class that ensure to handle the FluxAttribute
///</summary>
internal static class MonoFluxExtension
{
internal static readonly BindingFlags m_bindingflag_all = (BindingFlags)(-1);
//
internal static readonly Type m_type_monoflux = typeof(MonoFlux);
//
internal static readonly Type m_type_flux = typeof(Core.Internal.Flux<>);
internal static readonly Type m_type_flux_delegate = typeof(Action);
internal static readonly string m_type_flux_method = nameof(Core.Internal.Flux<object>.Store);
//
internal static readonly Type m_type_fluxparam = typeof(Core.Internal.FluxParam<,>);
internal static readonly Type m_type_fluxparam_delegate = typeof(Action<>);
internal static readonly string m_type_fluxparam_method = nameof(Core.Internal.FluxParam<object,object>.Store);
//
internal static readonly Type m_type_fluxreturn = typeof(Core.Internal.FluxReturn<,>);
internal static readonly Type m_type_fluxreturn_delegate = typeof(Func<>);
internal static readonly string m_type_fluxreturn_method = nameof(Core.Internal.FluxReturn<object,object>.Store);
//
internal static readonly Type m_type_fluxparamreturn = typeof(Core.Internal.FluxParamReturn<,,>);
internal static readonly Type m_type_fluxparamreturn_delegate = typeof(Func<,>);
internal static readonly string m_type_fluxparamreturn_method = nameof(Core.Internal.FluxParamReturn<object,object,object>.Store);
//
///<summary>
/// typeof(void)
///</summary>
internal static readonly Type m_type_void = typeof(void);
///<summary>
/// Dictionary to cache each MonoFlux instance's methods
///</summary>
internal static readonly Dictionary<MonoFlux, List<MethodInfo>> m_monofluxes = new Dictionary<MonoFlux, List<MethodInfo>>();
///<summary>
/// Dictionary to cache the FluxAttribute of each MethodInfo
///</summary>
internal static readonly Dictionary<MethodInfo, | FluxAttribute> m_methods = new Dictionary<MethodInfo, FluxAttribute>(); |
///<summary>
/// Allows subscribe methods using `FluxAttribute` by reflection
/// ~ where magic happens ~
///</summary>
internal static void Subscribe(this MonoFlux monoflux, in bool condition)
{
if (!m_monofluxes.ContainsKey(monoflux))
{
m_monofluxes.Add(
monoflux,
monoflux.gameObject.GetComponent(m_type_monoflux).GetType().GetMethods(m_bindingflag_all).Where(method =>
{
if(System.Attribute.GetCustomAttributes(method).FirstOrDefault((_att) => _att is FluxAttribute) is FluxAttribute _attribute)
{
if(!m_methods.ContainsKey(method)) m_methods.Add(method, _attribute); // ADD <Method, Attribute>!
return true;
}
else return false;
}).ToList()
);
}
//
List<MethodInfo> methods = m_monofluxes[monoflux];
//
for (int i = 0; i < methods.Count; i++)
{
var _Parameters = methods[i].GetParameters();
#if UNITY_EDITOR
if(_Parameters.Length > 1) // Auth Params is 0 or 1
{
throw new System.Exception($"Error '{methods[i].Name}' : Theres more than one parameter, please set 1 or 0 parameter. (if you need to add more than 1 argument use Tuples or create a struct, record o class...)");
}
#endif
switch ((_Parameters.Length.Equals(1), !methods[i].ReturnType.Equals(m_type_void)))
{
case (false, false): // Flux
m_type_flux
.MakeGenericType(m_methods[methods[i]].key.GetType())
.GetMethod(m_type_flux_method, m_bindingflag_all)
.Invoke( null, new object[]{ m_methods[methods[i]].key, methods[i].CreateDelegate(m_type_flux_delegate, monoflux), condition})
;
break;
case (true, false): // FluxParam
m_type_fluxparam
.MakeGenericType(m_methods[methods[i]].key.GetType(), _Parameters[0].ParameterType)
.GetMethod(m_type_fluxparam_method, m_bindingflag_all)
.Invoke( null, new object[]{ m_methods[methods[i]].key, methods[i].CreateDelegate(m_type_fluxparam_delegate.MakeGenericType(_Parameters[0].ParameterType), monoflux), condition})
;
break;
case (false, true): //FluxReturn
m_type_fluxreturn
.MakeGenericType(m_methods[methods[i]].key.GetType(), methods[i].ReturnType)
.GetMethod(m_type_fluxreturn_method, m_bindingflag_all)
.Invoke( null, new object[]{ m_methods[methods[i]].key, methods[i].CreateDelegate(m_type_fluxreturn_delegate.MakeGenericType(methods[i].ReturnType), monoflux), condition})
;
break;
case (true, true): //FluxParamReturn
m_type_fluxparamreturn
.MakeGenericType(m_methods[methods[i]].key.GetType(), _Parameters[0].ParameterType, methods[i].ReturnType)
.GetMethod(m_type_fluxparamreturn_method, m_bindingflag_all)
.Invoke( null, new object[]{ m_methods[methods[i]].key, methods[i].CreateDelegate(m_type_fluxparamreturn_delegate.MakeGenericType(_Parameters[0].ParameterType, methods[i].ReturnType), monoflux), condition})
;
break;
}
}
}
// internal static void Subscribe_v2(this MonoFlux monoflux, in bool condition)
// {
// var methods = new List<(MethodInfo Method, FluxAttribute Attribute)>();
// var methods_raw = monoflux.GetType().GetMethods(m_bindingflag_all);
// foreach (var method in methods_raw)
// {
// var attribute = method.GetCustomAttribute<FluxAttribute>();
// if (attribute != null)
// {
// #if UNITY_EDITOR
// if (method.GetParameters().Length > 1)
// {
// throw new System.Exception($"Error '{method.Name}' : Theres more than one parameter, please set 1 or 0 parameter. (if you need to add more than 1 argument use Tuples or create a struct, record o class...)");
// }
// #endif
// methods.Add((method, attribute));
// }
// }
// foreach (var (method, attribute) in methods)
// {
// var parameters = method.GetParameters();
// var returnType = method.ReturnType;
// switch ((parameters.Length == 1, returnType != m_type_void))
// {
// case (false, false):
// m_type_flux.MakeGenericType(attribute.key.GetType())
// .GetMethod(m_type_flux_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_flux_delegate, monoflux, method), condition });
// break;
// case (true, false):
// m_type_fluxparam.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType)
// .GetMethod(m_type_fluxparam_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxparam_delegate.MakeGenericType(parameters[0].ParameterType), monoflux, method), condition });
// break;
// case (false, true):
// m_type_fluxreturn.MakeGenericType(attribute.key.GetType(), returnType)
// .GetMethod(m_type_fluxreturn_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxreturn_delegate.MakeGenericType(returnType), monoflux, method), condition });
// break;
// case (true, true):
// m_type_fluxparamreturn.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType, returnType)
// .GetMethod(m_type_fluxparamreturn_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxparamreturn_delegate.MakeGenericType(parameters[0].ParameterType, returnType), monoflux, method), condition });
// break;
// }
// }
// }
// internal static void Subscribe_v3(this MonoFlux monoflux, in bool condition)
// {
// var methods_raw = monoflux.GetType().GetMethods(m_bindingflag_all);
// var methods = new (MethodInfo Method, FluxAttribute Attribute)[methods_raw.Length];
// var method_count = 0;
// for (int i = 0; i < methods_raw.Length; i++)
// {
// var attribute = methods_raw[i].GetCustomAttribute<FluxAttribute>();
// if (attribute != null)
// {
// #if UNITY_EDITOR
// if (methods_raw[i].GetParameters().Length > 1) throw new System.Exception($"Error '{methods_raw[i].Name}' : Theres more than one parameter, please set 1 or 0 parameter. (if you need to add more than 1 argument use Tuples or create a struct, record o class...)");
// #endif
// methods[method_count++] = (methods_raw[i], attribute);
// }
// }
// for (int i = 0; i < method_count; i++)
// {
// var method = methods[i].Method;
// var attribute = methods[i].Attribute;
// var parameters = method.GetParameters();
// var returnType = method.ReturnType;
// switch ((parameters.Length == 1, returnType != m_type_void))
// {
// case (false, false):
// m_type_flux.MakeGenericType(attribute.key.GetType())
// .GetMethod(m_type_flux_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_flux_delegate, monoflux, method), condition }.ToArray());
// break;
// case (true, false):
// m_type_fluxparam.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType)
// .GetMethod(m_type_fluxparam_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxparam_delegate.MakeGenericType(parameters[0].ParameterType), monoflux, method), condition }.ToArray());
// break;
// case (false, true):
// m_type_fluxreturn.MakeGenericType(attribute.key.GetType(), returnType)
// .GetMethod(m_type_fluxreturn_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxreturn_delegate.MakeGenericType(returnType), monoflux, method), condition }.ToArray());
// break;
// case (true, true):
// m_type_fluxparamreturn.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType, returnType)
// .GetMethod(m_type_fluxparamreturn_method, m_bindingflag_all)
// .Invoke(null, new object[] { attribute.key, Delegate.CreateDelegate(m_type_fluxparamreturn_delegate.MakeGenericType(parameters[0].ParameterType, returnType), monoflux, method), condition }.ToArray());
// break;
// }
// }
// }
// internal static void Subscribe_v4(this MonoFlux monoflux, in bool condition)
// {
// var methods_raw = monoflux.GetType().GetMethods(m_bindingflag_all);
// var methods = new (MethodInfo Method, FluxAttribute Attribute)[methods_raw.Length];
// var method_count = 0;
// for (int i = 0; i < methods_raw.Length; i++)
// {
// var attribute = methods_raw[i].GetCustomAttribute<FluxAttribute>();
// if (attribute != null)
// {
// methods[method_count++] = (methods_raw[i], attribute);
// }
// }
// for (int i = 0; i < method_count; i++)
// {
// var method = methods[i].Method;
// var attribute = methods[i].Attribute;
// var parameters = method.GetParameters();
// var returnType = method.ReturnType;
// switch ((parameters.Length == 1, returnType != m_type_void))
// {
// case (false, false):
// var genericType = m_type_flux.MakeGenericType(attribute.key.GetType());
// var methodInfo = genericType.GetMethod(m_type_flux_method, m_bindingflag_all);
// var delegateType = m_type_flux_delegate;
// var delegateMethod = Delegate.CreateDelegate(delegateType, monoflux, method);
// var arguments = new object[] { attribute.key, delegateMethod, condition };
// methodInfo.Invoke(null, arguments);
// break;
// case (true, false):
// genericType = m_type_fluxparam.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType);
// methodInfo = genericType.GetMethod(m_type_fluxparam_method, m_bindingflag_all);
// delegateType = m_type_fluxparam_delegate.MakeGenericType(parameters[0].ParameterType);
// delegateMethod = Delegate.CreateDelegate(delegateType, monoflux, method);
// arguments = new object[] { attribute.key, delegateMethod, condition };
// methodInfo.Invoke(null, arguments);
// break;
// case (false, true):
// genericType = m_type_fluxreturn.MakeGenericType(attribute.key.GetType(), returnType);
// methodInfo = genericType.GetMethod(m_type_fluxreturn_method, m_bindingflag_all);
// delegateType = m_type_fluxreturn_delegate.MakeGenericType(returnType);
// delegateMethod = Delegate.CreateDelegate(delegateType, monoflux, method);
// arguments = new object[] { attribute.key, delegateMethod, condition };
// methodInfo.Invoke(null, arguments);
// break;
// case (true, true):
// genericType = m_type_fluxparamreturn.MakeGenericType(attribute.key.GetType(), parameters[0].ParameterType, returnType);
// methodInfo = genericType.GetMethod(m_type_fluxparamreturn_method, m_bindingflag_all);
// delegateType = m_type_fluxparamreturn_delegate.MakeGenericType(parameters[0].ParameterType, returnType);
// delegateMethod = Delegate.CreateDelegate(delegateType, monoflux, method);
// arguments = new object[] { attribute.key, delegateMethod, condition };
// methodInfo.Invoke(null, arguments);
// break;
// }
// }
// }
}
} | Runtime/MonoFluxExtension.cs | xavierarpa-UniFlux-a2d46de | [
{
"filename": "Runtime/Core/Internal/Flux_T.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux Action\n ///</summary>\n internal static class Flux<T> //(T, Action)\n {\n ///<summary>\n /// Defines a static instance of ActionFlux<T>\n ///</summary>\n internal static readonly IFlux<T, Action> flux_action = new ActionFlux<T>();",
"score": 0.8228046298027039
},
{
"filename": "Runtime/Core/Internal/FluxParam_T_T2.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux<T> Action<T2>\n ///</summary>\n internal static class FluxParam<T,T2> // (T, Action<T2>)\n {\n ///<summary>\n /// Defines a static instance of ActionFluxParam<T, T2>\n ///</summary>\n internal static readonly IFluxParam<T, T2, Action<T2>> flux_action_param = new ActionFluxParam<T,T2>();",
"score": 0.7945641875267029
},
{
"filename": "Runtime/Core/Internal/FluxReturn_T_T2.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux<T> Func<out T2>\n ///</summary>\n internal static class FluxReturn<T,T2> // (T, Func<out T2>)\n {\n ///<summary>\n /// Defines a static instance of FuncFlux<T,T2>\n ///</summary>\n internal static readonly IFluxReturn<T, T2, Func<T2>> flux_func = new FuncFlux<T,T2>();",
"score": 0.790158748626709
},
{
"filename": "Runtime/Core/Internal/FluxParamReturn_T_T2_T3.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux<T> Func<T2, out T3>\n ///</summary>\n internal static class FluxParamReturn<T,T2,T3> // (T, Func<T2, out T3>)\n {\n ///<summary>\n /// Defines a static instance of FuncFluxParam<T, T2, T3>\n ///</summary>\n internal static readonly IFluxParamReturn<T, T2, T3, Func<T2,T3>> flux_func_param = new FuncFluxParam<T, T2, T3>();",
"score": 0.780022382736206
},
{
"filename": "Runtime/Core/Internal/ActionFluxParam.cs",
"retrieved_chunk": "namespace Kingdox.UniFlux.Core.Internal\n{\n ///<summary>\n /// This class represents an implementation of an IFlux interface with a TKey key and an action without parameters.\n ///</summary>\n internal sealed class ActionFluxParam<TKey, TValue> : IFluxParam<TKey, TValue, Action<TValue>>\n {\n /// <summary>\n /// A dictionary that stores functions with parameters\n /// </summary>",
"score": 0.7569762468338013
}
] | csharp | FluxAttribute> m_methods = new Dictionary<MethodInfo, FluxAttribute>(); |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace csharp_test_client
{
public partial class mainForm
{
Dictionary<PACKET_ID, Action<byte[]>> PacketFuncDic = new Dictionary<PACKET_ID, Action<byte[]>>();
void SetPacketHandler()
{
PacketFuncDic.Add(PACKET_ID.DEV_ECHO, PacketProcess_DevEcho);
PacketFuncDic.Add(PACKET_ID.LOGIN_RES, PacketProcess_LoginResponse);
PacketFuncDic.Add(PACKET_ID.ROOM_ENTER_RES, PacketProcess_RoomEnterResponse);
PacketFuncDic.Add(PACKET_ID.ROOM_USER_LIST_NTF, PacketProcess_RoomUserListNotify);
PacketFuncDic.Add(PACKET_ID.ROOM_NEW_USER_NTF, PacketProcess_RoomNewUserNotify);
PacketFuncDic.Add(PACKET_ID.ROOM_LEAVE_RES, PacketProcess_RoomLeaveResponse);
PacketFuncDic.Add(PACKET_ID.ROOM_LEAVE_USER_NTF, PacketProcess_RoomLeaveUserNotify);
PacketFuncDic.Add(PACKET_ID.ROOM_CHAT_RES, PacketProcess_RoomChatResponse);
PacketFuncDic.Add(PACKET_ID.ROOM_CHAT_NOTIFY, PacketProcess_RoomChatNotify);
}
void PacketProcess( | PacketData packet)
{ |
var packetType = (PACKET_ID)packet.PacketID;
//DevLog.Write("Packet Error: PacketID:{packet.PacketID.ToString()}, Error: {(ERROR_CODE)packet.Result}");
//DevLog.Write("RawPacket: " + packet.PacketID.ToString() + ", " + PacketDump.Bytes(packet.BodyData));
if (PacketFuncDic.ContainsKey(packetType))
{
PacketFuncDic[packetType](packet.BodyData);
}
else
{
DevLog.Write("Unknown Packet Id: " + packet.PacketID.ToString());
}
}
void PacketProcess_DevEcho(byte[] bodyData)
{
DevLog.Write($"Echo: {Encoding.UTF8.GetString(bodyData)}");
}
void PacketProcess_LoginResponse(byte[] bodyData)
{
var responsePkt = new LoginResPacket();
responsePkt.FromBytes(bodyData);
DevLog.Write($"로그인 결과: {(ERROR_CODE)responsePkt.Result}");
}
void PacketProcess_RoomEnterResponse(byte[] bodyData)
{
var responsePkt = new RoomEnterResPacket();
responsePkt.FromBytes(bodyData);
DevLog.Write($"방 입장 결과: {(ERROR_CODE)responsePkt.Result}");
}
void PacketProcess_RoomUserListNotify(byte[] bodyData)
{
var notifyPkt = new RoomUserListNtfPacket();
notifyPkt.FromBytes(bodyData);
for (int i = 0; i < notifyPkt.UserCount; ++i)
{
AddRoomUserList(notifyPkt.UserUniqueIdList[i], notifyPkt.UserIDList[i]);
}
DevLog.Write($"방의 기존 유저 리스트 받음");
}
void PacketProcess_RoomNewUserNotify(byte[] bodyData)
{
var notifyPkt = new RoomNewUserNtfPacket();
notifyPkt.FromBytes(bodyData);
AddRoomUserList(notifyPkt.UserUniqueId, notifyPkt.UserID);
DevLog.Write($"방에 새로 들어온 유저 받음");
}
void PacketProcess_RoomLeaveResponse(byte[] bodyData)
{
var responsePkt = new RoomLeaveResPacket();
responsePkt.FromBytes(bodyData);
DevLog.Write($"방 나가기 결과: {(ERROR_CODE)responsePkt.Result}");
}
void PacketProcess_RoomLeaveUserNotify(byte[] bodyData)
{
var notifyPkt = new RoomLeaveUserNtfPacket();
notifyPkt.FromBytes(bodyData);
RemoveRoomUserList(notifyPkt.UserUniqueId);
DevLog.Write($"방에서 나간 유저 받음");
}
void PacketProcess_RoomChatResponse(byte[] bodyData)
{
var responsePkt = new RoomChatResPacket();
responsePkt.FromBytes(bodyData);
var errorCode = (ERROR_CODE)responsePkt.Result;
var msg = $"방 채팅 요청 결과: {(ERROR_CODE)responsePkt.Result}";
if (errorCode == ERROR_CODE.ERROR_NONE)
{
DevLog.Write(msg, LOG_LEVEL.ERROR);
}
else
{
AddRoomChatMessageList("", msg);
}
}
void PacketProcess_RoomChatNotify(byte[] bodyData)
{
var responsePkt = new RoomChatNtfPacket();
responsePkt.FromBytes(bodyData);
AddRoomChatMessageList(responsePkt.UserID, responsePkt.Message);
}
void AddRoomChatMessageList(string userID, string msgssage)
{
var msg = $"{userID}: {msgssage}";
if (listBoxRoomChatMsg.Items.Count > 512)
{
listBoxRoomChatMsg.Items.Clear();
}
listBoxRoomChatMsg.Items.Add(msg);
listBoxRoomChatMsg.SelectedIndex = listBoxRoomChatMsg.Items.Count - 1;
}
void PacketProcess_RoomRelayNotify(byte[] bodyData)
{
var notifyPkt = new RoomRelayNtfPacket();
notifyPkt.FromBytes(bodyData);
var stringData = Encoding.UTF8.GetString(notifyPkt.RelayData);
DevLog.Write($"방에서 릴레이 받음. {notifyPkt.UserUniqueId} - {stringData}");
}
}
}
| cpp/Demo_2020-02-15/Client/PacketProcessForm.cs | jacking75-how_to_use_redis_lib-d3accba | [
{
"filename": "cpp/Demo_2020-02-15/Client/mainForm.cs",
"retrieved_chunk": " var requestPkt = new RoomEnterReqPacket();\n requestPkt.SetValue(textBoxRoomNumber.Text.ToInt32());\n PostSendPacket(PACKET_ID.ROOM_ENTER_REQ, requestPkt.ToBytes());\n DevLog.Write($\"방 입장 요청: {textBoxRoomNumber.Text} 번\");\n }\n private void btn_RoomLeave_Click(object sender, EventArgs e)\n {\n PostSendPacket(PACKET_ID.ROOM_LEAVE_REQ, null);\n DevLog.Write($\"방 입장 요청: {textBoxRoomNumber.Text} 번\");\n }",
"score": 0.7414976358413696
},
{
"filename": "cpp/Demo_2020-02-15/Client/mainForm.Designer.cs",
"retrieved_chunk": " this.button2.UseVisualStyleBackColor = true;\n this.button2.Click += new System.EventHandler(this.button2_Click);\n // \n // Room\n // \n this.Room.Controls.Add(this.textBoxRelay);\n this.Room.Controls.Add(this.btnRoomRelay);\n this.Room.Controls.Add(this.btnRoomChat);\n this.Room.Controls.Add(this.textBoxRoomSendMsg);\n this.Room.Controls.Add(this.listBoxRoomChatMsg);",
"score": 0.7106717824935913
},
{
"filename": "cpp/Demo_2020-02-15/Client/Packet.cs",
"retrieved_chunk": " {\n UserID = Encoding.UTF8.GetString(bodyData, 0, PacketDef.MAX_USER_ID_BYTE_LENGTH);\n UserID = UserID.Trim();\n Message = Encoding.UTF8.GetString(bodyData, PacketDef.MAX_USER_ID_BYTE_LENGTH, PacketDef.MAX_CHAT_MSG_SIZE);\n Message = Message.Trim();\n return true;\n }\n }\n public class RoomLeaveResPacket\n {",
"score": 0.6968920230865479
},
{
"filename": "cpp/Demo_2020-02-15/Client/PacketDefine.cs",
"retrieved_chunk": " ROOM_ENTER_REQ = 206,\n ROOM_ENTER_RES = 207, \n ROOM_NEW_USER_NTF = 208,\n ROOM_USER_LIST_NTF = 209,\n ROOM_LEAVE_REQ = 215,\n ROOM_LEAVE_RES = 216,\n ROOM_LEAVE_USER_NTF = 217,\n ROOM_CHAT_REQ = 221,\n ROOM_CHAT_RES = 222,\n ROOM_CHAT_NOTIFY = 223,",
"score": 0.6860803365707397
},
{
"filename": "cpp/Demo_2020-02-15/Client/mainForm.cs",
"retrieved_chunk": " // 로그인 요청\n private void button2_Click(object sender, EventArgs e)\n {\n var loginReq = new LoginReqPacket();\n loginReq.SetValue(textBoxUserID.Text, textBoxUserPW.Text);\n PostSendPacket(PACKET_ID.LOGIN_REQ, loginReq.ToBytes()); \n DevLog.Write($\"로그인 요청: {textBoxUserID.Text}, {textBoxUserPW.Text}\");\n }\n private void btn_RoomEnter_Click(object sender, EventArgs e)\n {",
"score": 0.6819393634796143
}
] | csharp | PacketData packet)
{ |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using AssemblyCacheHelper.DTO;
namespace AssemblyCacheExplorer
{
public partial class AssemblyProperties : Form
{
public | NetAssembly NetAssemblyProperties { | get; set; }
public AssemblyProperties()
{
InitializeComponent();
}
private void AssemblyProperties_Load(object sender, EventArgs e)
{
string imageRuntimeVersion = AssemblyCacheHelper.NetAssemblies.GetImageRuntimeVersion(NetAssemblyProperties.AssemblyFilename);
lblAssemblyNameValue.Text = NetAssemblyProperties.AssemblyName;
lblAssemblyVersionValue.Text = NetAssemblyProperties.AssemblyVersion;
lblCultureValue.Text = NetAssemblyProperties.Culture;
lblPublicKeyTokenValue.Text = NetAssemblyProperties.PublicKeyToken;
lblProcesorArchitectureValue.Text = NetAssemblyProperties.ProcessorArchitecture;
lblRuntimeVersionValue.Text = (imageRuntimeVersion != "") ? String.Format("{0} ({1})", NetAssemblyProperties.RuntimeVersion, imageRuntimeVersion) : NetAssemblyProperties.RuntimeVersion;
lblModifiedDateValue.Text = NetAssemblyProperties.ModifiedDate;
lblFileSizeValue.Text = NetAssemblyProperties.FileSize;
lblAssemblyFilenameValue.Text = Path.GetFileName(NetAssemblyProperties.AssemblyFilename);
lblFileVersionValue.Text = NetAssemblyProperties.FileVersion;
lblFileDescriptionValue.Text = NetAssemblyProperties.FileDescription;
lblCompanyValue.Text = NetAssemblyProperties.Company;
lblProductNameValue.Text = NetAssemblyProperties.ProductName;
}
private void btnOK_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
| AssemblyCacheExplorer/AssemblyProperties.cs | peterbaccaro-assembly-cache-explorer-a5dae15 | [
{
"filename": "AssemblyCacheExplorer/AssemblyCacheExplorer.cs",
"retrieved_chunk": "using System.Configuration;\nusing System.Reflection;\nusing System.IO;\nusing AssemblyCacheHelper;\nusing AssemblyCacheHelper.DTO;\nusing AssemblyCacheExplorer.ListView;\nnamespace AssemblyCacheExplorer\n{\n public partial class AssemblyCacheExplorer : Form\n {",
"score": 0.912053108215332
},
{
"filename": "AssemblyCacheHelper/DTO/NetAssemblyFile.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace AssemblyCacheHelper.DTO\n{\n public class NetAssemblyFile\n {\n public string AssemblyFilename { get; set; }\n public string RuntimeVersion { get; set; } ",
"score": 0.8970538377761841
},
{
"filename": "AssemblyCacheHelper/DTO/NetAssembly.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace AssemblyCacheHelper.DTO\n{\n public class NetAssembly\n {\n public string AssemblyName { get; set; }\n public string AssemblyFullName { get; set; }",
"score": 0.8889633417129517
},
{
"filename": "AssemblyCacheHelper/GACUtil.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace AssemblyCacheHelper\n{\n public class GACUtil\n {\n public static string AssemblyInstall(string gacUtilFullPath, string assemblyFullPath, bool force)\n {",
"score": 0.8707677721977234
},
{
"filename": "AssemblyCacheHelper/Serialization.cs",
"retrieved_chunk": "using System;\nusing System.IO;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Serialization;\nnamespace AssemblyCacheHelper\n{\n public class Serialization\n {\n public static T DeserializeObject<T>(string xml)",
"score": 0.8654162287712097
}
] | csharp | NetAssembly NetAssemblyProperties { |
/*
Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox')
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace Kingdox.UniFlux.Core.Internal
{
/// <summary>
/// The `FuncFlux` class represents a flux that stores functions with no parameters and a return value of type `TReturn`.
/// It provides a dictionary to store the functions and methods to subscribe and trigger the stored functions.
/// </summary>
/// <typeparam name="TKey">The type of the keys used to store the functions in the dictionary.</typeparam>
/// <typeparam name="TReturn">The return type of the functions stored in the dictionary.</typeparam>
internal sealed class FuncFlux<TKey, TReturn> : | IFluxReturn<TKey, TReturn, Func<TReturn>>
{ |
/// <summary>
/// A dictionary that stores functions with no parameters and a return value of type `TReturn`.
/// </summary>
internal readonly Dictionary<TKey, Func<TReturn>> dictionary = new Dictionary<TKey, Func<TReturn>>();
/// <summary>
/// Subscribes the provided function to the dictionary with the specified key when `condition` is true.
/// If `condition` is false and the dictionary contains the specified key, the function is removed from the dictionary.
/// </summary>
void IStore<TKey, Func<TReturn>>.Store(in bool condition, TKey key, Func<TReturn> func)
{
if(dictionary.TryGetValue(key, out var values))
{
if (condition) dictionary[key] += func;
else
{
values -= func;
if (values is null) dictionary.Remove(key);
else dictionary[key] = values;
}
}
else if (condition) dictionary.Add(key, func);
}
// <summary>
/// Triggers the function stored in the dictionary with the specified key and returns its return value.
/// If the dictionary does not contain the specified key, returns the default value of type `TReturn`.
/// </summary>
TReturn IFluxReturn<TKey, TReturn, Func<TReturn>>.Dispatch(TKey key)
{
if(dictionary.TryGetValue(key, out var _actions))
{
return _actions.Invoke();
}
return default;
}
}
} | Runtime/Core/Internal/FuncFlux.cs | xavierarpa-UniFlux-a2d46de | [
{
"filename": "Runtime/Core/Internal/FuncFluxParam.cs",
"retrieved_chunk": "namespace Kingdox.UniFlux.Core.Internal\n{\n /// <summary>\n /// The `FuncFluxParam` class represents a flux that stores functions with one parameter of type `TParam` and a return value of type `TReturn`.\n /// It provides a dictionary to store the functions and methods to subscribe and trigger the stored functions.\n /// </summary>\n /// <typeparam name=\"TKey\">The type of the keys used to store the functions in the dictionary.</typeparam>\n /// <typeparam name=\"TParam\">The type of the parameter passed to the functions stored in the dictionary.</typeparam>\n /// <typeparam name=\"TReturn\">The return type of the functions stored in the dictionary.</typeparam>\n internal sealed class FuncFluxParam<TKey, TParam, TReturn> : IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>>",
"score": 0.9737309813499451
},
{
"filename": "Runtime/Core/Internal/FuncFluxParam.cs",
"retrieved_chunk": " {\n /// <summary>\n /// A dictionary that stores functions with one parameter of type `TParam` and a return value of type `TReturn`.\n /// </summary>\n internal readonly Dictionary<TKey, Func<TParam, TReturn>> dictionary = new Dictionary<TKey, Func<TParam, TReturn>>();\n /// <summary>\n /// Subscribes the provided function to the dictionary with the specified key when `condition` is true. \n /// If `condition` is false and the dictionary contains the specified key, the function is removed from the dictionary.\n /// </summary>\n void IStore<TKey, Func<TParam, TReturn>>.Store(in bool condition, TKey key, Func<TParam, TReturn> func)",
"score": 0.9129353761672974
},
{
"filename": "Runtime/Core/Internal/ActionFluxParam.cs",
"retrieved_chunk": "namespace Kingdox.UniFlux.Core.Internal\n{\n ///<summary>\n /// This class represents an implementation of an IFlux interface with a TKey key and an action without parameters.\n ///</summary>\n internal sealed class ActionFluxParam<TKey, TValue> : IFluxParam<TKey, TValue, Action<TValue>>\n {\n /// <summary>\n /// A dictionary that stores functions with parameters\n /// </summary>",
"score": 0.8990321755409241
},
{
"filename": "Runtime/Core/Internal/ActionFlux.cs",
"retrieved_chunk": "namespace Kingdox.UniFlux.Core.Internal\n{\n ///<summary>\n /// This class represents an implementation of an IFlux interface with a TKey key and an action without parameters.\n ///</summary>\n internal sealed class ActionFlux<TKey> : IFlux<TKey, Action>\n {\n /// <summary>\n /// A dictionary that stores functions with no parameters\n /// </summary>",
"score": 0.8935495018959045
},
{
"filename": "Runtime/Core/Internal/FuncFluxParam.cs",
"retrieved_chunk": " }\n else if (condition) dictionary.Add(key, func);\n }\n /// <summary>\n /// Triggers the function stored in the dictionary with the specified key and parameter, and returns its return value. \n /// If the dictionary does not contain the specified key, returns the default value of type `TReturn`.\n /// </summary>\n TReturn IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>>.Dispatch(TKey key, TParam param)\n {\n if(dictionary.TryGetValue(key, out var _actions))",
"score": 0.890709638595581
}
] | csharp | IFluxReturn<TKey, TReturn, Func<TReturn>>
{ |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XiaoFeng;
using XiaoFeng.Http;
using FayElf.Plugins.WeChat.OfficialAccount.Model;
/****************************************************************
* Copyright © (2022) www.fayelf.com All Rights Reserved. *
* Author : jacky *
* QQ : 7092734 *
* Email : [email protected] *
* Site : www.fayelf.com *
* Create Time : 2022-03-16 14:32:27 *
* Version : v 1.0.0 *
* CLR Version : 4.0.30319.42000 *
*****************************************************************/
namespace FayElf.Plugins.WeChat.OfficialAccount
{
/// <summary>
/// 对应微信API的 "用户管理"=> "网页授权获取用户基本信息”
/// http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
/// </summary>
public class OAuthAPI
{
#region 构造器
/// <summary>
/// 无参构造器
/// </summary>
public OAuthAPI()
{
}
#endregion
#region 属性
#endregion
#region 方法
#region 通过code换取网页授权access_token
/// <summary>
/// 通过code换取网页授权access_token
/// </summary>
/// <param name="appID">公众号的唯一标识</param>
/// <param name="appSecret">公众号的appsecret</param>
/// <param name="code">填写第一步获取的code参数</param>
/// <returns></returns>
public static AccessTokenModel GetAccessToken(string appID, string appSecret, string code)
{
var AccessToken = XiaoFeng.Cache.CacheHelper.Get<AccessTokenModel>("AccessTokenModel" + appID);
if (AccessToken.IsNotNullOrEmpty())
{
if (AccessToken.ExpiresIn <= 60)
{
return RefreshAccessToken(appID, AccessToken.RefreshToken);
}
return AccessToken;
}
var result = HttpHelper.GetHtml(new HttpRequest
{
Method = HttpMethod.Get,
Address = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appID}&secret={appSecret}&code={code}&grant_type=authorization_code"
});
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
return result.Html.JsonToObject<AccessTokenModel>();
}
else
{
return new AccessTokenModel
{
ErrMsg = "请求出错.",
ErrCode = 500
};
}
}
#endregion
#region 刷新access_token
/// <summary>
/// 刷新access_token
/// </summary>
/// <param name="appID">公众号的唯一标识</param>
/// <param name="refreshtoken">填写为refresh_token</param>
/// <returns></returns>
public static AccessTokenModel RefreshAccessToken(string appID, string refreshtoken)
{
var result = HttpHelper.GetHtml(new HttpRequest
{
Method = HttpMethod.Get,
Address = $"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={appID}&grant_type=refresh_token&refresh_token={refreshtoken}"
});
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
return result.Html.JsonToObject<AccessTokenModel>();
}
else
{
return new AccessTokenModel
{
ErrMsg = "请求出错.",
ErrCode = 500
};
}
}
#endregion
#region 拉取用户信息(需scope为 snsapi_userinfo)
/// <summary>
/// 拉取用户信息(需scope为 snsapi_userinfo)
/// </summary>
/// <param name="accessToken">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>
/// <param name="openId">用户的唯一标识</param>
/// <param name="lang">返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语</param>
/// <returns></returns>
public static | UserInfoModel GetUserInfo(string accessToken, string openId, string lang = "zh_CN")
{ |
var result = HttpHelper.GetHtml(new HttpRequest
{
Method = HttpMethod.Get,
Address = $"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}&lang={lang}"
});
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
return result.Html.JsonToObject<UserInfoModel>();
}
else
{
return new UserInfoModel
{
ErrMsg = "请求出错.",
ErrCode = 500
};
}
}
#endregion
#region 检验授权凭证(access_token)是否有效
/// <summary>
/// 检验授权凭证(access_token)是否有效
/// </summary>
/// <param name="accessToken">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>
/// <param name="openId">用户的唯一标识</param>
/// <returns></returns>
public static Boolean CheckAccessToken(string accessToken, string openId)
{
var result = HttpHelper.GetHtml(new HttpRequest
{
Method = HttpMethod.Get,
Address = $" https://api.weixin.qq.com/sns/auth?access_token={accessToken}&openid={openId}"
});
if (result.StatusCode == System.Net.HttpStatusCode.OK)
return result.Html.JsonToObject<BaseResult>().ErrCode == 0;
return false;
}
#endregion
#endregion
}
} | OfficialAccount/OAuthAPI.cs | zhuovi-FayElf.Plugins.WeChat-5725d1e | [
{
"filename": "OfficialAccount/Subscribe.cs",
"retrieved_chunk": " /// </summary>\n /// <param name=\"tid\">模板标题 id,可通过getPubTemplateTitleList接口获取,也可登录公众号后台查看获取</param>\n /// <param name=\"kidList\">开发者自行组合好的模板关键词列表,关键词顺序可以自由搭配(例如 [3,5,4] 或 [4,5,3]),最多支持5个,最少2个关键词组合</param>\n /// <param name=\"sceneDesc\">服务场景描述,15个字以内</param>\n /// <returns></returns>\n public AddTemplateResult AddTemplate(string tid, int kidList, string sceneDesc)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);\n return Common.Execute(config.AppID, config.AppSecret, token =>\n {",
"score": 0.8520952463150024
},
{
"filename": "Applets/Applets.cs",
"retrieved_chunk": " #region 获取小程序二维码\n /// <summary>\n /// 获取小程序二维码\n /// </summary>\n /// <param name=\"path\">扫码进入的小程序页面路径,最大长度 128 字节,不能为空;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 \"?foo=bar\",即可在 wx.getLaunchOptionsSync 接口中的 query 参数获取到 {foo:\"bar\"}。</param>\n /// <param name=\"width\">二维码的宽度,单位 px。最小 280px,最大 1280px;默认是430</param>\n /// <returns></returns>\n public QrCodeResult CreateQRCode(string path, int width)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);",
"score": 0.8326566219329834
},
{
"filename": "OfficialAccount/QRCode.cs",
"retrieved_chunk": " ErrMsg = \"请求出错.\"\n };\n }\n #endregion\n #region 通过ticket 获取二维码\n /// <summary>\n /// 通过ticket 获取二维码\n /// </summary>\n /// <param name=\"ticket\">二维码ticket</param>\n /// <returns>ticket正确情况下,http 返回码是200,是一张图片,可以直接展示或者下载。</returns>",
"score": 0.8265067934989929
},
{
"filename": "Applets/Model/UniformSendData.cs",
"retrieved_chunk": " /// </summary>\n public class UniformSendData\n {\n /// <summary>\n /// 接口调用凭证\n /// </summary>\n public string access_token { get; set; }\n /// <summary>\n /// 用户openid,可以是小程序的openid,也可以是mp_template_msg.appid对应的公众号的openid\n /// </summary>",
"score": 0.8256452083587646
},
{
"filename": "OfficialAccount/QRCode.cs",
"retrieved_chunk": " /// <param name=\"qrcodeType\">二维码类型</param>\n /// <param name=\"scene_id\">开发者自行设定的参数</param>\n /// <param name=\"seconds\">该二维码有效时间,以秒为单位。 最大不超过2592000(即30天),此字段如果不填,则默认有效期为60秒。</param>\n /// <returns></returns>\n public static QRCodeResult CreateParameterQRCode(string accessToken, QrcodeType qrcodeType, int scene_id, int seconds = 60)\n {\n var result = HttpHelper.GetHtml(new HttpRequest\n {\n Method = HttpMethod.Post,\n Address = $\"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={accessToken}\",",
"score": 0.8173716068267822
}
] | csharp | UserInfoModel GetUserInfo(string accessToken, string openId, string lang = "zh_CN")
{ |
using System.Text.Json.Serialization;
namespace BlazorApp.Models
{
/// <summary>
/// This represents the entity for authentication details.
/// </summary>
public class AuthenticationDetails
{
/// <summary>
/// Gets or sets the <see cref="Models.ClientPrincipal"/> instance.
/// </summary>
[JsonPropertyName("clientPrincipal")]
public | ClientPrincipal? ClientPrincipal { | get; set; }
}
} | src/BlazorApp/Models/AuthenticationDetails.cs | justinyoo-ms-graph-on-aswa-83b3f54 | [
{
"filename": "src/FunctionApp/Models/ClientPrincipal.cs",
"retrieved_chunk": "using Newtonsoft.Json;\nnamespace FunctionApp.Models\n{\n /// <summary>\n /// This represents the entity for the client principal.\n /// </summary>\n public class ClientPrincipal\n {\n /// <summary>\n /// Gets or sets the identity provider.",
"score": 0.9326837062835693
},
{
"filename": "src/BlazorApp/Models/ClientPrincipal.cs",
"retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace BlazorApp.Models\n{\n /// <summary>\n /// This represents the entity for the client principal.\n /// </summary>\n public class ClientPrincipal\n {\n /// <summary>\n /// Gets or sets the identity provider.",
"score": 0.9256964325904846
},
{
"filename": "src/FunctionApp/Configurations/GraphSettings.cs",
"retrieved_chunk": "namespace FunctionApp.Configurations\n{\n /// <summary>\n /// This represents the app settings entity for Microsoft Graph.\n /// </summary>\n public class GraphSettings\n {\n /// <summary>\n /// Gets the app settings name.\n /// </summary>",
"score": 0.9119866490364075
},
{
"filename": "src/BlazorApp/Models/LoggedInUserDetails.cs",
"retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace BlazorApp.Models\n{\n /// <summary>\n /// This represents the entity for the logged-in user details.\n /// </summary>\n public class LoggedInUserDetails\n {\n /// <summary>\n /// Gets or sets the UPN.",
"score": 0.9113689064979553
},
{
"filename": "src/BlazorApp/Helpers/GraphHelper.cs",
"retrieved_chunk": " /// </summary>\n public class GraphHelper : IGraphHelper\n {\n private readonly HttpClient _http;\n /// <summary>\n /// Initializes a new instance of the <see cref=\"GraphHelper\"/> class.\n /// </summary>\n /// <param name=\"httpClient\"><see cref=\"HttpClient\"/> instance.</param>\n public GraphHelper(HttpClient httpClient)\n {",
"score": 0.8923428654670715
}
] | csharp | ClientPrincipal? ClientPrincipal { |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WAGIapp.AI.AICommands
{
internal class RemoveNoteCommand : Command
{
public override string Name => "remove-note";
public override string Description => "Removes a note from the list";
public override string | Format => "remove-note | number of the note to remove"; |
public override async Task<string> Execute(Master caller, string[] args)
{
if (args.Length < 2)
return "error! not enough parameters";
if (!int.TryParse(args[1], out int number))
return "error! number could not be parsed";
if (number - 1 >= caller.Notes.Count)
return "error! number out of range";
caller.Notes.RemoveAt(number - 1);
return $"Note {number} removed";
}
}
}
| WAGIapp/AI/AICommands/RemoveNoteCommand.cs | Woltvint-WAGI-d808927 | [
{
"filename": "WAGIapp/AI/AICommands/RemoveLineCommand.cs",
"retrieved_chunk": "namespace WAGIapp.AI.AICommands\n{\n internal class RemoveLineCommand : Command\n {\n public override string Name => \"remove-line\";\n public override string Description => \"deletes a line from the script\";\n public override string Format => \"remove-line | line number\";\n public override async Task<string> Execute(Master caller, string[] args)\n {\n if (args.Length < 2)",
"score": 0.9138537049293518
},
{
"filename": "WAGIapp/AI/AICommands/WriteLineCommand.cs",
"retrieved_chunk": "namespace WAGIapp.AI.AICommands\n{\n internal class WriteLineCommand : Command\n {\n public override string Name => \"write-line\";\n public override string Description => \"writes the given text to the line number\";\n public override string Format => \"write-line | line number | text\";\n public override async Task<string> Execute(Master caller, string[] args)\n {\n if (args.Length < 3)",
"score": 0.8931201696395874
},
{
"filename": "WAGIapp/AI/AICommands/Command.cs",
"retrieved_chunk": "namespace WAGIapp.AI.AICommands\n{\n internal abstract class Command\n {\n public abstract string Name { get; }\n public abstract string Description { get; }\n public abstract string Format { get; }\n public abstract Task<string> Execute(Master caller, string[] args);\n }\n}",
"score": 0.8642517924308777
},
{
"filename": "WAGIapp/AI/AICommands/NoActionCommand.cs",
"retrieved_chunk": " public override string Name => \"no-action\";\n public override string Description => \"does nothing\";\n public override string Format => \"no-action\";\n public override async Task<string> Execute(Master caller, string[] args)\n {\n return \"command did nothing\";\n }\n }\n}",
"score": 0.8341188430786133
},
{
"filename": "WAGIapp/AI/Commands.cs",
"retrieved_chunk": "using WAGIapp.AI.AICommands;\nnamespace WAGIapp.AI\n{\n internal class Commands\n {\n private static Dictionary<string, Command> commands;\n static Commands()\n {\n commands = new Dictionary<string, Command>();\n Command c;",
"score": 0.8258518576622009
}
] | csharp | Format => "remove-note | number of the note to remove"; |
// Copyright (c) 2023, João Matos
// Check the end of the file for extended copyright notice.
using System.Net.Sockets;
using System.Text;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System;
using ProtoIP.Common;
using static ProtoIP.Packet;
namespace ProtoIP
{
public class ProtoStream
{
const int BUFFER_SIZE = Common.Network.DEFAULT_BUFFER_SIZE;
private NetworkStream _stream;
private List<Packet> _packets = new List<Packet>();
private byte[] _buffer;
private string _LastError;
/* CONSTRUCTORS */
public ProtoStream() { }
public ProtoStream(NetworkStream stream) { this._stream = stream; }
public ProtoStream(List<Packet> packets) { this._packets = packets; }
public ProtoStream(List<Packet> packets, NetworkStream stream) { this._packets = packets; this._stream = stream; }
/* PRIVATE METHODS & HELPER FUNCTIONS */
/*
* Tries to read from the stream to construct a packet
* Returns the deserialized packet
*/
private Packet receivePacket()
{
this._buffer = new byte[BUFFER_SIZE];
if (this.TryRead(this._buffer) < BUFFER_SIZE)
{
this._LastError = "Failed to receive the packet";
return null;
}
return Packet.Deserialize(this._buffer);
}
/*
* Receives an ACK packet from the peer
* Returns true if the packet was received successfully, false otherwise
*/
private bool peerReceiveAck()
{
Packet packet = this.receivePacket();
if (packet._GetType() != (int)Packet.Type.ACK)
{
this._LastError = "Invalid packet type";
return false;
}
return true;
}
/*
* Sends the ACK packet to the peer
* Returns true if the packet was sent successfully, false otherwise
*/
private bool peerSendAck()
{
Packet packet = new Packet(Packet.Type.ACK);
this._buffer = Packet.Serialize(packet);
if (this.TryWrite(this._buffer) < BUFFER_SIZE)
{
this._LastError = "Failed to send the ACK packet";
return false;
}
return true;
}
/*
* Sends the SOT packet to the peer
* Returns true if the packet was sent successfully, false otherwise
*/
private bool peerSendSot()
{
this._buffer = Packet.Serialize(new Packet(Packet.Type.SOT));
if (this.TryWrite(this._buffer) < BUFFER_SIZE)
{
this._LastError = "Failed to send the START_OF_TRANSMISSION packet";
return false;
}
return true;
}
/*
* Receives the SOT packet from the peer
* Returns true if the packet was received successfully, false otherwise
*/
private bool peerReceiveSot()
{
Packet packet = this.receivePacket();
if (packet != null && packet._GetType() != (int)Packet.Type.SOT)
{
this._LastError = "Invalid packet type";
return false;
}
return true;
}
/*
* Sends the EOT packet to the peer
* Returns true if the packet was sent successfully, false otherwise
*/
private bool peerSendEot()
{
this._buffer = Packet.Serialize(new Packet(Packet.Type.EOT));
if (this.TryWrite(this._buffer) < BUFFER_SIZE)
{
this._LastError = "Failed to send the END_OF_TRANSMISSION packet";
return false;
}
return true;
}
/*
* Receives the EOT packet from the peer
* Returns true if the packet was received successfully, false otherwise
*/
private bool peerReceiveEot()
{
Packet packet = this.receivePacket();
if (packet._GetType() != (int)Packet.Type.EOT)
{
this._LastError = "Invalid packet type";
return false;
}
return true;
}
/*
* Sends a REPEAT packet with the missing packet IDs to the peer
*/
private bool peerSendRepeat(List<int> missingPackets)
{
Packet packet = new Packet(Packet.Type.REPEAT);
byte[] payload = new byte[missingPackets.Count * sizeof(int)];
Buffer.BlockCopy(missingPackets.ToArray(), 0, payload, 0, payload.Length);
packet.SetPayload(payload);
this._buffer = Packet.Serialize(packet);
if (this.TryWrite(this._buffer) < BUFFER_SIZE)
{
this._LastError = "Failed to send the REPEAT packet";
return false;
}
return true;
}
/*
* Receives the REPEAT packet from the requesting peer
* Returns the missing packet IDs
*/
private List<int> peerReceiveRepeat()
{
Packet packet = this.receivePacket();
if (packet._GetType() != (int)Packet.Type.REPEAT)
{
this._LastError = "Invalid packet type";
return null;
}
byte[] payload = packet.GetDataAs<byte[]>();
int[] missingPackets = new int[payload.Length / sizeof(int)];
Buffer.BlockCopy(payload, 0, missingPackets, 0, payload.Length);
return new List<int>(missingPackets);
}
/*
* Resends the missing packets to the peer
*/
private bool peerResendMissingPackets(List<int> packetIDs)
{
for (int i = 0; i < packetIDs.Count; i++)
{
this._buffer = Packet.Serialize(this._packets[packetIDs[i]]);
if (this.TryWrite(this._buffer) < BUFFER_SIZE)
{
this._LastError = "Failed to send the packet " + packetIDs[i];
return false;
}
}
return true;
}
/*
* Receives the missing packets from the peer and adds them to the packet List
*/
private bool peerReceiveMissingPackets(int packetCount)
{
for (int i = 0; i < packetCount; i++)
{
this._buffer = new byte[BUFFER_SIZE];
if (this.TryRead(this._buffer) < BUFFER_SIZE)
{
this._LastError = "Failed to receive the packet " + i;
return false;
}
Packet packet = Packet.Deserialize(this._buffer);
this._packets.Add(packet);
}
return true;
}
/*
* Validate the packet List
*
* Check if there are any null packets or if there are any ID jumps
*/
private bool ValidatePackets()
{
for (int i = 0; i < this._packets.Count; i++)
{
if (this._packets[i] == null)
{
this._LastError = "Packet " + i + " is null";
return false;
}
if (this._packets[i]._GetId() != i)
{
this._LastError = "Packet " + i + " has an invalid id (Expected: " + i + ", Actual: " + this._packets[i]._GetId() + ")";
return false;
}
}
return true;
}
/*
* Returns a list with the missing packet IDs
*
* Check for any ID jumps, if there is an ID jump, add the missing IDs to the list
*/
private List<int> GetMissingPacketIDs()
{
List<int> missingPackets = new List<int>();
int lastId = 0;
foreach (Packet packet in this._packets)
{
if (packet._GetId() - lastId > 1)
{
for (int i = lastId + 1; i < packet._GetId(); i++)
{
missingPackets.Add(i);
}
}
lastId = packet._GetId();
}
return missingPackets;
}
/*
* Orders the packets by id and assembles the data buffer
*
* Allocates a buffer with the total length of the data and copies the data from the packets to the buffer
*/
private int Assemble()
{
ProtoStream.OrderPackets(this._packets);
if (!this.ValidatePackets())
{
return -1;
}
int dataLength = 0;
for (int i = 0; i < this._packets.Count; i++) { dataLength += this._packets[i].GetDataAs<byte[]>().Length; }
byte[] data = new byte[dataLength];
int dataOffset = 0;
for (int i = 0; i < this._packets.Count; i++)
{
byte[] packetData = this._packets[i].GetDataAs<byte[]>();
Array.Copy(packetData, 0, data, dataOffset, packetData.Length);
dataOffset += packetData.Length;
}
this._buffer = data;
return 0;
}
/*
* Attemps to write the data to the stream until it succeeds or the number of tries is reached
*/
private int TryWrite(byte[] data, int tries = | Network.MAX_TRIES)
{ |
int bytesWritten = 0;
while (bytesWritten < data.Length && tries > 0)
{
try
{
if (this._stream.CanWrite)
{
this._stream.Write(data, bytesWritten, data.Length - bytesWritten);
bytesWritten += data.Length - bytesWritten;
}
}
catch (Exception e)
{
tries--;
}
}
return bytesWritten;
}
/*
* Attemps to read the data from the stream until it succeeds or the number of tries is reached
*/
private int TryRead(byte[] data, int tries = Network.MAX_TRIES)
{
int bytesRead = 0;
while (bytesRead < data.Length && tries > 0)
{
try
{
if (this._stream.DataAvailable || this._stream.CanRead)
bytesRead += this._stream.Read(data, bytesRead, data.Length - bytesRead);
}
catch (Exception e)
{
tries--;
}
}
return bytesRead;
}
/*
* Partitions the data into packets and adds them to the Packet list
*/
private void Partition(byte[] data)
{
if (data.Length > (BUFFER_SIZE) - Packet.HEADER_SIZE)
{
int numPackets = (int)Math.Ceiling((double)data.Length / ((BUFFER_SIZE) - Packet.HEADER_SIZE));
int packetSize = (int)Math.Ceiling((double)data.Length / numPackets);
this._packets = new List<Packet>();
for (int i = 0; i < numPackets; i++)
{
int packetDataSize = (i == numPackets - 1) ? data.Length - (i * packetSize) : packetSize;
byte[] packetData = new byte[packetDataSize];
Array.Copy(data, i * packetSize, packetData, 0, packetDataSize);
this._packets.Add(new Packet(Packet.Type.BYTES, i, packetDataSize, packetData));
}
}
else
{
this._packets = new List<Packet>();
this._packets.Add(new Packet(Packet.Type.BYTES, 0, data.Length, data));
}
}
/* PUBLIC METHODS */
/*
* Checks if a peer is connected to the stream
*/
public bool IsConnected()
{
return this._stream != null && this._stream.CanRead && this._stream.CanWrite;
}
/*
* Transmits the data to the peer
*
* Ensures that the peer is ready to receive the data.
* Partitions the data into packets and sends them to the peer.
* Waits for the peer to acknowledge the data.
* Allows the peer to request missing packets until all the data
* has been received or the maximum number of tries has been reached.
*/
public int Transmit(byte[] data)
{
this.Partition(data);
this.peerSendSot();
if (this.peerReceiveAck() == false) { return -1; }
ProtoStream.SendPackets(this._stream, this._packets);
this.peerSendEot();
int tries = 0;
while (tries < Network.MAX_TRIES)
{
Packet response = this.receivePacket();
if (response == null) { return -1; }
if (response._GetType() == (int)Packet.Type.ACK) { break; }
else if (response._GetType() == (int)Packet.Type.REPEAT)
{
List<int> missingPacketIDs = this.peerReceiveRepeat();
if (missingPacketIDs.Any()) { this.peerResendMissingPackets(missingPacketIDs); }
else { return -1; }
}
tries++;
}
this._packets = new List<Packet>();
return 0;
}
/*
* Sends a string to the peer
*/
public int Transmit(string data)
{
return this.Transmit(Encoding.ASCII.GetBytes(data));
}
/*
* Receives data from the peer until the EOT packet is received
*/
public int Receive()
{
bool dataFullyReceived = false;
int tries = Network.MAX_TRIES;
if (this.peerReceiveSot() == false) { return -1; }
if (this.peerSendAck() == false) { return -1; }
while (true)
{
if (this.TryRead(this._buffer) < BUFFER_SIZE) { return -1; }
Packet packet = Packet.Deserialize(this._buffer);
if (packet._GetType() == (int)Packet.Type.EOT) { break; }
this._packets.Add(packet);
}
while (!dataFullyReceived && tries > 0)
{
List<int> missingPacketIDs = GetMissingPacketIDs();
if (missingPacketIDs.Count > 0)
{
this.peerSendRepeat(missingPacketIDs);
this.peerReceiveMissingPackets(missingPacketIDs.Count);
}
else
{
if (this.peerSendAck() == false) { return -1; }
dataFullyReceived = true;
}
tries--;
}
return 0;
}
// Return the assembled data as a primitive type T
public T GetDataAs<T>()
{
this.Assemble();
byte[] data = this._buffer;
// Convert the data to the specified type
switch (typeof(T).Name)
{
case "String":
return (T)(object)Encoding.ASCII.GetString(data);
case "Int32":
return (T)(object)BitConverter.ToInt32(data, 0);
case "Int64":
return (T)(object)BitConverter.ToInt64(data, 0);
case "Byte[]":
return (T)(object)data;
default:
this._LastError = "Invalid type";
return default(T);
}
}
/* STATIC METHODS */
/*
* OrderPackets
* Orders the packets by id
*/
static void OrderPackets(List<Packet> packets)
{
packets.Sort((x, y) => x._GetId().CompareTo(y._GetId()));
}
/*
* SendPackets
* Sends the packets to the peer
*/
static void SendPackets(NetworkStream stream, List<Packet> packets)
{
for (int i = 0; i < packets.Count; i++)
{
SendPacket(stream, packets[i]);
}
}
public static void SendPacket(NetworkStream stream, Packet packet)
{
stream.Write(Packet.Serialize(packet), 0, BUFFER_SIZE);
}
}
}
// MIT License
//
// Copyright (c) 2023 João Matos
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
| src/protoStream.cs | JoaoAJMatos-ProtoIP-84f8797 | [
{
"filename": "src/ethernet.cs",
"retrieved_chunk": " catch (WebException)\n {\n return false;\n }\n }\n return outputBuffer != null;\n }\n // Returns the MAC address string of the specified MAC address bytes\n public static string MacAddressBytesToString(byte[] macAddressBytes)\n {",
"score": 0.8643931746482849
},
{
"filename": "src/common.cs",
"retrieved_chunk": " OK,\n ERROR\n }\n }\n public class Network {\n public const int DEFAULT_BUFFER_SIZE = 1024;\n public const int MAX_TRIES = 3;\n public const int MAX_PACKETS = 1024;\n // Network connection object\n public struct Connection {",
"score": 0.8532221913337708
},
{
"filename": "src/client.cs",
"retrieved_chunk": " }\n // Send data to a remote host using a ProtoStream.\n //\n // Call the OnSend() method.\n public void Send(byte[] data)\n {\n _protoStream.Transmit(data);\n OnSend();\n }\n // Send overload for sending string data",
"score": 0.8529973030090332
},
{
"filename": "src/ethernet.cs",
"retrieved_chunk": " {\n bytes[i] = Convert.ToByte(macAddressBytes[i], 16);\n }\n return bytes;\n }\n // Returns the MAC address bytes of the specified IP address.\n // Attempts to fetch the MAC address from an IP address using an ARP request.\n // If the ARP request fails, it iterates through all network interfaces\n // to find the one with the specified IP address.\n public static byte[] GetMACAddressBytesFromIP(string ipAddressString)",
"score": 0.8461585640907288
},
{
"filename": "src/server.cs",
"retrieved_chunk": " _isRunning = false;\n _LastError = \"\";\n }\n // Send data to the client and call the OnResponse() method\n public void Send(byte[] data, int userID)\n {\n _clients[userID].Transmit(data);\n OnResponse(userID);\n }\n // Send data to all the connected clients",
"score": 0.8443059325218201
}
] | csharp | Network.MAX_TRIES)
{ |
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Ultrapain.Patches
{
public class OrbitalStrikeFlag : MonoBehaviour
{
public CoinChainList chainList;
public bool isOrbitalRay = false;
public bool exploded = false;
public float activasionDistance;
}
public class Coin_Start
{
static void Postfix(Coin __instance)
{
__instance.gameObject.AddComponent<OrbitalStrikeFlag>();
}
}
public class CoinChainList : MonoBehaviour
{
public List<Coin> chainList = new List<Coin>();
public bool isOrbitalStrike = false;
public float activasionDistance;
}
class Punch_BlastCheck
{
[HarmonyBefore(new string[] { "tempy.fastpunch" })]
static bool Prefix(Punch __instance)
{
__instance.blastWave = GameObject.Instantiate(Plugin.explosionWaveKnuckleblaster, new Vector3(1000000, 1000000, 1000000), Quaternion.identity);
__instance.blastWave.AddComponent<OrbitalStrikeFlag>();
return true;
}
[HarmonyBefore(new string[] { "tempy.fastpunch" })]
static void Postfix(Punch __instance)
{
GameObject.Destroy(__instance.blastWave);
__instance.blastWave = Plugin.explosionWaveKnuckleblaster;
}
}
class Explosion_Collide
{
static bool Prefix(Explosion __instance, Collider __0, List<Collider> ___hitColliders)
{
if (___hitColliders.Contains(__0)/* || __instance.transform.parent.GetComponent<OrbitalStrikeFlag>() == null*/)
return true;
Coin coin = __0.GetComponent<Coin>();
if (coin != null)
{
OrbitalStrikeFlag flag = coin.GetComponent<OrbitalStrikeFlag>();
if(flag == null)
{
coin.gameObject.AddComponent<OrbitalStrikeFlag>();
Debug.Log("Added orbital strike flag");
}
}
return true;
}
}
class Coin_DelayedReflectRevolver
{
static void Postfix(Coin __instance, GameObject ___altBeam)
{
CoinChainList flag = null;
OrbitalStrikeFlag orbitalBeamFlag = null;
if (___altBeam != null)
{
orbitalBeamFlag = ___altBeam.GetComponent<OrbitalStrikeFlag>();
if (orbitalBeamFlag == null)
{
orbitalBeamFlag = ___altBeam.AddComponent<OrbitalStrikeFlag>();
GameObject obj = new GameObject();
obj.AddComponent<RemoveOnTime>().time = 5f;
flag = obj.AddComponent<CoinChainList>();
orbitalBeamFlag.chainList = flag;
}
else
flag = orbitalBeamFlag.chainList;
}
else
{
if (__instance.ccc == null)
{
GameObject obj = new GameObject();
__instance.ccc = obj.AddComponent<CoinChainCache>();
obj.AddComponent<RemoveOnTime>().time = 5f;
}
flag = __instance.ccc.gameObject.GetComponent<CoinChainList>();
if(flag == null)
flag = __instance.ccc.gameObject.AddComponent<CoinChainList>();
}
if (flag == null)
return;
if (!flag.isOrbitalStrike && flag.chainList.Count != 0 && __instance.GetComponent<OrbitalStrikeFlag>() != null)
{
Coin lastCoin = flag.chainList.LastOrDefault();
float distance = Vector3.Distance(__instance.transform.position, lastCoin.transform.position);
if (distance >= ConfigManager.orbStrikeMinDistance.value)
{
flag.isOrbitalStrike = true;
flag.activasionDistance = distance;
if (orbitalBeamFlag != null)
{
orbitalBeamFlag.isOrbitalRay = true;
orbitalBeamFlag.activasionDistance = distance;
}
Debug.Log("Coin valid for orbital strike");
}
}
if (flag.chainList.Count == 0 || flag.chainList.LastOrDefault() != __instance)
flag.chainList.Add(__instance);
}
}
class Coin_ReflectRevolver
{
public static bool coinIsShooting = false;
public static Coin shootingCoin = null;
public static GameObject shootingAltBeam;
public static float lastCoinTime = 0;
static bool Prefix(Coin __instance, GameObject ___altBeam)
{
coinIsShooting = true;
shootingCoin = __instance;
lastCoinTime = Time.time;
shootingAltBeam = ___altBeam;
return true;
}
static void Postfix(Coin __instance)
{
coinIsShooting = false;
}
}
class RevolverBeam_Start
{
static bool Prefix(RevolverBeam __instance)
{
OrbitalStrikeFlag flag = __instance.GetComponent<OrbitalStrikeFlag>();
if (flag != null && flag.isOrbitalRay)
{
RevolverBeam_ExecuteHits.orbitalBeam = __instance;
RevolverBeam_ExecuteHits.orbitalBeamFlag = flag;
}
return true;
}
}
class RevolverBeam_ExecuteHits
{
public static bool isOrbitalRay = false;
public static RevolverBeam orbitalBeam = null;
public static OrbitalStrikeFlag orbitalBeamFlag = null;
static bool Prefix(RevolverBeam __instance)
{
OrbitalStrikeFlag flag = __instance.GetComponent<OrbitalStrikeFlag>();
if (flag != null && flag.isOrbitalRay)
{
isOrbitalRay = true;
orbitalBeam = __instance;
orbitalBeamFlag = flag;
}
return true;
}
static void Postfix()
{
isOrbitalRay = false;
}
}
class OrbitalExplosionInfo : MonoBehaviour
{
public bool active = true;
public string id;
public int points;
}
class Grenade_Explode
{
class StateInfo
{
public bool state = false;
public string id;
public int points;
public GameObject templateExplosion;
}
static bool Prefix(Grenade __instance, ref float __3, out StateInfo __state,
bool __1, bool __2)
{
__state = new StateInfo();
if((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null) || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f))
{
CoinChainList list = null;
if (Coin_ReflectRevolver.shootingAltBeam != null)
{
OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>();
if (orbitalFlag != null)
list = orbitalFlag.chainList;
}
else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null)
list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>();
if (list != null && list.isOrbitalStrike)
{
if (__1)
{
__state.templateExplosion = GameObject.Instantiate(__instance.harmlessExplosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity);
__instance.harmlessExplosion = __state.templateExplosion;
}
else if (__2)
{
__state.templateExplosion = GameObject.Instantiate(__instance.superExplosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity);
__instance.superExplosion = __state.templateExplosion;
}
else
{
__state.templateExplosion = GameObject.Instantiate(__instance.explosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity);
__instance.explosion = __state.templateExplosion;
}
OrbitalExplosionInfo info = __state.templateExplosion.AddComponent<OrbitalExplosionInfo>();
info.id = "";
__state.state = true;
float damageMulti = 1f;
float sizeMulti = 1f;
// REVOLVER NORMAL
if (Coin_ReflectRevolver.shootingAltBeam == null)
{
if (ConfigManager.orbStrikeRevolverGrenade.value)
{
damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value;
sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value;
info.id = ConfigManager.orbStrikeRevolverStyleText.guid;
info.points = ConfigManager.orbStrikeRevolverStylePoint.value;
}
}
else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam))
{
if (beam.beamType == BeamType.Revolver)
{
// REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT)
if (beam.ultraRicocheter)
{
if (ConfigManager.orbStrikeRevolverChargedGrenade.value)
{
damageMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraDamage.value;
sizeMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraSize.value;
info.id = ConfigManager.orbStrikeRevolverChargedStyleText.guid;
info.points = ConfigManager.orbStrikeRevolverChargedStylePoint.value;
}
}
// REVOLVER ALT
else
{
if (ConfigManager.orbStrikeRevolverGrenade.value)
{
damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value;
sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value;
info.id = ConfigManager.orbStrikeRevolverStyleText.guid;
info.points = ConfigManager.orbStrikeRevolverStylePoint.value;
}
}
}
// ELECTRIC RAILCANNON
else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500)
{
if (ConfigManager.orbStrikeElectricCannonGrenade.value)
{
damageMulti += ConfigManager.orbStrikeElectricCannonExplosionDamage.value;
sizeMulti += ConfigManager.orbStrikeElectricCannonExplosionSize.value;
info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid;
info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value;
}
}
// MALICIOUS RAILCANNON
else if (beam.beamType == BeamType.Railgun)
{
if (ConfigManager.orbStrikeMaliciousCannonGrenade.value)
{
damageMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraDamage.value;
sizeMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraSize.value;
info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid;
info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value;
}
}
else
__state.state = false;
}
else
__state.state = false;
if(sizeMulti != 1 || damageMulti != 1)
foreach(Explosion exp in __state.templateExplosion.GetComponentsInChildren<Explosion>())
{
exp.maxSize *= sizeMulti;
exp.speed *= sizeMulti;
exp.damage = (int)(exp.damage * damageMulti);
}
Debug.Log("Applied orbital strike bonus");
}
}
return true;
}
static void Postfix(Grenade __instance, StateInfo __state)
{
if (__state.templateExplosion != null)
GameObject.Destroy(__state.templateExplosion);
if (!__state.state)
return;
}
}
class Cannonball_Explode
{
static bool Prefix(Cannonball __instance, GameObject ___interruptionExplosion, ref GameObject ___breakEffect)
{
if ((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null) || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f))
{
CoinChainList list = null;
if (Coin_ReflectRevolver.shootingAltBeam != null)
{
OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>();
if (orbitalFlag != null)
list = orbitalFlag.chainList;
}
else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null)
list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>();
if (list != null && list.isOrbitalStrike && ___interruptionExplosion != null)
{
float damageMulti = 1f;
float sizeMulti = 1f;
GameObject explosion = GameObject.Instantiate<GameObject>(___interruptionExplosion, __instance.transform.position, Quaternion.identity);
OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>();
info.id = "";
// REVOLVER NORMAL
if (Coin_ReflectRevolver.shootingAltBeam == null)
{
if (ConfigManager.orbStrikeRevolverGrenade.value)
{
damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value;
sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value;
info.id = ConfigManager.orbStrikeRevolverStyleText.guid;
info.points = ConfigManager.orbStrikeRevolverStylePoint.value;
}
}
else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam))
{
if (beam.beamType == BeamType.Revolver)
{
// REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT)
if (beam.ultraRicocheter)
{
if (ConfigManager.orbStrikeRevolverChargedGrenade.value)
{
damageMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraDamage.value;
sizeMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraSize.value;
info.id = ConfigManager.orbStrikeRevolverChargedStyleText.guid;
info.points = ConfigManager.orbStrikeRevolverChargedStylePoint.value;
}
}
// REVOLVER ALT
else
{
if (ConfigManager.orbStrikeRevolverGrenade.value)
{
damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value;
sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value;
info.id = ConfigManager.orbStrikeRevolverStyleText.guid;
info.points = ConfigManager.orbStrikeRevolverStylePoint.value;
}
}
}
// ELECTRIC RAILCANNON
else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500)
{
if (ConfigManager.orbStrikeElectricCannonGrenade.value)
{
damageMulti += ConfigManager.orbStrikeElectricCannonExplosionDamage.value;
sizeMulti += ConfigManager.orbStrikeElectricCannonExplosionSize.value;
info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid;
info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value;
}
}
// MALICIOUS RAILCANNON
else if (beam.beamType == BeamType.Railgun)
{
if (ConfigManager.orbStrikeMaliciousCannonGrenade.value)
{
damageMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraDamage.value;
sizeMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraSize.value;
info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid;
info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value;
}
}
}
if (sizeMulti != 1 || damageMulti != 1)
foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>())
{
exp.maxSize *= sizeMulti;
exp.speed *= sizeMulti;
exp.damage = (int)(exp.damage * damageMulti);
}
if (MonoSingleton<PrefsManager>.Instance.GetBoolLocal("simpleExplosions", false))
{
___breakEffect = null;
}
__instance.Break();
return false;
}
}
return true;
}
}
class Explosion_CollideOrbital
{
static bool Prefix(Explosion __instance, Collider __0)
{
OrbitalExplosionInfo flag = __instance.transform.parent.GetComponent<OrbitalExplosionInfo>();
if (flag == null || !flag.active)
return true;
if ( __0.gameObject.tag != "Player" && (__0.gameObject.layer == 10 || __0.gameObject.layer == 11)
&& __instance.canHit != AffectedSubjects.PlayerOnly)
{
EnemyIdentifierIdentifier componentInParent = __0.GetComponentInParent<EnemyIdentifierIdentifier>();
if (componentInParent != null && componentInParent.eid != null && !componentInParent.eid.blessed/* && !componentInParent.eid.dead*/)
{
flag.active = false;
if(flag.id != "")
StyleHUD.Instance.AddPoints(flag.points, flag.id);
}
}
return true;
}
}
class EnemyIdentifier_DeliverDamage
{
static | Coin lastExplosiveCoin = null; |
class StateInfo
{
public bool canPostStyle = false;
public OrbitalExplosionInfo info = null;
}
static bool Prefix(EnemyIdentifier __instance, out StateInfo __state, Vector3 __2, ref float __3)
{
//if (Coin_ReflectRevolver.shootingCoin == lastExplosiveCoin)
// return true;
__state = new StateInfo();
bool causeExplosion = false;
if (__instance.dead)
return true;
if ((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null)/* || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f)*/)
{
CoinChainList list = null;
if (Coin_ReflectRevolver.shootingAltBeam != null)
{
OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>();
if (orbitalFlag != null)
list = orbitalFlag.chainList;
}
else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null)
list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>();
if (list != null && list.isOrbitalStrike)
{
causeExplosion = true;
}
}
else if (RevolverBeam_ExecuteHits.isOrbitalRay && RevolverBeam_ExecuteHits.orbitalBeam != null)
{
if (RevolverBeam_ExecuteHits.orbitalBeamFlag != null && !RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded)
{
causeExplosion = true;
}
}
if(causeExplosion)
{
__state.canPostStyle = true;
// REVOLVER NORMAL
if (Coin_ReflectRevolver.shootingAltBeam == null)
{
if(ConfigManager.orbStrikeRevolverExplosion.value)
{
GameObject explosion = GameObject.Instantiate(Plugin.explosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity);
foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>())
{
exp.enemy = false;
exp.hitterWeapon = "";
exp.maxSize *= ConfigManager.orbStrikeRevolverExplosionSize.value;
exp.speed *= ConfigManager.orbStrikeRevolverExplosionSize.value;
exp.damage = (int)(exp.damage * ConfigManager.orbStrikeRevolverExplosionDamage.value);
}
OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>();
info.id = ConfigManager.orbStrikeRevolverStyleText.guid;
info.points = ConfigManager.orbStrikeRevolverStylePoint.value;
__state.info = info;
}
}
else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam))
{
if (beam.beamType == BeamType.Revolver)
{
// REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT)
if (beam.ultraRicocheter)
{
if(ConfigManager.orbStrikeRevolverChargedInsignia.value)
{
GameObject insignia = GameObject.Instantiate(Plugin.virtueInsignia, /*__instance.transform.position*/__2, Quaternion.identity);
// This is required for ff override to detect this insignia as non ff attack
insignia.gameObject.name = "PlayerSpawned";
float horizontalSize = ConfigManager.orbStrikeRevolverChargedInsigniaSize.value;
insignia.transform.localScale = new Vector3(horizontalSize, insignia.transform.localScale.y, horizontalSize);
VirtueInsignia comp = insignia.GetComponent<VirtueInsignia>();
comp.windUpSpeedMultiplier = ConfigManager.orbStrikeRevolverChargedInsigniaDelayBoost.value;
comp.damage = ConfigManager.orbStrikeRevolverChargedInsigniaDamage.value;
comp.predictive = false;
comp.hadParent = false;
comp.noTracking = true;
StyleHUD.Instance.AddPoints(ConfigManager.orbStrikeRevolverChargedStylePoint.value, ConfigManager.orbStrikeRevolverChargedStyleText.guid);
__state.canPostStyle = false;
}
}
// REVOLVER ALT
else
{
if (ConfigManager.orbStrikeRevolverExplosion.value)
{
GameObject explosion = GameObject.Instantiate(Plugin.explosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity);
foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>())
{
exp.enemy = false;
exp.hitterWeapon = "";
exp.maxSize *= ConfigManager.orbStrikeRevolverExplosionSize.value;
exp.speed *= ConfigManager.orbStrikeRevolverExplosionSize.value;
exp.damage = (int)(exp.damage * ConfigManager.orbStrikeRevolverExplosionDamage.value);
}
OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>();
info.id = ConfigManager.orbStrikeRevolverStyleText.guid;
info.points = ConfigManager.orbStrikeRevolverStylePoint.value;
__state.info = info;
}
}
}
// ELECTRIC RAILCANNON
else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500)
{
if(ConfigManager.orbStrikeElectricCannonExplosion.value)
{
GameObject lighning = GameObject.Instantiate(Plugin.lightningStrikeExplosive, /*__instance.gameObject.transform.position*/ __2, Quaternion.identity);
foreach (Explosion exp in lighning.GetComponentsInChildren<Explosion>())
{
exp.enemy = false;
exp.hitterWeapon = "";
if (exp.damage == 0)
exp.maxSize /= 2;
exp.maxSize *= ConfigManager.orbStrikeElectricCannonExplosionSize.value;
exp.speed *= ConfigManager.orbStrikeElectricCannonExplosionSize.value;
exp.damage = (int)(exp.damage * ConfigManager.orbStrikeElectricCannonExplosionDamage.value);
exp.canHit = AffectedSubjects.All;
}
OrbitalExplosionInfo info = lighning.AddComponent<OrbitalExplosionInfo>();
info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid;
info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value;
__state.info = info;
}
}
// MALICIOUS RAILCANNON
else if (beam.beamType == BeamType.Railgun)
{
// UNUSED
causeExplosion = false;
}
// MALICIOUS BEAM
else if (beam.beamType == BeamType.MaliciousFace)
{
GameObject explosion = GameObject.Instantiate(Plugin.sisyphiusPrimeExplosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity);
foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>())
{
exp.enemy = false;
exp.hitterWeapon = "";
exp.maxSize *= ConfigManager.maliciousChargebackExplosionSizeMultiplier.value;
exp.speed *= ConfigManager.maliciousChargebackExplosionSizeMultiplier.value;
exp.damage = (int)(exp.damage * ConfigManager.maliciousChargebackExplosionDamageMultiplier.value);
}
OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>();
info.id = ConfigManager.maliciousChargebackStyleText.guid;
info.points = ConfigManager.maliciousChargebackStylePoint.value;
__state.info = info;
}
// SENTRY BEAM
else if (beam.beamType == BeamType.Enemy)
{
StyleHUD.Instance.AddPoints(ConfigManager.sentryChargebackStylePoint.value, ConfigManager.sentryChargebackStyleText.formattedString);
if (ConfigManager.sentryChargebackExtraBeamCount.value > 0)
{
List<Tuple<EnemyIdentifier, float>> enemies = UnityUtils.GetClosestEnemies(__2, ConfigManager.sentryChargebackExtraBeamCount.value, UnityUtils.doNotCollideWithPlayerValidator);
foreach (Tuple<EnemyIdentifier, float> enemy in enemies)
{
RevolverBeam newBeam = GameObject.Instantiate(beam, beam.transform.position, Quaternion.identity);
newBeam.hitEids.Add(__instance);
newBeam.transform.LookAt(enemy.Item1.transform);
GameObject.Destroy(newBeam.GetComponent<OrbitalStrikeFlag>());
}
}
RevolverBeam_ExecuteHits.isOrbitalRay = false;
}
}
if (causeExplosion && RevolverBeam_ExecuteHits.orbitalBeamFlag != null)
RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded = true;
Debug.Log("Applied orbital strike explosion");
}
return true;
}
static void Postfix(EnemyIdentifier __instance, StateInfo __state)
{
if(__state.canPostStyle && __instance.dead && __state.info != null)
{
__state.info.active = false;
if (__state.info.id != "")
StyleHUD.Instance.AddPoints(__state.info.points, __state.info.id);
}
}
}
class RevolverBeam_HitSomething
{
static bool Prefix(RevolverBeam __instance, out GameObject __state)
{
__state = null;
if (RevolverBeam_ExecuteHits.orbitalBeam == null)
return true;
if (__instance.beamType != BeamType.Railgun)
return true;
if (__instance.hitAmount != 1)
return true;
if (RevolverBeam_ExecuteHits.orbitalBeam.GetInstanceID() == __instance.GetInstanceID())
{
if (!RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded && ConfigManager.orbStrikeMaliciousCannonExplosion.value)
{
Debug.Log("MALICIOUS EXPLOSION EXTRA SIZE");
GameObject tempExp = GameObject.Instantiate(__instance.hitParticle, new Vector3(1000000, 1000000, 1000000), Quaternion.identity);
foreach (Explosion exp in tempExp.GetComponentsInChildren<Explosion>())
{
exp.maxSize *= ConfigManager.orbStrikeMaliciousCannonExplosionSizeMultiplier.value;
exp.speed *= ConfigManager.orbStrikeMaliciousCannonExplosionSizeMultiplier.value;
exp.damage = (int)(exp.damage * ConfigManager.orbStrikeMaliciousCannonExplosionDamageMultiplier.value);
}
__instance.hitParticle = tempExp;
OrbitalExplosionInfo info = tempExp.AddComponent<OrbitalExplosionInfo>();
info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid;
info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value;
RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded = true;
}
Debug.Log("Already exploded");
}
else
Debug.Log("Not the same instance");
return true;
}
static void Postfix(RevolverBeam __instance, GameObject __state)
{
if (__state != null)
GameObject.Destroy(__state);
}
}
}
| Ultrapain/Patches/OrbitalStrike.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Solider.cs",
"retrieved_chunk": " if (___eid.enemyType != EnemyType.Soldier)\n return;\n ___eid.weakPoint = null;\n }\n }\n class SoliderGrenadeFlag : MonoBehaviour\n {\n public GameObject tempExplosion;\n }\n class Solider_ThrowProjectile_Patch",
"score": 0.854490339756012
},
{
"filename": "Ultrapain/Patches/Panopticon.cs",
"retrieved_chunk": " explosion.damage = Mathf.RoundToInt((float)explosion.damage * ___eid.totalDamageModifier);\n explosion.maxSize *= ___eid.totalDamageModifier;\n }\n }\n }\n class Panopticon_SpawnFleshDrones\n {\n struct StateInfo\n {\n public GameObject template;",
"score": 0.8469861149787903
},
{
"filename": "Ultrapain/Patches/V2Second.cs",
"retrieved_chunk": " V2SecondSwitchWeapon.SwitchWeapon.Invoke(__instance, new object[1] { 0 });\n Debug.Log(\"Preparing to fire for grenade\");\n }\n }\n }\n return true;\n }\n }\n class V2SecondShootWeapon\n {",
"score": 0.8406987190246582
},
{
"filename": "Ultrapain/Patches/Parry.cs",
"retrieved_chunk": " GameObject.Destroy(flag.temporaryBigExplosion);\n flag.temporaryBigExplosion = null;\n }\n }\n }\n }\n class Grenade_Collision_Patch\n {\n static float lastTime = 0;\n static bool Prefix(Grenade __instance, Collider __0)",
"score": 0.8389217853546143
},
{
"filename": "Ultrapain/Patches/Screwdriver.cs",
"retrieved_chunk": " {\n targetEids.Clear();\n }\n }\n }\n }\n class Harpoon_Start\n {\n static void Postfix(Harpoon __instance)\n {",
"score": 0.8361303806304932
}
] | csharp | Coin lastExplosiveCoin = null; |
using HarmonyLib;
using System.Collections.Generic;
using UnityEngine;
namespace Ultrapain.Patches
{
class HookArm_FixedUpdate_Patch
{
static bool Prefix(HookArm __instance, ref Grenade ___caughtGrenade, ref | Vector3 ___caughtPoint, ref Vector3 ___hookPoint, ref float ___cooldown, ref List<Rigidbody> ___caughtObjects)
{ |
if (___caughtGrenade != null && ___caughtGrenade.rocket && !___caughtGrenade.playerRiding && MonoSingleton<WeaponCharges>.Instance.rocketFrozen)
{
if (__instance.state == HookState.Throwing)
{
if (!MonoSingleton<InputManager>.Instance.InputSource.Hook.IsPressed && (___cooldown <= 0.1f || ___caughtObjects.Count > 0))
{
__instance.StopThrow(0f, false);
}
return false;
}
else if (__instance.state == HookState.Ready)
{
if (MonoSingleton<NewMovement>.Instance.boost || MonoSingleton<NewMovement>.Instance.sliding)
return true;
___hookPoint = ___caughtGrenade.transform.position + ___caughtPoint; //__instance.caughtTransform.position + __instance.caughtPoint;
__instance.beingPulled = true;
MonoSingleton<NewMovement>.Instance.rb.velocity = (/*___hookPoint*/___caughtGrenade.transform.position - MonoSingleton<NewMovement>.Instance.transform.position).normalized * 60f;
if (MonoSingleton<NewMovement>.Instance.gc.onGround)
MonoSingleton<NewMovement>.Instance.rb.MovePosition(MonoSingleton<NewMovement>.Instance.transform.position + Vector3.up);
return false;
}
}
return true;
}
}
}
| Ultrapain/Patches/Whiplash.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Schism.cs",
"retrieved_chunk": "using HarmonyLib;\nusing System.ComponentModel;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class ZombieProjectile_ShootProjectile_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, Animator ___anim, EnemyIdentifier ___eid)\n {\n /*Projectile proj = ___currentProjectile.GetComponent<Projectile>();",
"score": 0.8436098098754883
},
{
"filename": "Ultrapain/Patches/Stalker.cs",
"retrieved_chunk": "using HarmonyLib;\nusing ULTRAKILL.Cheats;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n public class Stalker_SandExplode_Patch\n {\n static bool Prefix(Stalker __instance, ref int ___difficulty, ref EnemyIdentifier ___eid, int __0,\n ref bool ___exploding, ref float ___countDownAmount, ref float ___explosionCharge,\n ref Color ___currentColor, Color[] ___lightColors, AudioSource ___lightAud, AudioClip[] ___lightSounds,",
"score": 0.8372967839241028
},
{
"filename": "Ultrapain/Patches/Solider.cs",
"retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Solider_Start_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref GameObject ___decProjectile, ref GameObject ___projectile, ref EnemyIdentifier ___eid, ref Animator ___anim)\n {\n if (___eid.enemyType != EnemyType.Soldier)\n return;",
"score": 0.8352733850479126
},
{
"filename": "Ultrapain/Patches/StreetCleaner.cs",
"retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class StreetCleaner_Start_Patch\n {\n static void Postfix(Streetcleaner __instance, ref EnemyIdentifier ___eid)\n {\n ___eid.weakPoint = null;\n }",
"score": 0.8269377946853638
},
{
"filename": "Ultrapain/Patches/Filth.cs",
"retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class SwingCheck2_CheckCollision_Patch2\n {\n static bool Prefix(SwingCheck2 __instance, Collider __0, EnemyIdentifier ___eid)\n {\n if (__0.gameObject.tag != \"Player\")\n return true;",
"score": 0.824076235294342
}
] | csharp | Vector3 ___caughtPoint, ref Vector3 ___hookPoint, ref float ___cooldown, ref List<Rigidbody> ___caughtObjects)
{ |
#nullable enable
using System;
using System.Collections.Generic;
namespace Mochineko.RelentStateMachine
{
public sealed class StateStoreBuilder<TContext>
: IStateStoreBuilder<TContext>
{
private readonly IStackState<TContext> initialState;
private readonly List<IStackState<TContext>> states = new();
private bool disposed = false;
public static StateStoreBuilder<TContext> Create<TInitialState>()
where TInitialState : | IStackState<TContext>, new()
{ |
var initialState = new TInitialState();
return new StateStoreBuilder<TContext>(initialState);
}
private StateStoreBuilder(IStackState<TContext> initialState)
{
this.initialState = initialState;
states.Add(this.initialState);
}
public void Dispose()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(StateStoreBuilder<TContext>));
}
disposed = true;
}
public void Register<TState>()
where TState : IStackState<TContext>, new()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(StateStoreBuilder<TContext>));
}
foreach (var state in states)
{
if (state is TState)
{
throw new InvalidOperationException($"Already registered state: {typeof(TState)}");
}
}
states.Add(new TState());
}
public IStateStore<TContext> Build()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(StateStoreBuilder<TContext>));
}
var result = new StateStore<TContext>(
initialState,
states);
// Cannot reuse builder after build.
this.Dispose();
return result;
}
}
} | Assets/Mochineko/RelentStateMachine/StateStoreBuilder.cs | mochi-neko-RelentStateMachine-64762eb | [
{
"filename": "Assets/Mochineko/RelentStateMachine/StackStateMachine.cs",
"retrieved_chunk": " {\n private readonly IStateStore<TContext> stateStore;\n public TContext Context { get; }\n private readonly Stack<IStackState<TContext>> stack = new();\n public bool IsCurrentState<TState>()\n where TState : IStackState<TContext>\n => stack.Peek() is TState;\n private readonly SemaphoreSlim semaphore = new(\n initialCount: 1,\n maxCount: 1);",
"score": 0.9116198420524597
},
{
"filename": "Assets/Mochineko/RelentStateMachine/StateStore.cs",
"retrieved_chunk": "#nullable enable\nusing System;\nusing System.Collections.Generic;\nnamespace Mochineko.RelentStateMachine\n{\n public sealed class StateStore<TContext> : IStateStore<TContext>\n {\n private readonly IStackState<TContext> initialState;\n private readonly IReadOnlyList<IStackState<TContext>> states;\n public StateStore(",
"score": 0.9064158201217651
},
{
"filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs",
"retrieved_chunk": " private readonly Dictionary<IState<TEvent, TContext>, Dictionary<TEvent, IState<TEvent, TContext>>>\n transitionMap = new();\n private readonly Dictionary<TEvent, IState<TEvent, TContext>>\n anyTransitionMap = new();\n private bool disposed = false;\n public static TransitionMapBuilder<TEvent, TContext> Create<TInitialState>()\n where TInitialState : IState<TEvent, TContext>, new()\n {\n var initialState = new TInitialState();\n return new TransitionMapBuilder<TEvent, TContext>(initialState);",
"score": 0.9029010534286499
},
{
"filename": "Assets/Mochineko/RelentStateMachine/FiniteStateMachine.cs",
"retrieved_chunk": " private readonly ITransitionMap<TEvent, TContext> transitionMap;\n public TContext Context { get; }\n private IState<TEvent, TContext> currentState;\n public bool IsCurrentState<TState>()\n where TState : IState<TEvent, TContext>\n => currentState is TState;\n private readonly SemaphoreSlim semaphore = new(\n initialCount: 1,\n maxCount: 1);\n private readonly TimeSpan semaphoreTimeout;",
"score": 0.8882420659065247
},
{
"filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs",
"retrieved_chunk": "#nullable enable\nusing System;\nusing System.Collections.Generic;\nnamespace Mochineko.RelentStateMachine\n{\n public sealed class TransitionMapBuilder<TEvent, TContext>\n : ITransitionMapBuilder<TEvent, TContext>\n {\n private readonly IState<TEvent, TContext> initialState;\n private readonly List<IState<TEvent, TContext>> states = new();",
"score": 0.887150764465332
}
] | csharp | IStackState<TContext>, new()
{ |
using HarmonyLib;
using UnityEngine;
namespace Ultrapain.Patches
{
class TurretFlag : MonoBehaviour
{
public int shootCountRemaining = ConfigManager.turretBurstFireCount.value;
}
class TurretStart
{
static void Postfix(Turret __instance)
{
__instance.gameObject.AddComponent<TurretFlag>();
}
}
class TurretShoot
{
static bool Prefix(Turret __instance, ref EnemyIdentifier ___eid, ref RevolverBeam ___beam, ref Transform ___shootPoint,
ref float ___aimTime, ref float ___maxAimTime, ref float ___nextBeepTime, ref float ___flashTime)
{
TurretFlag flag = __instance.GetComponent<TurretFlag>();
if (flag == null)
return true;
if (flag.shootCountRemaining > 0)
{
RevolverBeam revolverBeam = GameObject.Instantiate<RevolverBeam>(___beam, new Vector3(__instance.transform.position.x, ___shootPoint.transform.position.y, __instance.transform.position.z), ___shootPoint.transform.rotation);
revolverBeam.alternateStartPoint = ___shootPoint.transform.position;
RevolverBeam revolverBeam2;
if (___eid.totalDamageModifier != 1f && revolverBeam.TryGetComponent<RevolverBeam>(out revolverBeam2))
{
revolverBeam2.damage *= ___eid.totalDamageModifier;
}
___nextBeepTime = 0;
___flashTime = 0;
___aimTime = ___maxAimTime - ConfigManager.turretBurstFireDelay.value;
if (___aimTime < 0)
___aimTime = 0;
flag.shootCountRemaining -= 1;
return false;
}
else
flag.shootCountRemaining = ConfigManager.turretBurstFireCount.value;
return true;
}
}
class TurretAim
{
static void Postfix( | Turret __instance)
{ |
TurretFlag flag = __instance.GetComponent<TurretFlag>();
if (flag == null)
return;
flag.shootCountRemaining = ConfigManager.turretBurstFireCount.value;
}
}
}
| Ultrapain/Patches/Turret.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/MinosPrime.cs",
"retrieved_chunk": " }\n }\n // aka PREPARE THYSELF\n class MinosPrime_Combo\n {\n static float timing = 3f;\n static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid)\n {\n if (!ConfigManager.minosPrimeComboToggle.value)\n return;",
"score": 0.8494329452514648
},
{
"filename": "Ultrapain/Patches/Screwdriver.cs",
"retrieved_chunk": " {\n targetEids.Clear();\n }\n }\n }\n }\n class Harpoon_Start\n {\n static void Postfix(Harpoon __instance)\n {",
"score": 0.8483366966247559
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " return true;\n }\n static void Postfix(Coin __instance)\n {\n coinIsShooting = false;\n }\n }\n class RevolverBeam_Start\n {\n static bool Prefix(RevolverBeam __instance)",
"score": 0.847679853439331
},
{
"filename": "Ultrapain/Patches/Panopticon.cs",
"retrieved_chunk": " if (___fleshDroneCooldown < 1f)\n {\n ___fleshDroneCooldown = 1f;\n }\n return false;\n }\n }\n class Panopticon_HomingProjectileAttack\n {\n static void Postfix(FleshPrison __instance, EnemyIdentifier ___eid)",
"score": 0.8385609984397888
},
{
"filename": "Ultrapain/Patches/Solider.cs",
"retrieved_chunk": " //counter.remainingShots = ConfigManager.soliderShootCount.value;\n }\n }\n class Grenade_Explode_Patch\n {\n static bool Prefix(Grenade __instance, out bool __state)\n {\n __state = false;\n SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>();\n if (flag == null)",
"score": 0.8375315070152283
}
] | csharp | Turret __instance)
{ |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Experimental.GraphView;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
namespace QuestSystem.QuestEditor
{
public class QuestGraphView : GraphView
{
public string misionName;
private QuestNodeSearchWindow _searchWindow;
public Quest questRef;
private QuestGraphView _self;
private QuestGraphEditor editorWindow;
public QuestGraphView(EditorWindow _editorWindow, Quest q = null)
{
questRef = q;
editorWindow = (QuestGraphEditor)_editorWindow;
styleSheets.Add(Resources.Load<StyleSheet>("QuestGraph"));
SetupZoom(ContentZoomer.DefaultMinScale, ContentZoomer.DefaultMaxScale);
this.AddManipulator(new ContentDragger());
this.AddManipulator(new SelectionDragger());
this.AddManipulator(new RectangleSelector());
//Grid
var grid = new GridBackground();
Insert(0, grid);
grid.StretchToParentSize();
this.AddElement(GenerateEntryPointNode());
this.AddSearchWindow(editorWindow);
_self = this;
}
//TODO: Create node at desired position with fewer hide
/*public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
base.BuildContextualMenu(evt);
if (evt.target is GraphView)
{
evt.menu.InsertAction(1,"Create Node", (e) => {
var a = editorWindow.rootVisualElement; var b = editorWindow.position.position; var c = editorWindow.rootVisualElement.parent;
var context = new SearchWindowContext(e.eventInfo.mousePosition, a.worldBound.x, a.worldBound.y);
Vector2 mousePosition = editorWindow.rootVisualElement.ChangeCoordinatesTo(editorWindow.rootVisualElement, context.screenMousePosition - editorWindow.position.position);
Vector2 graphViewMousePosition = this.contentViewContainer.WorldToLocal(mousePosition);
CreateNode("NodeQuest", mousePosition);
});
}
}*/
private void AddSearchWindow(EditorWindow editorWindow)
{
_searchWindow = ScriptableObject.CreateInstance<QuestNodeSearchWindow>();
_searchWindow.Init(this, editorWindow);
nodeCreationRequest = context => SearchWindow.Open(new SearchWindowContext(context.screenMousePosition),_searchWindow);
}
private Port GeneratePort(NodeQuestGraph node, Direction direction, Port.Capacity capacity = Port.Capacity.Single)
{
return node.InstantiatePort(Orientation.Horizontal, direction, capacity, typeof(float));
}
public NodeQuestGraph GenerateEntryPointNode()
{
var node = new NodeQuestGraph
{
title = "Start",
GUID = Guid.NewGuid().ToString(),
entryPoint = true
};
//Add ouput port
var generatetPort = GeneratePort(node, Direction.Output);
generatetPort.portName = "Next";
node.outputContainer.Add(generatetPort);
//Quest params
var box = new Box();
//
var misionName = new TextField("Mision Name:")
{
value = "Temp name"
};
misionName.RegisterValueChangedCallback(evt =>
{
node.misionName = evt.newValue;
});
box.Add(misionName);
//
var isMain = new Toggle();
isMain.label = "isMain";
isMain.value = false;
isMain.RegisterValueChangedCallback(evt =>
{
node.isMain = evt.newValue;
});
//isMain.SetValueWithoutNotify(false);
box.Add(isMain);
//
var startDay = new IntegerField("Start Day:")
{
value = 0
};
startDay.RegisterValueChangedCallback(evt =>
{
node.startDay = evt.newValue;
});
box.Add(startDay);
//
var limitDay = new IntegerField("Limit Day:")
{
value = 0
};
limitDay.RegisterValueChangedCallback(evt =>
{
node.limitDay = evt.newValue;
});
box.Add(limitDay);
node.mainContainer.Add(box);
//Refresh visual part
node.RefreshExpandedState();
node.RefreshPorts();
node.SetPosition(new Rect(100, 200, 100, 150));
return node;
}
public override List<Port> GetCompatiblePorts(Port startPort, NodeAdapter nodeAdapter)
{
var compatiblePorts = new List<Port>();
//Reglas de conexions
ports.ForEach(port =>
{
if (startPort != port && startPort.node != port.node)
compatiblePorts.Add(port);
});
return compatiblePorts;
}
public void CreateNode(string nodeName, Vector2 position)
{
AddElement(CreateNodeQuest(nodeName,position));
}
public NodeQuestGraph CreateNodeQuest(string nodeName, Vector2 position, TextAsset ta = null, bool end = false)
{
var node = new NodeQuestGraph
{
title = nodeName,
GUID = Guid.NewGuid().ToString(),
questObjectives = new List<QuestObjectiveGraph>(),
};
//Add Input port
var generatetPortIn = GeneratePort(node, Direction.Input, Port.Capacity.Multi);
generatetPortIn.portName = "Input";
node.inputContainer.Add(generatetPortIn);
node.styleSheets.Add(Resources.Load<StyleSheet>("Node"));
//Add button to add ouput
var button = new Button(clickEvent: () =>
{
AddNextNodePort(node);
});
button.text = "New Next Node";
node.titleContainer.Add(button);
//Button to add more objectives
var button2 = new Button(clickEvent: () =>
{
AddNextQuestObjective(node);
});
button2.text = "Add new Objective";
//Hide/Unhide elements
var hideButton = new Button(clickEvent: () =>
{
HideUnhide(node, button2);
});
hideButton.text = "Hide/Unhide";
//Extra information
var extraText = new ObjectField("Extra information:");
extraText.objectType = typeof(TextAsset);
extraText.RegisterValueChangedCallback(evt =>
{
node.extraText = evt.newValue as TextAsset;
});
extraText.SetValueWithoutNotify(ta);
//Bool es final
var togle = new Toggle();
togle.label = "isFinal";
togle.RegisterValueChangedCallback(evt =>
{
node.isFinal = evt.newValue;
});
togle.SetValueWithoutNotify(end);
var container = new Box();
node.mainContainer.Add(container);// Container per a tenir fons solid
container.Add(extraText);
container.Add(togle);
container.Add(hideButton);
container.Add(button2);
node.objectivesRef = new Box();
container.Add(node.objectivesRef);
//Refresh la part Visual
node.RefreshExpandedState();
node.RefreshPorts();
node.SetPosition(new Rect(position.x, position.y, 400, 450));
return node;
}
private void HideUnhide(NodeQuestGraph node, Button b)
{
bool show = !b.visible;
b.visible = show;
foreach (var objective in node.questObjectives)
{
if (show)
{
node.objectivesRef.Add(objective);
}
else
{
node.objectivesRef.Remove(objective);
}
}
node.RefreshExpandedState();
node.RefreshPorts();
}
public void AddNextNodePort( | NodeQuestGraph node, string overrideName = "")
{ |
var generatetPort = GeneratePort(node, Direction.Output);
int nPorts = node.outputContainer.Query("connector").ToList().Count;
//generatetPort.portName = "NextNode " + nPorts;
string choicePortName = string.IsNullOrEmpty(overrideName) ? "NextNode " + nPorts : overrideName;
generatetPort.portName = choicePortName;
var deleteButton = new Button(clickEvent: () => RemovePort(node, generatetPort))
{
text = "x"
};
generatetPort.contentContainer.Add(deleteButton);
node.outputContainer.Add(generatetPort);
node.RefreshPorts();
node.RefreshExpandedState();
}
private void RemovePort(NodeQuestGraph node, Port p)
{
var targetEdge = edges.ToList().Where(x => x.output.portName == p.portName && x.output.node == p.node);
if (targetEdge.Any())
{
var edge = targetEdge.First();
edge.input.Disconnect(edge);
RemoveElement(targetEdge.First());
}
node.outputContainer.Remove(p);
node.RefreshPorts();
node.RefreshExpandedState();
}
public void removeQuestObjective(NodeQuestGraph nodes, QuestObjectiveGraph objective)
{
nodes.objectivesRef.Remove(objective);
nodes.questObjectives.Remove(objective);
nodes.RefreshExpandedState();
}
private void AddNextQuestObjective(NodeQuestGraph node)
{
var Q = new QuestObjectiveGraph();
var deleteButton = new Button(clickEvent: () => removeQuestObjective(node, Q))
{
text = "x"
};
Q.contentContainer.Add(deleteButton);
//Visual Box separator
var newBox = new Box();
Q.Add(newBox);
node.objectivesRef.Add(Q);
node.questObjectives.Add(Q);
node.RefreshPorts();
node.RefreshExpandedState();
}
public NodeQuestGraph GetEntryPointNode()
{
List<NodeQuestGraph> nodeList = this.nodes.ToList().Cast<NodeQuestGraph>().ToList();
return nodeList.First(node => node.entryPoint);
}
}
} | Editor/GraphEditor/QuestGraphView.cs | lluispalerm-QuestSystem-cd836cc | [
{
"filename": "Runtime/QuestObjectiveUpdater.cs",
"retrieved_chunk": " returnList.Add(nodeToUpdate.nodeObjectives[i].keyName);\n }\n }\n }\n return returnList.ToArray();\n }\n public void Interact()\n {\n if (isAbleToUpdateQuest())\n {",
"score": 0.8678523898124695
},
{
"filename": "Runtime/Quest.cs",
"retrieved_chunk": " nodeActual = nodeActual.nextNode[i];\n }\n }\n public void ResetNodeLinksGraph()\n {\n nodeLinkData = new List<NodeLinksGraph>();\n }\n }\n}",
"score": 0.8325139880180359
},
{
"filename": "Runtime/QuestOnObjectWorld.cs",
"retrieved_chunk": " g.SetActive(objectsForQuestTable[i].tableNodes[j].activate);\n }\n hasBeenActivated = true;\n }\n }\n }\n }\n public void PopulateChildListDefault()\n {\n int numberOfChilds = transform.childCount;",
"score": 0.8258470892906189
},
{
"filename": "Runtime/Quest.cs",
"retrieved_chunk": " EditorUtility.SetDirty(n);\n#endif\n }\n QuestManager.GetInstance().misionLog.RemoveQuest(this);\n }\n public void AdvanceToCurrentNode()\n {\n nodeActual = firtsNode;\n foreach (int i in state)\n {",
"score": 0.8238421082496643
},
{
"filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs",
"retrieved_chunk": " _targetGraphView.AddElement(tempNode);\n var nodePorts = Q.nodeLinkData.Where(x => x.baseNodeGUID == node.GUID).ToList();\n nodePorts.ForEach(x => _targetGraphView.AddNextNodePort(tempNode));\n }\n }\n private void ConectNodes(Quest Q)\n {\n List<NodeQuestGraph> nodeListCopy = new List<NodeQuestGraph>(node);\n for (int i = 0; i < nodeListCopy.Count; i++)\n {",
"score": 0.8180931806564331
}
] | csharp | NodeQuestGraph node, string overrideName = "")
{ |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.UIElements.UIR;
namespace Ultrapain.Patches
{
class DrillFlag : MonoBehaviour
{
public Harpoon drill;
public Rigidbody rb;
public List<Tuple< | EnemyIdentifier, float>> targetEids = new List<Tuple<EnemyIdentifier, float>>(); |
public List<EnemyIdentifier> piercedEids = new List<EnemyIdentifier>();
public Transform currentTargetTrans;
public Collider currentTargetCol;
public EnemyIdentifier currentTargetEid;
void Awake()
{
if (drill == null)
drill = GetComponent<Harpoon>();
if (rb == null)
rb = GetComponent<Rigidbody>();
}
void Update()
{
if(targetEids != null)
{
if (currentTargetEid == null || currentTargetEid.dead || currentTargetEid.blessed || currentTargetEid.stuckMagnets.Count == 0)
{
currentTargetEid = null;
foreach (Tuple<EnemyIdentifier, float> item in targetEids)
{
EnemyIdentifier eid = item.Item1;
if (eid == null || eid.dead || eid.blessed || eid.stuckMagnets.Count == 0)
continue;
currentTargetEid = eid;
currentTargetTrans = eid.transform;
if (currentTargetEid.gameObject.TryGetComponent(out Collider col))
currentTargetCol = col;
break;
}
}
if(currentTargetEid != null)
{
transform.LookAt(currentTargetCol == null ? currentTargetTrans.position : currentTargetCol.bounds.center);
rb.velocity = transform.forward * 150f;
}
else
{
targetEids.Clear();
}
}
}
}
class Harpoon_Start
{
static void Postfix(Harpoon __instance)
{
if (!__instance.drill)
return;
DrillFlag flag = __instance.gameObject.AddComponent<DrillFlag>();
flag.drill = __instance;
}
}
class Harpoon_Punched
{
static void Postfix(Harpoon __instance, EnemyIdentifierIdentifier ___target)
{
if (!__instance.drill)
return;
DrillFlag flag = __instance.GetComponent<DrillFlag>();
if (flag == null)
return;
if(___target != null && ___target.eid != null)
flag.targetEids = UnityUtils.GetClosestEnemies(__instance.transform.position, 3, (sourcePos, enemy) =>
{
if (enemy == ___target.eid)
return false;
foreach (Magnet m in enemy.stuckMagnets)
{
if (m != null)
return true;
}
return false;
});
else
flag.targetEids = UnityUtils.GetClosestEnemies(__instance.transform.position, 3, (sourcePos, enemy) =>
{
foreach(Magnet m in enemy.stuckMagnets)
{
if (m != null)
return true;
}
return false;
});
}
}
class Harpoon_OnTriggerEnter_Patch
{
public static float forwardForce = 10f;
public static float upwardForce = 10f;
static LayerMask envLayer = new LayerMask() { m_Mask = 16777472 };
private static Harpoon lastHarpoon;
static bool Prefix(Harpoon __instance, Collider __0)
{
if (!__instance.drill)
return true;
if(__0.TryGetComponent(out EnemyIdentifierIdentifier eii))
{
if (eii.eid == null)
return true;
EnemyIdentifier eid = eii.eid;
DrillFlag flag = __instance.GetComponent<DrillFlag>();
if (flag == null)
return true;
if(flag.currentTargetEid != null)
{
if(flag.currentTargetEid == eid)
{
flag.targetEids.Clear();
flag.piercedEids.Clear();
flag.currentTargetEid = null;
flag.currentTargetTrans = null;
flag.currentTargetCol = null;
if(ConfigManager.screwDriverHomeDestroyMagnets.value)
{
foreach (Magnet h in eid.stuckMagnets)
if (h != null)
GameObject.Destroy(h.gameObject);
eid.stuckMagnets.Clear();
}
return true;
}
else if (!flag.piercedEids.Contains(eid))
{
if (ConfigManager.screwDriverHomePierceDamage.value > 0)
{
eid.hitter = "harpoon";
eid.DeliverDamage(__0.gameObject, __instance.transform.forward, __instance.transform.position, ConfigManager.screwDriverHomePierceDamage.value, false, 0, null, false);
flag.piercedEids.Add(eid);
}
return false;
}
return false;
}
}
Coin sourceCoin = __0.gameObject.GetComponent<Coin>();
if (sourceCoin != null)
{
if (__instance == lastHarpoon)
return true;
Quaternion currentRotation = Quaternion.Euler(0, __0.transform.eulerAngles.y, 0);
int totalCoinCount = ConfigManager.screwDriverCoinSplitCount.value;
float rotationPerIteration = 360f / totalCoinCount;
for(int i = 0; i < totalCoinCount; i++)
{
GameObject coinClone = GameObject.Instantiate(Plugin.coin, __instance.transform.position, currentRotation);
Coin comp = coinClone.GetComponent<Coin>();
comp.sourceWeapon = sourceCoin.sourceWeapon;
comp.power = sourceCoin.power;
Rigidbody rb = coinClone.GetComponent<Rigidbody>();
rb.AddForce(coinClone.transform.forward * forwardForce + Vector3.up * upwardForce, ForceMode.VelocityChange);
currentRotation = Quaternion.Euler(0, currentRotation.eulerAngles.y + rotationPerIteration, 0);
}
GameObject.Destroy(__0.gameObject);
GameObject.Destroy(__instance.gameObject);
lastHarpoon = __instance;
return false;
}
Grenade sourceGrn = __0.GetComponent<Grenade>();
if(sourceGrn != null)
{
if (__instance == lastHarpoon)
return true;
Quaternion currentRotation = Quaternion.Euler(0, __0.transform.eulerAngles.y, 0);
int totalGrenadeCount = ConfigManager.screwDriverCoinSplitCount.value;
float rotationPerIteration = 360f / totalGrenadeCount;
List<Tuple<EnemyIdentifier , float>> targetEnemies = new List<Tuple<EnemyIdentifier, float>>();
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
float sqrMagnitude = (enemy.transform.position - __0.transform.position).sqrMagnitude;
if (targetEnemies.Count < totalGrenadeCount || sqrMagnitude < targetEnemies.Last().Item2)
{
EnemyIdentifier eid = enemy.GetComponent<EnemyIdentifier>();
if (eid == null || eid.dead || eid.blessed)
continue;
if (Physics.Raycast(__0.transform.position, enemy.transform.position - __0.transform.position, out RaycastHit hit, Vector3.Distance(__0.transform.position, enemy.transform.position) - 0.5f, envLayer))
continue;
if(targetEnemies.Count == 0)
{
targetEnemies.Add(new Tuple<EnemyIdentifier, float>(eid, sqrMagnitude));
continue;
}
int insertionPoint = targetEnemies.Count;
while (insertionPoint != 0 && targetEnemies[insertionPoint - 1].Item2 > sqrMagnitude)
insertionPoint -= 1;
targetEnemies.Insert(insertionPoint, new Tuple<EnemyIdentifier, float>(eid, sqrMagnitude));
if (targetEnemies.Count > totalGrenadeCount)
targetEnemies.RemoveAt(totalGrenadeCount);
}
}
for (int i = 0; i < totalGrenadeCount; i++)
{
Grenade grenadeClone = GameObject.Instantiate(sourceGrn, __instance.transform.position, currentRotation);
Rigidbody rb = grenadeClone.GetComponent<Rigidbody>();
rb.velocity = Vector3.zero;
if(i <= targetEnemies.Count - 1 || targetEnemies.Count != 0)
{
grenadeClone.transform.LookAt(targetEnemies[i <= targetEnemies.Count - 1 ? i : 0].Item1.transform);
if (!grenadeClone.rocket)
{
rb.AddForce(grenadeClone.transform.forward * 50f, ForceMode.VelocityChange);
rb.useGravity = false;
}
else
{
grenadeClone.rocketSpeed = 150f;
}
}
else
{
rb.AddForce(grenadeClone.transform.forward * forwardForce + Vector3.up * upwardForce, ForceMode.VelocityChange);
}
currentRotation = Quaternion.Euler(0, currentRotation.eulerAngles.y + rotationPerIteration, 0);
}
GameObject.Destroy(__instance.gameObject);
GameObject.Destroy(sourceGrn.gameObject);
lastHarpoon = __instance;
return false;
}
return true;
}
}
}
| Ultrapain/Patches/Screwdriver.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nusing UnityEngine.AI;\nnamespace Ultrapain.Patches\n{\n public class StrayFlag : MonoBehaviour\n {\n //public int extraShotsRemaining = 6;\n private Animator anim;\n private EnemyIdentifier eid;",
"score": 0.8353004455566406
},
{
"filename": "Ultrapain/Patches/SomethingWicked.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nnamespace Ultrapain.Patches\n{\n class SomethingWickedFlag : MonoBehaviour\n {\n public GameObject spear;",
"score": 0.8140295147895813
},
{
"filename": "Ultrapain/Patches/Cerberus.cs",
"retrieved_chunk": "using UnityEngine;\nnamespace Ultrapain.Patches\n{\n class CerberusFlag : MonoBehaviour\n {\n public int extraDashesRemaining = ConfigManager.cerberusTotalDashCount.value - 1;\n public Transform head;\n public float lastParryTime;\n private EnemyIdentifier eid;\n private void Awake()",
"score": 0.8115748167037964
},
{
"filename": "Ultrapain/Patches/HideousMass.cs",
"retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n public class HideousMassProjectile : MonoBehaviour\n {\n public float damageBuf = 1f;\n public float speedBuf = 1f;\n }\n public class Projectile_Explode_Patch ",
"score": 0.811495840549469
},
{
"filename": "Ultrapain/Patches/SwordsMachine.cs",
"retrieved_chunk": "using HarmonyLib;\nusing System.Security.Cryptography;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class SwordsMachineFlag : MonoBehaviour\n {\n public SwordsMachine sm;\n public Animator anim;\n public EnemyIdentifier eid;",
"score": 0.8100320100784302
}
] | csharp | EnemyIdentifier, float>> targetEids = new List<Tuple<EnemyIdentifier, float>>(); |
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Build.Utilities
{
internal static class DependencyTableCache
{
private class TaskItemItemSpecIgnoreCaseComparer : IEqualityComparer<ITaskItem>
{
public bool Equals(ITaskItem x, ITaskItem y)
{
if (x == y)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return string.Equals(x.ItemSpec, y.ItemSpec, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(ITaskItem obj)
{
if (obj != null)
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.ItemSpec);
}
return 0;
}
}
private static readonly char[] s_numerals = new char[10] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private static readonly TaskItemItemSpecIgnoreCaseComparer s_taskItemComparer = new TaskItemItemSpecIgnoreCaseComparer();
internal static Dictionary<string, DependencyTableCacheEntry> DependencyTable { get; } = new Dictionary<string, DependencyTableCacheEntry>(StringComparer.OrdinalIgnoreCase);
private static bool DependencyTableIsUpToDate( | DependencyTableCacheEntry dependencyTable)
{ |
DateTime tableTime = dependencyTable.TableTime;
ITaskItem[] tlogFiles = dependencyTable.TlogFiles;
for (int i = 0; i < tlogFiles.Length; i++)
{
if (NativeMethods.GetLastWriteFileUtcTime(FileUtilities.NormalizePath(tlogFiles[i].ItemSpec)) > tableTime)
{
return false;
}
}
return true;
}
internal static DependencyTableCacheEntry GetCachedEntry(string tLogRootingMarker)
{
if (DependencyTable.TryGetValue(tLogRootingMarker, out var value))
{
if (DependencyTableIsUpToDate(value))
{
return value;
}
DependencyTable.Remove(tLogRootingMarker);
}
return null;
}
internal static string FormatNormalizedTlogRootingMarker(ITaskItem[] tlogFiles)
{
HashSet<ITaskItem> hashSet = new HashSet<ITaskItem>(s_taskItemComparer);
for (int i = 0; i < tlogFiles.Length; i++)
{
ITaskItem taskItem = new TaskItem(tlogFiles[i]);
taskItem.ItemSpec = NormalizeTlogPath(tlogFiles[i].ItemSpec);
hashSet.Add(taskItem);
}
return FileTracker.FormatRootingMarker(hashSet.ToArray());
}
private static string NormalizeTlogPath(string tlogPath)
{
if (tlogPath.IndexOfAny(s_numerals) == -1)
{
return tlogPath;
}
StringBuilder stringBuilder = new StringBuilder();
int num = tlogPath.Length - 1;
while (num >= 0 && tlogPath[num] != '\\')
{
if (tlogPath[num] == '.' || tlogPath[num] == '-')
{
stringBuilder.Append(tlogPath[num]);
int num2 = num - 1;
while (num2 >= 0 && tlogPath[num2] != '\\' && tlogPath[num2] >= '0' && tlogPath[num2] <= '9')
{
num2--;
}
if (num2 >= 0 && tlogPath[num2] == '.')
{
stringBuilder.Append("]DI[");
stringBuilder.Append(tlogPath[num2]);
num = num2;
}
}
else
{
stringBuilder.Append(tlogPath[num]);
}
num--;
}
StringBuilder stringBuilder2 = new StringBuilder(num + stringBuilder.Length);
if (num >= 0)
{
stringBuilder2.Append(tlogPath, 0, num + 1);
}
for (int num3 = stringBuilder.Length - 1; num3 >= 0; num3--)
{
stringBuilder2.Append(stringBuilder[num3]);
}
return stringBuilder2.ToString();
}
}
}
| Microsoft.Build.Utilities/DependencyTableCache.cs | Chuyu-Team-MSBuildCppCrossToolset-6c84a69 | [
{
"filename": "Microsoft.Build.Utilities/CanonicalTrackedInputFiles.cs",
"retrieved_chunk": " }\n }\n DependencyTable = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);\n if (_tlogFiles != null)\n {\n ConstructDependencyTable();\n }\n }\n public ITaskItem[] ComputeSourcesNeedingCompilation()\n {",
"score": 0.8224772214889526
},
{
"filename": "Microsoft.Build.Utilities/CanonicalTrackedInputFiles.cs",
"retrieved_chunk": " private bool _useMinimalRebuildOptimization;\n private bool _tlogAvailable;\n private bool _maintainCompositeRootingMarkers;\n private readonly HashSet<string> _excludedInputPaths = new HashSet<string>(StringComparer.Ordinal);\n private readonly ConcurrentDictionary<string, DateTime> _lastWriteTimeCache = new ConcurrentDictionary<string, DateTime>(StringComparer.Ordinal);\n internal ITaskItem[] SourcesNeedingCompilation { get; set; }\n public Dictionary<string, Dictionary<string, string>> DependencyTable { get; private set; }\n public CanonicalTrackedInputFiles(ITaskItem[] tlogFiles, ITaskItem[] sourceFiles, CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers)\n {\n InternalConstruct(null, tlogFiles, sourceFiles, null, null, outputs, useMinimalRebuildOptimization, maintainCompositeRootingMarkers);",
"score": 0.812127947807312
},
{
"filename": "Microsoft.Build.Utilities/CanonicalTrackedOutputFiles.cs",
"retrieved_chunk": " if (flag)\n {\n DependencyTableCache.DependencyTable.Remove(text);\n DependencyTable = new Dictionary<string, Dictionary<string, DateTime>>(StringComparer.OrdinalIgnoreCase);\n }\n else\n {\n DependencyTableCache.DependencyTable[text] = new DependencyTableCacheEntry(_tlogFiles, DependencyTable);\n }\n }",
"score": 0.8094508647918701
},
{
"filename": "Microsoft.Build.CPPTasks/VCToolTask.cs",
"retrieved_chunk": " rhs = messageStruct;\n }\n }\n private Dictionary<string, ToolSwitch> activeToolSwitchesValues = new Dictionary<string, ToolSwitch>();\n#if __REMOVE\n private IntPtr cancelEvent;\n private string cancelEventName;\n#endif\n private bool fCancelled;\n private Dictionary<string, ToolSwitch> activeToolSwitches = new Dictionary<string, ToolSwitch>(StringComparer.OrdinalIgnoreCase);",
"score": 0.8070939779281616
},
{
"filename": "Microsoft.Build.CPPTasks/VCToolTask.cs",
"retrieved_chunk": " foreach (ITaskItem taskItem in value)\n {\n errorListRegexListExclusion.Add(new Regex(taskItem.ItemSpec, RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromMilliseconds(100.0)));\n }\n }\n }\n public bool EnableErrorListRegex { get; set; } = true;\n public bool ForceSinglelineErrorListRegex { get; set; }\n public virtual string[] AcceptableNonzeroExitCodes { get; set; }\n public Dictionary<string, ToolSwitch> ActiveToolSwitchesValues",
"score": 0.8062912225723267
}
] | csharp | DependencyTableCacheEntry dependencyTable)
{ |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Ultrapain.Patches
{
public static class V2Utils
{
public static Transform GetClosestGrenade()
{
Transform closestTransform = null;
float closestDistance = 1000000;
foreach(Grenade g in GrenadeList.Instance.grenadeList)
{
float dist = Vector3.Distance(g.transform.position, PlayerTracker.Instance.GetTarget().position);
if(dist < closestDistance)
{
closestTransform = g.transform;
closestDistance = dist;
}
}
foreach (Cannonball c in GrenadeList.Instance.cannonballList)
{
float dist = Vector3.Distance(c.transform.position, PlayerTracker.Instance.GetTarget().position);
if (dist < closestDistance)
{
closestTransform = c.transform;
closestDistance = dist;
}
}
return closestTransform;
}
public static Vector3 GetDirectionAwayFromTarget( | Vector3 center, Vector3 target)
{ |
// Calculate the direction vector from the center to the target
Vector3 direction = target - center;
// Set the Y component of the direction vector to 0
direction.y = 0;
// Normalize the direction vector
direction.Normalize();
// Reverse the direction vector to face away from the target
direction = -direction;
return direction;
}
}
class V2CommonExplosion
{
static void Postfix(Explosion __instance)
{
if (__instance.sourceWeapon == null)
return;
V2MaliciousCannon malCanComp = __instance.sourceWeapon.GetComponent<V2MaliciousCannon>();
if(malCanComp != null)
{
Debug.Log("Grenade explosion triggered by V2 malicious cannon");
__instance.toIgnore.Add(EnemyType.V2);
__instance.toIgnore.Add(EnemyType.V2Second);
return;
}
EnemyRevolver revComp = __instance.sourceWeapon.GetComponentInChildren<EnemyRevolver>();
if(revComp != null)
{
Debug.Log("Grenade explosion triggered by V2 revolver");
__instance.toIgnore.Add(EnemyType.V2);
__instance.toIgnore.Add(EnemyType.V2Second);
return;
}
}
}
// SHARPSHOOTER
class V2CommonRevolverComp : MonoBehaviour
{
public bool secondPhase = false;
public bool shootingForSharpshooter = false;
}
class V2CommonRevolverPrepareAltFire
{
static bool Prefix(EnemyRevolver __instance, GameObject ___altCharge)
{
if(__instance.TryGetComponent<V2CommonRevolverComp>(out V2CommonRevolverComp comp))
{
if ((comp.secondPhase && !ConfigManager.v2SecondSharpshooterToggle.value)
|| (!comp.secondPhase && !ConfigManager.v2FirstSharpshooterToggle.value))
return true;
bool sharp = UnityEngine.Random.Range(0f, 100f) <= (comp.secondPhase ? ConfigManager.v2SecondSharpshooterChance.value : ConfigManager.v2FirstSharpshooterChance.value);
Transform quad = ___altCharge.transform.Find("MuzzleFlash/Quad");
MeshRenderer quadRenderer = quad.gameObject.GetComponent<MeshRenderer>();
quadRenderer.material.color = sharp ? new Color(1f, 0.1f, 0f) : new Color(1f, 1f, 1f);
comp.shootingForSharpshooter = sharp;
}
return true;
}
}
class V2CommonRevolverBulletSharp : MonoBehaviour
{
public int reflectionCount = 2;
public float autoAimAngle = 30f;
public Projectile proj;
public float speed = 350f;
public bool hasTargetPoint = false;
public Vector3 shootPoint;
public Vector3 targetPoint;
public RaycastHit targetHit;
public bool alreadyHitPlayer = false;
public bool alreadyReflected = false;
private void Awake()
{
proj = GetComponent<Projectile>();
proj.speed = 0;
GetComponent<Rigidbody>().isKinematic = true;
}
private void Update()
{
if (!hasTargetPoint)
transform.position += transform.forward * speed;
else
{
if (transform.position != targetPoint)
{
transform.position = Vector3.MoveTowards(transform.position, targetPoint, Time.deltaTime * speed);
if (transform.position == targetPoint)
proj.SendMessage("Collided", targetHit.collider);
}
else
proj.SendMessage("Collided", targetHit.collider);
}
}
}
class V2CommonRevolverBullet
{
static bool Prefix(Projectile __instance, Collider __0)
{
V2CommonRevolverBulletSharp comp = __instance.GetComponent<V2CommonRevolverBulletSharp>();
if (comp == null)
return true;
if ((__0.gameObject.tag == "Head" || __0.gameObject.tag == "Body" || __0.gameObject.tag == "Limb" || __0.gameObject.tag == "EndLimb") && __0.gameObject.tag != "Armor")
{
EnemyIdentifierIdentifier eii = __instance.GetComponent<EnemyIdentifierIdentifier>();
if (eii != null)
{
eii.eid.hitter = "enemy";
eii.eid.DeliverDamage(__0.gameObject, __instance.transform.forward * 100f, __instance.transform.position, comp.proj.damage / 10f, false, 0f, null, false);
return false;
}
}
if (comp.alreadyReflected)
return false;
bool isPlayer = __0.gameObject.tag == "Player";
if (isPlayer)
{
if (comp.alreadyHitPlayer)
return false;
NewMovement.Instance.GetHurt(Mathf.RoundToInt(comp.proj.damage), true, 1f, false, false);
comp.alreadyHitPlayer = true;
return false;
}
if (!comp.hasTargetPoint || comp.transform.position != comp.targetPoint)
return false;
if(comp.reflectionCount <= 0)
{
comp.alreadyReflected = true;
return true;
}
// REFLECTION
LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };
GameObject reflectedBullet = GameObject.Instantiate(__instance.gameObject, comp.targetPoint, __instance.transform.rotation);
V2CommonRevolverBulletSharp reflectComp = reflectedBullet.GetComponent<V2CommonRevolverBulletSharp>();
reflectComp.reflectionCount -= 1;
reflectComp.shootPoint = reflectComp.transform.position;
reflectComp.alreadyReflected = false;
reflectComp.alreadyHitPlayer = false;
reflectedBullet.transform.forward = Vector3.Reflect(comp.transform.forward, comp.targetHit.normal).normalized;
Vector3 playerPos = NewMovement.Instance.transform.position;
Vector3 playerVectorFromBullet = playerPos - reflectedBullet.transform.position;
float angle = Vector3.Angle(playerVectorFromBullet, reflectedBullet.transform.forward);
if (angle <= ConfigManager.v2FirstSharpshooterAutoaimAngle.value)
{
Quaternion lastRotation = reflectedBullet.transform.rotation;
reflectedBullet.transform.LookAt(NewMovement.Instance.playerCollider.bounds.center);
RaycastHit[] hits = Physics.RaycastAll(reflectedBullet.transform.position, reflectedBullet.transform.forward, Vector3.Distance(reflectedBullet.transform.position, playerPos));
bool hitEnv = false;
foreach (RaycastHit rayHit in hits)
{
if (rayHit.transform.gameObject.layer == 8 || rayHit.transform.gameObject.layer == 24)
{
hitEnv = true;
break;
}
}
if (hitEnv)
{
reflectedBullet.transform.rotation = lastRotation;
}
}
if(Physics.Raycast(reflectedBullet.transform.position, reflectedBullet.transform.forward, out RaycastHit hit, float.PositiveInfinity, envMask))
{
reflectComp.targetPoint = hit.point;
reflectComp.targetHit = hit;
reflectComp.hasTargetPoint = true;
}
else
{
reflectComp.hasTargetPoint = false;
}
comp.alreadyReflected = true;
GameObject.Instantiate(Plugin.ricochetSfx, reflectedBullet.transform.position, Quaternion.identity);
return true;
}
}
class V2CommonRevolverAltShoot
{
static bool Prefix(EnemyRevolver __instance, EnemyIdentifier ___eid)
{
if (__instance.TryGetComponent<V2CommonRevolverComp>(out V2CommonRevolverComp comp) && comp.shootingForSharpshooter)
{
__instance.CancelAltCharge();
Vector3 position = __instance.shootPoint.position;
if (Vector3.Distance(__instance.transform.position, ___eid.transform.position) > Vector3.Distance(MonoSingleton<NewMovement>.Instance.transform.position, ___eid.transform.position))
{
position = new Vector3(___eid.transform.position.x, __instance.transform.position.y, ___eid.transform.position.z);
}
GameObject bullet = GameObject.Instantiate(__instance.altBullet, position, __instance.shootPoint.rotation);
V2CommonRevolverBulletSharp bulletComp = bullet.AddComponent<V2CommonRevolverBulletSharp>();
bulletComp.autoAimAngle = comp.secondPhase ? ConfigManager.v2SecondSharpshooterAutoaimAngle.value : ConfigManager.v2FirstSharpshooterAutoaimAngle.value;
bulletComp.reflectionCount = comp.secondPhase ? ConfigManager.v2SecondSharpshooterReflections.value : ConfigManager.v2FirstSharpshooterReflections.value;
bulletComp.speed *= comp.secondPhase ? ConfigManager.v2SecondSharpshooterSpeed.value : ConfigManager.v2FirstSharpshooterSpeed.value;
TrailRenderer rend = UnityUtils.GetComponentInChildrenRecursively<TrailRenderer>(bullet.transform);
rend.endColor = rend.startColor = new Color(1, 0, 0);
Projectile component = bullet.GetComponent<Projectile>();
if (component)
{
component.safeEnemyType = __instance.safeEnemyType;
component.damage *= comp.secondPhase ? ConfigManager.v2SecondSharpshooterDamage.value : ConfigManager.v2FirstSharpshooterDamage.value;
}
LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };
float v2Height = -1;
RaycastHit v2Ground;
if (!Physics.Raycast(position, Vector3.down, out v2Ground, float.PositiveInfinity, envMask))
v2Height = v2Ground.distance;
float playerHeight = -1;
RaycastHit playerGround;
if (!Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out playerGround, float.PositiveInfinity, envMask))
playerHeight = playerGround.distance;
if (v2Height != -1 && playerHeight != -1)
{
Vector3 playerGroundFromV2 = playerGround.point - v2Ground.point;
float distance = Vector3.Distance(playerGround.point, v2Ground.point);
float k = playerHeight / v2Height;
float d1 = (distance * k) / (1 + k);
Vector3 lookPoint = v2Ground.point + (playerGroundFromV2 / distance) * d1;
bullet.transform.LookAt(lookPoint);
}
else
{
Vector3 mid = ___eid.transform.position + (NewMovement.Instance.transform.position - ___eid.transform.position) * 0.5f;
if (Physics.Raycast(mid, Vector3.down, out RaycastHit hit, 1000f, new LayerMask() { value = 1 << 8 | 1 << 24 }))
{
bullet.transform.LookAt(hit.point);
}
else
{
bullet.transform.LookAt(NewMovement.Instance.playerCollider.bounds.center);
}
}
GameObject.Instantiate(__instance.muzzleFlashAlt, __instance.shootPoint.position, __instance.shootPoint.rotation);
if (Physics.Raycast(bullet.transform.position, bullet.transform.forward, out RaycastHit predictedHit, float.PositiveInfinity, envMask))
{
bulletComp.targetPoint = predictedHit.point;
bulletComp.targetHit = predictedHit;
bulletComp.hasTargetPoint = true;
}
else
{
bulletComp.hasTargetPoint = false;
}
comp.shootingForSharpshooter = false;
return false;
}
return true;
}
}
}
| Ultrapain/Patches/V2Common.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " protected override void OnCreateUI(RectTransform fieldUI)\n {\n currentUI = fieldUI;\n fieldUI.sizeDelta = new Vector2(fieldUI.sizeDelta.x, space);\n }\n }\n public static class ConfigManager\n {\n public static PluginConfigurator config = null;\n public static void AddMissingPresets()",
"score": 0.8104211688041687
},
{
"filename": "Ultrapain/Patches/V2First.cs",
"retrieved_chunk": " __instance.ForceDodge(V2Utils.GetDirectionAwayFromTarget(flag.v2collider.bounds.center, closestGrenade.transform.position));\n return false;\n }\n }\n }\n return true;\n }\n }\n class V2FirstStart\n {",
"score": 0.7983100414276123
},
{
"filename": "Ultrapain/Patches/CommonComponents.cs",
"retrieved_chunk": " public Quaternion targetRotation;\n private void Awake()\n {\n transform.rotation = targetRotation;\n }\n }\n public class CommonActivator : MonoBehaviour\n {\n public int originalId;\n public Renderer rend;",
"score": 0.7958981990814209
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " imgRect.anchorMax = imgRect.anchorMin = new Vector2(0f, 0.5f);\n Image imgComp = currentImage = img.AddComponent<Image>();\n imgComp.sprite = sprite;\n imgComp.color = color;\n SetSize();\n }\n }\n // Separates fields by a small space\n public class SpaceField : CustomConfigField\n {",
"score": 0.792701244354248
},
{
"filename": "Ultrapain/Patches/Drone.cs",
"retrieved_chunk": " }\n public float attackDelay = -1;\n public bool homingTowardsPlayer = false;\n Transform target;\n Rigidbody rb;\n private void Update()\n {\n if(homingTowardsPlayer)\n {\n if(target == null)",
"score": 0.784387469291687
}
] | csharp | Vector3 center, Vector3 target)
{ |
using System.Text;
using System.Net;
using Microsoft.Extensions.Caching.Memory;
using Serilog;
using Serilog.Events;
using Iced.Intel;
using static Iced.Intel.AssemblerRegisters;
namespace OGXbdmDumper
{
public class Xbox : IDisposable
{
#region Properties
private bool _disposed;
private const int _cacheDuration = 1; // in minutes
private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });
private bool? _hasFastGetmem;
public ScratchBuffer StaticScratch;
public bool HasFastGetmem
{
get
{
if (_hasFastGetmem == null)
{
try
{
long testAddress = 0x10000;
if (IsValidAddress(testAddress))
{
Session.SendCommandStrict("getmem2 addr={0} length=1", testAddress.ToHexString());
Session.ClearReceiveBuffer();
_hasFastGetmem = true;
Log.Information("Fast getmem support detected.");
}
else _hasFastGetmem = false;
}
catch
{
_hasFastGetmem = false;
}
}
return _hasFastGetmem.Value;
}
}
/// <summary>
/// Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.
/// </summary>
public bool SafeMode { get; set; } = true;
public bool IsConnected => Session.IsConnected;
public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }
public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }
public Connection Session { get; private set; } = new Connection();
public ConnectionInfo? ConnectionInfo { get; protected set; }
/// <summary>
/// The Xbox memory stream.
/// </summary>
public | XboxMemoryStream Memory { | get; private set; }
public Kernel Kernel { get; private set; }
public List<Module> Modules => GetModules();
public List<Thread> Threads => GetThreads();
public Version Version => GetVersion();
#endregion
#region Connection
public void Connect(string host, int port = 731)
{
_cache.Clear();
ConnectionInfo = Session.Connect(host, port);
// init subsystems
Memory = new XboxMemoryStream(this);
Kernel = new Kernel(this);
StaticScratch = new ScratchBuffer(this);
Log.Information("Loaded Modules:");
foreach (var module in Modules)
{
Log.Information("\t{0} ({1})", module.Name, module.TimeStamp);
}
Log.Information("Xbdm Version {0}", Version);
Log.Information("Kernel Version {0}", Kernel.Version);
// enable remote code execution and use the remainder reloc section as scratch
PatchXbdm(this);
}
public void Disconnect()
{
Session.Disconnect();
ConnectionInfo = null;
_cache.Clear();
}
public List<ConnectionInfo> Discover(int timeout = 500)
{
return ConnectionInfo.DiscoverXbdm(731, timeout);
}
public void Connect(IPEndPoint endpoint)
{
Connect(endpoint.Address.ToString(), endpoint.Port);
}
public void Connect(int timeout = 500)
{
Connect(Discover(timeout).First().Endpoint);
}
#endregion
#region Memory
public bool IsValidAddress(long address)
{
try
{
Session.SendCommandStrict("getmem addr={0} length=1", address.ToHexString());
return "??" != Session.ReceiveMultilineResponse()[0];
}
catch
{
return false;
}
}
public void ReadMemory(long address, Span<byte> buffer)
{
if (HasFastGetmem && !SafeMode)
{
Session.SendCommandStrict("getmem2 addr={0} length={1}", address.ToHexString(), buffer.Length);
Session.Read(buffer);
if (Log.IsEnabled(LogEventLevel.Verbose))
{
Log.Verbose(buffer.ToHexString());
}
}
else if (!SafeMode)
{
// custom getmem2
Session.SendCommandStrict("funccall type=1 addr={0} length={1}", address, buffer.Length);
Session.ReadExactly(buffer);
if (Log.IsEnabled(LogEventLevel.Verbose))
{
Log.Verbose(buffer.ToHexString());
}
}
else
{
Session.SendCommandStrict("getmem addr={0} length={1}", address.ToHexString(), buffer.Length);
int bytesRead = 0;
string hexString;
while ((hexString = Session.ReceiveLine()) != ".")
{
Span<byte> slice = buffer.Slice(bytesRead, hexString.Length / 2);
slice.FromHexString(hexString);
bytesRead += slice.Length;
}
}
}
public void ReadMemory(long address, byte[] buffer, int offset, int count)
{
ReadMemory(address, buffer.AsSpan(offset, count));
}
public void ReadMemory(long address, int count, Stream destination)
{
// argument checks
if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
if (destination == null) throw new ArgumentNullException(nameof(destination));
Span<byte> buffer = stackalloc byte[1024 * 80];
while (count > 0)
{
int bytesToRead = Math.Min(buffer.Length, count);
Span<byte> slice = buffer.Slice(0, bytesToRead);
ReadMemory(address, slice);
destination.Write(slice);
count -= bytesToRead;
address += (uint)bytesToRead;
}
}
public void WriteMemory(long address, ReadOnlySpan<byte> buffer)
{
const int maxBytesPerLine = 240;
int totalWritten = 0;
while (totalWritten < buffer.Length)
{
ReadOnlySpan<byte> slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));
Session.SendCommandStrict("setmem addr={0} data={1}", (address + totalWritten).ToHexString(), slice.ToHexString());
totalWritten += slice.Length;
}
}
public void WriteMemory(long address, byte[] buffer, int offset, int count)
{
WriteMemory(address, buffer.AsSpan(offset, count));
}
public void WriteMemory(long address, int count, Stream source)
{
// argument checks
if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
if (source == null) throw new ArgumentNullException(nameof(source));
Span<byte> buffer = stackalloc byte[1024 * 80];
while (count > 0)
{
int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));
WriteMemory(address, buffer.Slice(0, bytesRead));
count -= bytesRead;
address += bytesRead;
}
}
#endregion
#region Process
public List<Thread> GetThreads()
{
List<Thread> threads = new List<Thread>();
Session.SendCommandStrict("threads");
foreach (var threadId in Session.ReceiveMultilineResponse())
{
Session.SendCommandStrict("threadinfo thread={0}", threadId);
var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));
threads.Add(new Thread
{
Id = Convert.ToInt32(threadId),
Suspend = (int)(uint)info["suspend"], // initially -1 in earlier xbdm versions, 0 in later ones
Priority = (int)(uint)info["priority"],
TlsBase = (uint)info["tlsbase"],
// optional depending on xbdm version
Start = info.ContainsKey("start") ? (uint)info["start"] : 0,
Base = info.ContainsKey("base") ? (uint)info["base"] : 0,
Limit = info.ContainsKey("limit") ? (uint)info["limit"] : 0,
CreationTime = DateTime.FromFileTime(
(info.ContainsKey("createhi") ? (((long)(uint)info["createhi"]) << 32) : 0) |
(info.ContainsKey("createlo") ? (uint)info["createlo"] : 0))
});
}
return threads;
}
public List<Module> GetModules()
{
List<Module> modules = new List<Module>();
Session.SendCommandStrict("modules");
foreach (var moduleResponse in Session.ReceiveMultilineResponse())
{
var moduleInfo = Connection.ParseKvpResponse(moduleResponse);
Module module = new Module
{
Name = (string)moduleInfo["name"],
BaseAddress = (uint)moduleInfo["base"],
Size = (int)(uint)moduleInfo["size"],
Checksum = (uint)moduleInfo["check"],
TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo["timestamp"]).DateTime,
Sections = new List<ModuleSection>(),
HasTls = moduleInfo.ContainsKey("tls"),
IsXbe = moduleInfo.ContainsKey("xbe")
};
Session.SendCommandStrict("modsections name=\"{0}\"", module.Name);
foreach (var sectionResponse in Session.ReceiveMultilineResponse())
{
var sectionInfo = Connection.ParseKvpResponse(sectionResponse);
module.Sections.Add(new ModuleSection
{
Name = (string)sectionInfo["name"],
Base = (uint)sectionInfo["base"],
Size = (int)(uint)sectionInfo["size"],
Flags = (uint)sectionInfo["flags"]
});
}
modules.Add(module);
}
return modules;
}
public Version GetVersion()
{
var version = _cache.Get<Version>(nameof(GetVersion));
if (version == null)
{
try
{
// peek inside VS_VERSIONINFO struct
var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals("xbdm.dll")).GetSection(".rsrc").Base + 0x98;
// call getmem directly to avoid dependency loops with ReadMemory checking the version
Span<byte> buffer = stackalloc byte[sizeof(ushort) * 4];
Session.SendCommandStrict("getmem addr={0} length={1}", versionAddress.ToHexString(), buffer.Length);
buffer.FromHexString(Session.ReceiveMultilineResponse().First());
version = new Version(
BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),
BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),
BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),
BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))
);
// cache the result
_cache.Set(nameof(GetVersion), version);
}
catch
{
version = new Version("0.0.0.0");
}
}
return version;
}
public void Stop()
{
Log.Information("Suspending xbox execution.");
Session.SendCommand("stop");
}
public void Go()
{
Log.Information("Resuming xbox execution.");
Session.SendCommand("go");
}
/// <summary>
/// Calls an Xbox function.
/// </summary>
/// <param name="address">The function address.</param>
/// <param name="args">The function arguments.</param>
/// <returns>Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.</returns>
public uint Call(long address, params object[] args)
{
// TODO: call context (~4039+ which requires qwordparam)
// injected script pushes arguments in reverse order for simplicity, this corrects that
var reversedArgs = args.Reverse().ToArray();
StringBuilder command = new StringBuilder();
command.AppendFormat("funccall type=0 addr={0} ", address);
for (int i = 0; i < reversedArgs.Length; i++)
{
command.AppendFormat("arg{0}={1} ", i, Convert.ToUInt32(reversedArgs[i]));
}
var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);
return (uint)returnValues["eax"];
}
/// <summary>
/// Original Xbox Debug Monitor runtime patches.
/// Prevents crashdumps from being written to the HDD and enables remote code execution.
/// </summary>
/// <param name="target"></param>
private void PatchXbdm(Xbox target)
{
// the spin routine to be patched in after the signature patterns
// spin:
// jmp spin
// int 3
var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };
// prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)
if (target.Signatures.ContainsKey("ReadWriteOneSector"))
{
Log.Information("Disabling crashdump functionality.");
target.WriteMemory(target.Signatures["ReadWriteOneSector"] + 9, spinBytes);
}
else if (target.Signatures.ContainsKey("WriteSMBusByte"))
{
// this will prevent the LED state from changing upon crash
Log.Information("Disabling crashdump functionality.");
target.WriteMemory(target.Signatures["WriteSMBusByte"] + 9, spinBytes);
}
Log.Information("Patching xbdm memory to enable remote code execution.");
uint argThreadStringAddress = StaticScratch.Alloc("thread\0");
uint argTypeStringAddress = StaticScratch.Alloc("type\0");
uint argAddrStringAddress = StaticScratch.Alloc("addr\0");
uint argLengthStringAddress = StaticScratch.Alloc("length\0");
uint argFormatStringAddress = StaticScratch.Alloc("arg%01d\0");
uint returnFormatAddress = StaticScratch.Alloc("eax=0x%X\0");
var asm = new Assembler(32);
#region HrSendGetMemory2Data
uint getmem2CallbackAddress = 0;
if (!HasFastGetmem)
{
// labels
var label1 = asm.CreateLabel();
var label2 = asm.CreateLabel();
var label3 = asm.CreateLabel();
asm.push(ebx);
asm.mov(ebx, __dword_ptr[esp + 8]); // pdmcc
asm.mov(eax, __dword_ptr[ebx + 0x14]); // size
asm.test(eax, eax);
asm.mov(edx, __dword_ptr[ebx + 0x10]);
asm.ja(label1);
//asm.push(__dword_ptr[ebx + 8]);
//asm.call((uint)target.Signatures["DmFreePool"]);
//asm.and(__dword_ptr[ebx + 8], 0);
asm.mov(eax, 0x82DB0104);
asm.jmp(label3);
asm.Label(ref label1);
asm.mov(ecx, __dword_ptr[ebx + 0xC]); // buffer size
asm.cmp(eax, ecx);
asm.jb(label2);
asm.mov(eax, ecx);
asm.Label(ref label2);
asm.push(ebp);
asm.push(esi);
asm.mov(esi, __dword_ptr[edx + 0x14]); // address
asm.push(edi);
asm.mov(edi, __dword_ptr[ebx + 8]);
asm.mov(ecx, eax);
asm.mov(ebp, ecx);
asm.shr(ecx, 2);
asm.rep.movsd();
asm.mov(ecx, ebp);
asm.and(ecx, 3);
asm.rep.movsb();
asm.sub(__dword_ptr[ebx + 0x14], eax);
asm.pop(edi);
asm.mov(__dword_ptr[ebx + 4], eax);
asm.add(__dword_ptr[edx + 0x14], eax);
asm.pop(esi);
asm.mov(eax, 0x2DB0000);
asm.pop(ebp);
asm.Label(ref label3);
asm.pop(ebx);
asm.ret(0xC);
getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));
}
#endregion
#region HrFunctionCall
// 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different
asm = new Assembler(32);
// labels
var binaryResponseLabel = asm.CreateLabel();
var getmem2Label = asm.CreateLabel();
var errorLabel = asm.CreateLabel();
var successLabel = asm.CreateLabel();
// prolog
asm.push(ebp);
asm.mov(ebp, esp);
asm.sub(esp, 0x10); // carve out arbitrary space for local temp variables
asm.pushad();
// disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space
asm.mov(eax, cr0);
asm.and(eax, 0xFFFEFFFF);
asm.mov(cr0, eax);
// arguments
var commandPtr = ebp + 0x8;
var responseAddress = ebp + 0xC;
var pdmcc = ebp + 0x14;
// local variables
var temp = ebp - 0x4;
var callAddress = ebp - 0x8;
var argName = ebp - 0x10;
// check for thread id
asm.lea(eax, temp);
asm.push(eax);
asm.push(argThreadStringAddress); // 'thread', 0
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetDwParam"]);
asm.test(eax, eax);
var customCommandLabel = asm.CreateLabel();
asm.je(customCommandLabel);
// call original code if thread id exists
asm.push(__dword_ptr[temp]);
asm.call((uint)target.Signatures["DmSetupFunctionCall"]);
var doneLabel = asm.CreateLabel();
asm.jmp(doneLabel);
// thread argument doesn't exist, must be a custom command
asm.Label(ref customCommandLabel);
// determine custom function type
asm.lea(eax, temp);
asm.push(eax);
asm.push(argTypeStringAddress); // 'type', 0
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetDwParam"]);
asm.test(eax, eax);
asm.je(errorLabel);
#region Custom Call (type 0)
asm.cmp(__dword_ptr[temp], 0);
asm.jne(getmem2Label);
// get the call address
asm.lea(eax, __dword_ptr[callAddress]);
asm.push(eax);
asm.push(argAddrStringAddress); // 'addr', 0
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetDwParam"]);
asm.test(eax, eax);
asm.je(errorLabel);
// push arguments (leave it up to caller to reverse argument order and supply the correct amount)
asm.xor(edi, edi);
var nextArgLabel = asm.CreateLabel();
var noMoreArgsLabel = asm.CreateLabel();
asm.Label(ref nextArgLabel);
{
// get argument name
asm.push(edi); // argument index
asm.push(argFormatStringAddress); // format string address
asm.lea(eax, __dword_ptr[argName]); // argument name address
asm.push(eax);
asm.call((uint)target.Signatures["sprintf"]);
asm.add(esp, 0xC);
// check if it's included in the command
asm.lea(eax, __[temp]); // argument value address
asm.push(eax);
asm.lea(eax, __[argName]); // argument name address
asm.push(eax);
asm.push(__dword_ptr[commandPtr]); // command
asm.call((uint)target.Signatures["FGetDwParam"]);
asm.test(eax, eax);
asm.je(noMoreArgsLabel);
// push it on the stack
asm.push(__dword_ptr[temp]);
asm.inc(edi);
// move on to the next argument
asm.jmp(nextArgLabel);
}
asm.Label(ref noMoreArgsLabel);
// perform the call
asm.call(__dword_ptr[callAddress]);
// print response message
asm.push(eax); // integer return value
asm.push(returnFormatAddress); // format string address
asm.push(__dword_ptr[responseAddress]); // response address
asm.call((uint)target.Signatures["sprintf"]);
asm.add(esp, 0xC);
asm.jmp(successLabel);
#endregion
#region Fast Getmem (type 1)
asm.Label(ref getmem2Label);
asm.cmp(__dword_ptr[temp], 1);
asm.jne(errorLabel);
if (!HasFastGetmem)
{
// TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)
StaticScratch.Align16();
uint getmem2BufferSize = 512;
uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);
// get length and size args
asm.mov(esi, __dword_ptr[pdmcc]);
asm.push(__dword_ptr[responseAddress]);
asm.mov(edi, __dword_ptr[esi + 0x10]);
asm.lea(eax, __dword_ptr[pdmcc]);
asm.push(eax);
asm.push(argAddrStringAddress);
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetNamedDwParam"]);
asm.test(eax, eax);
asm.jz(errorLabel);
asm.push(__dword_ptr[responseAddress]);
asm.lea(eax, __dword_ptr[responseAddress]);
asm.push(eax);
asm.push(argLengthStringAddress);
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetNamedDwParam"]);
asm.test(eax, eax);
asm.jz(errorLabel);
asm.mov(eax, __dword_ptr[pdmcc]); // address
asm.and(__dword_ptr[edi + 0x10], 0);
asm.mov(__dword_ptr[edi + 0x14], eax);
//asm.mov(eax, 0x2000); // TODO: increase pool size?
//asm.push(eax);
//asm.call((uint)target.Signatures["DmAllocatePool"]); // TODO: crashes in here, possible IRQ issues?
asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); // buffer size
asm.mov(__dword_ptr[esi + 8], getmem2buffer); // buffer address
asm.mov(eax, __dword_ptr[responseAddress]);
asm.mov(__dword_ptr[esi + 0x14], eax);
asm.mov(__dword_ptr[esi], getmem2CallbackAddress);
asm.jmp(binaryResponseLabel);
}
#endregion
#region Return Codes
// if we're here, must be an unknown custom type
asm.jmp(errorLabel);
// generic success epilog
asm.Label(ref successLabel);
asm.popad();
asm.leave();
asm.mov(eax, 0x2DB0000);
asm.ret(0x10);
// successful binary response follows epilog
asm.Label(ref binaryResponseLabel);
asm.popad();
asm.leave();
asm.mov(eax, 0x2DB0003);
asm.ret(0x10);
// generic failure epilog
asm.Label(ref errorLabel);
asm.popad();
asm.leave();
asm.mov(eax, 0x82DB0000);
asm.ret(0x10);
// original epilog
asm.Label(ref doneLabel);
asm.popad();
asm.leave();
asm.ret(0x10);
#endregion
// inject RPC handler and hook
uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));
Log.Information("HrFuncCall address {0}", caveAddress.ToHexString());
asm.Hook(target, target.Signatures["HrFunctionCall"], caveAddress);
#endregion
}
public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)
{
// read code from xbox memory
byte[] code = Memory.ReadBytes(address, length);
// disassemble valid instructions
var decoder = Iced.Intel.Decoder.Create(32, code);
decoder.IP = (ulong)address;
var instructions = new List<Instruction>();
while (decoder.IP < decoder.IP + (uint)code.Length)
{
var insn = decoder.Decode();
if (insn.IsInvalid)
break;
instructions.Add(insn);
}
// formatting options
var formatter = new MasmFormatter();
formatter.Options.FirstOperandCharIndex = 8;
formatter.Options.SpaceAfterOperandSeparator = true;
// convert to string
var output = new StringOutput();
var disassembly = new StringBuilder();
bool firstInstruction = true;
foreach (var instr in instructions)
{
// skip newline for the first instruction
if (firstInstruction)
{
firstInstruction = false;
} else disassembly.AppendLine();
// optionally indent
if (tabPrefix)
{
disassembly.Append('\t');
}
// output address
disassembly.Append(instr.IP.ToString("X8"));
disassembly.Append(' ');
// optionally output instruction bytes
if (showBytes)
{
for (int i = 0; i < instr.Length; i++)
disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString("X2"));
int missingBytes = 10 - instr.Length;
for (int i = 0; i < missingBytes; i++)
disassembly.Append(" ");
disassembly.Append(' ');
}
// output the decoded instruction
formatter.Format(instr, output);
disassembly.Append(output.ToStringAndReset());
}
return disassembly.ToString();
}
public Dictionary<string, long> Signatures
{
get
{
var signatures = _cache.Get<Dictionary<string, long>>(nameof(Signatures));
if (signatures == null)
{
var resolver = new SignatureResolver
{
// NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect
// universal pattern
new SodmaSignature("ReadWriteOneSector")
{
// mov ebp, esp
new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),
// mov dx, 1F6h
new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),
// mov al, 0A0h
new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })
},
// universal pattern
new SodmaSignature("WriteSMBusByte")
{
// mov al, 20h
new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),
// mov dx, 0C004h
new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),
},
// universal pattern
new SodmaSignature("FGetDwParam")
{
// jz short 0x2C
new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),
// push 20h
new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),
// mov [ecx], eax
new OdmPattern(0x33, new byte[] { 0x89, 0x01 })
},
// universal pattern
new SodmaSignature("FGetNamedDwParam")
{
// mov ebp, esp
new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),
// jnz short 0x17
new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),
// retn 10h
new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })
},
// universal pattern
new SodmaSignature("DmSetupFunctionCall")
{
// test ax, 280h
new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),
// push 63666D64h
new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })
},
// early revisions
new SodmaSignature("HrFunctionCall")
{
// mov eax, 80004005h
new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),
// mov ebx, 10008h
new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })
},
// later revisions
new SodmaSignature("HrFunctionCall")
{
// mov eax, 80004005h
new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),
// mov ebx, 10008h
new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })
},
// xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha/dvt3/dvt4/dvt6 etc.
new SodmaSignature("sprintf")
{
// mov esi, [ebp+arg_0]
new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),
// mov [ebp+var_1C], 7FFFFFFFh
new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })
},
// early revisions
new SodmaSignature("DmAllocatePool")
{
// push ebp
new OdmPattern(0x0, new byte[] { 0x55 }),
// mov ebp, esp
new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),
// push 'enoN'
new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })
},
// later revisions
new SodmaSignature("DmAllocatePool")
{
// push 'enoN'
new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),
// retn 4
new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })
},
// universal pattern
new SodmaSignature("DmFreePool")
{
// cmp eax, 0B0000000h
new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })
}
};
// read xbdm .text section
var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals("xbdm.dll")).GetSection(".text");
byte[] data = new byte[xbdmTextSegment.Size];
ReadMemory(xbdmTextSegment.Base, data);
// scan for signatures
signatures = resolver.Resolve(data, xbdmTextSegment.Base);
// cache the result indefinitely
_cache.Set(nameof(Signatures), signatures);
}
return signatures;
}
}
#endregion
#region File
public char[] GetDrives()
{
return Session.SendCommandStrict("drivelist").Message.ToCharArray();
}
public List<XboxFileInformation> GetDirectoryList(string path)
{
var list = new List<XboxFileInformation>();
Session.SendCommandStrict("dirlist name=\"{0}\"", path);
foreach (string file in Session.ReceiveMultilineResponse())
{
var fileInfo = file.ParseXboxResponseLine();
var info = new XboxFileInformation();
info.FullName = Path.Combine(path, (string)fileInfo["name"]);
info.Size = ((long)fileInfo["sizehi"] << 32) | (long)fileInfo["sizelo"];
info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo["createhi"] << 32) | (long)fileInfo["createlo"]);
info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo["changehi"] << 32) | (long)fileInfo["changelo"]);
info.Attributes |= file.Contains("directory") ? FileAttributes.Directory : FileAttributes.Normal;
info.Attributes |= file.Contains("readonly") ? FileAttributes.ReadOnly : 0;
info.Attributes |= file.Contains("hidden") ? FileAttributes.Hidden : 0;
list.Add(info);
}
return list;
}
public void GetFile(string localPath, string remotePath)
{
Session.SendCommandStrict("getfile name=\"{0}\"", remotePath);
using var lfs = File.Create(localPath);
Session.CopyToCount(lfs, Session.Reader.ReadInt32());
}
#endregion
#region IDisposable
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
Session?.Dispose();
// TODO: set large fields to null
_disposed = true;
}
}
~Xbox()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| src/OGXbdmDumper/Xbox.cs | Ernegien-OGXbdmDumper-07a1e82 | [
{
"filename": "src/OGXbdmDumper/Connection.cs",
"retrieved_chunk": " /// <summary>\n /// The time in milliseconds to wait while sending data before throwing a TimeoutException.\n /// </summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n /// <summary>\n /// The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n /// </summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction",
"score": 0.90028977394104
},
{
"filename": "src/OGXbdmDumper/Connection.cs",
"retrieved_chunk": " /// </summary>\n public BinaryReader Reader { get; private set; }\n /// <summary>\n /// The binary writer for the session stream.\n /// </summary>\n public BinaryWriter Writer { get; private set; }\n /// <summary>\n /// Returns true if the session thinks it's connected based on the most recent operation.\n /// </summary>\n public bool IsConnected => _client.Connected;",
"score": 0.8911946415901184
},
{
"filename": "src/OGXbdmDumper/ConnectionInfo.cs",
"retrieved_chunk": " public IPEndPoint Endpoint { get; set; }\n public string? Name { get; set; }\n public ConnectionInfo(IPEndPoint endpoint, string? name = null)\n {\n Endpoint = endpoint;\n Name = name;\n }\n public static List<ConnectionInfo> DiscoverXbdm(int port, int timeout = 500)\n {\n Log.Information(\"Performing Xbox debug monitor network discovery broadcast on UDP port {Port}.\", port);",
"score": 0.8700642585754395
},
{
"filename": "src/OGXbdmDumper/XboxMemoryStream.cs",
"retrieved_chunk": " public override void Flush() { throw new NotSupportedException(); }\n /// <summary>\n /// TODO: description. possibly return total memory size\n /// </summary>\n public override long Length { get { throw new NotSupportedException(); } }\n /// <summary>\n /// TODO: description\n /// </summary>\n /// <param name=\"value\"></param>\n public override void SetLength(long value) { throw new NotSupportedException(); }",
"score": 0.8405430912971497
},
{
"filename": "src/OGXbdmDumper/MemoryRegion.cs",
"retrieved_chunk": "namespace OGXbdmDumper\n{\n public class MemoryRegion\n {\n public uint Address { get; }\n public int Size { get; }\n public MemoryRegion(uint address, int size)\n { \n Address = address;\n Size = size;",
"score": 0.8391302824020386
}
] | csharp | XboxMemoryStream Memory { |
using JWLSLMerge.Data.Attributes;
namespace JWLSLMerge.Data.Models
{
public class BlockRange
{
[ | Ignore]
public int BlockRangeId { | get; set; }
public int BlockType { get; set; }
public int Identifier { get; set; }
public int? StartToken { get; set; }
public int? EndToken { get; set; }
public int UserMarkId { get; set; }
}
}
| JWLSLMerge.Data/Models/BlockRange.cs | pliniobrunelli-JWLSLMerge-7fe66dc | [
{
"filename": "JWLSLMerge.Data/Attributes/Ignore.cs",
"retrieved_chunk": "namespace JWLSLMerge.Data.Attributes\n{\n [AttributeUsage(AttributeTargets.Property)]\n public class IgnoreAttribute : Attribute { }\n}",
"score": 0.8364207744598389
},
{
"filename": "JWLSLMerge.Data/Models/Tag.cs",
"retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class Tag\n {\n [Ignore]\n public int TagId { get; set; }\n public int Type { get; set; }\n public string Name { get; set; } = null!;\n [Ignore]",
"score": 0.7987631559371948
},
{
"filename": "JWLSLMerge.Data/JWDal.cs",
"retrieved_chunk": "using Dapper;\nusing JWLSLMerge.Data.Attributes;\nusing System.Data;\nusing System.Data.SQLite;\nnamespace JWLSLMerge.Data\n{\n public class JWDal\n {\n private string connectionString;\n public JWDal(string dbPath)",
"score": 0.7899674773216248
},
{
"filename": "JWLSLMerge.Data/Models/UserMark.cs",
"retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class UserMark\n {\n [Ignore]\n public int UserMarkId { get; set; }\n public int ColorIndex { get; set; }\n public int LocationId { get; set; }\n public int StyleIndex { get; set; }",
"score": 0.7788680791854858
},
{
"filename": "JWLSLMerge.Data/Models/Location.cs",
"retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class Location\n {\n [Ignore]\n public int LocationId { get; set; }\n public int? BookNumber { get; set; }\n public int? ChapterNumber { get; set; }\n public int? DocumentId { get; set; }",
"score": 0.7784022092819214
}
] | csharp | Ignore]
public int BlockRangeId { |
using System;
using UnityEngine;
namespace Kingdox.UniFlux.Benchmark
{
public sealed class Benchmark_Nest_UniFlux : MonoFlux
{
[SerializeField] private Marker _mark_fluxAttribute = new Marker()
{
K = "NestedModel Flux Attribute"
};
[SerializeField] private Marker _mark_store = new Marker()
{
K = "NestedModel Store"
};
private readonly Lazy<GUIStyle> _style = new Lazy<GUIStyle>(() => new GUIStyle("label")
{
fontSize = 28,
alignment = TextAnchor.MiddleLeft,
padding = new RectOffset(10, 0, 0, 0)
});
private Rect rect_area;
public int iteration;
protected override void OnFlux(in bool condition)
{
"1".Store(Store_1, condition);
"2".Store(Store_2, condition);
"3".Store(Store_3, condition);
"4".Store(Store_4, condition);
"5".Store(Store_5, condition);
}
private void Update()
{
Sample();
Sample_2();
}
[ | Flux("A")] private void A() => "B".Dispatch(); |
[Flux("B")] private void B() => "C".Dispatch();
[Flux("C")] private void C() => "D".Dispatch();
[Flux("D")] private void D() => "E".Dispatch();
[Flux("E")] private void E() {}
private void Store_1() => "2".Dispatch();
private void Store_2() => "3".Dispatch();
private void Store_3() => "4".Dispatch();
private void Store_4() => "5".Dispatch();
private void Store_5() {}
private void Sample()
{
if (_mark_fluxAttribute.Execute)
{
_mark_fluxAttribute.iteration = iteration;
_mark_fluxAttribute.Begin();
for (int i = 0; i < iteration; i++) "A".Dispatch();
_mark_fluxAttribute.End();
}
}
private void Sample_2()
{
if (_mark_store.Execute)
{
_mark_store.iteration = iteration;
_mark_store.Begin();
for (int i = 0; i < iteration; i++) "1".Dispatch();
_mark_store.End();
}
}
private void OnGUI()
{
if (_mark_fluxAttribute.Execute)
{
// Flux
rect_area = new Rect(0, _style.Value.lineHeight, Screen.width, Screen.height / 2);
GUI.Label(rect_area, _mark_fluxAttribute.Visual, _style.Value);
}
if (_mark_store.Execute)
{
// Store
rect_area = new Rect(0, _style.Value.lineHeight * 2, Screen.width, Screen.height / 2);
GUI.Label(rect_area, _mark_store.Visual, _style.Value);
}
}
}
} | Benchmark/Nest/Benchmark_Nest_UniFlux.cs | xavierarpa-UniFlux-a2d46de | [
{
"filename": "Tests/EditMode/EditMode_Test_1.cs",
"retrieved_chunk": " [Test] public void SubscribeFuncParam()\n {\n Flux.Store<string,float,float>(\"OnTest\", OnTest_FuncPatam, true);\n }\n [Test] public void DispatchAction()\n {\n Flux.Dispatch(\"OnTest\");\n }\n [Test] public void DispatchActionParam()\n {",
"score": 0.8549137711524963
},
{
"filename": "Samples/UniFlux.Sample.2/Sample_2.cs",
"retrieved_chunk": "{\n public sealed class Sample_2 : MonoFlux\n {\n protected override void OnFlux(in bool condition)\n {\n \"Sample_2\".Store(Method, condition);\n }\n private void Start() \n {\n \"Sample_2\".Dispatch();",
"score": 0.8364790678024292
},
{
"filename": "Samples/UniFlux.Sample.1/Sample_1.cs",
"retrieved_chunk": "{\n public sealed class Sample_1 : MonoFlux\n {\n private void Start() \n {\n \"Sample_1\".Dispatch();\n }\n [Flux(\"Sample_1\")] private void Method() \n {\n Debug.Log(\"Sample_1 !\");",
"score": 0.8356789350509644
},
{
"filename": "Tests/EditMode/EditMode_Test_1.cs",
"retrieved_chunk": " Flux.Dispatch(\"OnTest\", true);\n }\n [Test] public void DispatchFunc()\n {\n var val = Flux.Dispatch<string,int>(\"OnTest\");\n }\n [Test] public void DispatchFuncParam()\n {\n var val_2 = Flux.Dispatch<string, float, float>(\"OnTest\", 3f);\n }",
"score": 0.8345603942871094
},
{
"filename": "Tests/EditMode/EditMode_Test_1.cs",
"retrieved_chunk": " Flux.Store<string, int>(\"OnTest\", OnTest_Func, false);\n }\n [Test] public void UnsubscribeFuncParam()\n {\n Flux.Store<string, float, float>(\"OnTest\", OnTest_FuncPatam, false);\n }\n public void OnTest_Action() {}\n public void OnTest_ActionParam(bool condition) {}\n public int OnTest_Func() => 1;\n public float OnTest_FuncPatam(float value) => value;",
"score": 0.8286561965942383
}
] | csharp | Flux("A")] private void A() => "B".Dispatch(); |
using Canvas.CLI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Canvas.Library.Services
{
public class StudentService
{
private static StudentService? instance;
private static object _lock = new object();
public static StudentService Current {
get
{
lock(_lock)
{
if (instance == null)
{
instance = new StudentService();
}
}
return instance;
}
}
private List< | Student> enrollments; |
private StudentService()
{
enrollments = new List<Student>
{
new Student{Id = 1, Name = "John Smith"},
new Student{Id = 2, Name = "Bob Smith"},
new Student{Id = 3, Name = "Sue Smith"}
};
}
public List<Student> Enrollments
{
get { return enrollments; }
}
public List<Student> Search(string query)
{
return Enrollments.Where(s => s.Name.ToUpper().Contains(query.ToUpper())).ToList();
}
public Student? Get(int id)
{
return enrollments.FirstOrDefault(e => e.Id == id);
}
public void Add(Student? student)
{
if (student != null) {
enrollments.Add(student);
}
}
public void Delete(int id)
{
var enrollmentToRemove = Get(id);
if (enrollmentToRemove != null)
{
enrollments.Remove(enrollmentToRemove);
}
}
public void Delete(Student s)
{
Delete(s.Id);
}
public void Read()
{
enrollments.ForEach(Console.WriteLine);
}
}
}
| Canvas.Library/Services/StudentService.cs | crmillsfsu-Canvas_Su2023-bcfeccd | [
{
"filename": "Canvas.CLI/Program.cs",
"retrieved_chunk": " CourseMenu(courses);\n }\n static void CourseMenu(List<Course> courses) {\n var myStudentService = StudentService.Current;\n }\n static void StudentMenu()\n {\n var studentService = StudentService.Current;\n while (true)\n {",
"score": 0.8272334337234497
},
{
"filename": "Canvas.MAUI/ViewModels/MainViewModel.cs",
"retrieved_chunk": " if(SelectedStudent == null)\n {\n return;\n }\n StudentService.Current.Delete(SelectedStudent);\n NotifyPropertyChanged(\"Students\");\n }\n public Student SelectedStudent { get; set; }\n public event PropertyChangedEventHandler PropertyChanged;\n private void NotifyPropertyChanged([CallerMemberName] String propertyName = \"\")",
"score": 0.819542407989502
},
{
"filename": "Canvas.MAUI/ViewModels/MainViewModel.cs",
"retrieved_chunk": " }\n return new ObservableCollection<Student>(StudentService.Current.Search(Query));\n }\n }\n public string Query { get; set; }\n public void Search() {\n NotifyPropertyChanged(\"Students\");\n }\n public void Delete()\n {",
"score": 0.8150521516799927
},
{
"filename": "Canvas.Library/Models/Student.cs",
"retrieved_chunk": " public string Name { get; set; }\n public Student()\n {\n Name = string.Empty;\n }\n public override string ToString()\n {\n return $\"{Id}. {Name}\";\n }\n }",
"score": 0.7972747087478638
},
{
"filename": "Canvas.CLI/Program.cs",
"retrieved_chunk": " }\n else\n {\n Console.WriteLine(\"Sorry, that functionality isn't supported\");\n }\n }\n }\n }\n}",
"score": 0.7929888963699341
}
] | csharp | Student> enrollments; |
using ChatGPTConnection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChatUI
{
public delegate void ChatGPTResponseEventHandler(object sender, ChatGPTResponseEventArgs e);
public class ChatGPTResponseEventArgs : EventArgs
{
public | ChatGPTResponseModel Response { | get; private set; }
public ChatGPTResponseEventArgs(ChatGPTResponseModel response)
{
Response = response;
}
}
}
| ChatUI/ChatGPTResponseEvent.cs | 4kk11-ChatGPTforRhino-382323e | [
{
"filename": "ChatUI/MainWindow.xaml.cs",
"retrieved_chunk": "using ChatUI.MVVM.ViewModel;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing ChatGPTConnection;\nnamespace ChatUI\n{\n\tpublic partial class MainWindow : Window\n\t{\n\t\tpublic static string DllDirectory\n\t\t{",
"score": 0.8048213720321655
},
{
"filename": "ChatGPTforRhino/ChatGPTforRhinoPlugin.cs",
"retrieved_chunk": "using Rhino;\nusing Rhino.PlugIns;\nusing System;\nnamespace ChatGPTforRhino\n{\n\tpublic class ChatGPTforRhinoPlugin : Rhino.PlugIns.PlugIn\n\t{\n\t\tpublic ChatGPTforRhinoPlugin()\n\t\t{\n\t\t\tInstance = this;",
"score": 0.8025808334350586
},
{
"filename": "ChatUI/MVVM/ViewModel/MainViewModel.cs",
"retrieved_chunk": "using System.Threading.Tasks;\nusing System.Windows;\nnamespace ChatUI.MVVM.ViewModel\n{\n\tinternal class MainViewModel : ObservableObject\n\t{\n\t\tpublic ObservableCollection<MessageModel> Messages { get; set; }\n\t\tprivate MainWindow MainWindow { get; set; }\n\t\tpublic RelayCommand SendCommand { get; set; }\n\t\tprivate string _message = \"\";",
"score": 0.7771339416503906
},
{
"filename": "ChatGPTforRhino/RhinoCommand.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Rhino;\nnamespace ChatGPTforRhino\n{\n\tpublic class RhinoCommands\n\t{",
"score": 0.7693415880203247
},
{
"filename": "ChatUI/Core/RelayCommand.cs",
"retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nnamespace ChatUI.Core\n{\n\tclass RelayCommand : ICommand\n\t{",
"score": 0.7689300179481506
}
] | csharp | ChatGPTResponseModel Response { |
using NowPlaying.Utils;
using NowPlaying.ViewModels;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
namespace NowPlaying.Views
{
/// <summary>
/// Interaction logic for AddGameCachesView.xaml
/// </summary>
public partial class AddGameCachesView : UserControl
{
private readonly | AddGameCachesViewModel viewModel; |
public AddGameCachesView(AddGameCachesViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
this.viewModel = viewModel;
}
public void EligibleGames_OnMouseUp(object sender, MouseButtonEventArgs e)
{
viewModel.SelectedGames = EligibleGames.SelectedItems.Cast<GameViewModel>().ToList();
}
public void EligibleGames_ClearSelected()
{
EligibleGames.SelectedItems.Clear();
viewModel.SelectedGames = new List<GameViewModel>();
}
public void EligibleGames_SelectAll()
{
EligibleGames.SelectAll();
viewModel.SelectedGames = viewModel.EligibleGames;
}
private void PreviewMouseWheelToParent(object sender, MouseWheelEventArgs e)
{
GridViewUtils.MouseWheelToParent(sender, e);
}
}
}
| source/Views/AddGameCachesView.xaml.cs | gittromney-Playnite-NowPlaying-23eec41 | [
{
"filename": "source/Views/AddCacheRootView.xaml.cs",
"retrieved_chunk": "using NowPlaying.ViewModels;\nusing System.Windows.Controls;\nnamespace NowPlaying.Views\n{\n /// <summary>\n /// Interaction logic for AddCacheRootView.xaml\n /// </summary>\n public partial class AddCacheRootView : UserControl\n {\n public AddCacheRootView(AddCacheRootViewModel viewModel)",
"score": 0.9467419981956482
},
{
"filename": "source/Views/TopPanelView.xaml.cs",
"retrieved_chunk": "using NowPlaying.ViewModels;\nusing System.Windows.Controls;\nnamespace NowPlaying.Views\n{\n /// <summary>\n /// Interaction logic for PercentDone.xaml\n /// </summary>\n public partial class TopPanelView : UserControl\n {\n public TopPanelView(TopPanelViewModel viewModel)",
"score": 0.9338080883026123
},
{
"filename": "source/Views/EditMaxFillView.xaml.cs",
"retrieved_chunk": "using NowPlaying.ViewModels;\nusing System.Windows.Controls;\nnamespace NowPlaying.Views\n{\n /// <summary>\n /// Interaction logic for EditMaxFillView.xaml\n /// </summary>\n public partial class EditMaxFillView : UserControl\n {\n public EditMaxFillView(EditMaxFillViewModel viewModel)",
"score": 0.9321449398994446
},
{
"filename": "source/Views/InstallProgressView.xaml.cs",
"retrieved_chunk": "\nusing NowPlaying.ViewModels;\nusing System.Windows.Controls;\nnamespace NowPlaying.Views\n{\n /// <summary>\n /// Interaction logic for InstallProgressView.xaml\n /// </summary>\n public partial class InstallProgressView : UserControl\n {",
"score": 0.9121559858322144
},
{
"filename": "source/Views/NowPlayingPanelView.xaml.cs",
"retrieved_chunk": "{\n /// <summary>\n /// Interaction logic for NowPlayingPanelView.xaml\n /// </summary>\n public partial class NowPlayingPanelView : UserControl\n {\n NowPlayingPanelViewModel viewModel;\n public NowPlayingPanelView(NowPlayingPanelViewModel viewModel)\n {\n InitializeComponent();",
"score": 0.8906940221786499
}
] | csharp | AddGameCachesViewModel viewModel; |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using System.Threading.Tasks;
using Magic.IndexedDb.Helpers;
using Magic.IndexedDb.Models;
using Magic.IndexedDb.SchemaAnnotations;
using Microsoft.JSInterop;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using static System.Collections.Specialized.BitVector32;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Magic.IndexedDb
{
/// <summary>
/// Provides functionality for accessing IndexedDB from Blazor application
/// </summary>
public class IndexedDbManager
{
readonly DbStore _dbStore;
readonly IJSRuntime _jsRuntime;
const string InteropPrefix = "window.magicBlazorDB";
DotNetObjectReference<IndexedDbManager> _objReference;
IDictionary<Guid, WeakReference<Action<BlazorDbEvent>>> _transactions = new Dictionary<Guid, WeakReference<Action<BlazorDbEvent>>>();
IDictionary<Guid, TaskCompletionSource<BlazorDbEvent>> _taskTransactions = new Dictionary<Guid, TaskCompletionSource<BlazorDbEvent>>();
private IJSObjectReference? _module { get; set; }
/// <summary>
/// A notification event that is raised when an action is completed
/// </summary>
public event EventHandler<BlazorDbEvent> ActionCompleted;
/// <summary>
/// Ctor
/// </summary>
/// <param name="dbStore"></param>
/// <param name="jsRuntime"></param>
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
internal IndexedDbManager(DbStore dbStore, IJSRuntime jsRuntime)
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
{
_objReference = DotNetObjectReference.Create(this);
_dbStore = dbStore;
_jsRuntime = jsRuntime;
}
public async Task<IJSObjectReference> GetModule(IJSRuntime jsRuntime)
{
if (_module == null)
{
_module = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/Magic.IndexedDb/magicDB.js");
}
return _module;
}
public List<StoreSchema> Stores => _dbStore.StoreSchemas;
public string CurrentVersion => _dbStore.Version;
public string DbName => _dbStore.Name;
/// <summary>
/// Opens the IndexedDB defined in the DbStore. Under the covers will create the database if it does not exist
/// and create the stores defined in DbStore.
/// </summary>
/// <returns></returns>
public async Task<Guid> OpenDb(Action<BlazorDbEvent>? action = null)
{
var trans = GenerateTransaction(action);
await CallJavascriptVoid(IndexedDbFunctions.CREATE_DB, trans, _dbStore);
return trans;
}
/// <summary>
/// Deletes the database corresponding to the dbName passed in
/// </summary>
/// <param name="dbName">The name of database to delete</param>
/// <returns></returns>
public async Task<Guid> DeleteDb(string dbName, Action<BlazorDbEvent>? action = null)
{
if (string.IsNullOrEmpty(dbName))
{
throw new ArgumentException("dbName cannot be null or empty", nameof(dbName));
}
var trans = GenerateTransaction(action);
await CallJavascriptVoid(IndexedDbFunctions.DELETE_DB, trans, dbName);
return trans;
}
/// <summary>
/// Deletes the database corresponding to the dbName passed in
/// Waits for response
/// </summary>
/// <param name="dbName">The name of database to delete</param>
/// <returns></returns>
public async Task<BlazorDbEvent> DeleteDbAsync(string dbName)
{
if (string.IsNullOrEmpty(dbName))
{
throw new ArgumentException("dbName cannot be null or empty", nameof(dbName));
}
var trans = GenerateTransaction();
await CallJavascriptVoid(IndexedDbFunctions.DELETE_DB, trans.trans, dbName);
return await trans.task;
}
/// <summary>
/// Adds a new record/object to the specified store
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="recordToAdd">An instance of StoreRecord that provides the store name and the data to add</param>
/// <returns></returns>
private async Task<Guid> AddRecord<T>(StoreRecord<T> recordToAdd, Action<BlazorDbEvent>? action = null)
{
var trans = GenerateTransaction(action);
try
{
recordToAdd.DbName = DbName;
await CallJavascriptVoid(IndexedDbFunctions.ADD_ITEM, trans, recordToAdd);
}
catch (JSException e)
{
RaiseEvent(trans, true, e.Message);
}
return trans;
}
public async Task<Guid> Add<T>(T record, Action<BlazorDbEvent>? action = null) where T : class
{
string schemaName = SchemaHelper.GetSchemaName<T>();
T? myClass = null;
object? processedRecord = await ProcessRecord(record);
if (processedRecord is ExpandoObject)
myClass = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(processedRecord));
else
myClass = (T?)processedRecord;
var trans = GenerateTransaction(action);
try
{
Dictionary<string, object?>? convertedRecord = null;
if (processedRecord is ExpandoObject)
{
var result = ((ExpandoObject)processedRecord)?.ToDictionary(kv => kv.Key, kv => (object?)kv.Value);
if (result != null)
{
convertedRecord = result;
}
}
else
{
convertedRecord = ManagerHelper.ConvertRecordToDictionary(myClass);
}
var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
// Convert the property names in the convertedRecord dictionary
if (convertedRecord != null)
{
var updatedRecord = ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings);
if (updatedRecord != null)
{
StoreRecord<Dictionary<string, object?>> RecordToSend = new StoreRecord<Dictionary<string, object?>>()
{
DbName = this.DbName,
StoreName = schemaName,
Record = updatedRecord
};
await CallJavascriptVoid(IndexedDbFunctions.ADD_ITEM, trans, RecordToSend);
}
}
}
catch (JSException e)
{
RaiseEvent(trans, true, e.Message);
}
return trans;
}
public async Task<string> Decrypt(string EncryptedValue)
{
EncryptionFactory encryptionFactory = new EncryptionFactory(_jsRuntime, this);
string decryptedValue = await encryptionFactory.Decrypt(EncryptedValue, _dbStore.EncryptionKey);
return decryptedValue;
}
private async Task<object?> ProcessRecord<T>(T record) where T : class
{
string schemaName = SchemaHelper.GetSchemaName<T>();
StoreSchema? storeSchema = Stores.FirstOrDefault(s => s.Name == schemaName);
if (storeSchema == null)
{
throw new InvalidOperationException($"StoreSchema not found for '{schemaName}'");
}
// Encrypt properties with EncryptDb attribute
var propertiesToEncrypt = typeof(T).GetProperties()
.Where(p => p.GetCustomAttributes(typeof(MagicEncryptAttribute), false).Length > 0);
EncryptionFactory encryptionFactory = new EncryptionFactory(_jsRuntime, this);
foreach (var property in propertiesToEncrypt)
{
if (property.PropertyType != typeof(string))
{
throw new InvalidOperationException("EncryptDb attribute can only be used on string properties.");
}
string? originalValue = property.GetValue(record) as string;
if (!string.IsNullOrWhiteSpace(originalValue))
{
string encryptedValue = await encryptionFactory.Encrypt(originalValue, _dbStore.EncryptionKey);
property.SetValue(record, encryptedValue);
}
else
{
property.SetValue(record, originalValue);
}
}
// Proceed with adding the record
if (storeSchema.PrimaryKeyAuto)
{
var primaryKeyProperty = typeof(T)
.GetProperties()
.FirstOrDefault(p => p.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length > 0);
if (primaryKeyProperty != null)
{
Dictionary<string, object?> recordAsDict;
var primaryKeyValue = primaryKeyProperty.GetValue(record);
if (primaryKeyValue == null || primaryKeyValue.Equals(GetDefaultValue(primaryKeyValue.GetType())))
{
recordAsDict = typeof(T).GetProperties()
.Where(p => p.Name != primaryKeyProperty.Name && p.GetCustomAttributes(typeof(MagicNotMappedAttribute), false).Length == 0)
.ToDictionary(p => p.Name, p => p.GetValue(record));
}
else
{
recordAsDict = typeof(T).GetProperties()
.Where(p => p.GetCustomAttributes(typeof(MagicNotMappedAttribute), false).Length == 0)
.ToDictionary(p => p.Name, p => p.GetValue(record));
}
// Create a new ExpandoObject and copy the key-value pairs from the dictionary
var expandoRecord = new ExpandoObject() as IDictionary<string, object?>;
foreach (var kvp in recordAsDict)
{
expandoRecord.Add(kvp);
}
return expandoRecord as ExpandoObject;
}
}
return record;
}
// Returns the default value for the given type
private static object? GetDefaultValue(Type type)
{
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
/// <summary>
/// Adds records/objects to the specified store in bulk
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="recordsToBulkAdd">The data to add</param>
/// <returns></returns>
private async Task<Guid> BulkAddRecord<T>(string storeName, IEnumerable<T> recordsToBulkAdd, Action<BlazorDbEvent>? action = null)
{
var trans = GenerateTransaction(action);
try
{
await CallJavascriptVoid(IndexedDbFunctions.BULKADD_ITEM, trans, DbName, storeName, recordsToBulkAdd);
}
catch (JSException e)
{
RaiseEvent(trans, true, e.Message);
}
return trans;
}
//public async Task<Guid> AddRange<T>(IEnumerable<T> records, Action<BlazorDbEvent> action = null) where T : class
//{
// string schemaName = SchemaHelper.GetSchemaName<T>();
// var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
// List<object> processedRecords = new List<object>();
// foreach (var record in records)
// {
// object processedRecord = await ProcessRecord(record);
// if (processedRecord is ExpandoObject)
// {
// var convertedRecord = ((ExpandoObject)processedRecord).ToDictionary(kv => kv.Key, kv => (object)kv.Value);
// processedRecords.Add(ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings));
// }
// else
// {
// var convertedRecord = ManagerHelper.ConvertRecordToDictionary((T)processedRecord);
// processedRecords.Add(ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings));
// }
// }
// return await BulkAddRecord(schemaName, processedRecords, action);
//}
/// <summary>
/// Adds records/objects to the specified store in bulk
/// Waits for response
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="recordsToBulkAdd">An instance of StoreRecord that provides the store name and the data to add</param>
/// <returns></returns>
private async Task< | BlazorDbEvent> BulkAddRecordAsync<T>(string storeName, IEnumerable<T> recordsToBulkAdd)
{ |
var trans = GenerateTransaction();
try
{
await CallJavascriptVoid(IndexedDbFunctions.BULKADD_ITEM, trans.trans, DbName, storeName, recordsToBulkAdd);
}
catch (JSException e)
{
RaiseEvent(trans.trans, true, e.Message);
}
return await trans.task;
}
public async Task AddRange<T>(IEnumerable<T> records) where T : class
{
string schemaName = SchemaHelper.GetSchemaName<T>();
//var trans = GenerateTransaction(null);
//var TableCount = await CallJavascript<int>(IndexedDbFunctions.COUNT_TABLE, trans, DbName, schemaName);
List<Dictionary<string, object?>> processedRecords = new List<Dictionary<string, object?>>();
foreach (var record in records)
{
bool IsExpando = false;
T? myClass = null;
object? processedRecord = await ProcessRecord(record);
if (processedRecord is ExpandoObject)
{
myClass = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(processedRecord));
IsExpando = true;
}
else
myClass = (T?)processedRecord;
Dictionary<string, object?>? convertedRecord = null;
if (processedRecord is ExpandoObject)
{
var result = ((ExpandoObject)processedRecord)?.ToDictionary(kv => kv.Key, kv => (object?)kv.Value);
if (result != null)
convertedRecord = result;
}
else
{
convertedRecord = ManagerHelper.ConvertRecordToDictionary(myClass);
}
var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
// Convert the property names in the convertedRecord dictionary
if (convertedRecord != null)
{
var updatedRecord = ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings);
if (updatedRecord != null)
{
if (IsExpando)
{
//var test = updatedRecord.Cast<Dictionary<string, object>();
var dictionary = updatedRecord as Dictionary<string, object?>;
processedRecords.Add(dictionary);
}
else
{
processedRecords.Add(updatedRecord);
}
}
}
}
await BulkAddRecordAsync(schemaName, processedRecords);
}
public async Task<Guid> Update<T>(T item, Action<BlazorDbEvent>? action = null) where T : class
{
var trans = GenerateTransaction(action);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute)));
if (primaryKeyProperty != null)
{
object? primaryKeyValue = primaryKeyProperty.GetValue(item);
var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item);
if (primaryKeyValue != null)
{
UpdateRecord<Dictionary<string, object?>> record = new UpdateRecord<Dictionary<string, object?>>()
{
Key = primaryKeyValue,
DbName = this.DbName,
StoreName = schemaName,
Record = convertedRecord
};
// Get the primary key value of the item
await CallJavascriptVoid(IndexedDbFunctions.UPDATE_ITEM, trans, record);
}
else
{
throw new ArgumentException("Item being updated must have a key.");
}
}
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
public async Task<Guid> UpdateRange<T>(IEnumerable<T> items, Action<BlazorDbEvent>? action = null) where T : class
{
var trans = GenerateTransaction(action);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute)));
if (primaryKeyProperty != null)
{
List<UpdateRecord<Dictionary<string, object?>>> recordsToUpdate = new List<UpdateRecord<Dictionary<string, object?>>>();
foreach (var item in items)
{
object? primaryKeyValue = primaryKeyProperty.GetValue(item);
var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item);
if (primaryKeyValue != null)
{
recordsToUpdate.Add(new UpdateRecord<Dictionary<string, object?>>()
{
Key = primaryKeyValue,
DbName = this.DbName,
StoreName = schemaName,
Record = convertedRecord
});
}
await CallJavascriptVoid(IndexedDbFunctions.BULKADD_UPDATE, trans, recordsToUpdate);
}
}
else
{
throw new ArgumentException("Item being update range item must have a key.");
}
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
public async Task<TResult?> GetById<TResult>(object key) where TResult : class
{
string schemaName = SchemaHelper.GetSchemaName<TResult>();
// Find the primary key property
var primaryKeyProperty = typeof(TResult)
.GetProperties()
.FirstOrDefault(p => p.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length > 0);
if (primaryKeyProperty == null)
{
throw new InvalidOperationException("No primary key property found with PrimaryKeyDbAttribute.");
}
// Check if the key is of the correct type
if (!primaryKeyProperty.PropertyType.IsInstanceOfType(key))
{
throw new ArgumentException($"Invalid key type. Expected: {primaryKeyProperty.PropertyType}, received: {key.GetType()}");
}
var trans = GenerateTransaction(null);
string columnName = primaryKeyProperty.GetPropertyColumnName<MagicPrimaryKeyAttribute>();
var data = new { DbName = DbName, StoreName = schemaName, Key = columnName, KeyValue = key };
try
{
var propertyMappings = ManagerHelper.GeneratePropertyMapping<TResult>();
var RecordToConvert = await CallJavascript<Dictionary<string, object>>(IndexedDbFunctions.FIND_ITEMV2, trans, data.DbName, data.StoreName, data.KeyValue);
if (RecordToConvert != null)
{
var ConvertedResult = ConvertIndexedDbRecordToCRecord<TResult>(RecordToConvert, propertyMappings);
return ConvertedResult;
}
else
{
return default(TResult);
}
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return default(TResult);
}
public MagicQuery<T> Where<T>(Expression<Func<T, bool>> predicate) where T : class
{
string schemaName = SchemaHelper.GetSchemaName<T>();
MagicQuery<T> query = new MagicQuery<T>(schemaName, this);
// Preprocess the predicate to break down Any and All expressions
var preprocessedPredicate = PreprocessPredicate(predicate);
var asdf = preprocessedPredicate.ToString();
CollectBinaryExpressions(preprocessedPredicate.Body, preprocessedPredicate, query.JsonQueries);
return query;
}
private Expression<Func<T, bool>> PreprocessPredicate<T>(Expression<Func<T, bool>> predicate)
{
var visitor = new PredicateVisitor<T>();
var newExpression = visitor.Visit(predicate.Body);
return Expression.Lambda<Func<T, bool>>(newExpression, predicate.Parameters);
}
internal async Task<IList<T>?> WhereV2<T>(string storeName, List<string> jsonQuery, MagicQuery<T> query) where T : class
{
var trans = GenerateTransaction(null);
try
{
string? jsonQueryAdditions = null;
if (query != null && query.storedMagicQueries != null && query.storedMagicQueries.Count > 0)
{
jsonQueryAdditions = Newtonsoft.Json.JsonConvert.SerializeObject(query.storedMagicQueries.ToArray());
}
var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
IList<Dictionary<string, object>>? ListToConvert =
await CallJavascript<IList<Dictionary<string, object>>>
(IndexedDbFunctions.WHEREV2, trans, DbName, storeName, jsonQuery.ToArray(), jsonQueryAdditions!, query?.ResultsUnique!);
var resultList = ConvertListToRecords<T>(ListToConvert, propertyMappings);
return resultList;
}
catch (Exception jse)
{
RaiseEvent(trans, true, jse.Message);
}
return default;
}
private void CollectBinaryExpressions<T>(Expression expression, Expression<Func<T, bool>> predicate, List<string> jsonQueries) where T : class
{
var binaryExpr = expression as BinaryExpression;
if (binaryExpr != null && binaryExpr.NodeType == ExpressionType.OrElse)
{
// Split the OR condition into separate expressions
var left = binaryExpr.Left;
var right = binaryExpr.Right;
// Process left and right expressions recursively
CollectBinaryExpressions(left, predicate, jsonQueries);
CollectBinaryExpressions(right, predicate, jsonQueries);
}
else
{
// If the expression is a single condition, create a query for it
var test = expression.ToString();
var tes2t = predicate.ToString();
string jsonQuery = GetJsonQueryFromExpression(Expression.Lambda<Func<T, bool>>(expression, predicate.Parameters));
jsonQueries.Add(jsonQuery);
}
}
private object ConvertValueToType(object value, Type targetType)
{
if (targetType == typeof(Guid) && value is string stringValue)
{
return Guid.Parse(stringValue);
}
return Convert.ChangeType(value, targetType);
}
private IList<TRecord> ConvertListToRecords<TRecord>(IList<Dictionary<string, object>> listToConvert, Dictionary<string, string> propertyMappings)
{
var records = new List<TRecord>();
var recordType = typeof(TRecord);
foreach (var item in listToConvert)
{
var record = Activator.CreateInstance<TRecord>();
foreach (var kvp in item)
{
if (propertyMappings.TryGetValue(kvp.Key, out var propertyName))
{
var property = recordType.GetProperty(propertyName);
var value = ManagerHelper.GetValueFromValueKind(kvp.Value);
if (property != null)
{
property.SetValue(record, ConvertValueToType(value!, property.PropertyType));
}
}
}
records.Add(record);
}
return records;
}
private TRecord ConvertIndexedDbRecordToCRecord<TRecord>(Dictionary<string, object> item, Dictionary<string, string> propertyMappings)
{
var recordType = typeof(TRecord);
var record = Activator.CreateInstance<TRecord>();
foreach (var kvp in item)
{
if (propertyMappings.TryGetValue(kvp.Key, out var propertyName))
{
var property = recordType.GetProperty(propertyName);
var value = ManagerHelper.GetValueFromValueKind(kvp.Value);
if (property != null)
{
property.SetValue(record, ConvertValueToType(value!, property.PropertyType));
}
}
}
return record;
}
private string GetJsonQueryFromExpression<T>(Expression<Func<T, bool>> predicate) where T : class
{
var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var conditions = new List<JObject>();
var orConditions = new List<List<JObject>>();
void TraverseExpression(Expression expression, bool inOrBranch = false)
{
if (expression is BinaryExpression binaryExpression)
{
if (binaryExpression.NodeType == ExpressionType.AndAlso)
{
TraverseExpression(binaryExpression.Left, inOrBranch);
TraverseExpression(binaryExpression.Right, inOrBranch);
}
else if (binaryExpression.NodeType == ExpressionType.OrElse)
{
if (inOrBranch)
{
throw new InvalidOperationException("Nested OR conditions are not supported.");
}
TraverseExpression(binaryExpression.Left, !inOrBranch);
TraverseExpression(binaryExpression.Right, !inOrBranch);
}
else
{
AddCondition(binaryExpression, inOrBranch);
}
}
else if (expression is MethodCallExpression methodCallExpression)
{
AddCondition(methodCallExpression, inOrBranch);
}
}
void AddCondition(Expression expression, bool inOrBranch)
{
if (expression is BinaryExpression binaryExpression)
{
var leftMember = binaryExpression.Left as MemberExpression;
var rightMember = binaryExpression.Right as MemberExpression;
var leftConstant = binaryExpression.Left as ConstantExpression;
var rightConstant = binaryExpression.Right as ConstantExpression;
var operation = binaryExpression.NodeType.ToString();
if (leftMember != null && rightConstant != null)
{
AddConditionInternal(leftMember, rightConstant, operation, inOrBranch);
}
else if (leftConstant != null && rightMember != null)
{
// Swap the order of the left and right expressions and the operation
if (operation == "GreaterThan")
{
operation = "LessThan";
}
else if (operation == "LessThan")
{
operation = "GreaterThan";
}
else if (operation == "GreaterThanOrEqual")
{
operation = "LessThanOrEqual";
}
else if (operation == "LessThanOrEqual")
{
operation = "GreaterThanOrEqual";
}
AddConditionInternal(rightMember, leftConstant, operation, inOrBranch);
}
}
else if (expression is MethodCallExpression methodCallExpression)
{
if (methodCallExpression.Method.DeclaringType == typeof(string) &&
(methodCallExpression.Method.Name == "Equals" || methodCallExpression.Method.Name == "Contains" || methodCallExpression.Method.Name == "StartsWith"))
{
var left = methodCallExpression.Object as MemberExpression;
var right = methodCallExpression.Arguments[0] as ConstantExpression;
var operation = methodCallExpression.Method.Name;
var caseSensitive = true;
if (methodCallExpression.Arguments.Count > 1)
{
var stringComparison = methodCallExpression.Arguments[1] as ConstantExpression;
if (stringComparison != null && stringComparison.Value is StringComparison comparisonValue)
{
caseSensitive = comparisonValue == StringComparison.Ordinal || comparisonValue == StringComparison.CurrentCulture;
}
}
AddConditionInternal(left, right, operation == "Equals" ? "StringEquals" : operation, inOrBranch, caseSensitive);
}
}
}
void AddConditionInternal(MemberExpression? left, ConstantExpression? right, string operation, bool inOrBranch, bool caseSensitive = false)
{
if (left != null && right != null)
{
var propertyInfo = typeof(T).GetProperty(left.Member.Name);
if (propertyInfo != null)
{
bool index = propertyInfo.GetCustomAttributes(typeof(MagicIndexAttribute), false).Length == 0;
bool unique = propertyInfo.GetCustomAttributes(typeof(MagicUniqueIndexAttribute), false).Length == 0;
bool primary = propertyInfo.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length == 0;
if (index == true && unique == true && primary == true)
{
throw new InvalidOperationException($"Property '{propertyInfo.Name}' does not have the IndexDbAttribute.");
}
string? columnName = null;
if (index == false)
columnName = propertyInfo.GetPropertyColumnName<MagicIndexAttribute>();
else if (unique == false)
columnName = propertyInfo.GetPropertyColumnName<MagicUniqueIndexAttribute>();
else if (primary == false)
columnName = propertyInfo.GetPropertyColumnName<MagicPrimaryKeyAttribute>();
bool _isString = false;
JToken? valSend = null;
if (right != null && right.Value != null)
{
valSend = JToken.FromObject(right.Value);
_isString = right.Value is string;
}
var jsonCondition = new JObject
{
{ "property", columnName },
{ "operation", operation },
{ "value", valSend },
{ "isString", _isString },
{ "caseSensitive", caseSensitive }
};
if (inOrBranch)
{
var currentOrConditions = orConditions.LastOrDefault();
if (currentOrConditions == null)
{
currentOrConditions = new List<JObject>();
orConditions.Add(currentOrConditions);
}
currentOrConditions.Add(jsonCondition);
}
else
{
conditions.Add(jsonCondition);
}
}
}
}
TraverseExpression(predicate.Body);
if (conditions.Any())
{
orConditions.Add(conditions);
}
return JsonConvert.SerializeObject(orConditions, serializerSettings);
}
public class QuotaUsage
{
public long quota { get; set; }
public long usage { get; set; }
}
/// <summary>
/// Returns Mb
/// </summary>
/// <returns></returns>
public async Task<(double quota, double usage)> GetStorageEstimateAsync()
{
var storageInfo = await CallJavascriptNoTransaction<QuotaUsage>(IndexedDbFunctions.GET_STORAGE_ESTIMATE);
double quotaInMB = ConvertBytesToMegabytes(storageInfo.quota);
double usageInMB = ConvertBytesToMegabytes(storageInfo.usage);
return (quotaInMB, usageInMB);
}
private static double ConvertBytesToMegabytes(long bytes)
{
return (double)bytes / (1024 * 1024);
}
public async Task<IEnumerable<T>> GetAll<T>() where T : class
{
var trans = GenerateTransaction(null);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();
IList<Dictionary<string, object>>? ListToConvert = await CallJavascript<IList<Dictionary<string, object>>>(IndexedDbFunctions.TOARRAY, trans, DbName, schemaName);
var resultList = ConvertListToRecords<T>(ListToConvert, propertyMappings);
return resultList;
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return Enumerable.Empty<T>();
}
public async Task<Guid> Delete<T>(T item, Action<BlazorDbEvent>? action = null) where T : class
{
var trans = GenerateTransaction(action);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute)));
if (primaryKeyProperty != null)
{
object? primaryKeyValue = primaryKeyProperty.GetValue(item);
var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item);
if (primaryKeyValue != null)
{
UpdateRecord<Dictionary<string, object?>> record = new UpdateRecord<Dictionary<string, object?>>()
{
Key = primaryKeyValue,
DbName = this.DbName,
StoreName = schemaName,
Record = convertedRecord
};
// Get the primary key value of the item
await CallJavascriptVoid(IndexedDbFunctions.DELETE_ITEM, trans, record);
}
else
{
throw new ArgumentException("Item being Deleted must have a key.");
}
}
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
public async Task<int> DeleteRange<TResult>(IEnumerable<TResult> items) where TResult : class
{
List<object> keys = new List<object>();
foreach (var item in items)
{
PropertyInfo? primaryKeyProperty = typeof(TResult).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute)));
if (primaryKeyProperty == null)
{
throw new InvalidOperationException("No primary key property found with PrimaryKeyDbAttribute.");
}
object? primaryKeyValue = primaryKeyProperty.GetValue(item);
if (primaryKeyValue != null)
keys.Add(primaryKeyValue);
}
string schemaName = SchemaHelper.GetSchemaName<TResult>();
var trans = GenerateTransaction(null);
var data = new { DbName = DbName, StoreName = schemaName, Keys = keys };
try
{
var deletedCount = await CallJavascript<int>(IndexedDbFunctions.BULK_DELETE, trans, data.DbName, data.StoreName, data.Keys);
return deletedCount;
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return 0;
}
/// <summary>
/// Clears all data from a Table but keeps the table
/// </summary>
/// <param name="storeName"></param>
/// <param name="action"></param>
/// <returns></returns>
public async Task<Guid> ClearTable(string storeName, Action<BlazorDbEvent>? action = null)
{
var trans = GenerateTransaction(action);
try
{
await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans, DbName, storeName);
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
public async Task<Guid> ClearTable<T>(Action<BlazorDbEvent>? action = null) where T : class
{
var trans = GenerateTransaction(action);
try
{
string schemaName = SchemaHelper.GetSchemaName<T>();
await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans, DbName, schemaName);
}
catch (JSException jse)
{
RaiseEvent(trans, true, jse.Message);
}
return trans;
}
/// <summary>
/// Clears all data from a Table but keeps the table
/// Wait for response
/// </summary>
/// <param name="storeName"></param>
/// <returns></returns>
public async Task<BlazorDbEvent> ClearTableAsync(string storeName)
{
var trans = GenerateTransaction();
try
{
await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans.trans, DbName, storeName);
}
catch (JSException jse)
{
RaiseEvent(trans.trans, true, jse.Message);
}
return await trans.task;
}
[JSInvokable("BlazorDBCallback")]
public void CalledFromJS(Guid transaction, bool failed, string message)
{
if (transaction != Guid.Empty)
{
WeakReference<Action<BlazorDbEvent>>? r = null;
_transactions.TryGetValue(transaction, out r);
TaskCompletionSource<BlazorDbEvent>? t = null;
_taskTransactions.TryGetValue(transaction, out t);
if (r != null && r.TryGetTarget(out Action<BlazorDbEvent>? action))
{
action?.Invoke(new BlazorDbEvent()
{
Transaction = transaction,
Message = message,
Failed = failed
});
_transactions.Remove(transaction);
}
else if (t != null)
{
t.TrySetResult(new BlazorDbEvent()
{
Transaction = transaction,
Message = message,
Failed = failed
});
_taskTransactions.Remove(transaction);
}
else
RaiseEvent(transaction, failed, message);
}
}
//async Task<TResult> CallJavascriptNoTransaction<TResult>(string functionName, params object[] args)
//{
// return await _jsRuntime.InvokeAsync<TResult>($"{InteropPrefix}.{functionName}", args);
//}
async Task<TResult> CallJavascriptNoTransaction<TResult>(string functionName, params object[] args)
{
var mod = await GetModule(_jsRuntime);
return await mod.InvokeAsync<TResult>($"{functionName}", args);
}
private const string dynamicJsCaller = "DynamicJsCaller";
/// <summary>
///
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="functionName"></param>
/// <param name="transaction"></param>
/// <param name="timeout">in ms</param>
/// <param name="args"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public async Task<TResult> CallJS<TResult>(string functionName, double Timeout, params object[] args)
{
List<object> modifiedArgs = new List<object>(args);
modifiedArgs.Insert(0, $"{InteropPrefix}.{functionName}");
Task<JsResponse<TResult>> task = _jsRuntime.InvokeAsync<JsResponse<TResult>>(dynamicJsCaller, modifiedArgs.ToArray()).AsTask();
Task delay = Task.Delay(TimeSpan.FromMilliseconds(Timeout));
if (await Task.WhenAny(task, delay) == task)
{
JsResponse<TResult> response = await task;
if (response.Success)
return response.Data;
else
throw new ArgumentException(response.Message);
}
else
{
throw new ArgumentException("Timed out after 1 minute");
}
}
//public async Task<TResult> CallJS<TResult>(string functionName, JsSettings Settings, params object[] args)
//{
// var newArgs = GetNewArgs(Settings.Transaction, args);
// Task<JsResponse<TResult>> task = _jsRuntime.InvokeAsync<JsResponse<TResult>>($"{InteropPrefix}.{functionName}", newArgs).AsTask();
// Task delay = Task.Delay(TimeSpan.FromMilliseconds(Settings.Timeout));
// if (await Task.WhenAny(task, delay) == task)
// {
// JsResponse<TResult> response = await task;
// if (response.Success)
// return response.Data;
// else
// throw new ArgumentException(response.Message);
// }
// else
// {
// throw new ArgumentException("Timed out after 1 minute");
// }
//}
//async Task<TResult> CallJavascript<TResult>(string functionName, Guid transaction, params object[] args)
//{
// var newArgs = GetNewArgs(transaction, args);
// return await _jsRuntime.InvokeAsync<TResult>($"{InteropPrefix}.{functionName}", newArgs);
//}
//async Task CallJavascriptVoid(string functionName, Guid transaction, params object[] args)
//{
// var newArgs = GetNewArgs(transaction, args);
// await _jsRuntime.InvokeVoidAsync($"{InteropPrefix}.{functionName}", newArgs);
//}
async Task<TResult> CallJavascript<TResult>(string functionName, Guid transaction, params object[] args)
{
var mod = await GetModule(_jsRuntime);
var newArgs = GetNewArgs(transaction, args);
return await mod.InvokeAsync<TResult>($"{functionName}", newArgs);
}
async Task CallJavascriptVoid(string functionName, Guid transaction, params object[] args)
{
var mod = await GetModule(_jsRuntime);
var newArgs = GetNewArgs(transaction, args);
await mod.InvokeVoidAsync($"{functionName}", newArgs);
}
object[] GetNewArgs(Guid transaction, params object[] args)
{
var newArgs = new object[args.Length + 2];
newArgs[0] = _objReference;
newArgs[1] = transaction;
for (var i = 0; i < args.Length; i++)
newArgs[i + 2] = args[i];
return newArgs;
}
(Guid trans, Task<BlazorDbEvent> task) GenerateTransaction()
{
bool generated = false;
var transaction = Guid.Empty;
TaskCompletionSource<BlazorDbEvent> tcs = new TaskCompletionSource<BlazorDbEvent>();
do
{
transaction = Guid.NewGuid();
if (!_taskTransactions.ContainsKey(transaction))
{
generated = true;
_taskTransactions.Add(transaction, tcs);
}
} while (!generated);
return (transaction, tcs.Task);
}
Guid GenerateTransaction(Action<BlazorDbEvent>? action)
{
bool generated = false;
Guid transaction = Guid.Empty;
do
{
transaction = Guid.NewGuid();
if (!_transactions.ContainsKey(transaction))
{
generated = true;
_transactions.Add(transaction, new WeakReference<Action<BlazorDbEvent>>(action!));
}
} while (!generated);
return transaction;
}
void RaiseEvent(Guid transaction, bool failed, string message)
=> ActionCompleted?.Invoke(this, new BlazorDbEvent { Transaction = transaction, Failed = failed, Message = message });
}
}
| Magic.IndexedDb/IndexDbManager.cs | magiccodingman-Magic.IndexedDb-a279d6d | [
{
"filename": "Magic.IndexedDb/Models/MagicQuery.cs",
"retrieved_chunk": " JsonQueries = new List<string>();\n }\n public List<StoredMagicQuery> storedMagicQueries { get; set; } = new List<StoredMagicQuery>();\n public bool ResultsUnique { get; set; } = true;\n /// <summary>\n /// Return a list of items in which the items do not have to be unique. Therefore, you can get \n /// duplicate instances of an object depending on how you write your query.\n /// </summary>\n /// <param name=\"amount\"></param>\n /// <returns></returns>",
"score": 0.8168597221374512
},
{
"filename": "Magic.IndexedDb/Models/JsResponse.cs",
"retrieved_chunk": " {\n Data = data;\n Success = success;\n Message = message;\n }\n /// <summary>\n /// Dynamic typed response data\n /// </summary>\n public T Data { get; set; }\n /// <summary>",
"score": 0.8034190535545349
},
{
"filename": "Magic.IndexedDb/Models/JsResponse.cs",
"retrieved_chunk": " /// Boolean indicator for successful API call\n /// </summary>\n public bool Success { get; set; }\n /// <summary>\n /// Human readable message to describe success / error conditions\n /// </summary>\n public string Message { get; set; }\n }\n}",
"score": 0.7823774814605713
},
{
"filename": "Magic.IndexedDb/Factories/MagicDbFactory.cs",
"retrieved_chunk": " return _dbs[dbName];\n#pragma warning disable CS8603 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.\n return null;\n#pragma warning restore CS8603 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.\n }\n public Task<IndexedDbManager> GetDbManager(DbStore dbStore)\n => GetDbManager(dbStore.Name);\n async Task BuildFromServices()\n {\n var dbStores = _serviceProvider.GetServices<DbStore>();",
"score": 0.7653624415397644
},
{
"filename": "Magic.IndexedDb/Models/MagicQuery.cs",
"retrieved_chunk": " return this;\n }\n public async Task<IEnumerable<T>> Execute()\n {\n return await Manager.WhereV2<T>(SchemaName, JsonQueries, this) ?? Enumerable.Empty<T>();\n }\n public async Task<int> Count()\n {\n var result = await Manager.WhereV2<T>(SchemaName, JsonQueries, this);\n int num = result?.Count() ?? 0;",
"score": 0.7583798170089722
}
] | csharp | BlazorDbEvent> BulkAddRecordAsync<T>(string storeName, IEnumerable<T> recordsToBulkAdd)
{ |
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Ultrapain.Patches
{
/*public class ObjectActivator : MonoBehaviour
{
public int originalInstanceID = 0;
public MonoBehaviour activator;
void Start()
{
if (gameObject.GetInstanceID() == originalInstanceID)
return;
activator?.Invoke("OnClone", 0f);
}
}*/
public class CommonLinearScaler : MonoBehaviour
{
public Transform targetTransform;
public float scaleSpeed = 1f;
void Update()
{
float deltaSize = Time.deltaTime * scaleSpeed;
targetTransform.localScale = new Vector3(targetTransform.localScale.x + deltaSize, targetTransform.localScale.y + deltaSize, targetTransform.localScale.y + deltaSize);
}
}
public class CommonAudioPitchScaler : MonoBehaviour
{
public AudioSource targetAud;
public float scaleSpeed = 1f;
void Update()
{
float deltaPitch = Time.deltaTime * scaleSpeed;
targetAud.pitch += deltaPitch;
}
}
public class RotateOnSpawn : MonoBehaviour
{
public Quaternion targetRotation;
private void Awake()
{
transform.rotation = targetRotation;
}
}
public class CommonActivator : MonoBehaviour
{
public int originalId;
public Renderer rend;
public Rigidbody rb;
public bool kinematic;
public bool colDetect;
public Collider col;
public AudioSource aud;
public List<MonoBehaviour> comps = new List<MonoBehaviour>();
void Awake()
{
if (originalId == gameObject.GetInstanceID())
return;
if (rend != null)
rend.enabled = true;
if (rb != null)
{
rb.isKinematic = kinematic;
rb.detectCollisions = colDetect;
}
if (col != null)
col.enabled = true;
if (aud != null)
aud.enabled = true;
foreach (MonoBehaviour comp in comps)
comp.enabled = true;
foreach (Transform child in gameObject.transform)
child.gameObject.SetActive(true);
}
}
public class GrenadeExplosionOverride : MonoBehaviour
{
public bool harmlessMod = false;
public float harmlessSize = 1f;
public float harmlessSpeed = 1f;
public float harmlessDamage = 1f;
public int harmlessPlayerDamageOverride = -1;
public bool normalMod = false;
public float normalSize = 1f;
public float normalSpeed = 1f;
public float normalDamage = 1f;
public int normalPlayerDamageOverride = -1;
public bool superMod = false;
public float superSize = 1f;
public float superSpeed = 1f;
public float superDamage = 1f;
public int superPlayerDamageOverride = -1;
struct StateInfo
{
public | GameObject tempHarmless; |
public GameObject tempNormal;
public GameObject tempSuper;
public StateInfo()
{
tempHarmless = tempNormal = tempSuper = null;
}
}
[HarmonyBefore]
static bool Prefix(Grenade __instance, out StateInfo __state)
{
__state = new StateInfo();
GrenadeExplosionOverride flag = __instance.GetComponent<GrenadeExplosionOverride>();
if (flag == null)
return true;
if (flag.harmlessMod)
{
__state.tempHarmless = __instance.harmlessExplosion = GameObject.Instantiate(__instance.harmlessExplosion);
foreach (Explosion exp in __instance.harmlessExplosion.GetComponentsInChildren<Explosion>())
{
exp.damage = (int)(exp.damage * flag.harmlessDamage);
exp.maxSize *= flag.harmlessSize;
exp.speed *= flag.harmlessSize * flag.harmlessSpeed;
exp.playerDamageOverride = flag.harmlessPlayerDamageOverride;
}
}
if (flag.normalMod)
{
__state.tempNormal = __instance.explosion = GameObject.Instantiate(__instance.explosion);
foreach (Explosion exp in __instance.explosion.GetComponentsInChildren<Explosion>())
{
exp.damage = (int)(exp.damage * flag.normalDamage);
exp.maxSize *= flag.normalSize;
exp.speed *= flag.normalSize * flag.normalSpeed;
exp.playerDamageOverride = flag.normalPlayerDamageOverride;
}
}
if (flag.superMod)
{
__state.tempSuper = __instance.superExplosion = GameObject.Instantiate(__instance.superExplosion);
foreach (Explosion exp in __instance.superExplosion.GetComponentsInChildren<Explosion>())
{
exp.damage = (int)(exp.damage * flag.superDamage);
exp.maxSize *= flag.superSize;
exp.speed *= flag.superSize * flag.superSpeed;
exp.playerDamageOverride = flag.superPlayerDamageOverride;
}
}
return true;
}
static void Postfix(StateInfo __state)
{
if (__state.tempHarmless != null)
GameObject.Destroy(__state.tempHarmless);
if (__state.tempNormal != null)
GameObject.Destroy(__state.tempNormal);
if (__state.tempSuper != null)
GameObject.Destroy(__state.tempSuper);
}
}
}
| Ultrapain/Patches/CommonComponents.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " public GameObject standardProjectile;\n public GameObject standardDecorativeProjectile;\n public int comboRemaining = ConfigManager.strayShootCount.value;\n public bool inCombo = false;\n public float lastSpeed = 1f;\n public enum AttackMode\n {\n ProjectileCombo,\n FastHoming\n }",
"score": 0.8868994116783142
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " // ENEMY STAT CONFIG\n public static char resistanceSeparator = (char)1;\n public struct EidStatContainer\n {\n public FloatField health;\n public FloatField damage;\n public FloatField speed;\n public StringField resistanceStr;\n public Dictionary<string, float> resistanceDict;\n public void SetHidden(bool hidden)",
"score": 0.883283257484436
},
{
"filename": "Ultrapain/Patches/V2Common.cs",
"retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;",
"score": 0.8701077103614807
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " {\n private LeviathanHead comp;\n private Animator anim;\n //private Collider col;\n private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };\n public float playerRocketRideTracker = 0;\n private GameObject currentProjectileEffect;\n private AudioSource currentProjectileAud;\n private Transform shootPoint;\n public float currentProjectileSize = 0;",
"score": 0.8666630983352661
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " {\n public CoinChainList chainList;\n public bool isOrbitalRay = false;\n public bool exploded = false;\n public float activasionDistance;\n }\n public class Coin_Start\n {\n static void Postfix(Coin __instance)\n {",
"score": 0.8656529188156128
}
] | csharp | GameObject tempHarmless; |
using HarmonyLib;
using System.Reflection;
using UnityEngine;
namespace Ultrapain.Patches
{
class Mindflayer_Start_Patch
{
static void Postfix(Mindflayer __instance, ref EnemyIdentifier ___eid)
{
__instance.gameObject.AddComponent<MindflayerPatch>();
//___eid.SpeedBuff();
}
}
class Mindflayer_ShootProjectiles_Patch
{
public static float maxProjDistance = 5;
public static float initialProjectileDistance = -1f;
public static float distancePerProjShot = 0.2f;
static bool Prefix( | Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)
{ |
/*for(int i = 0; i < 20; i++)
{
Quaternion randomRotation = Quaternion.LookRotation(MonoSingleton<PlayerTracker>.Instance.GetTarget().position - __instance.transform.position);
randomRotation.eulerAngles += new Vector3(UnityEngine.Random.Range(-15.0f, 15.0f), UnityEngine.Random.Range(-15.0f, 15.0f), UnityEngine.Random.Range(-15.0f, 15.0f));
Projectile componentInChildren = GameObject.Instantiate(Plugin.homingProjectile.gameObject, __instance.transform.position + __instance.transform.forward, randomRotation).GetComponentInChildren<Projectile>();
Vector3 randomPos = __instance.tentacles[UnityEngine.Random.RandomRangeInt(0, __instance.tentacles.Length)].position;
if (!Physics.Raycast(__instance.transform.position, randomPos - __instance.transform.position, Vector3.Distance(randomPos, __instance.transform.position), ___environmentMask))
componentInChildren.transform.position = randomPos;
componentInChildren.speed = 10f * ___eid.totalSpeedModifier * UnityEngine.Random.Range(0.5f, 1.5f);
componentInChildren.turnSpeed *= UnityEngine.Random.Range(0.5f, 1.5f);
componentInChildren.target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
componentInChildren.safeEnemyType = EnemyType.Mindflayer;
componentInChildren.damage *= ___eid.totalDamageModifier;
}
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
__instance.cooldown = (float)UnityEngine.Random.Range(4, 5);
return false;*/
MindflayerPatch counter = __instance.GetComponent<MindflayerPatch>();
if (counter == null)
return true;
if (counter.shotsLeft == 0)
{
counter.shotsLeft = ConfigManager.mindflayerShootAmount.value;
__instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);
__instance.cooldown = (float)UnityEngine.Random.Range(4, 5);
return false;
}
Quaternion randomRotation = Quaternion.LookRotation(MonoSingleton<PlayerTracker>.Instance.GetTarget().position - __instance.transform.position);
randomRotation.eulerAngles += new Vector3(UnityEngine.Random.Range(-10.0f, 10.0f), UnityEngine.Random.Range(-10.0f, 10.0f), UnityEngine.Random.Range(-10.0f, 10.0f));
Projectile componentInChildren = GameObject.Instantiate(Plugin.homingProjectile, __instance.transform.position + __instance.transform.forward, randomRotation).GetComponentInChildren<Projectile>();
Vector3 randomPos = __instance.tentacles[UnityEngine.Random.RandomRangeInt(0, __instance.tentacles.Length)].position;
if (!Physics.Raycast(__instance.transform.position, randomPos - __instance.transform.position, Vector3.Distance(randomPos, __instance.transform.position), ___environmentMask))
componentInChildren.transform.position = randomPos;
int shotCount = ConfigManager.mindflayerShootAmount.value - counter.shotsLeft;
componentInChildren.transform.position += componentInChildren.transform.forward * Mathf.Clamp(initialProjectileDistance + shotCount * distancePerProjShot, 0, maxProjDistance);
componentInChildren.speed = ConfigManager.mindflayerShootInitialSpeed.value * ___eid.totalSpeedModifier;
componentInChildren.turningSpeedMultiplier = ConfigManager.mindflayerShootTurnSpeed.value;
componentInChildren.target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
componentInChildren.safeEnemyType = EnemyType.Mindflayer;
componentInChildren.damage *= ___eid.totalDamageModifier;
componentInChildren.sourceWeapon = __instance.gameObject;
counter.shotsLeft -= 1;
__instance.Invoke("ShootProjectiles", ConfigManager.mindflayerShootDelay.value / ___eid.totalSpeedModifier);
return false;
}
}
class EnemyIdentifier_DeliverDamage_MF
{
static bool Prefix(EnemyIdentifier __instance, ref float __3, GameObject __6)
{
if (__instance.enemyType != EnemyType.Mindflayer)
return true;
if (__6 == null || __6.GetComponent<Mindflayer>() == null)
return true;
__3 *= ConfigManager.mindflayerProjectileSelfDamageMultiplier.value / 100f;
return true;
}
}
class SwingCheck2_CheckCollision_Patch
{
static FieldInfo goForward = typeof(Mindflayer).GetField("goForward", BindingFlags.NonPublic | BindingFlags.Instance);
static MethodInfo meleeAttack = typeof(Mindflayer).GetMethod("MeleeAttack", BindingFlags.NonPublic | BindingFlags.Instance);
static bool Prefix(Collider __0, out int __state)
{
__state = __0.gameObject.layer;
return true;
}
static void Postfix(SwingCheck2 __instance, Collider __0, int __state)
{
if (__0.tag == "Player")
Debug.Log($"Collision with {__0.name} with tag {__0.tag} and layer {__state}");
if (__0.gameObject.tag != "Player" || __state == 15)
return;
if (__instance.transform.parent == null)
return;
Debug.Log("Parent check");
Mindflayer mf = __instance.transform.parent.gameObject.GetComponent<Mindflayer>();
if (mf == null)
return;
//MindflayerPatch patch = mf.gameObject.GetComponent<MindflayerPatch>();
Debug.Log("Attempting melee combo");
__instance.DamageStop();
goForward.SetValue(mf, false);
meleeAttack.Invoke(mf, new object[] { });
/*if (patch.swingComboLeft > 0)
{
patch.swingComboLeft -= 1;
__instance.DamageStop();
goForward.SetValue(mf, false);
meleeAttack.Invoke(mf, new object[] { });
}
else
patch.swingComboLeft = 2;*/
}
}
class Mindflayer_MeleeTeleport_Patch
{
public static Vector3 deltaPosition = new Vector3(0, -10, 0);
static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged)
{
if (___eid.drillers.Count > 0)
return false;
Vector3 targetPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.9f) + deltaPosition;
float distance = Vector3.Distance(__instance.transform.position, targetPosition);
Ray targetRay = new Ray(__instance.transform.position, targetPosition - __instance.transform.position);
RaycastHit hit;
if (Physics.Raycast(targetRay, out hit, distance, ___environmentMask, QueryTriggerInteraction.Ignore))
{
targetPosition = targetRay.GetPoint(Mathf.Max(0.0f, hit.distance - 1.0f));
}
MonoSingleton<HookArm>.Instance.StopThrow(1f, true);
__instance.transform.position = targetPosition;
___goingLeft = !___goingLeft;
GameObject.Instantiate<GameObject>(__instance.teleportSound, __instance.transform.position, Quaternion.identity);
GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.decoy, __instance.transform.GetChild(0).position, __instance.transform.GetChild(0).rotation);
Animator componentInChildren = gameObject.GetComponentInChildren<Animator>();
AnimatorStateInfo currentAnimatorStateInfo = ___anim.GetCurrentAnimatorStateInfo(0);
componentInChildren.Play(currentAnimatorStateInfo.shortNameHash, 0, currentAnimatorStateInfo.normalizedTime);
componentInChildren.speed = 0f;
if (___enraged)
{
gameObject.GetComponent<MindflayerDecoy>().enraged = true;
}
___anim.speed = 0f;
__instance.CancelInvoke("ResetAnimSpeed");
__instance.Invoke("ResetAnimSpeed", 0.25f / ___eid.totalSpeedModifier);
return false;
}
}
class SwingCheck2_DamageStop_Patch
{
static void Postfix(SwingCheck2 __instance)
{
if (__instance.transform.parent == null)
return;
GameObject parent = __instance.transform.parent.gameObject;
Mindflayer mf = parent.GetComponent<Mindflayer>();
if (mf == null)
return;
MindflayerPatch patch = parent.GetComponent<MindflayerPatch>();
patch.swingComboLeft = 2;
}
}
class MindflayerPatch : MonoBehaviour
{
public int shotsLeft = ConfigManager.mindflayerShootAmount.value;
public int swingComboLeft = 2;
}
}
| Ultrapain/Patches/Mindflayer.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " /*__instance.projectile = Plugin.homingProjectile;\n __instance.decProjectile = Plugin.decorativeProjectile2;*/\n }\n }\n public class ZombieProjectile_ThrowProjectile_Patch\n {\n public static float normalizedTime = 0f;\n public static float animSpeed = 20f;\n public static float projectileSpeed = 75;\n public static float turnSpeedMultiplier = 0.45f;",
"score": 0.8783000707626343
},
{
"filename": "Ultrapain/Patches/V2Common.cs",
"retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;",
"score": 0.8763320446014404
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " class Leviathan_FixedUpdate\n {\n public static float projectileForward = 10f;\n static bool Roll(float chancePercent)\n {\n return UnityEngine.Random.Range(0, 99.9f) <= chancePercent;\n }\n static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown,\n Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack)\n {",
"score": 0.8725496530532837
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " }\n return false;\n }\n }\n class Leviathan_ProjectileBurst\n {\n static bool Prefix(LeviathanHead __instance, Animator ___anim,\n ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction)\n {\n if (!__instance.active)",
"score": 0.868247389793396
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " class EnemyIdentifier_DeliverDamage\n {\n static Coin lastExplosiveCoin = null;\n class StateInfo\n {\n public bool canPostStyle = false;\n public OrbitalExplosionInfo info = null;\n }\n static bool Prefix(EnemyIdentifier __instance, out StateInfo __state, Vector3 __2, ref float __3)\n {",
"score": 0.8664442896842957
}
] | csharp | Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)
{ |
// -------------------------------------------------------------
// Copyright (c) - The Standard Community - All rights reserved.
// -------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Standard.REST.RESTFulSense.Models.Foundations.StatusDetails;
using Standard.REST.RESTFulSense.Models.Foundations.StatusDetails.Exceptions;
using Xeptions;
namespace Standard.REST.RESTFulSense.Services.Foundations.StatusDetails
{
internal partial class StatusDetailService
{
private delegate IQueryable< | StatusDetail> ReturningStatusDetailsFunction(); |
private delegate StatusDetail ReturningStatusDetailFunction();
private IQueryable<StatusDetail> TryCatch(ReturningStatusDetailsFunction returningStatusDetailsFunction)
{
try
{
return returningStatusDetailsFunction();
}
catch (JsonReaderException jsonReaderException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonReaderException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (JsonSerializationException jsonSerializationException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonSerializationException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (JsonException jsonException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (ArgumentNullException argumentNullException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(argumentNullException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (ArgumentException argumentException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(argumentException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (PathTooLongException pathTooLongException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(pathTooLongException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(directoryNotFoundException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (FileNotFoundException fileNotFoundException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(fileNotFoundException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(unauthorizedAccessException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (NotSupportedException notSupportedException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(notSupportedException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (IOException iOException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(iOException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (Exception exception)
{
var failedStatusDetailServiceException =
new FailedStatusDetailServiceException(exception);
throw CreateAndLogServiceException(failedStatusDetailServiceException);
}
}
private StatusDetail TryCatch(ReturningStatusDetailFunction returningStatusDetailFunction)
{
try
{
return returningStatusDetailFunction();
}
catch (NotFoundStatusDetailException notFoundStatusDetailException)
{
throw CreateAndLogValidationException(notFoundStatusDetailException);
}
catch (JsonReaderException jsonReaderException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonReaderException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (JsonSerializationException jsonSerializationException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonSerializationException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (JsonException jsonException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(jsonException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (ArgumentNullException argumentNullException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(argumentNullException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (ArgumentException argumentException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(argumentException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (PathTooLongException pathTooLongException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(pathTooLongException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(directoryNotFoundException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (FileNotFoundException fileNotFoundException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(fileNotFoundException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(unauthorizedAccessException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (NotSupportedException notSupportedException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(notSupportedException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (IOException iOException)
{
var failedStatusDetailStorageException =
new FailedStatusDetailStorageException(iOException);
throw CreateAndLogDependencyException(failedStatusDetailStorageException);
}
catch (Exception exception)
{
var failedStatusDetailServiceException =
new FailedStatusDetailServiceException(exception);
throw CreateAndLogServiceException(failedStatusDetailServiceException);
}
}
private StatusDetailDependencyException CreateAndLogDependencyException(Xeption exception)
{
var statusDetailDependencyException =
new StatusDetailDependencyException(exception);
return statusDetailDependencyException;
}
private StatusDetailValidationException CreateAndLogValidationException(Xeption exception)
{
var statusDetailValidationException =
new StatusDetailValidationException(exception);
return statusDetailValidationException;
}
private StatusDetailServiceException CreateAndLogServiceException(Xeption exception)
{
var statusDetailServiceException =
new StatusDetailServiceException(exception);
return statusDetailServiceException;
}
}
}
| Standard.REST.RESTFulSense/Services/Foundations/StatusDetails/StatusDetailService.Exceptions.cs | The-Standard-Organization-Standard.REST.RESTFulSense-7598bbe | [
{
"filename": "Standard.REST.RESTFulSense.Tests.Unit/Services/Foundations/StatusDetails/StatusDetailServiceTests.cs",
"retrieved_chunk": "using Standard.REST.RESTFulSense.Models.Foundations.StatusDetails;\nusing Standard.REST.RESTFulSense.Services.Foundations.StatusDetails;\nusing Tynamix.ObjectFiller;\nusing Xunit;\nnamespace Standard.REST.RESTFulSense.Tests.Unit.Services.Foundations.StatusDetails\n{\n public partial class StatusDetailServiceTests\n {\n private readonly Mock<IStorageBroker> storageBrokerMock;\n private readonly IStatusDetailService statusDetailService;",
"score": 0.9145359396934509
},
{
"filename": "Standard.REST.RESTFulSense/Services/Foundations/StatusDetails/StatusDetailService.Validations.cs",
"retrieved_chunk": "// -------------------------------------------------------------\n// Copyright (c) - The Standard Community - All rights reserved.\n// -------------------------------------------------------------\nusing Standard.REST.RESTFulSense.Models.Foundations.StatusDetails;\nusing Standard.REST.RESTFulSense.Models.Foundations.StatusDetails.Exceptions;\nnamespace Standard.REST.RESTFulSense.Services.Foundations.StatusDetails\n{\n internal partial class StatusDetailService\n {\n private static void ValidateStorageStatusDetail(StatusDetail maybeStatusDetail, int statusCode)",
"score": 0.891791820526123
},
{
"filename": "Standard.REST.RESTFulSense/Services/Foundations/StatusDetails/StatusDetailService.cs",
"retrieved_chunk": "// -------------------------------------------------------------\n// Copyright (c) - The Standard Community - All rights reserved.\n// -------------------------------------------------------------\nusing System.Linq;\nusing Standard.REST.RESTFulSense.Brokers.Storages;\nusing Standard.REST.RESTFulSense.Models.Foundations.StatusDetails;\nnamespace Standard.REST.RESTFulSense.Services.Foundations.StatusDetails\n{\n internal partial class StatusDetailService : IStatusDetailService\n {",
"score": 0.8625883460044861
},
{
"filename": "Standard.REST.RESTFulSense/Brokers/Storages/IStorageBroker.StatusDetails.cs",
"retrieved_chunk": "// -------------------------------------------------------------\n// Copyright (c) - The Standard Community - All rights reserved.\n// -------------------------------------------------------------\nusing System.Linq;\nusing Standard.REST.RESTFulSense.Models.Foundations.StatusDetails;\nnamespace Standard.REST.RESTFulSense.Brokers.Storages\n{\n internal partial interface IStorageBroker\n {\n IQueryable<StatusDetail> SelectAllStatusDetails();",
"score": 0.8251667022705078
},
{
"filename": "Standard.REST.RESTFulSense.Tests.Unit/Services/Foundations/StatusDetails/StatusDetailServiceTests.Exceptions.RetrieveStatusDetailByStatusCode.cs",
"retrieved_chunk": "// -------------------------------------------------------------\n// Copyright (c) - The Standard Community - All rights reserved.\n// -------------------------------------------------------------\nusing System;\nusing FluentAssertions;\nusing Moq;\nusing Standard.REST.RESTFulSense.Models.Foundations.StatusDetails.Exceptions;\nusing Xunit;\nnamespace Standard.REST.RESTFulSense.Tests.Unit.Services.Foundations.StatusDetails\n{",
"score": 0.8248202800750732
}
] | csharp | StatusDetail> ReturningStatusDetailsFunction(); |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using UnityEditor.Experimental.GraphView;
using UnityEditor;
using UnityEngine.Windows;
using System;
namespace QuestSystem.QuestEditor
{
public class QuestGraphSaveUtility
{
private QuestGraphView _targetGraphView;
private List<Edge> Edges => _targetGraphView.edges.ToList();
private List<NodeQuestGraph> node => _targetGraphView.nodes.ToList().Cast<NodeQuestGraph>().ToList();
private List<NodeQuest> _cacheNodes = new List<NodeQuest>();
public static QuestGraphSaveUtility GetInstance(QuestGraphView targetGraphView)
{
return new QuestGraphSaveUtility
{
_targetGraphView = targetGraphView,
};
}
private void creteNodeQuestAssets(Quest Q, ref List<NodeQuest> NodesInGraph)
{
int j = 0;
CheckFolders(Q);
string path = QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}/Nodes";
string tempPath = QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}/Temp";
//Move all nodes OUT to temp
if (AssetDatabase.IsValidFolder(path)) {
AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER + $"{Q.misionName}", "Temp");
var debug = AssetDatabase.MoveAsset(path, tempPath);
}
Debug.Log("GUID: " + AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}", "Nodes"));
//Order by position
List<NodeQuestGraph> nodeList = node.Where(node => !node.entryPoint).ToList();
foreach (var nodequest in nodeList)
{
//Visual part
string nodeSaveName = Q.misionName + "_Node" + j;
NodeQuest saveNode;
//Si existe en temps
bool alredyExists = false;
if (alredyExists = !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(tempPath + "/" + nodeSaveName + ".asset")))
{
saveNode = AssetDatabase.LoadAssetAtPath<NodeQuest>(tempPath + "/" + nodeSaveName + ".asset");
}
else
{
saveNode = ScriptableObject.CreateInstance<NodeQuest>();
}
saveNode.GUID = nodequest.GUID;
saveNode.position = nodequest.GetPosition().position;
//Quest Part
saveNode.isFinal = nodequest.isFinal;
saveNode.extraText = nodequest.extraText;
saveNode.nodeObjectives = createObjectivesFromGraph(nodequest.questObjectives);
if(!alredyExists)
AssetDatabase.CreateAsset(saveNode, $"{QuestConstants.MISIONS_FOLDER}/{Q.misionName}/Nodes/{nodeSaveName}.asset");
else
{
AssetDatabase.MoveAsset(tempPath + "/" + nodeSaveName + ".asset", path + "/" + nodeSaveName + ".asset");
}
EditorUtility.SetDirty(saveNode);
AssetDatabase.SaveAssets();
NodesInGraph.Add(saveNode);
j++;
}
AssetDatabase.DeleteAsset(tempPath);
}
public void CheckFolders(Quest Q)
{
if (!AssetDatabase.IsValidFolder(QuestConstants.RESOURCES_PATH))
{
AssetDatabase.CreateFolder(QuestConstants.PARENT_PATH, QuestConstants.RESOURCES_NAME);
}
if (!AssetDatabase.IsValidFolder(QuestConstants.MISIONS_FOLDER))
{
AssetDatabase.CreateFolder(QuestConstants.RESOURCES_PATH, QuestConstants.MISIONS_NAME);
}
if (!AssetDatabase.IsValidFolder(QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}"))
{
AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER, $"{Q.misionName}");
}
}
private void saveConections(Quest Q, List<NodeQuest> nodesInGraph)
{
var connectedPorts = Edges.Where(x => x.input.node != null).ToArray();
Q.ResetNodeLinksGraph();
foreach (NodeQuest currentNode in nodesInGraph)
{
currentNode.nextNode.Clear();
}
for (int i = 0; i < connectedPorts.Length; i++)
{
var outputNode = connectedPorts[i].output.node as NodeQuestGraph;
var inputNode = connectedPorts[i].input.node as NodeQuestGraph;
Q.nodeLinkData.Add(new Quest.NodeLinksGraph
{
baseNodeGUID = outputNode.GUID,
portName = connectedPorts[i].output.portName,
targetNodeGUID = inputNode.GUID
});
//Add to next node list
NodeQuest baseNode = nodesInGraph.Find(n => n.GUID == outputNode.GUID);
NodeQuest targetNode = nodesInGraph.Find(n => n.GUID == inputNode.GUID);
if (targetNode != null && baseNode != null)
baseNode.nextNode.Add(targetNode);
}
}
public void SaveGraph(Quest Q)
{
if (!Edges.Any()) return;
List<NodeQuest> NodesInGraph = new List<NodeQuest>();
// Nodes
creteNodeQuestAssets(Q, ref NodesInGraph);
// Conections
saveConections(Q, NodesInGraph);
//Last Quest parameters
var startNode = node.Find(node => node.entryPoint); //Find the first node Graph
Q.startDay = startNode.startDay;
Q.limitDay = startNode.limitDay;
Q.isMain = startNode.isMain;
//Questionable
var firstMisionNode = Edges.Find(x => x.output.portName == "Next");
var firstMisionNode2 = firstMisionNode.input.node as NodeQuestGraph;
string GUIDfirst = firstMisionNode2.GUID;
Q.firtsNode = NodesInGraph.Find(n => n.GUID == GUIDfirst);
EditorUtility.SetDirty(Q);
}
public void LoadGraph(Quest Q)
{
if (Q == null)
{
EditorUtility.DisplayDialog("Error!!", "Quest aprece como null, revisa el scriptable object", "OK");
return;
}
NodeQuest[] getNodes = Resources.LoadAll<NodeQuest>($"{QuestConstants.MISIONS_NAME}/{ Q.misionName}/Nodes");
_cacheNodes = new List<NodeQuest>(getNodes);
clearGraph(Q);
LoadNodes(Q);
ConectNodes(Q);
}
private void clearGraph(Quest Q)
{
node.Find(x => x.entryPoint).GUID = Q.nodeLinkData[0].baseNodeGUID;
foreach (var node in node)
{
if (node.entryPoint)
{
var aux = node.mainContainer.Children().ToList();
var aux2 = aux[2].Children().ToList();
// C
TextField misionName = aux2[0] as TextField;
Toggle isMain = aux2[1] as Toggle;
IntegerField startDay = aux2[2] as IntegerField;
IntegerField limitDay = aux2[3] as IntegerField;
misionName.value = Q.misionName;
isMain.value = Q.isMain;
startDay.value = Q.startDay;
limitDay.value = Q.limitDay;
//
node.limitDay = Q.limitDay;
node.startDay = Q.startDay;
node.isMain = Q.isMain;
node.misionName = Q.misionName;
continue;
}
//Remove edges
Edges.Where(x => x.input.node == node).ToList().ForEach(edge => _targetGraphView.RemoveElement(edge));
//Remove Node
_targetGraphView.RemoveElement(node);
}
}
private void LoadNodes(Quest Q)
{
foreach (var node in _cacheNodes)
{
var tempNode = _targetGraphView.CreateNodeQuest(node.name, Vector2.zero, node.extraText, node.isFinal);
//Load node variables
tempNode.GUID = node.GUID;
tempNode.extraText = node.extraText;
tempNode.isFinal = node.isFinal;
tempNode.RefreshPorts();
if (node.nodeObjectives != null) {
foreach (QuestObjective qObjective in node.nodeObjectives)
{
//CreateObjectives
QuestObjectiveGraph objtemp = new QuestObjectiveGraph(qObjective.keyName, qObjective.maxItems, qObjective.actualItems,
qObjective.description, qObjective.hiddenObjective, qObjective.autoExitOnCompleted);
var deleteButton = new Button(clickEvent: () => _targetGraphView.removeQuestObjective(tempNode, objtemp))
{
text = "x"
};
objtemp.Add(deleteButton);
var newBox = new Box();
objtemp.Add(newBox);
objtemp.actualItems = qObjective.actualItems;
objtemp.description = qObjective.description;
objtemp.maxItems = qObjective.maxItems;
objtemp.keyName = qObjective.keyName;
objtemp.hiddenObjective = qObjective.hiddenObjective;
objtemp.autoExitOnCompleted = qObjective.autoExitOnCompleted;
tempNode.objectivesRef.Add(objtemp);
tempNode.questObjectives.Add(objtemp);
}
}
_targetGraphView.AddElement(tempNode);
var nodePorts = Q.nodeLinkData.Where(x => x.baseNodeGUID == node.GUID).ToList();
nodePorts.ForEach(x => _targetGraphView.AddNextNodePort(tempNode));
}
}
private void ConectNodes(Quest Q)
{
List<NodeQuestGraph> nodeListCopy = new List<NodeQuestGraph>(node);
for (int i = 0; i < nodeListCopy.Count; i++)
{
var conections = Q.nodeLinkData.Where(x => x.baseNodeGUID == nodeListCopy[i].GUID).ToList();
for (int j = 0; j < conections.Count(); j++)
{
string targetNodeGUID = conections[j].targetNodeGUID;
var targetNode = nodeListCopy.Find(x => x.GUID == targetNodeGUID);
LinkNodes(nodeListCopy[i].outputContainer[j].Q<Port>(), (Port)targetNode.inputContainer[0]);
targetNode.SetPosition(new Rect(_cacheNodes.First(x => x.GUID == targetNodeGUID).position, new Vector2(150, 200)));
}
}
}
private void LinkNodes(Port outpor, Port inport)
{
var tempEdge = new Edge
{
output = outpor,
input = inport
};
tempEdge.input.Connect(tempEdge);
tempEdge.output.Connect(tempEdge);
_targetGraphView.Add(tempEdge);
}
public | QuestObjective[] createObjectivesFromGraph(List<QuestObjectiveGraph> qog)
{ |
List<QuestObjective> Listaux = new List<QuestObjective>();
foreach (QuestObjectiveGraph obj in qog)
{
QuestObjective aux = new QuestObjective
{
keyName = obj.keyName,
maxItems = obj.maxItems,
actualItems = obj.actualItems,
description = obj.description,
hiddenObjective = obj.hiddenObjective,
autoExitOnCompleted = obj.autoExitOnCompleted
};
Listaux.Add(aux);
}
return Listaux.ToArray();
}
}
} | Editor/GraphEditor/QuestGraphSaveUtility.cs | lluispalerm-QuestSystem-cd836cc | [
{
"filename": "Editor/GraphEditor/QuestGraphView.cs",
"retrieved_chunk": " GUID = Guid.NewGuid().ToString(),\n questObjectives = new List<QuestObjectiveGraph>(),\n };\n //Add Input port\n var generatetPortIn = GeneratePort(node, Direction.Input, Port.Capacity.Multi);\n generatetPortIn.portName = \"Input\";\n node.inputContainer.Add(generatetPortIn);\n node.styleSheets.Add(Resources.Load<StyleSheet>(\"Node\"));\n //Add button to add ouput\n var button = new Button(clickEvent: () =>",
"score": 0.789525032043457
},
{
"filename": "Editor/GraphEditor/QuestGraphView.cs",
"retrieved_chunk": " Q.Add(newBox);\n node.objectivesRef.Add(Q);\n node.questObjectives.Add(Q);\n node.RefreshPorts();\n node.RefreshExpandedState();\n }\n public NodeQuestGraph GetEntryPointNode()\n {\n List<NodeQuestGraph> nodeList = this.nodes.ToList().Cast<NodeQuestGraph>().ToList();\n return nodeList.First(node => node.entryPoint);",
"score": 0.7854962348937988
},
{
"filename": "Editor/GraphEditor/QuestGraphView.cs",
"retrieved_chunk": " }\n private void RemovePort(NodeQuestGraph node, Port p)\n {\n var targetEdge = edges.ToList().Where(x => x.output.portName == p.portName && x.output.node == p.node);\n if (targetEdge.Any())\n {\n var edge = targetEdge.First();\n edge.input.Disconnect(edge);\n RemoveElement(targetEdge.First());\n }",
"score": 0.7841238379478455
},
{
"filename": "Runtime/QuestManager.cs",
"retrieved_chunk": " else\n {\n data = aux;\n misionLog.LoadUpdate(data);\n }\n }\n public void AddMisionToCurrent(Quest q)\n {\n q.nodeActual = q.firtsNode;\n q.nodeActual.ChangeTheStateOfObjects(true);",
"score": 0.7731035947799683
},
{
"filename": "Editor/GraphEditor/QuestGraphView.cs",
"retrieved_chunk": " }\n }\n node.RefreshExpandedState();\n node.RefreshPorts();\n }\n public void AddNextNodePort(NodeQuestGraph node, string overrideName = \"\")\n {\n var generatetPort = GeneratePort(node, Direction.Output);\n int nPorts = node.outputContainer.Query(\"connector\").ToList().Count;\n //generatetPort.portName = \"NextNode \" + nPorts;",
"score": 0.7724670767784119
}
] | csharp | QuestObjective[] createObjectivesFromGraph(List<QuestObjectiveGraph> qog)
{ |
using System.Xml.Linq;
using EnumsNET;
using LibreDteDotNet.Common;
using LibreDteDotNet.RestRequest.Help;
using LibreDteDotNet.RestRequest.Infraestructure;
using LibreDteDotNet.RestRequest.Interfaces;
namespace LibreDteDotNet.RestRequest.Services
{
internal class FolioCafService : ComunEnum, IFolioCaf
{
public Dictionary<string, string> InputsText { get; set; } =
new Dictionary<string, string>();
private readonly IRepositoryWeb repositoryWeb;
private const string input = "input[type='text'],input[type='hidden']";
public FolioCafService(IRepositoryWeb repositoryWeb)
{
this.repositoryWeb = repositoryWeb;
}
public async Task<string> GetHistorial(string rut, string dv, TipoDoc tipodoc)
{
using HttpResponseMessage? msg = await repositoryWeb.Send(
new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafHistorial)
{
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("RUT_EMP", rut),
new KeyValuePair<string, string>("DV_EMP", dv),
new KeyValuePair<string, string>("PAGINA", "1"), // PÁG. 2,3 ETC.
new KeyValuePair<string, string>(
"COD_DOCTO",
((int)tipodoc).ToString()
),
}
)
}
)!;
return await msg.Content.ReadAsStringAsync();
}
public async Task<IFolioCaf> ReObtener(
string rut,
string dv,
string cant,
string dia,
string mes,
string year,
string folioini,
string foliofin,
TipoDoc tipodoc
)
{
using HttpResponseMessage? msg = await repositoryWeb.Send(
new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafReobtiene)
{
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("RUT_EMP", rut),
new KeyValuePair<string, string>("DV_EMP", dv),
new KeyValuePair<string, string>(
"COD_DOCTO",
((int)tipodoc).ToString()
),
new KeyValuePair<string, string>("FOLIO_INI", folioini),
new KeyValuePair<string, string>("FOLIO_FIN", foliofin),
new KeyValuePair<string, string>("CANT_DOCTOS", cant),
new KeyValuePair<string, string>("DIA", dia),
new KeyValuePair<string, string>("MES", mes),
new KeyValuePair<string, string>("ANO", year),
}
)
}
)!;
InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None);
return this;
}
public async Task<IFolioCaf> Obtener(
string rut,
string dv,
string cant,
string cantmax,
TipoDoc tipodoc
)
{
using HttpResponseMessage? msg = await repositoryWeb.Send(
new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafConfirma)
{
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("RUT_EMP", rut),
new KeyValuePair<string, string>("DV_EMP", dv),
new KeyValuePair<string, string>("FOLIO_INICIAL", "0"),
new KeyValuePair<string, string>(
"COD_DOCTO",
((int)tipodoc).ToString()
),
new KeyValuePair<string, string>("AFECTO_IVA", "S"),
new KeyValuePair<string, string>("ANOTACION", "N"),
new KeyValuePair<string, string>("CON_CREDITO", "1"),
new KeyValuePair<string, string>("CON_AJUSTE", "0"),
new KeyValuePair<string, string>("FACTOR", "1.00"),
new KeyValuePair<string, string>("MAX_AUTOR", cantmax),
new KeyValuePair<string, string>("ULT_TIMBRAJE", "1"),
new KeyValuePair<string, string>("CON_HISTORIA", "0"),
new KeyValuePair<string, string>("FOLIO_INICRE", ""),
new KeyValuePair<string, string>("FOLIO_FINCRE", ""),
new KeyValuePair<string, string>("FECHA_ANT", ""),
new KeyValuePair<string, string>("ESTADO_TIMBRAJE", ""),
new KeyValuePair<string, string>("CONTROL", ""),
new KeyValuePair<string, string>("CANT_TIMBRAJES", ""),
new KeyValuePair<string, string>("CANT_DOCTOS", cant),
new KeyValuePair<string, string>("FOLIOS_DISP", "21")
}
)
}
)!;
InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None);
return this;
}
public async Task<XDocument> Descargar()
{
using HttpResponseMessage? msg = await repositoryWeb.Send(
new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafGeneraFile)
{
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>(
"RUT_EMP",
InputsText.GetValueOrDefault("RUT_EMP")!
),
new KeyValuePair<string, string>(
"DV_EMP",
InputsText.GetValueOrDefault("DV_EMP")!
),
new KeyValuePair<string, string>(
"COD_DOCTO",
InputsText.GetValueOrDefault("COD_DOCTO")!
),
new KeyValuePair<string, string>(
"FOLIO_INI",
InputsText.GetValueOrDefault("FOLIO_INI")!
),
new KeyValuePair<string, string>(
"FOLIO_FIN",
InputsText.GetValueOrDefault("FOLIO_FIN")!
),
new KeyValuePair<string, string>(
"FECHA",
$"{InputsText.GetValueOrDefault("FECHA")!}"
)
}
)
}
)!;
using StreamReader reader = new(await msg.Content.ReadAsStreamAsync());
return XDocument.Load(reader);
}
public async Task<IFolioCaf> SetCookieCertificado()
{
HttpStatCode = await repositoryWeb.Conectar(Properties.Resources.UrlBasePalena);
return this;
}
public async Task<Dictionary<string, string>> GetRangoMax(
string rut,
string dv,
TipoDoc tipodoc
)
{
using HttpResponseMessage? msg = await repositoryWeb.Send(
new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafMaxRango)
{
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>(
"AFECTO_IVA",
tipodoc.AsString(EnumFormat.Description)!
),
new KeyValuePair<string, string>("RUT_EMP", rut),
new KeyValuePair<string, string>("DV_EMP", dv),
new KeyValuePair<string, string>("COD_DOCTO", ((int)tipodoc).ToString())
}
)
}
)!;
InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None);
return InputsText;
}
public async Task< | IFolioCaf> Confirmar()
{ |
using HttpResponseMessage? msg = await repositoryWeb.Send(
new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafConfirmaFile)
{
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>(
"NOMUSU",
InputsText.GetValueOrDefault("NOMUSU")!
),
new KeyValuePair<string, string>(
"CON_CREDITO",
InputsText.GetValueOrDefault("CON_CREDITO")!
),
new KeyValuePair<string, string>(
"CON_AJUSTE",
InputsText.GetValueOrDefault("CON_AJUSTE")!
),
new KeyValuePair<string, string>(
"FOLIOS_DISP",
InputsText.GetValueOrDefault("FOLIOS_DISP")!
),
new KeyValuePair<string, string>(
"MAX_AUTOR",
InputsText.GetValueOrDefault("MAX_AUTOR")!
),
new KeyValuePair<string, string>(
"ULT_TIMBRAJE",
InputsText.GetValueOrDefault("ULT_TIMBRAJE")!
),
new KeyValuePair<string, string>(
"CON_HISTORIA",
InputsText.GetValueOrDefault("CON_HISTORIA")!
),
new KeyValuePair<string, string>(
"CANT_TIMBRAJES",
InputsText.GetValueOrDefault("CANT_TIMBRAJES")!
),
new KeyValuePair<string, string>(
"CON_AJUSTE",
InputsText.GetValueOrDefault("CON_AJUSTE")!
),
new KeyValuePair<string, string>(
"FOLIO_INICRE",
InputsText.GetValueOrDefault("FOLIO_INICRE")!
),
new KeyValuePair<string, string>(
"FOLIO_FINCRE",
InputsText.GetValueOrDefault("FOLIO_FINCRE")!
),
new KeyValuePair<string, string>(
"FECHA_ANT",
InputsText.GetValueOrDefault("FECHA_ANT")!
),
new KeyValuePair<string, string>(
"ESTADO_TIMBRAJE",
InputsText.GetValueOrDefault("ESTADO_TIMBRAJE")!
),
new KeyValuePair<string, string>(
"CONTROL",
InputsText.GetValueOrDefault("CONTROL")!
),
new KeyValuePair<string, string>(
"FOLIO_INI",
InputsText.GetValueOrDefault("FOLIO_INI")!
),
new KeyValuePair<string, string>(
"FOLIO_FIN",
InputsText.GetValueOrDefault("FOLIO_FIN")!
),
new KeyValuePair<string, string>(
"DIA",
InputsText.GetValueOrDefault("DIA")!
),
new KeyValuePair<string, string>(
"MES",
InputsText.GetValueOrDefault("MES")!
),
new KeyValuePair<string, string>(
"ANO",
InputsText.GetValueOrDefault("ANO")!
),
new KeyValuePair<string, string>(
"HORA",
InputsText.GetValueOrDefault("HORA")!
),
new KeyValuePair<string, string>(
"MINUTO",
InputsText.GetValueOrDefault("MINUTO")!
),
new KeyValuePair<string, string>(
"RUT_EMP",
InputsText.GetValueOrDefault("RUT_EMP")!
),
new KeyValuePair<string, string>(
"DV_EMP",
InputsText.GetValueOrDefault("DV_EMP")!
),
new KeyValuePair<string, string>(
"COD_DOCTO",
InputsText.GetValueOrDefault("COD_DOCTO")!
),
new KeyValuePair<string, string>(
"CANT_DOCTOS",
InputsText.GetValueOrDefault("CANT_DOCTOS")!
)
}
)
}
)!;
InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None);
return this;
}
}
}
| LibreDteDotNet.RestRequest/Services/FolioCafService.cs | sergiokml-LibreDteDotNet.RestRequest-6843109 | [
{
"filename": "LibreDteDotNet.RestRequest/Services/BoletaService.cs",
"retrieved_chunk": " new KeyValuePair<string, string>(\"AREA\", \"P\")\n }\n )\n }\n )!;\n return await msg.Content.ReadAsStringAsync();\n }\n public async Task<IBoleta> SetCookieCertificado()\n {\n HttpStatCode = await repositoryWeb.Conectar(Properties.Resources.UrlBasePalena);",
"score": 0.8300681114196777
},
{
"filename": "LibreDteDotNet.RestRequest/Services/LibroService.cs",
"retrieved_chunk": " }\n catch (Exception)\n {\n throw;\n }\n }\n public async Task<ReqLibroResumenCsv?> GetCsvFile(\n string token,\n string rut,\n string dv,",
"score": 0.8046249151229858
},
{
"filename": "LibreDteDotNet.RestRequest/Help/HtmlParse.cs",
"retrieved_chunk": " {\n Dictionary<string, string> dics = new();\n HtmlParser? parser = new();\n IHtmlDocument? document = await parser.ParseDocumentAsync(\n await msg!.Content.ReadAsStreamAsync(),\n token\n );\n try\n {\n await GuardarHtml(msg);",
"score": 0.7997903227806091
},
{
"filename": "LibreDteDotNet.RestRequest/Services/LibroService.cs",
"retrieved_chunk": " {\n HttpResponseMessage msg = await repositoryRest.PostJson(json, url, token)!;\n return await msg.EnsureSuccessStatusCode()\n .Content.ReadFromJsonAsync<ReqLibroResumenCsv>(options);\n }\n catch (Exception)\n {\n throw;\n }\n }",
"score": 0.7994894981384277
},
{
"filename": "LibreDteDotNet.RestRequest/Services/LibroService.cs",
"retrieved_chunk": " json,\n Properties.Resources.UrlLibroResumen,\n token\n )!;\n return await msg.EnsureSuccessStatusCode()\n .Content.ReadFromJsonAsync<ResLibroResumen>(options);\n }\n catch (Exception)\n {\n throw;",
"score": 0.7985326051712036
}
] | csharp | IFolioCaf> Confirmar()
{ |
namespace Beeching.Models
{
internal class AxeStatus
{
public List< | Resource> AxeList { | get; set; }
public bool Status { get; set; }
public AxeStatus()
{
AxeList = new();
Status = true;
}
}
}
| src/Models/AxeStatus.cs | irarainey-beeching-e846af0 | [
{
"filename": "src/Commands/Interfaces/IAxe.cs",
"retrieved_chunk": "namespace Beeching.Commands.Interfaces\n{\n internal interface IAxe\n {\n Task<int> AxeResources(AxeSettings settings);\n }\n}",
"score": 0.7679523229598999
},
{
"filename": "src/Models/ResourceLock.cs",
"retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace Beeching.Models\n{\n internal class ResourceLock\n {\n [JsonPropertyName (\"properties\")]\n public ResourceLockProperties Properties { get; set; }\n [JsonPropertyName (\"id\")]\n public string Id { get; set; }\n [JsonPropertyName (\"type\")]",
"score": 0.7256249785423279
},
{
"filename": "src/Models/ApiVersion.cs",
"retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace Beeching.Models\n{\n internal class ApiVersion\n {\n [JsonPropertyName(\"resourceType\")]\n public string ResourceType { get; set; }\n [JsonPropertyName(\"locations\")]\n public List<string> Locations { get; set; }\n [JsonPropertyName(\"apiVersions\")]",
"score": 0.7238634824752808
},
{
"filename": "src/Models/Resource.cs",
"retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace Beeching.Models\n{\n internal class Resource\n {\n [JsonPropertyName(\"id\")]\n public string Id { get; set; }\n [JsonPropertyName(\"name\")]\n public string Name { get; set; }\n [JsonPropertyName(\"type\")]",
"score": 0.7187985181808472
},
{
"filename": "src/Models/ApiProfile.cs",
"retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace Beeching.Models\n{\n internal class ApiProfile\n {\n [JsonPropertyName(\"profileVersion\")]\n public string ProfileVersion { get; set; }\n [JsonPropertyName(\"apiVersion\")]\n public string ApiVersion { get; set; }\n }",
"score": 0.7139928340911865
}
] | csharp | Resource> AxeList { |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.UIElements.UIR;
namespace Ultrapain.Patches
{
class DrillFlag : MonoBehaviour
{
public Harpoon drill;
public Rigidbody rb;
public List<Tuple<EnemyIdentifier, float>> targetEids = new List<Tuple<EnemyIdentifier, float>>();
public List<EnemyIdentifier> piercedEids = new List<EnemyIdentifier>();
public Transform currentTargetTrans;
public Collider currentTargetCol;
public EnemyIdentifier currentTargetEid;
void Awake()
{
if (drill == null)
drill = GetComponent<Harpoon>();
if (rb == null)
rb = GetComponent<Rigidbody>();
}
void Update()
{
if(targetEids != null)
{
if (currentTargetEid == null || currentTargetEid.dead || currentTargetEid.blessed || currentTargetEid.stuckMagnets.Count == 0)
{
currentTargetEid = null;
foreach (Tuple<EnemyIdentifier, float> item in targetEids)
{
EnemyIdentifier eid = item.Item1;
if (eid == null || eid.dead || eid.blessed || eid.stuckMagnets.Count == 0)
continue;
currentTargetEid = eid;
currentTargetTrans = eid.transform;
if (currentTargetEid.gameObject.TryGetComponent(out Collider col))
currentTargetCol = col;
break;
}
}
if(currentTargetEid != null)
{
transform.LookAt(currentTargetCol == null ? currentTargetTrans.position : currentTargetCol.bounds.center);
rb.velocity = transform.forward * 150f;
}
else
{
targetEids.Clear();
}
}
}
}
class Harpoon_Start
{
static void Postfix(Harpoon __instance)
{
if (!__instance.drill)
return;
DrillFlag flag = __instance.gameObject.AddComponent<DrillFlag>();
flag.drill = __instance;
}
}
class Harpoon_Punched
{
static void Postfix(Harpoon __instance, EnemyIdentifierIdentifier ___target)
{
if (!__instance.drill)
return;
DrillFlag flag = __instance.GetComponent<DrillFlag>();
if (flag == null)
return;
if(___target != null && ___target.eid != null)
flag.targetEids = UnityUtils.GetClosestEnemies(__instance.transform.position, 3, (sourcePos, enemy) =>
{
if (enemy == ___target.eid)
return false;
foreach (Magnet m in enemy.stuckMagnets)
{
if (m != null)
return true;
}
return false;
});
else
flag.targetEids = UnityUtils.GetClosestEnemies(__instance.transform.position, 3, (sourcePos, enemy) =>
{
foreach(Magnet m in enemy.stuckMagnets)
{
if (m != null)
return true;
}
return false;
});
}
}
class Harpoon_OnTriggerEnter_Patch
{
public static float forwardForce = 10f;
public static float upwardForce = 10f;
static LayerMask envLayer = new LayerMask() { m_Mask = 16777472 };
private static | Harpoon lastHarpoon; |
static bool Prefix(Harpoon __instance, Collider __0)
{
if (!__instance.drill)
return true;
if(__0.TryGetComponent(out EnemyIdentifierIdentifier eii))
{
if (eii.eid == null)
return true;
EnemyIdentifier eid = eii.eid;
DrillFlag flag = __instance.GetComponent<DrillFlag>();
if (flag == null)
return true;
if(flag.currentTargetEid != null)
{
if(flag.currentTargetEid == eid)
{
flag.targetEids.Clear();
flag.piercedEids.Clear();
flag.currentTargetEid = null;
flag.currentTargetTrans = null;
flag.currentTargetCol = null;
if(ConfigManager.screwDriverHomeDestroyMagnets.value)
{
foreach (Magnet h in eid.stuckMagnets)
if (h != null)
GameObject.Destroy(h.gameObject);
eid.stuckMagnets.Clear();
}
return true;
}
else if (!flag.piercedEids.Contains(eid))
{
if (ConfigManager.screwDriverHomePierceDamage.value > 0)
{
eid.hitter = "harpoon";
eid.DeliverDamage(__0.gameObject, __instance.transform.forward, __instance.transform.position, ConfigManager.screwDriverHomePierceDamage.value, false, 0, null, false);
flag.piercedEids.Add(eid);
}
return false;
}
return false;
}
}
Coin sourceCoin = __0.gameObject.GetComponent<Coin>();
if (sourceCoin != null)
{
if (__instance == lastHarpoon)
return true;
Quaternion currentRotation = Quaternion.Euler(0, __0.transform.eulerAngles.y, 0);
int totalCoinCount = ConfigManager.screwDriverCoinSplitCount.value;
float rotationPerIteration = 360f / totalCoinCount;
for(int i = 0; i < totalCoinCount; i++)
{
GameObject coinClone = GameObject.Instantiate(Plugin.coin, __instance.transform.position, currentRotation);
Coin comp = coinClone.GetComponent<Coin>();
comp.sourceWeapon = sourceCoin.sourceWeapon;
comp.power = sourceCoin.power;
Rigidbody rb = coinClone.GetComponent<Rigidbody>();
rb.AddForce(coinClone.transform.forward * forwardForce + Vector3.up * upwardForce, ForceMode.VelocityChange);
currentRotation = Quaternion.Euler(0, currentRotation.eulerAngles.y + rotationPerIteration, 0);
}
GameObject.Destroy(__0.gameObject);
GameObject.Destroy(__instance.gameObject);
lastHarpoon = __instance;
return false;
}
Grenade sourceGrn = __0.GetComponent<Grenade>();
if(sourceGrn != null)
{
if (__instance == lastHarpoon)
return true;
Quaternion currentRotation = Quaternion.Euler(0, __0.transform.eulerAngles.y, 0);
int totalGrenadeCount = ConfigManager.screwDriverCoinSplitCount.value;
float rotationPerIteration = 360f / totalGrenadeCount;
List<Tuple<EnemyIdentifier , float>> targetEnemies = new List<Tuple<EnemyIdentifier, float>>();
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
float sqrMagnitude = (enemy.transform.position - __0.transform.position).sqrMagnitude;
if (targetEnemies.Count < totalGrenadeCount || sqrMagnitude < targetEnemies.Last().Item2)
{
EnemyIdentifier eid = enemy.GetComponent<EnemyIdentifier>();
if (eid == null || eid.dead || eid.blessed)
continue;
if (Physics.Raycast(__0.transform.position, enemy.transform.position - __0.transform.position, out RaycastHit hit, Vector3.Distance(__0.transform.position, enemy.transform.position) - 0.5f, envLayer))
continue;
if(targetEnemies.Count == 0)
{
targetEnemies.Add(new Tuple<EnemyIdentifier, float>(eid, sqrMagnitude));
continue;
}
int insertionPoint = targetEnemies.Count;
while (insertionPoint != 0 && targetEnemies[insertionPoint - 1].Item2 > sqrMagnitude)
insertionPoint -= 1;
targetEnemies.Insert(insertionPoint, new Tuple<EnemyIdentifier, float>(eid, sqrMagnitude));
if (targetEnemies.Count > totalGrenadeCount)
targetEnemies.RemoveAt(totalGrenadeCount);
}
}
for (int i = 0; i < totalGrenadeCount; i++)
{
Grenade grenadeClone = GameObject.Instantiate(sourceGrn, __instance.transform.position, currentRotation);
Rigidbody rb = grenadeClone.GetComponent<Rigidbody>();
rb.velocity = Vector3.zero;
if(i <= targetEnemies.Count - 1 || targetEnemies.Count != 0)
{
grenadeClone.transform.LookAt(targetEnemies[i <= targetEnemies.Count - 1 ? i : 0].Item1.transform);
if (!grenadeClone.rocket)
{
rb.AddForce(grenadeClone.transform.forward * 50f, ForceMode.VelocityChange);
rb.useGravity = false;
}
else
{
grenadeClone.rocketSpeed = 150f;
}
}
else
{
rb.AddForce(grenadeClone.transform.forward * forwardForce + Vector3.up * upwardForce, ForceMode.VelocityChange);
}
currentRotation = Quaternion.Euler(0, currentRotation.eulerAngles.y + rotationPerIteration, 0);
}
GameObject.Destroy(__instance.gameObject);
GameObject.Destroy(sourceGrn.gameObject);
lastHarpoon = __instance;
return false;
}
return true;
}
}
}
| Ultrapain/Patches/Screwdriver.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/V2Common.cs",
"retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;",
"score": 0.8790566921234131
},
{
"filename": "Ultrapain/Patches/Mindflayer.cs",
"retrieved_chunk": " //___eid.SpeedBuff();\n }\n }\n class Mindflayer_ShootProjectiles_Patch\n {\n public static float maxProjDistance = 5;\n public static float initialProjectileDistance = -1f;\n public static float distancePerProjShot = 0.2f;\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)\n {",
"score": 0.8732049465179443
},
{
"filename": "Ultrapain/Plugin.cs",
"retrieved_chunk": " public static GameObject maliciousRailcannon;\n // Variables\n public static float SoliderShootAnimationStart = 1.2f;\n public static float SoliderGrenadeForce = 10000f;\n public static float SwordsMachineKnockdownTimeNormalized = 0.8f;\n public static float SwordsMachineCoreSpeed = 80f;\n public static float MinGrenadeParryVelocity = 40f;\n public static GameObject _lighningBoltSFX;\n public static GameObject lighningBoltSFX\n {",
"score": 0.8729403018951416
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " {\n private LeviathanHead comp;\n private Animator anim;\n //private Collider col;\n private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };\n public float playerRocketRideTracker = 0;\n private GameObject currentProjectileEffect;\n private AudioSource currentProjectileAud;\n private Transform shootPoint;\n public float currentProjectileSize = 0;",
"score": 0.8721532225608826
},
{
"filename": "Ultrapain/Patches/CommonComponents.cs",
"retrieved_chunk": " public float superSize = 1f;\n public float superSpeed = 1f;\n public float superDamage = 1f;\n public int superPlayerDamageOverride = -1;\n struct StateInfo\n {\n public GameObject tempHarmless;\n public GameObject tempNormal;\n public GameObject tempSuper;\n public StateInfo()",
"score": 0.8688877820968628
}
] | csharp | Harpoon lastHarpoon; |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Ultrapain.Patches
{
public static class V2Utils
{
public static Transform GetClosestGrenade()
{
Transform closestTransform = null;
float closestDistance = 1000000;
foreach(Grenade g in GrenadeList.Instance.grenadeList)
{
float dist = Vector3.Distance(g.transform.position, PlayerTracker.Instance.GetTarget().position);
if(dist < closestDistance)
{
closestTransform = g.transform;
closestDistance = dist;
}
}
foreach (Cannonball c in GrenadeList.Instance.cannonballList)
{
float dist = Vector3.Distance(c.transform.position, PlayerTracker.Instance.GetTarget().position);
if (dist < closestDistance)
{
closestTransform = c.transform;
closestDistance = dist;
}
}
return closestTransform;
}
public static Vector3 GetDirectionAwayFromTarget(Vector3 center, Vector3 target)
{
// Calculate the direction vector from the center to the target
Vector3 direction = target - center;
// Set the Y component of the direction vector to 0
direction.y = 0;
// Normalize the direction vector
direction.Normalize();
// Reverse the direction vector to face away from the target
direction = -direction;
return direction;
}
}
class V2CommonExplosion
{
static void Postfix(Explosion __instance)
{
if (__instance.sourceWeapon == null)
return;
V2MaliciousCannon malCanComp = __instance.sourceWeapon.GetComponent<V2MaliciousCannon>();
if(malCanComp != null)
{
Debug.Log("Grenade explosion triggered by V2 malicious cannon");
__instance.toIgnore.Add(EnemyType.V2);
__instance.toIgnore.Add(EnemyType.V2Second);
return;
}
EnemyRevolver revComp = __instance.sourceWeapon.GetComponentInChildren<EnemyRevolver>();
if(revComp != null)
{
Debug.Log("Grenade explosion triggered by V2 revolver");
__instance.toIgnore.Add(EnemyType.V2);
__instance.toIgnore.Add(EnemyType.V2Second);
return;
}
}
}
// SHARPSHOOTER
class V2CommonRevolverComp : MonoBehaviour
{
public bool secondPhase = false;
public bool shootingForSharpshooter = false;
}
class V2CommonRevolverPrepareAltFire
{
static bool Prefix(EnemyRevolver __instance, GameObject ___altCharge)
{
if(__instance.TryGetComponent<V2CommonRevolverComp>(out V2CommonRevolverComp comp))
{
if ((comp.secondPhase && !ConfigManager.v2SecondSharpshooterToggle.value)
|| (!comp.secondPhase && !ConfigManager.v2FirstSharpshooterToggle.value))
return true;
bool sharp = UnityEngine.Random.Range(0f, 100f) <= (comp.secondPhase ? ConfigManager.v2SecondSharpshooterChance.value : ConfigManager.v2FirstSharpshooterChance.value);
Transform quad = ___altCharge.transform.Find("MuzzleFlash/Quad");
MeshRenderer quadRenderer = quad.gameObject.GetComponent<MeshRenderer>();
quadRenderer.material.color = sharp ? new Color(1f, 0.1f, 0f) : new Color(1f, 1f, 1f);
comp.shootingForSharpshooter = sharp;
}
return true;
}
}
class V2CommonRevolverBulletSharp : MonoBehaviour
{
public int reflectionCount = 2;
public float autoAimAngle = 30f;
public Projectile proj;
public float speed = 350f;
public bool hasTargetPoint = false;
public Vector3 shootPoint;
public | Vector3 targetPoint; |
public RaycastHit targetHit;
public bool alreadyHitPlayer = false;
public bool alreadyReflected = false;
private void Awake()
{
proj = GetComponent<Projectile>();
proj.speed = 0;
GetComponent<Rigidbody>().isKinematic = true;
}
private void Update()
{
if (!hasTargetPoint)
transform.position += transform.forward * speed;
else
{
if (transform.position != targetPoint)
{
transform.position = Vector3.MoveTowards(transform.position, targetPoint, Time.deltaTime * speed);
if (transform.position == targetPoint)
proj.SendMessage("Collided", targetHit.collider);
}
else
proj.SendMessage("Collided", targetHit.collider);
}
}
}
class V2CommonRevolverBullet
{
static bool Prefix(Projectile __instance, Collider __0)
{
V2CommonRevolverBulletSharp comp = __instance.GetComponent<V2CommonRevolverBulletSharp>();
if (comp == null)
return true;
if ((__0.gameObject.tag == "Head" || __0.gameObject.tag == "Body" || __0.gameObject.tag == "Limb" || __0.gameObject.tag == "EndLimb") && __0.gameObject.tag != "Armor")
{
EnemyIdentifierIdentifier eii = __instance.GetComponent<EnemyIdentifierIdentifier>();
if (eii != null)
{
eii.eid.hitter = "enemy";
eii.eid.DeliverDamage(__0.gameObject, __instance.transform.forward * 100f, __instance.transform.position, comp.proj.damage / 10f, false, 0f, null, false);
return false;
}
}
if (comp.alreadyReflected)
return false;
bool isPlayer = __0.gameObject.tag == "Player";
if (isPlayer)
{
if (comp.alreadyHitPlayer)
return false;
NewMovement.Instance.GetHurt(Mathf.RoundToInt(comp.proj.damage), true, 1f, false, false);
comp.alreadyHitPlayer = true;
return false;
}
if (!comp.hasTargetPoint || comp.transform.position != comp.targetPoint)
return false;
if(comp.reflectionCount <= 0)
{
comp.alreadyReflected = true;
return true;
}
// REFLECTION
LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };
GameObject reflectedBullet = GameObject.Instantiate(__instance.gameObject, comp.targetPoint, __instance.transform.rotation);
V2CommonRevolverBulletSharp reflectComp = reflectedBullet.GetComponent<V2CommonRevolverBulletSharp>();
reflectComp.reflectionCount -= 1;
reflectComp.shootPoint = reflectComp.transform.position;
reflectComp.alreadyReflected = false;
reflectComp.alreadyHitPlayer = false;
reflectedBullet.transform.forward = Vector3.Reflect(comp.transform.forward, comp.targetHit.normal).normalized;
Vector3 playerPos = NewMovement.Instance.transform.position;
Vector3 playerVectorFromBullet = playerPos - reflectedBullet.transform.position;
float angle = Vector3.Angle(playerVectorFromBullet, reflectedBullet.transform.forward);
if (angle <= ConfigManager.v2FirstSharpshooterAutoaimAngle.value)
{
Quaternion lastRotation = reflectedBullet.transform.rotation;
reflectedBullet.transform.LookAt(NewMovement.Instance.playerCollider.bounds.center);
RaycastHit[] hits = Physics.RaycastAll(reflectedBullet.transform.position, reflectedBullet.transform.forward, Vector3.Distance(reflectedBullet.transform.position, playerPos));
bool hitEnv = false;
foreach (RaycastHit rayHit in hits)
{
if (rayHit.transform.gameObject.layer == 8 || rayHit.transform.gameObject.layer == 24)
{
hitEnv = true;
break;
}
}
if (hitEnv)
{
reflectedBullet.transform.rotation = lastRotation;
}
}
if(Physics.Raycast(reflectedBullet.transform.position, reflectedBullet.transform.forward, out RaycastHit hit, float.PositiveInfinity, envMask))
{
reflectComp.targetPoint = hit.point;
reflectComp.targetHit = hit;
reflectComp.hasTargetPoint = true;
}
else
{
reflectComp.hasTargetPoint = false;
}
comp.alreadyReflected = true;
GameObject.Instantiate(Plugin.ricochetSfx, reflectedBullet.transform.position, Quaternion.identity);
return true;
}
}
class V2CommonRevolverAltShoot
{
static bool Prefix(EnemyRevolver __instance, EnemyIdentifier ___eid)
{
if (__instance.TryGetComponent<V2CommonRevolverComp>(out V2CommonRevolverComp comp) && comp.shootingForSharpshooter)
{
__instance.CancelAltCharge();
Vector3 position = __instance.shootPoint.position;
if (Vector3.Distance(__instance.transform.position, ___eid.transform.position) > Vector3.Distance(MonoSingleton<NewMovement>.Instance.transform.position, ___eid.transform.position))
{
position = new Vector3(___eid.transform.position.x, __instance.transform.position.y, ___eid.transform.position.z);
}
GameObject bullet = GameObject.Instantiate(__instance.altBullet, position, __instance.shootPoint.rotation);
V2CommonRevolverBulletSharp bulletComp = bullet.AddComponent<V2CommonRevolverBulletSharp>();
bulletComp.autoAimAngle = comp.secondPhase ? ConfigManager.v2SecondSharpshooterAutoaimAngle.value : ConfigManager.v2FirstSharpshooterAutoaimAngle.value;
bulletComp.reflectionCount = comp.secondPhase ? ConfigManager.v2SecondSharpshooterReflections.value : ConfigManager.v2FirstSharpshooterReflections.value;
bulletComp.speed *= comp.secondPhase ? ConfigManager.v2SecondSharpshooterSpeed.value : ConfigManager.v2FirstSharpshooterSpeed.value;
TrailRenderer rend = UnityUtils.GetComponentInChildrenRecursively<TrailRenderer>(bullet.transform);
rend.endColor = rend.startColor = new Color(1, 0, 0);
Projectile component = bullet.GetComponent<Projectile>();
if (component)
{
component.safeEnemyType = __instance.safeEnemyType;
component.damage *= comp.secondPhase ? ConfigManager.v2SecondSharpshooterDamage.value : ConfigManager.v2FirstSharpshooterDamage.value;
}
LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };
float v2Height = -1;
RaycastHit v2Ground;
if (!Physics.Raycast(position, Vector3.down, out v2Ground, float.PositiveInfinity, envMask))
v2Height = v2Ground.distance;
float playerHeight = -1;
RaycastHit playerGround;
if (!Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out playerGround, float.PositiveInfinity, envMask))
playerHeight = playerGround.distance;
if (v2Height != -1 && playerHeight != -1)
{
Vector3 playerGroundFromV2 = playerGround.point - v2Ground.point;
float distance = Vector3.Distance(playerGround.point, v2Ground.point);
float k = playerHeight / v2Height;
float d1 = (distance * k) / (1 + k);
Vector3 lookPoint = v2Ground.point + (playerGroundFromV2 / distance) * d1;
bullet.transform.LookAt(lookPoint);
}
else
{
Vector3 mid = ___eid.transform.position + (NewMovement.Instance.transform.position - ___eid.transform.position) * 0.5f;
if (Physics.Raycast(mid, Vector3.down, out RaycastHit hit, 1000f, new LayerMask() { value = 1 << 8 | 1 << 24 }))
{
bullet.transform.LookAt(hit.point);
}
else
{
bullet.transform.LookAt(NewMovement.Instance.playerCollider.bounds.center);
}
}
GameObject.Instantiate(__instance.muzzleFlashAlt, __instance.shootPoint.position, __instance.shootPoint.rotation);
if (Physics.Raycast(bullet.transform.position, bullet.transform.forward, out RaycastHit predictedHit, float.PositiveInfinity, envMask))
{
bulletComp.targetPoint = predictedHit.point;
bulletComp.targetHit = predictedHit;
bulletComp.hasTargetPoint = true;
}
else
{
bulletComp.hasTargetPoint = false;
}
comp.shootingForSharpshooter = false;
return false;
}
return true;
}
}
}
| Ultrapain/Patches/V2Common.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " public GameObject standardProjectile;\n public GameObject standardDecorativeProjectile;\n public int comboRemaining = ConfigManager.strayShootCount.value;\n public bool inCombo = false;\n public float lastSpeed = 1f;\n public enum AttackMode\n {\n ProjectileCombo,\n FastHoming\n }",
"score": 0.8941492438316345
},
{
"filename": "Ultrapain/Patches/OrbitalStrike.cs",
"retrieved_chunk": " {\n public CoinChainList chainList;\n public bool isOrbitalRay = false;\n public bool exploded = false;\n public float activasionDistance;\n }\n public class Coin_Start\n {\n static void Postfix(Coin __instance)\n {",
"score": 0.8919864892959595
},
{
"filename": "Ultrapain/Patches/SomethingWicked.cs",
"retrieved_chunk": " public MassSpear spearComp;\n public EnemyIdentifier eid;\n public Transform spearOrigin;\n public Rigidbody spearRb;\n public static float SpearTriggerDistance = 80f;\n public static LayerMask envMask = new LayerMask() { value = (1 << 8) | (1 << 24) };\n void Awake()\n {\n if (eid == null)\n eid = GetComponent<EnemyIdentifier>();",
"score": 0.8912842273712158
},
{
"filename": "Ultrapain/Patches/CommonComponents.cs",
"retrieved_chunk": " public Quaternion targetRotation;\n private void Awake()\n {\n transform.rotation = targetRotation;\n }\n }\n public class CommonActivator : MonoBehaviour\n {\n public int originalId;\n public Renderer rend;",
"score": 0.8898299932479858
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " {\n private LeviathanHead comp;\n private Animator anim;\n //private Collider col;\n private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };\n public float playerRocketRideTracker = 0;\n private GameObject currentProjectileEffect;\n private AudioSource currentProjectileAud;\n private Transform shootPoint;\n public float currentProjectileSize = 0;",
"score": 0.8897082209587097
}
] | csharp | Vector3 targetPoint; |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Annotations;
using System.Windows.Media.Animation;
using ChatUI.MVVM.Model;
using System.Runtime.Remoting.Messaging;
using System.Collections.ObjectModel;
using ChatUI.MVVM.ViewModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using ChatGPTConnection;
namespace ChatUI
{
public partial class MainWindow : Window
{
public static string DllDirectory
{
get
{
string dllPath = System.IO.Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location);
string dllDirectory = System.IO.Directory.GetParent(dllPath).FullName;
return dllDirectory;
}
}
public event | ChatGPTResponseEventHandler ResponseReceived; |
public MainWindow()
{
InitializeComponent();
var vm = this.DataContext as MainViewModel;
}
private void Border_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void WindowStateButton_Click(object sender, RoutedEventArgs e)
{
if (this.WindowState != WindowState.Maximized)
{
this.WindowState = WindowState.Maximized;
}
else
{
this.WindowState = WindowState.Normal;
}
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void OptionButton_Click(object sender, RoutedEventArgs e)
{
var optionWindow = new OptionWindow();
optionWindow.Owner = this;
optionWindow.ShowDialog();
}
//デバッグモード
//ChatGPTのメッセージテキストが詳細化
private bool _isDebagMode;
public bool IsDebagMode
{
get => _isDebagMode;
set
{
_isDebagMode = value;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ChangeDebagMode(!_isDebagMode);
if (_isDebagMode) DebugButton.Background = Brushes.LightSlateGray;
else DebugButton.Background = Brushes.Transparent;
}
private void ChangeDebagMode(bool state)
{
IsDebagMode = state;
//メッセージのステートを変化させる
var vm = this.DataContext as MainViewModel;
foreach (MessageModel mm in vm.Messages)
{
mm.UseSubMessage = state;
}
}
internal void OnResponseReceived(ChatGPTResponseEventArgs e)
{
ResponseReceived?.Invoke(this, e);
}
}
}
| ChatUI/MainWindow.xaml.cs | 4kk11-ChatGPTforRhino-382323e | [
{
"filename": "ChatUI/MVVM/ViewModel/MainViewModel.cs",
"retrieved_chunk": "\t\tpublic string Message\n\t\t{\n\t\t\tget { return _message; }\n\t\t\tset\n\t\t\t{\n\t\t\t\t_message = value;\n\t\t\t\tOnPropertyChanged();\n\t\t\t}\n\t\t}\n\t\tprivate string CatIconPath => Path.Combine(MainWindow.DllDirectory, \"Icons/cat.jpeg\");",
"score": 0.7732841968536377
},
{
"filename": "ChatUI/Settings.cs",
"retrieved_chunk": "\tpublic class Settings\n\t{\n\t\tprivate static readonly string FileName = Path.Combine(MainWindow.DllDirectory, \"Settings.xml\");\n\t\tpublic string APIKey { get; set; }\n\t\tpublic string SystemMessage { get; set; }\n\t\tpublic Settings(string apikey, string systemMessage) \n\t\t{\n\t\t\tAPIKey = apikey;\n\t\t\tSystemMessage = systemMessage;\n\t\t}",
"score": 0.7450383901596069
},
{
"filename": "ChatGPTforRhino/SelectObjectCommand.cs",
"retrieved_chunk": "\t\t{\n\t\t\tusing (GetString gs = new GetString())\n\t\t\t{\n\t\t\t\tgs.SetCommandPrompt(\"Name\");\n\t\t\t\tgs.GetLiteralString();\n\t\t\t\tif (gs.CommandResult() != Result.Success)\n\t\t\t\t{\n\t\t\t\t\tuserMessage = null;\n\t\t\t\t\treturn false;\n\t\t\t\t}",
"score": 0.6900201439857483
},
{
"filename": "ChatUI/Properties/Settings.Designer.cs",
"retrieved_chunk": "{\n\t[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n\t[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator\", \"11.0.0.0\")]\n\tinternal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase\n\t{\n\t\tprivate static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));\n\t\tpublic static Settings Default\n\t\t{\n\t\t\tget\n\t\t\t{",
"score": 0.6891140341758728
},
{
"filename": "ChatUI/Core/ObservableObject.cs",
"retrieved_chunk": "\t{\n\t\tpublic event PropertyChangedEventHandler PropertyChanged;\n\t\tpublic void OnPropertyChanged([CallerMemberName] string propertyName = null)\n\t\t{\n\t\t\tPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n\t\t}\n\t}\n}",
"score": 0.675488293170929
}
] | csharp | ChatGPTResponseEventHandler ResponseReceived; |
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Timeline;
using UnityEngine;
using UnityEngine.Timeline;
namespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor
{
internal static class AbstractBoolValueControlTrackEditorUtility
{
internal static Color PrimaryColor = new(0.5f, 1f, 0.5f);
}
[CustomTimelineEditor(typeof(AbstractBoolValueControlTrack))]
public class AbstractBoolValueControlTrackCustomEditor : TrackEditor
{
public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)
{
track.name = "CustomTrack";
var options = base.GetTrackOptions(track, binding);
options.trackColor = AbstractBoolValueControlTrackEditorUtility.PrimaryColor;
// Debug.Log(binding.GetType());
return options;
}
}
[CustomTimelineEditor(typeof(AbstractBoolValueControlClip))]
public class AbstractBoolValueControlCustomEditor : ClipEditor
{
Dictionary<AbstractBoolValueControlClip, Texture2D> textures = new();
public override ClipDrawOptions GetClipOptions(TimelineClip clip)
{
var clipOptions = base.GetClipOptions(clip);
clipOptions.icons = null;
clipOptions.highlightColor = AbstractBoolValueControlTrackEditorUtility.PrimaryColor;
return clipOptions;
}
public override void DrawBackground(TimelineClip clip, ClipBackgroundRegion region)
{
var tex = GetSolidColorTexture(clip);
if (tex) GUI.DrawTexture(region.position, tex);
}
public override void OnClipChanged(TimelineClip clip)
{
GetSolidColorTexture(clip, true);
}
Texture2D GetSolidColorTexture(TimelineClip clip, bool update = false)
{
var tex = Texture2D.blackTexture;
var customClip = clip.asset as AbstractBoolValueControlClip;
if (update)
{
textures.Remove(customClip);
}
else
{
textures.TryGetValue(customClip, out tex);
if (tex) return tex;
}
var c = customClip.Value ? new Color(0.8f, 0.8f, 0.8f) : new Color(0.2f, 0.2f, 0.2f);
tex = new Texture2D(1, 1);
tex.SetPixel(0, 0, c);
tex.Apply();
if (textures.ContainsKey(customClip))
{
textures[customClip] = tex;
}
else
{
textures.Add(customClip, tex);
}
return tex;
}
}
[CanEditMultipleObjects]
[CustomEditor(typeof( | AbstractBoolValueControlClip))]
public class AbstractBoolValueControlClipEditor : UnityEditor.Editor
{ |
public override void OnInspectorGUI()
{
DrawDefaultInspector();
}
}
} | Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs | nmxi-Unity_AbstractTimelineExtention-b518049 | [
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n }\n [CanEditMultipleObjects]\n [CustomEditor(typeof(AbstractFloatValueControlClip))]\n public class AbstractFloatValueControlClipEditor : UnityEditor.Editor\n {\n public override void OnInspectorGUI()\n {\n DrawDefaultInspector();\n }",
"score": 0.9021965861320496
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractColorValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n else\n {\n textures.Add(customClip, tex); \n }\n return tex;\n }\n }\n [CanEditMultipleObjects]\n [CustomEditor(typeof(AbstractColorValueControlClip))]",
"score": 0.9016354084014893
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n }\n [CanEditMultipleObjects]\n [CustomEditor(typeof(AbstractIntValueControlClip))]\n public class AbstractIntValueControlClipEditor : UnityEditor.Editor\n {\n public override void OnInspectorGUI()\n {\n DrawDefaultInspector();\n }",
"score": 0.8995475769042969
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractColorValueControlTrackCustomEditor.cs",
"retrieved_chunk": " public class AbstractColorValueControlClipEditor : UnityEditor.Editor\n {\n public override void OnInspectorGUI()\n {\n DrawDefaultInspector();\n }\n }\n}",
"score": 0.8490903377532959
},
{
"filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractColorValueControlTrackCustomEditor.cs",
"retrieved_chunk": " }\n }\n [CustomTimelineEditor(typeof(AbstractColorValueControlClip))]\n public class AbstractColorValueControlCustomEditor : ClipEditor\n {\n Dictionary<AbstractColorValueControlClip, Texture2D> textures = new();\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);\n clipOptions.icons = null;",
"score": 0.8232599496841431
}
] | csharp | AbstractBoolValueControlClip))]
public class AbstractBoolValueControlClipEditor : UnityEditor.Editor
{ |
/*
Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox')
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
namespace Kingdox.UniFlux.Core.Internal
{
/// <summary>
/// TKey
/// </summary>
internal interface IFlux<in TKey, in TStorage>: IStore<TKey, TStorage>
{
/// <summary>
/// Dispatch the TKey
/// </summary>
void Dispatch(TKey key);
}
/// <summary>
/// TKey TParam
/// </summary>
internal interface IFluxParam<in TKey, in TParam, in TStorage> : IStore<TKey, TStorage>
{
/// <summary>
/// Dispatch the TKey with TParam
/// </summary>
void Dispatch(TKey key, TParam param);
}
/// <summary>
/// TKey TReturn
/// </summary>
internal interface IFluxReturn<in | TKey, out TReturn, in TStorage> : IStore<TKey, TStorage>
{ |
/// <summary>
/// Dispatch the TKey and return TReturn
/// </summary>
TReturn Dispatch(TKey key);
}
/// <summary>
/// TKey TParam TReturn
/// </summary>
internal interface IFluxParamReturn<in TKey, in TParam, out TReturn, in TStorage> : IStore<TKey, TStorage>
{
/// <summary>
/// Dispatch the TKey with TParam and return TReturn
/// </summary>
TReturn Dispatch(TKey key, TParam param);
}
} | Runtime/Core/Internal/IFlux.cs | xavierarpa-UniFlux-a2d46de | [
{
"filename": "Runtime/Core/Internal/IStore.cs",
"retrieved_chunk": " ///<summary>\n /// Flux Storage Interface\n ///</summary>\n internal interface IStore<in TKey, in TStorage>\n {\n ///<summary>\n /// Store TStorage with TKey\n ///</summary>\n void Store(in bool condition, TKey key, TStorage storage);\n }",
"score": 0.9192039966583252
},
{
"filename": "Runtime/Core/Internal/FuncFluxParam.cs",
"retrieved_chunk": " }\n else if (condition) dictionary.Add(key, func);\n }\n /// <summary>\n /// Triggers the function stored in the dictionary with the specified key and parameter, and returns its return value. \n /// If the dictionary does not contain the specified key, returns the default value of type `TReturn`.\n /// </summary>\n TReturn IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>>.Dispatch(TKey key, TParam param)\n {\n if(dictionary.TryGetValue(key, out var _actions))",
"score": 0.8587372303009033
},
{
"filename": "Runtime/Core/Internal/FluxReturn_T_T2.cs",
"retrieved_chunk": "{\n ///<summary>\n /// Flux<T> Func<out T2>\n ///</summary>\n internal static class FluxReturn<T,T2> // (T, Func<out T2>)\n {\n ///<summary>\n /// Defines a static instance of FuncFlux<T,T2>\n ///</summary>\n internal static readonly IFluxReturn<T, T2, Func<T2>> flux_func = new FuncFlux<T,T2>();",
"score": 0.8468619585037231
},
{
"filename": "Runtime/Core/Internal/FuncFluxParam.cs",
"retrieved_chunk": " {\n /// <summary>\n /// A dictionary that stores functions with one parameter of type `TParam` and a return value of type `TReturn`.\n /// </summary>\n internal readonly Dictionary<TKey, Func<TParam, TReturn>> dictionary = new Dictionary<TKey, Func<TParam, TReturn>>();\n /// <summary>\n /// Subscribes the provided function to the dictionary with the specified key when `condition` is true. \n /// If `condition` is false and the dictionary contains the specified key, the function is removed from the dictionary.\n /// </summary>\n void IStore<TKey, Func<TParam, TReturn>>.Store(in bool condition, TKey key, Func<TParam, TReturn> func)",
"score": 0.8463135957717896
},
{
"filename": "Runtime/Core/Internal/ActionFluxParam.cs",
"retrieved_chunk": "namespace Kingdox.UniFlux.Core.Internal\n{\n ///<summary>\n /// This class represents an implementation of an IFlux interface with a TKey key and an action without parameters.\n ///</summary>\n internal sealed class ActionFluxParam<TKey, TValue> : IFluxParam<TKey, TValue, Action<TValue>>\n {\n /// <summary>\n /// A dictionary that stores functions with parameters\n /// </summary>",
"score": 0.8425612449645996
}
] | csharp | TKey, out TReturn, in TStorage> : IStore<TKey, TStorage>
{ |
using BepInEx;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using HarmonyLib;
using System.IO;
using Ultrapain.Patches;
using System.Linq;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Reflection;
using Steamworks;
using Unity.Audio;
using System.Text;
using System.Collections.Generic;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.ResourceManagement.ResourceLocations;
using UnityEngine.UIElements;
using PluginConfig.API;
namespace Ultrapain
{
[BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)]
[BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")]
public class Plugin : BaseUnityPlugin
{
public const string PLUGIN_GUID = "com.eternalUnion.ultraPain";
public const string PLUGIN_NAME = "Ultra Pain";
public const string PLUGIN_VERSION = "1.1.0";
public static Plugin instance;
private static bool addressableInit = false;
public static T LoadObject<T>(string path)
{
if (!addressableInit)
{
Addressables.InitializeAsync().WaitForCompletion();
addressableInit = true;
}
return Addressables.LoadAssetAsync<T>(path).WaitForCompletion();
}
public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod)
{
Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f)
return target.position;
RaycastHit raycastHit;
if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider)
return target.position;
else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide))
{
return raycastHit.point;
}
else {
Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod;
return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z);
}
}
public static GameObject projectileSpread;
public static GameObject homingProjectile;
public static GameObject hideousMassProjectile;
public static GameObject decorativeProjectile2;
public static GameObject shotgunGrenade;
public static GameObject beam;
public static GameObject turretBeam;
public static GameObject lightningStrikeExplosiveSetup;
public static GameObject lightningStrikeExplosive;
public static GameObject lighningStrikeWindup;
public static GameObject explosion;
public static GameObject bigExplosion;
public static GameObject sandExplosion;
public static GameObject virtueInsignia;
public static GameObject rocket;
public static GameObject revolverBullet;
public static GameObject maliciousCannonBeam;
public static GameObject lightningBoltSFX;
public static GameObject revolverBeam;
public static GameObject blastwave;
public static GameObject cannonBall;
public static GameObject shockwave;
public static GameObject sisyphiusExplosion;
public static GameObject sisyphiusPrimeExplosion;
public static GameObject explosionWaveKnuckleblaster;
public static GameObject chargeEffect;
public static GameObject maliciousFaceProjectile;
public static GameObject hideousMassSpear;
public static GameObject coin;
public static GameObject sisyphusDestroyExplosion;
//public static GameObject idol;
public static GameObject ferryman;
public static GameObject minosPrime;
//public static GameObject maliciousFace;
public static GameObject somethingWicked;
public static Turret turret;
public static GameObject turretFinalFlash;
public static GameObject enrageEffect;
public static GameObject v2flashUnparryable;
public static GameObject ricochetSfx;
public static GameObject parryableFlash;
public static AudioClip cannonBallChargeAudio;
public static Material gabrielFakeMat;
public static Sprite blueRevolverSprite;
public static Sprite greenRevolverSprite;
public static Sprite redRevolverSprite;
public static Sprite blueShotgunSprite;
public static Sprite greenShotgunSprite;
public static Sprite blueNailgunSprite;
public static Sprite greenNailgunSprite;
public static Sprite blueSawLauncherSprite;
public static Sprite greenSawLauncherSprite;
public static GameObject rocketLauncherAlt;
public static GameObject maliciousRailcannon;
// Variables
public static float SoliderShootAnimationStart = 1.2f;
public static float SoliderGrenadeForce = 10000f;
public static float SwordsMachineKnockdownTimeNormalized = 0.8f;
public static float SwordsMachineCoreSpeed = 80f;
public static float MinGrenadeParryVelocity = 40f;
public static GameObject _lighningBoltSFX;
public static GameObject lighningBoltSFX
{
get
{
if (_lighningBoltSFX == null)
_lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject;
return _lighningBoltSFX;
}
}
private static bool loadedPrefabs = false;
public void LoadPrefabs()
{
if (loadedPrefabs)
return;
loadedPrefabs = true;
// Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab
projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab");
// Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab
homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab");
// Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab
decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab");
// Assets/Prefabs/Attacks and Projectiles/Grenade.prefab
shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab");
// Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab
turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab");
// Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab
beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab
lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab");
// Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab
lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab");
//[bundle-0][assets/prefabs/enemies/idol.prefab]
//idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab");
// Assets/Prefabs/Enemies/Ferryman.prefab
ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab
explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab");
//Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab
bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab");
//Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab
sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab");
// Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab
virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab");
// Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab
hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab");
// Assets/Particles/Enemies/RageEffect.prefab
enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab");
// Assets/Particles/Flashes/V2FlashUnparriable.prefab
v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab");
// Assets/Prefabs/Attacks and Projectiles/Rocket.prefab
rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab");
// Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab
revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab");
// Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab
maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab");
// Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab
revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab
blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab");
// Assets/Prefabs/Enemies/MinosPrime.prefab
minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab");
// Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab
cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab");
// get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab
cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip;
// Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab
shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab
sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab
sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab
explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab");
// Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab]
lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab");
// Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab
rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab");
// Assets/Prefabs/Weapons/Railcannon Malicious.prefab
maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab");
//Assets/Particles/SoundBubbles/Ricochet.prefab
ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab");
//Assets/Particles/Flashes/Flash.prefab
parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab");
//Assets/Prefabs/Attacks and Projectiles/Spear.prefab
hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab");
//Assets/Prefabs/Enemies/Wicked.prefab
somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab");
//Assets/Textures/UI/SingleRevolver.png
blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png");
//Assets/Textures/UI/RevolverSpecial.png
greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png");
//Assets/Textures/UI/RevolverSharp.png
redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png");
//Assets/Textures/UI/Shotgun.png
blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png");
//Assets/Textures/UI/Shotgun1.png
greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png");
//Assets/Textures/UI/Nailgun2.png
blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png");
//Assets/Textures/UI/NailgunOverheat.png
greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png");
//Assets/Textures/UI/SawbladeLauncher.png
blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png");
//Assets/Textures/UI/SawbladeLauncherOverheat.png
greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png");
//Assets/Prefabs/Attacks and Projectiles/Coin.prefab
coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab");
//Assets/Materials/GabrielFake.mat
gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat");
//Assets/Prefabs/Enemies/Turret.prefab
turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>();
//Assets/Particles/Flashes/GunFlashDistant.prefab
turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab");
//Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab
sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab");
//Assets/Prefabs/Effects/Charge Effect.prefab
chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab");
//Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab
maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab");
}
public static bool ultrapainDifficulty = false;
public static bool realUltrapainDifficulty = false;
public static GameObject currentDifficultyButton;
public static GameObject currentDifficultyPanel;
public static | Text currentDifficultyInfoText; |
public void OnSceneChange(Scene before, Scene after)
{
StyleIDs.RegisterIDs();
ScenePatchCheck();
string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902";
string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d";
string currentSceneName = SceneManager.GetActiveScene().name;
if (currentSceneName == mainMenuSceneName)
{
LoadPrefabs();
//Canvas/Difficulty Select (1)/Violent
Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)");
GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect);
currentDifficultyButton = ultrapainButton;
ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value;
ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5;
RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>();
ultrapainTrans.anchoredPosition = new Vector2(20f, -104f);
//Canvas/Difficulty Select (1)/Violent Info
GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect);
currentDifficultyPanel = info;
currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>();
currentDifficultyInfoText.text = ConfigManager.pluginInfo.value;
Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>();
currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--";
currentDifficultyHeaderText.resizeTextForBestFit = true;
currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap;
currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate;
info.SetActive(false);
EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>();
evt.triggers.Clear();
/*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent();
activate.AddListener((BaseEventData data) => info.SetActive(true));
EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent();
activate.AddListener((BaseEventData data) => info.SetActive(false));*/
EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter };
trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true));
EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit };
trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false));
evt.triggers.Add(trigger1);
evt.triggers.Add(trigger2);
foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>())
{
if (trigger.gameObject == ultrapainButton)
continue;
EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter };
closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false));
trigger.triggers.Add(closeTrigger);
}
}
else if(currentSceneName == bootSequenceSceneName)
{
LoadPrefabs();
//Canvas/Difficulty Select (1)/Violent
Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select");
GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect);
currentDifficultyButton = ultrapainButton;
ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value;
ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5;
RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>();
ultrapainTrans.anchoredPosition = new Vector2(20f, -104f);
//Canvas/Difficulty Select (1)/Violent Info
GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect);
currentDifficultyPanel = info;
currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>();
currentDifficultyInfoText.text = ConfigManager.pluginInfo.value;
Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>();
currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--";
currentDifficultyHeaderText.resizeTextForBestFit = true;
currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap;
currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate;
info.SetActive(false);
EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>();
evt.triggers.Clear();
/*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent();
activate.AddListener((BaseEventData data) => info.SetActive(true));
EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent();
activate.AddListener((BaseEventData data) => info.SetActive(false));*/
EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter };
trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true));
EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit };
trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false));
evt.triggers.Add(trigger1);
evt.triggers.Add(trigger2);
foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>())
{
if (trigger.gameObject == ultrapainButton)
continue;
EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter };
closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false));
trigger.triggers.Add(closeTrigger);
}
}
// LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG
MinosPrimeCharge.CreateDecoy();
GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave;
}
public static class StyleIDs
{
private static bool registered = false;
public static void RegisterIDs()
{
registered = false;
if (MonoSingleton<StyleHUD>.Instance == null)
return;
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString);
MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString);
registered = true;
Debug.Log("Registered all style ids");
}
private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
public static void UpdateID(string id, string newName)
{
if (!registered || StyleHUD.Instance == null)
return;
(idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName;
}
}
public static Harmony harmonyTweaks;
public static Harmony harmonyBase;
private static MethodInfo GetMethod<T>(string name)
{
return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
}
private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>();
private static HarmonyMethod GetHarmonyMethod(MethodInfo method)
{
if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod))
return harmonyMethod;
else
{
harmonyMethod = new HarmonyMethod(method);
methodCache.Add(method, harmonyMethod);
return harmonyMethod;
}
}
private static void PatchAllEnemies()
{
if (!ConfigManager.enemyTweakToggle.value)
return;
if (ConfigManager.friendlyFireDamageOverrideToggle.value)
{
harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix")));
harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix")));
harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix")));
harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix")));
}
harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix")));
harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix")));
if (ConfigManager.cerberusDashToggle.value)
harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix")));
if(ConfigManager.cerberusParryable.value)
{
harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix")));
if(ConfigManager.droneHomeToggle.value)
{
harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix")));
if(ConfigManager.ferrymanComboToggle.value)
harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix")));
if(ConfigManager.filthExplodeToggle.value)
harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix")));
if(ConfigManager.fleshPrisonSpinAttackToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix")));
if (ConfigManager.hideousMassInsigniaToggle.value)
{
harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix")));
harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix")));
if (ConfigManager.maliciousFaceHomingProjectileToggle.value)
{
harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix")));
}
if (ConfigManager.maliciousFaceRadianceOnEnrage.value)
harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix")));
if (ConfigManager.mindflayerShootTweakToggle.value)
{
harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix")));
}
if (ConfigManager.mindflayerTeleportComboToggle.value)
{
harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix")));
//harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix")));
}
if (ConfigManager.minosPrimeRandomTeleportToggle.value)
harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix")));
if (ConfigManager.minosPrimeTeleportTrail.value)
harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix")));
harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix")));
if (ConfigManager.minosPrimeCrushAttackToggle.value)
harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix")));
if (ConfigManager.minosPrimeComboExplosiveEndToggle.value)
harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix")));
if (ConfigManager.schismSpreadAttackToggle.value)
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix")));
if (ConfigManager.soliderShootTweakToggle.value)
{
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix")));
}
if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value)
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix")));
if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value)
{
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix")));
if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value)
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix")));
if (ConfigManager.strayShootToggle.value)
{
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix")));
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix")));
harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix")));
}
if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value)
harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix")));
if(ConfigManager.streetCleanerPredictiveDodgeToggle.value)
harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix")));
if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None)
{
harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix")));
//harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix")));
}
if (ConfigManager.swordsMachineExplosiveSwordToggle.value)
{
harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix")));
}
harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix")));
if(ConfigManager.turretBurstFireToggle.value)
{
harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix")));
harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix")));
}
harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix")));
harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix")));
harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix")));
harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix")));
harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix")));
//if(ConfigManager.v2SecondStartEnraged.value)
// harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix")));
harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix")));
//harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix")));
harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix")));
harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix")));
if(ConfigManager.v2SecondFastCoinToggle.value)
harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix")));
harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix")));
if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value)
{
harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix")));
harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix")));
harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix")));
}
harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix")));
harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix")));
if (ConfigManager.sisyInstJumpShockwave.value)
{
harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix")));
}
if(ConfigManager.sisyInstBoulderShockwave.value)
harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix")));
if(ConfigManager.sisyInstStrongerExplosion.value)
harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix")));
harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix")));
if (ConfigManager.somethingWickedSpear.value)
{
harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix")));
}
if(ConfigManager.somethingWickedSpawnOn43.value)
{
harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix")));
harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix")));
}
if (ConfigManager.panopticonFullPhase.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix")));
if (ConfigManager.panopticonAxisBeam.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix")));
if (ConfigManager.panopticonSpinAttackToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix")));
if (ConfigManager.panopticonBlackholeProj.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix")));
if (ConfigManager.panopticonBalanceEyes.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix")));
if (ConfigManager.panopticonBlueProjToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler")));
if (ConfigManager.idolExplosionToggle.value)
harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix")));
// ADDME
/*
harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix")));
harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix")));
harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix")));
harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix")));
*/
}
private static void PatchAllPlayers()
{
if (!ConfigManager.playerTweakToggle.value)
return;
harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix")));
harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix")));
harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix")));
if (ConfigManager.rocketBoostToggle.value)
harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix")));
if (ConfigManager.rocketGrabbingToggle.value)
harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix")));
if (ConfigManager.orbStrikeToggle.value)
{
harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix")));
harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix")));
harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix")));
harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix")));
harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix")));
harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix")));
harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix")));
harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix")));
harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix")));
harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix")));
harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix")));
}
if(ConfigManager.chargedRevRegSpeedMulti.value != 1)
harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix")));
if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1
|| ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1
|| ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1
|| ConfigManager.sawAmmoRegSpeedMulti.value != 1)
harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix")));
if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1)
harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix")));
if(ConfigManager.staminaRegSpeedMulti.value != 1)
harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix")));
if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1)
{
harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix")));
harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix")));
harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix")));
harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler")));
harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler")));
harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler")));
}
// ADDME
harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler")));
harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix")));
harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler")));
harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler")));
harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler")));
if (ConfigManager.hardDamagePercent.normalizedValue != 1)
harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix")));
harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix")));
harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler")));
foreach (HealthBarTracker hb in HealthBarTracker.instances)
{
if (hb != null)
hb.SetSliderRange();
}
harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix")));
if(ConfigManager.screwDriverHomeToggle.value)
harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix")));
if(ConfigManager.screwDriverSplitToggle.value)
harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix")));
}
private static void PatchAllMemes()
{
if (ConfigManager.enrageSfxToggle.value)
harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix")));
if(ConfigManager.funnyDruidKnightSFXToggle.value)
{
harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix")));
harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix")));
harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix")));
}
if (ConfigManager.fleshObamiumToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix")));
if (ConfigManager.obamapticonToggle.value)
harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix")));
}
public static bool methodsPatched = false;
public static void ScenePatchCheck()
{
if(methodsPatched && !ultrapainDifficulty)
{
harmonyTweaks.UnpatchSelf();
methodsPatched = false;
}
else if(!methodsPatched && ultrapainDifficulty)
{
PatchAll();
}
}
public static void PatchAll()
{
harmonyTweaks.UnpatchSelf();
methodsPatched = false;
if (!ultrapainDifficulty)
return;
if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value)
harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix")));
if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value)
harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix")));
PatchAllEnemies();
PatchAllPlayers();
PatchAllMemes();
methodsPatched = true;
}
public static string workingPath;
public static string workingDir;
public static AssetBundle bundle;
public static AudioClip druidKnightFullAutoAud;
public static AudioClip druidKnightFullerAutoAud;
public static AudioClip druidKnightDeathAud;
public static AudioClip enrageAudioCustom;
public static GameObject fleshObamium;
public static GameObject obamapticon;
public void Awake()
{
instance = this;
workingPath = Assembly.GetExecutingAssembly().Location;
workingDir = Path.GetDirectoryName(workingPath);
Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}");
try
{
bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain"));
druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav");
druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav");
druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav");
enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav");
fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab");
obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab");
}
catch (Exception e)
{
Logger.LogError($"Could not load the asset bundle:\n{e}");
}
// DEBUG
/*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt");
Logger.LogInfo($"Saving to {logPath}");
List<string> assetPaths = new List<string>()
{
"fonts.bundle",
"videos.bundle",
"shaders.bundle",
"particles.bundle",
"materials.bundle",
"animations.bundle",
"prefabs.bundle",
"physicsmaterials.bundle",
"models.bundle",
"textures.bundle",
};
//using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write))
//{
foreach(string assetPath in assetPaths)
{
Logger.LogInfo($"Attempting to load {assetPath}");
AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath));
bundles.Add(bundle);
//foreach (string name in bundle.GetAllAssetNames())
//{
// string line = $"[{bundle.name}][{name}]\n";
// log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length);
//}
bundle.LoadAllAssets();
}
//}
*/
// Plugin startup logic
Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!");
harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks");
harmonyBase = new Harmony(PLUGIN_GUID + "_base");
harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix")));
harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix")));
harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix")));
harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix")));
harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix")));
LoadPrefabs();
ConfigManager.Initialize();
SceneManager.activeSceneChanged += OnSceneChange;
}
}
public static class Tools
{
private static Transform _target;
private static Transform target { get
{
if(_target == null)
_target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
return _target;
}
}
public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null)
{
Vector3 projectedPlayerPos;
if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f)
{
return target.position;
}
RaycastHit raycastHit;
if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol)
{
projectedPlayerPos = target.position;
}
else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide))
{
projectedPlayerPos = raycastHit.point;
}
else
{
projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod;
projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z);
}
return projectedPlayerPos;
}
}
// Asset destroyer tracker
/*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })]
public class TempClass1
{
static void Postfix(UnityEngine.Object __0)
{
if (__0 != null && __0 == Plugin.homingProjectile)
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
Debug.LogError("Projectile destroyed");
Debug.LogError(t.ToString());
throw new Exception("Attempted to destroy proj");
}
}
}
[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })]
public class TempClass2
{
static void Postfix(UnityEngine.Object __0)
{
if (__0 != null && __0 == Plugin.homingProjectile)
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
Debug.LogError("Projectile destroyed");
Debug.LogError(t.ToString());
throw new Exception("Attempted to destroy proj");
}
}
}
[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })]
public class TempClass3
{
static void Postfix(UnityEngine.Object __0)
{
if (__0 != null && __0 == Plugin.homingProjectile)
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
Debug.LogError("Projectile destroyed");
Debug.LogError(t.ToString());
throw new Exception("Attempted to destroy proj");
}
}
}
[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })]
public class TempClass4
{
static void Postfix(UnityEngine.Object __0)
{
if (__0 != null && __0 == Plugin.homingProjectile)
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
Debug.LogError("Projectile destroyed");
Debug.LogError(t.ToString());
throw new Exception("Attempted to destroy proj");
}
}
}*/
}
| Ultrapain/Plugin.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static ConfigPanel leviathanPanel;\n public static ConfigPanel somethingWickedPanel;\n public static ConfigPanel panopticonPanel;\n public static ConfigPanel idolPanel;\n // GLOBAL ENEMY CONFIG\n public static BoolField friendlyFireDamageOverrideToggle;\n public static FloatSliderField friendlyFireDamageOverrideExplosion;\n public static FloatSliderField friendlyFireDamageOverrideProjectile;\n public static FloatSliderField friendlyFireDamageOverrideFire;\n public static FloatSliderField friendlyFireDamageOverrideMelee;",
"score": 0.8079357147216797
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static BoolField globalDifficultySwitch;\n public static ConfigPanel memePanel;\n // MEME PANEL\n public static BoolField enrageSfxToggle;\n public static BoolField funnyDruidKnightSFXToggle;\n public static BoolField fleshObamiumToggle;\n public static StringField fleshObamiumName;\n public static BoolField obamapticonToggle;\n public static StringField obamapticonName;\n // PLAYER PANEL",
"score": 0.7979597449302673
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static FloatField virtueEnragedLightningDamage;\n public static FloatField virtueEnragedLightningDelay;\n // MALICIOUS FACE\n public static BoolField maliciousFaceRadianceOnEnrage;\n public static IntField maliciousFaceRadianceAmount;\n public static BoolField maliciousFaceHomingProjectileToggle;\n public static IntField maliciousFaceHomingProjectileCount;\n public static IntField maliciousFaceHomingProjectileDamage;\n public static FloatField maliciousFaceHomingProjectileTurnSpeed;\n public static FloatField maliciousFaceHomingProjectileSpeed;",
"score": 0.7952994704246521
},
{
"filename": "Ultrapain/Patches/Stray.cs",
"retrieved_chunk": " public GameObject standardProjectile;\n public GameObject standardDecorativeProjectile;\n public int comboRemaining = ConfigManager.strayShootCount.value;\n public bool inCombo = false;\n public float lastSpeed = 1f;\n public enum AttackMode\n {\n ProjectileCombo,\n FastHoming\n }",
"score": 0.7901573181152344
},
{
"filename": "Ultrapain/ConfigManager.cs",
"retrieved_chunk": " public static IntField maliciousFaceBeamCountNormal;\n public static IntField maliciousFaceBeamCountEnraged;\n // MINDFLAYER\n public static BoolField mindflayerShootTweakToggle;\n public static IntField mindflayerShootAmount;\n public static FloatField mindflayerShootDelay;\n public static FloatField mindflayerShootInitialSpeed;\n public static FloatField mindflayerShootTurnSpeed;\n public static FloatSliderField mindflayerProjectileSelfDamageMultiplier;\n public static BoolField mindflayerTeleportComboToggle;",
"score": 0.7815340757369995
}
] | csharp | Text currentDifficultyInfoText; |
using HarmonyLib;
using UnityEngine;
using UnityEngine.AI;
namespace Ultrapain.Patches
{
public class StrayFlag : MonoBehaviour
{
//public int extraShotsRemaining = 6;
private Animator anim;
private EnemyIdentifier eid;
public GameObject standardProjectile;
public GameObject standardDecorativeProjectile;
public int comboRemaining = ConfigManager.strayShootCount.value;
public bool inCombo = false;
public float lastSpeed = 1f;
public enum AttackMode
{
ProjectileCombo,
FastHoming
}
public AttackMode currentMode = AttackMode.ProjectileCombo;
public void Awake()
{
anim = GetComponent<Animator>();
eid = GetComponent<EnemyIdentifier>();
}
public void Update()
{
if(eid.dead)
{
Destroy(this);
return;
}
if (inCombo)
{
anim.speed = ZombieProjectile_ThrowProjectile_Patch.animSpeed;
anim.SetFloat("Speed", ZombieProjectile_ThrowProjectile_Patch.animSpeed);
}
}
}
public class ZombieProjectile_Start_Patch1
{
static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)
{
if (___eid.enemyType != EnemyType.Stray)
return;
StrayFlag flag = __instance.gameObject.AddComponent<StrayFlag>();
flag.standardProjectile = __instance.projectile;
flag.standardDecorativeProjectile = __instance.decProjectile;
flag.currentMode = StrayFlag.AttackMode.ProjectileCombo;
/*__instance.projectile = Plugin.homingProjectile;
__instance.decProjectile = Plugin.decorativeProjectile2;*/
}
}
public class ZombieProjectile_ThrowProjectile_Patch
{
public static float normalizedTime = 0f;
public static float animSpeed = 20f;
public static float projectileSpeed = 75;
public static float turnSpeedMultiplier = 0.45f;
public static int projectileDamage = 10;
public static int explosionDamage = 20;
public static float coreSpeed = 110f;
static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref Animator ___anim, ref GameObject ___currentProjectile
, ref | NavMeshAgent ___nma, ref Zombie ___zmb)
{ |
if (___eid.enemyType != EnemyType.Stray)
return;
StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>();
if (flag == null)
return;
if (flag.currentMode == StrayFlag.AttackMode.FastHoming)
{
Projectile proj = ___currentProjectile.GetComponent<Projectile>();
if (proj != null)
{
proj.target = MonoSingleton<PlayerTracker>.Instance.GetTarget();
proj.speed = projectileSpeed * ___eid.totalSpeedModifier;
proj.turningSpeedMultiplier = turnSpeedMultiplier;
proj.safeEnemyType = EnemyType.Stray;
proj.damage = projectileDamage * ___eid.totalDamageModifier;
}
flag.currentMode = StrayFlag.AttackMode.ProjectileCombo;
__instance.projectile = flag.standardProjectile;
__instance.decProjectile = flag.standardDecorativeProjectile;
}
else if(flag.currentMode == StrayFlag.AttackMode.ProjectileCombo)
{
flag.comboRemaining -= 1;
if (flag.comboRemaining == 0)
{
flag.comboRemaining = ConfigManager.strayShootCount.value;
//flag.currentMode = StrayFlag.AttackMode.FastHoming;
flag.inCombo = false;
___anim.speed = flag.lastSpeed;
___anim.SetFloat("Speed", flag.lastSpeed);
//__instance.projectile = Plugin.homingProjectile;
//__instance.decProjectile = Plugin.decorativeProjectile2;
}
else
{
flag.inCombo = true;
__instance.swinging = true;
__instance.seekingPlayer = false;
___nma.updateRotation = false;
__instance.transform.LookAt(new Vector3(___zmb.target.position.x, __instance.transform.position.y, ___zmb.target.position.z));
flag.lastSpeed = ___anim.speed;
//___anim.Play("ThrowProjectile", 0, ZombieProjectile_ThrowProjectile_Patch.normalizedTime);
___anim.speed = ConfigManager.strayShootSpeed.value;
___anim.SetFloat("Speed", ConfigManager.strayShootSpeed.value);
___anim.SetTrigger("Swing");
//___anim.SetFloat("AttackType", 0f);
//___anim.StopPlayback();
//flag.Invoke("LateCombo", 0.01f);
//___anim.runtimeAnimatorController.animationClips.Where(clip => clip.name == "ThrowProjectile").First().
//___anim.fireEvents = true;
}
}
}
}
class Swing
{
static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)
{
if (___eid.enemyType != EnemyType.Stray)
return;
___eid.weakPoint = null;
}
}
/*[HarmonyPatch(typeof(ZombieProjectiles), "Swing")]
class Swing
{
static void Postfix()
{
Debug.Log("Swing()");
}
}*/
class SwingEnd
{
static bool Prefix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)
{
if (___eid.enemyType != EnemyType.Stray)
return true;
StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>();
if (flag == null)
return true;
if (flag.inCombo)
return false;
return true;
}
}
/*[HarmonyPatch(typeof(ZombieProjectiles), "DamageStart")]
class DamageStart
{
static void Postfix()
{
Debug.Log("DamageStart()");
}
}*/
class DamageEnd
{
static bool Prefix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)
{
if (___eid.enemyType != EnemyType.Stray)
return true;
StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>();
if (flag == null)
return true;
if (flag.inCombo)
return false;
return true;
}
}
}
| Ultrapain/Patches/Stray.cs | eternalUnion-UltraPain-ad924af | [
{
"filename": "Ultrapain/Patches/Mindflayer.cs",
"retrieved_chunk": " //___eid.SpeedBuff();\n }\n }\n class Mindflayer_ShootProjectiles_Patch\n {\n public static float maxProjDistance = 5;\n public static float initialProjectileDistance = -1f;\n public static float distancePerProjShot = 0.2f;\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)\n {",
"score": 0.9031639695167542
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " class Leviathan_FixedUpdate\n {\n public static float projectileForward = 10f;\n static bool Roll(float chancePercent)\n {\n return UnityEngine.Random.Range(0, 99.9f) <= chancePercent;\n }\n static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown,\n Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack)\n {",
"score": 0.8853850364685059
},
{
"filename": "Ultrapain/Plugin.cs",
"retrieved_chunk": " public static GameObject maliciousRailcannon;\n // Variables\n public static float SoliderShootAnimationStart = 1.2f;\n public static float SoliderGrenadeForce = 10000f;\n public static float SwordsMachineKnockdownTimeNormalized = 0.8f;\n public static float SwordsMachineCoreSpeed = 80f;\n public static float MinGrenadeParryVelocity = 40f;\n public static GameObject _lighningBoltSFX;\n public static GameObject lighningBoltSFX\n {",
"score": 0.882080614566803
},
{
"filename": "Ultrapain/Patches/CommonComponents.cs",
"retrieved_chunk": " public float superSize = 1f;\n public float superSpeed = 1f;\n public float superDamage = 1f;\n public int superPlayerDamageOverride = -1;\n struct StateInfo\n {\n public GameObject tempHarmless;\n public GameObject tempNormal;\n public GameObject tempSuper;\n public StateInfo()",
"score": 0.8616822361946106
},
{
"filename": "Ultrapain/Patches/Leviathan.cs",
"retrieved_chunk": " {\n private LeviathanHead comp;\n private Animator anim;\n //private Collider col;\n private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };\n public float playerRocketRideTracker = 0;\n private GameObject currentProjectileEffect;\n private AudioSource currentProjectileAud;\n private Transform shootPoint;\n public float currentProjectileSize = 0;",
"score": 0.8556698560714722
}
] | csharp | NavMeshAgent ___nma, ref Zombie ___zmb)
{ |
using Octokit;
using WebApi.Configurations;
using WebApi.Helpers;
using WebApi.Models;
namespace WebApi.Services
{
public interface IGitHubService
{
Task<GitHubIssueCollectionResponse> GetIssuesAsync(GitHubApiRequestHeaders headers, GitHubApiRequestQueries req);
Task< | GitHubIssueItemResponse> GetIssueAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req); |
Task<GitHubIssueItemSummaryResponse> GetIssueSummaryAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req);
}
public class GitHubService : IGitHubService
{
private readonly GitHubSettings _settings;
private readonly IOpenAIHelper _helper;
public GitHubService(GitHubSettings settings, IOpenAIHelper helper)
{
this._settings = settings ?? throw new ArgumentNullException(nameof(settings));
this._helper = helper ?? throw new ArgumentNullException(nameof(helper));
}
public async Task<GitHubIssueCollectionResponse> GetIssuesAsync(GitHubApiRequestHeaders headers, GitHubApiRequestQueries req)
{
var user = req.User;
var repository = req.Repository;
var github = this.GetGitHubClient(headers);
var issues = await github.Issue.GetAllForRepository(user, repository);
var res = new GitHubIssueCollectionResponse()
{
Items = issues.Select(p => new GitHubIssueItemResponse()
{
Id = p.Id,
Number = p.Number,
Title = p.Title,
Body = p.Body,
})
};
return res;
}
public async Task<GitHubIssueItemResponse> GetIssueAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req)
{
var user = req.User;
var repository = req.Repository;
var github = this.GetGitHubClient(headers);
var issue = await github.Issue.Get(user, repository, id);
var res = new GitHubIssueItemResponse()
{
Id = issue.Id,
Number = issue.Number,
Title = issue.Title,
Body = issue.Body,
};
return res;
}
public async Task<GitHubIssueItemSummaryResponse> GetIssueSummaryAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req)
{
var issue = await this.GetIssueAsync(id, headers, req);
var prompt = issue.Body;
var completion = await this._helper.GetChatCompletionAsync(prompt);
var res = new GitHubIssueItemSummaryResponse()
{
Id = issue.Id,
Number = issue.Number,
Title = issue.Title,
Body = issue.Body,
Summary = completion.Completion,
};
return res;
}
private IGitHubClient GetGitHubClient(GitHubApiRequestHeaders headers)
{
var accessToken = headers.GitHubToken;
var credentials = new Credentials(accessToken, AuthenticationType.Bearer);
var agent = this._settings.Agent.Replace(" ", "").Trim();
var github = new GitHubClient(new ProductHeaderValue(agent))
{
Credentials = credentials
};
return github;
}
}
} | src/IssueSummaryApi/Services/GitHubService.cs | Azure-Samples-vs-apim-cuscon-powerfx-500a170 | [
{
"filename": "src/IssueSummaryApi/Controllers/GitHubController.cs",
"retrieved_chunk": " [HttpGet(\"issues\", Name = \"Issues\")]\n [ProducesResponseType(typeof(GitHubIssueCollectionResponse), StatusCodes.Status200OK)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)]\n public async Task<IActionResult> GetIssues([FromQuery] GitHubApiRequestQueries req)\n {\n var hvr = this._validation.ValidateHeaders<GitHubApiRequestHeaders>(this.Request.Headers);\n if (hvr.Validated != true)\n {\n return await Task.FromResult(hvr.ActionResult);",
"score": 0.8116099238395691
},
{
"filename": "src/IssueSummaryApi/Controllers/GitHubController.cs",
"retrieved_chunk": " [ProducesResponseType(typeof(GitHubIssueItemResponse), StatusCodes.Status200OK)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)]\n public async Task<IActionResult> GetIssue(int id, [FromQuery] GitHubApiRequestQueries req)\n {\n var validation = this._validation.ValidateHeaders<GitHubApiRequestHeaders>(this.Request.Headers);\n if (validation.Validated != true)\n {\n return await Task.FromResult(validation.ActionResult);\n }",
"score": 0.8077076077461243
},
{
"filename": "src/IssueSummaryApi/Controllers/GitHubController.cs",
"retrieved_chunk": " [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)]\n [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)]\n public async Task<IActionResult> GetIssueSummary(int id, [FromQuery] GitHubApiRequestQueries req)\n {\n var validation = this._validation.ValidateHeaders<GitHubApiRequestHeaders>(this.Request.Headers);\n if (validation.Validated != true)\n {\n return await Task.FromResult(validation.ActionResult);\n }\n var qvr = this._validation.ValidateQueries(req);",
"score": 0.8061864376068115
},
{
"filename": "src/IssueSummaryApi/Models/GitHubIssueCollectionResponse.cs",
"retrieved_chunk": "namespace WebApi.Models\n{\n public class GitHubIssueCollectionResponse\n {\n public virtual IEnumerable<GitHubIssueItemResponse>? Items { get; set; } = new List<GitHubIssueItemResponse>();\n }\n}",
"score": 0.8032745122909546
},
{
"filename": "src/IssueSummaryApi/Services/ValidationService.cs",
"retrieved_chunk": "using Microsoft.AspNetCore.Mvc;\nusing WebApi.Configurations;\nusing WebApi.Extensions;\nusing WebApi.Models;\nnamespace WebApi.Services\n{\n public interface IValidationService\n {\n HeaderValidationResult<T> ValidateHeaders<T>(IHeaderDictionary requestHeaders) where T : ApiRequestHeaders;\n QueryValidationResult<T> ValidateQueries<T>(T requestQueries) where T : ApiRequestQueries;",
"score": 0.7868329286575317
}
] | csharp | GitHubIssueItemResponse> GetIssueAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req); |
using Microsoft.SemanticKernel.Orchestration;
using Microsoft.SemanticKernel;
using SKernel.Factory.Config;
using SKernel.Factory;
using Microsoft.AspNetCore.Http;
namespace SKernel.Service
{
public static class Extensions
{
public static ApiKey ToApiKeyConfig(this HttpRequest request)
{
var apiConfig = new ApiKey();
if (request.Headers.TryGetValue(Headers.TextCompletionKey, out var textKey))
apiConfig.Text = textKey.First()!;
apiConfig.Embedding = request.Headers.TryGetValue(Headers.EmbeddingKey, out var embeddingKey)
? embeddingKey.First()!
: apiConfig.Text;
apiConfig.Chat = request.Headers.TryGetValue(Headers.ChatCompletionKey, out var chatKey)
? chatKey.First()!
: apiConfig.Text;
return apiConfig;
}
public static bool TryGetKernel(this HttpRequest request, | SemanticKernelFactory factory,
out IKernel? kernel, IList<string>? selected = null)
{ |
var api = request.ToApiKeyConfig();
kernel = api is { Text: { }, Embedding: { } } ? factory.Create(api, selected) : null;
return kernel != null;
}
public static IResult ToResult(this SKContext result, IList<string>? skills) => (result.ErrorOccurred)
? Results.BadRequest(result.LastErrorDescription)
: Results.Ok(new Message { Variables = result.Variables, Skills = skills ?? new List<string>() });
}
}
| src/SKernel.Services/Extensions.cs | geffzhang-ai-search-aspnet-qdrant-chatgpt-378d2be | [
{
"filename": "src/SKernel/Factory/SemanticKernelFactory.cs",
"retrieved_chunk": " _config = config;\n _memoryStore = memoryStore;\n _logger = logger.CreateLogger<SemanticKernelFactory>();\n }\n public IKernel Create(ApiKey key, IList<string>? skills = null)\n {\n var selected = (skills ?? new List<string>())\n .Select(_ => _.ToLower()).ToList();\n var kernel = new KernelBuilder()\n .WithOpenAI(_config, key)",
"score": 0.8317053318023682
},
{
"filename": "src/SKernel.Services/Services/AsksService.cs",
"retrieved_chunk": " }\n public async Task<IResult> PostAsync([FromQuery(Name = \"iterations\")] int? iterations, Message message)\n {\n var httpRequest = this.contextAccessor?.HttpContext?.Request;\n return httpRequest.TryGetKernel(semanticKernelFactory, out var kernel)\n ? (message.Pipeline == null || message.Pipeline.Count == 0\n ? await planExecutor.Execute(kernel!, message, iterations ?? 10)\n : await kernel!.InvokePipedFunctions(message)).ToResult(message.Skills)\n : Results.BadRequest(\"API config is not valid\");\n }",
"score": 0.8276970982551575
},
{
"filename": "src/SKernel.Services/Services/SkillsService.cs",
"retrieved_chunk": " }\n public async Task<IResult> GetSkillFunctionAsync(string skill, string function)\n {\n var httpRequest = this.contextAccessor?.HttpContext?.Request;\n return httpRequest.TryGetKernel(semanticKernelFactory, out var kernel)\n ? kernel!.Skills.HasFunction(skill, function)\n ? Results.Ok(kernel.Skills.GetFunction(skill, function).Describe())\n : Results.NotFound()\n : Results.BadRequest(\"API config is not valid\");\n }",
"score": 0.8152482509613037
},
{
"filename": "src/SKernel/KernelExtensions.cs",
"retrieved_chunk": " }\n private static string FunctionName(DirectoryInfo skill, DirectoryInfo? folder)\n {\n while (!skill.FullName.Equals(folder?.Parent?.FullName)) folder = folder?.Parent;\n return folder.Name;\n }\n internal static KernelBuilder WithOpenAI(this KernelBuilder builder, SKConfig config, ApiKey api) =>\n builder.Configure(_ =>\n {\n if (api.Text != null)",
"score": 0.8077771663665771
},
{
"filename": "src/SKernel.Services/Services/SkillsService.cs",
"retrieved_chunk": " public async Task<IResult> GetSkillsAsync()\n {\n var httpRequest = this.contextAccessor?.HttpContext?.Request;\n return httpRequest.TryGetKernel(semanticKernelFactory, out var kernel)\n ? Results.Ok(\n new Dictionary<string, List<Dictionary<string, object>>>\n {\n [\"skills\"] = (from function in kernel!.ToSkills()\n select new Dictionary<string, object>\n {",
"score": 0.7901917695999146
}
] | csharp | SemanticKernelFactory factory,
out IKernel? kernel, IList<string>? selected = null)
{ |
using FayElf.Plugins.WeChat.Applets;
using FayElf.Plugins.WeChat.Applets.Model;
using FayElf.Plugins.WeChat.OfficialAccount;
using System;
using System.Collections.Generic;
using System.Text;
using XiaoFeng;
using XiaoFeng.Http;
/****************************************************************
* Copyright © (2021) www.fayelf.com All Rights Reserved. *
* Author : jacky *
* QQ : 7092734 *
* Email : [email protected] *
* Site : www.fayelf.com *
* Create Time : 2021-12-22 14:24:58 *
* Version : v 1.0.0 *
* CLR Version : 4.0.30319.42000 *
*****************************************************************/
namespace FayElf.Plugins.WeChat
{
/// <summary>
/// 通用类
/// </summary>
public static class Common
{
#region 获取全局唯一后台接口调用凭据
/// <summary>
/// 获取全局唯一后台接口调用凭据
/// </summary>
/// <param name="appID">App ID</param>
/// <param name="appSecret">密钥</param>
/// <returns></returns>
public static AccessTokenData GetAccessToken(string appID, string appSecret)
{
var AccessToken = XiaoFeng.Cache.CacheHelper.Get<AccessTokenData>("AccessToken" + appID);
if (AccessToken.IsNotNullOrEmpty()) return AccessToken;
var data = new AccessTokenData();
var result = HttpHelper.GetHtml(new HttpRequest
{
Method = HttpMethod.Get,
Address = $"{HttpApi.HOST}/cgi-bin/token?grant_type=client_credential&appid={appID}&secret={appSecret}"
});
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
data = result.Html.JsonToObject<AccessTokenData>();
var dic = new Dictionary<int, string>
{
{-1,"系统繁忙,此时请开发者稍候再试" },
{0,"请求成功" },
{40001,"AppSecret 错误或者 AppSecret 不属于这个小程序,请开发者确认 AppSecret 的正确性" },
{40002,"请确保 grant_type 字段值为 client_credential" },
{40013,"不合法的 AppID,请开发者检查 AppID 的正确性,避免异常字符,注意大小写" }
};
if (data.ErrCode != 0)
{
data.ErrMsg += dic[data.ErrCode];
}
else
XiaoFeng.Cache.CacheHelper.Set("AccessToken" + appID, data, (data.ExpiresIn - 60) * 1000);
}
else
{
data.ErrMsg = "请求出错.";
data.ErrCode = 500;
}
return data;
}
/// <summary>
/// 获取全局唯一后台接口调用凭据
/// </summary>
/// <param name="config">配置</param>
/// <returns></returns>
public static AccessTokenData GetAccessToken(WeChatConfig config) => GetAccessToken(config.AppID, config.AppSecret);
/// <summary>
/// 获取全局唯一后台接口调用凭据
/// </summary>
/// <param name="weChatType">微信类型</param>
/// <returns></returns>
public static | AccessTokenData GetAccessToken(WeChatType weChatType = WeChatType.OfficeAccount) => GetAccessToken(new Config().GetConfig(weChatType)); |
#endregion
#region 运行
/// <summary>
/// 运行
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="appID">appid</param>
/// <param name="appSecret">密钥</param>
/// <param name="fun">委托</param>
/// <returns></returns>
public static T Execute<T>(string appID, string appSecret, Func<AccessTokenData, T> fun) where T : BaseResult, new()
{
var aToken = GetAccessToken(appID, appSecret);
if (aToken.ErrCode != 0)
{
return new T
{
ErrCode = 500,
ErrMsg = aToken.ErrMsg
};
}
return fun.Invoke(aToken);
}
/// <summary>
/// 运行
/// </summary>
/// <typeparam name="T">对象</typeparam>
/// <param name="path">请求路径</param>
/// <param name="data">请求数据</param>
/// <param name="errorMessage">错误消息</param>
/// <returns></returns>
public static T Execute<T>(string path, string data, Func<int, string>? errorMessage = null) where T : BaseResult, new()
{
var result = new HttpRequest()
{
Address = HttpApi.HOST + path,
Method = HttpMethod.Post,
BodyData = data
}.GetResponse();
var error = result.Html;
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
var val = result.Html.JsonToObject<T>();
if (val.ErrCode == 0) return val;
if (errorMessage != null)
{
error = errorMessage.Invoke(val.ErrCode);
}
}
return new T
{
ErrCode = 500,
ErrMsg = error
};
}
#endregion
}
} | Common.cs | zhuovi-FayElf.Plugins.WeChat-5725d1e | [
{
"filename": "Model/Config.cs",
"retrieved_chunk": " /// <summary>\n /// 开放平台配置\n /// </summary>\n [Description(\"开放平台配置\")]\n public WeChatConfig OpenPlatform { get; set; } = new WeChatConfig();\n /// <summary>\n /// 获取配置\n /// </summary>\n /// <param name=\"weChatType\">配置类型</param>\n /// <returns></returns>",
"score": 0.8820163607597351
},
{
"filename": "OfficialAccount/OAuthAPI.cs",
"retrieved_chunk": " /// </summary>\n /// <param name=\"appID\">公众号的唯一标识</param>\n /// <param name=\"appSecret\">公众号的appsecret</param>\n /// <param name=\"code\">填写第一步获取的code参数</param>\n /// <returns></returns>\n public static AccessTokenModel GetAccessToken(string appID, string appSecret, string code)\n {\n var AccessToken = XiaoFeng.Cache.CacheHelper.Get<AccessTokenModel>(\"AccessTokenModel\" + appID);\n if (AccessToken.IsNotNullOrEmpty())\n {",
"score": 0.8712620735168457
},
{
"filename": "Applets/Applets.cs",
"retrieved_chunk": " #region 登录凭证校验\n /// <summary>\n /// 登录凭证校验\n /// </summary>\n /// <param name=\"code\">登录时获取的 code</param>\n /// <returns></returns>\n public JsCodeSessionData JsCode2Session(string code)\n {\n var session = new JsCodeSessionData();\n var config = this.Config.GetConfig(WeChatType.Applets);",
"score": 0.8674536347389221
},
{
"filename": "Model/Config.cs",
"retrieved_chunk": " /// <summary>\n /// 公众号配置\n /// </summary>\n [Description(\"公众号配置\")]\n public WeChatConfig OfficeAccount { get; set; } = new WeChatConfig();\n /// <summary>\n /// 小程序配置\n /// </summary>\n [Description(\"小程序配置\")]\n public WeChatConfig Applets { get; set; } = new WeChatConfig();",
"score": 0.8492536544799805
},
{
"filename": "Applets/Applets.cs",
"retrieved_chunk": " #endregion\n #region 获取用户encryptKey\n /// <summary>\n /// 获取用户encryptKey\n /// </summary>\n /// <param name=\"session\">Session数据</param>\n /// <returns></returns>\n public UserEncryptKeyData GetUserEncryptKey(JsCodeSessionData session)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);",
"score": 0.8462070226669312
}
] | csharp | AccessTokenData GetAccessToken(WeChatType weChatType = WeChatType.OfficeAccount) => GetAccessToken(new Config().GetConfig(weChatType)); |