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 LogDashboard.Authorization; using LogDashboard.Extensions; using LogDashboard.Route; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LogDashboard { public class LogdashboardAccountAuthorizeFilter : ILogDashboardAuthorizationFilter { public string UserName { get; set; } public string Password { get; set; } public
LogDashboardCookieOptions CookieOptions {
get; set; } public LogdashboardAccountAuthorizeFilter(string userName, string password) { UserName = userName; Password = password; CookieOptions = new LogDashboardCookieOptions(); } public LogdashboardAccountAuthorizeFilter(string userName, string password, Action<LogDashboardCookieOptions> cookieConfig) { UserName = userName; Password = password; CookieOptions = new LogDashboardCookieOptions(); cookieConfig.Invoke(CookieOptions); } public bool Authorization(LogDashboardContext context) { bool isValidAuthorize = false; if (context.HttpContext.Request != null && context.HttpContext.Request.Cookies != null) { var (token, timestamp) = GetCookieValue(context.HttpContext); if (double.TryParse(timestamp, out var time) && time <= DateTime.Now.ToUnixTimestamp() && time > DateTime.Now.Add(-CookieOptions.Expire).ToUnixTimestamp()) { var vaildToken = GetToken(timestamp); isValidAuthorize = vaildToken == token; } } //Rediect if (!isValidAuthorize) { if (LogDashboardAuthorizationConsts.LoginRoute.ToLower() != context.HttpContext.Request?.Path.Value.ToLower()) { var loginPath = $"{context.Options.PathMatch}{LogDashboardAuthorizationConsts.LoginRoute}"; context.HttpContext.Response.Redirect(loginPath); } else { isValidAuthorize = true; } } return isValidAuthorize; } public (string, string) GetCookieValue(HttpContext context) { context.Request.Cookies.TryGetValue(CookieOptions.TokenKey, out var token); context.Request.Cookies.TryGetValue(CookieOptions.TimestampKey, out var timestamp); return (token, timestamp); } public void SetCookieValue(HttpContext context) { var timestamp = DateTime.Now.ToUnixTimestamp().ToString(); var token = GetToken(timestamp); context.Response.Cookies.Append(CookieOptions.TokenKey, token, new CookieOptions() { Expires = DateTime.Now.Add(CookieOptions.Expire) }); context.Response.Cookies.Append(CookieOptions.TimestampKey, timestamp, new CookieOptions() { Expires = DateTime.Now.Add(CookieOptions.Expire) }); } private string GetToken(string timestamp) { return $"{CookieOptions.Secure(this)}&&{timestamp}".ToMD5(); } } }
src/LogDashboard.Authorization/Authorization/LogdashboardAccountAuthorizeFilter.cs
Bryan-Cyf-LogDashboard.Authorization-14d4540
[ { "filename": "src/LogDashboard.Authorization/Models/LoginInput.cs", "retrieved_chunk": "using System;\nnamespace LogDashboard.Models\n{\n public class LoginInput\n {\n public string Name { get; set; }\n public string Password { get; set; }\n }\n}", "score": 0.9282578825950623 }, { "filename": "src/LogDashboard.Authorization/LogDashboardCookieOptions.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Http;\nnamespace LogDashboard\n{\n public class LogDashboardCookieOptions\n {\n public TimeSpan Expire { get; set; }\n public string TokenKey { get; set; }\n public string TimestampKey { get; set; }\n public Func<LogdashboardAccountAuthorizeFilter, string> Secure { get; set; }\n public LogDashboardCookieOptions()", "score": 0.9122210741043091 }, { "filename": "src/LogDashboard.Authorization/LogDashboardAuthorizationConsts.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace LogDashboard\n{\n public class LogDashboardAuthorizationConsts\n {\n public const string LoginRoute = \"/Authorization/Login\";\n }\n}", "score": 0.8628029823303223 }, { "filename": "src/LogDashboard.Authorization/Handle/AuthorizationHandle.cs", "retrieved_chunk": "using LogDashboard.Models;\nusing LogDashboard.Route;\nusing System;\nusing System.Threading.Tasks;\nnamespace LogDashboard.Handle\n{\n public class AuthorizationHandle : LogDashboardHandleBase\n {\n private readonly LogdashboardAccountAuthorizeFilter _filter;\n public AuthorizationHandle(", "score": 0.8459615111351013 }, { "filename": "src/LogDashboard.Authorization/Extensions/DateTimeExtensions.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace LogDashboard.Extensions\n{\n internal static class DateTimeExtensions\n {\n public static double ToUnixTimestamp(this DateTime target)\n {\n DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);", "score": 0.809593915939331 } ]
csharp
LogDashboardCookieOptions CookieOptions {
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": " headerToSearch.HeaderCoord = new HeaderCoord\n {\n Row = 1,\n Column = headerToSearch.ColumnIndex.Value,\n };\n }\n }\n private void AddHeaderCoordsFromCustomColumnHeaderMatch(ExcelWorksheet sheet)\n {\n List<HeaderToSearch> headersToSearch = HeadersToSearch", "score": 0.8462969064712524 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " {\n canAddRow = true;\n JXLExtractedRow extractedRow = new JXLExtractedRow();\n foreach (HeaderToSearch headerToSearch in HeadersToSearch)\n {\n string cellValue = DataReaderHelpers\n .GetCellValue(row, headerToSearch.HeaderCoord.Column, sheet);\n if (!headerToSearch.ConditionalToReadRow(cellValue))\n {\n canAddRow = false;", "score": 0.8154895305633545 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " }\n return extractedRow;\n }\n private void GetHeadersCoordinates(ExcelWorksheet sheet)\n {\n AddHeaderCoordsFromWorksheetColumnConfigurations(sheet);\n AddHeaderCoordsFromWorksheetColumnIndexesConfigurations();\n AddHeaderCoordsFromCustomColumnHeaderMatch(sheet);\n }\n private void AddHeaderCoordsFromWorksheetColumnConfigurations(ExcelWorksheet sheet)", "score": 0.8099037408828735 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " private void AddHeaderCoordsFromWorksheetColumnIndexesConfigurations()\n {\n List<HeaderToSearch> headersToSearch = HeadersToSearch\n .Where(h =>\n string.IsNullOrEmpty(h.ColumnHeaderName) &&\n h.ConditionalToReadColumnHeader is null &&\n h.ColumnIndex != null)\n .ToList();\n foreach (HeaderToSearch headerToSearch in headersToSearch)\n {", "score": 0.8093471527099609 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " List<JXLWorkbookData> data = GetWorkbooksData();\n DataTable dataTable = new DataTable();\n List<HeaderToSearch> orderedColumns = HeadersToSearch.OrderBy(column => column.HeaderCoord.Column).ToList();\n foreach (HeaderToSearch headerCoord in orderedColumns)\n {\n if (!string.IsNullOrEmpty(headerCoord.ColumnHeaderName))\n {\n dataTable.Columns.Add(headerCoord.ColumnHeaderName);\n }\n else", "score": 0.8060258626937866 } ]
csharp
IDataTableExtractorWorksheetConfiguration IDataTableExtractorColumnConfiguration.ConditionToExtractRow(Func<string, bool> conditional) {
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.8511125445365906 }, { "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.7336355447769165 }, { "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.715714693069458 }, { "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.6967019438743591 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IBadge.cs", "retrieved_chunk": "using DotNetDevBadgeWeb.Common;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IBadge\n {\n Task<string> GetSmallBadge(string id, ETheme theme, CancellationToken token);\n Task<string> GetMediumBadge(string id, ETheme theme, CancellationToken token);\n }\n public interface IBadgeV1 : IBadge\n {", "score": 0.6729886531829834 } ]
csharp
JsonProperty("solved_count")] public int SolvedCount {
#nullable enable using System; using System.Net.Http; using System.Threading; using Cysharp.Threading.Tasks; using Mochineko.Relent.UncertainResult; using Mochineko.YouTubeLiveStreamingClient.Responses; using UniRx; using UnityEngine; namespace Mochineko.YouTubeLiveStreamingClient { /// <summary> /// Collects and provides live chat messages from YouTube Data API v3. /// </summary> public sealed class LiveChatMessagesCollector : IDisposable { private readonly HttpClient httpClient; private readonly IAPIKeyProvider apiKeyProvider; private readonly string videoID; private readonly uint maxResultsOfMessages; private readonly bool dynamicInterval; private readonly bool verbose; private readonly CancellationTokenSource cancellationTokenSource = new(); private readonly Subject<VideosAPIResponse> onVideoInformationUpdated = new(); public IObservable<VideosAPIResponse> OnVideoInformationUpdated => onVideoInformationUpdated; private readonly Subject<
LiveChatMessageItem> onMessageCollected = new();
public IObservable<LiveChatMessageItem> OnMessageCollected => onMessageCollected; private bool isCollecting = false; private string? liveChatID = null; private string? nextPageToken = null; private float intervalSeconds; public LiveChatMessagesCollector( HttpClient httpClient, string apiKey, string videoID, uint maxResultsOfMessages = 500, bool dynamicInterval = false, float intervalSeconds = 5f, bool verbose = true) { if (string.IsNullOrEmpty(apiKey)) { throw new ArgumentException($"{nameof(apiKey)} must no be empty."); } if (string.IsNullOrEmpty(videoID)) { throw new ArgumentException($"{nameof(videoID)} must no be empty."); } this.httpClient = httpClient; this.apiKeyProvider = new SingleAPIKeyProvider(apiKey); this.videoID = videoID; this.maxResultsOfMessages = maxResultsOfMessages; this.dynamicInterval = dynamicInterval; this.intervalSeconds = intervalSeconds; this.verbose = verbose; } // TODO: Check private LiveChatMessagesCollector( HttpClient httpClient, string[] apiKeys, string videoID, uint maxResultsOfMessages = 500, bool dynamicInterval = false, float intervalSeconds = 5f, bool verbose = true) { if (apiKeys.Length == 0) { throw new ArgumentException($"{nameof(apiKeys)} must not be empty."); } if (string.IsNullOrEmpty(videoID)) { throw new ArgumentException($"{nameof(videoID)} must no be empty."); } this.httpClient = httpClient; this.apiKeyProvider = new MultiAPIKeyProvider(apiKeys); this.videoID = videoID; this.maxResultsOfMessages = maxResultsOfMessages; this.dynamicInterval = dynamicInterval; this.intervalSeconds = intervalSeconds; this.verbose = verbose; } public void Dispose() { cancellationTokenSource.Dispose(); } /// <summary> /// Begins collecting live chat messages. /// </summary> public void BeginCollection() { if (isCollecting) { return; } isCollecting = true; BeginCollectionAsync(cancellationTokenSource.Token) .Forget(); } private async UniTask BeginCollectionAsync( CancellationToken cancellationToken) { await UniTask.SwitchToThreadPool(); while (!cancellationToken.IsCancellationRequested) { await UpdateAsync(cancellationToken); try { await UniTask.Delay( TimeSpan.FromSeconds(intervalSeconds), cancellationToken: cancellationToken ); } // Catch cancellation catch (OperationCanceledException) { return; } } } private async UniTask UpdateAsync(CancellationToken cancellationToken) { if (liveChatID == null) { await GetLiveChatIDAsync(cancellationToken); // Succeeded to get live chat ID if (liveChatID != null) { await PollLiveChatMessagesAsync(liveChatID, cancellationToken); } } else { await PollLiveChatMessagesAsync(liveChatID, cancellationToken); } } private async UniTask GetLiveChatIDAsync(CancellationToken cancellationToken) { if (verbose) { Debug.Log($"[YouTubeLiveStreamingClient] Getting live chat ID from video ID:{videoID}..."); } var result = await VideosAPI.GetVideoInformationAsync( httpClient, apiKeyProvider.APIKey, videoID, cancellationToken); VideosAPIResponse response; switch (result) { case IUncertainSuccessResult<VideosAPIResponse> success: { if (verbose) { Debug.Log($"[YouTubeLiveStreamingClient] Succeeded to get video API response."); } response = success.Result; break; } case LimitExceededResult<VideosAPIResponse> limitExceeded: { if (verbose) { Debug.LogWarning( $"[YouTubeLiveStreamingClient] Failed to get live chat ID because -> {limitExceeded.Message}."); } if (apiKeyProvider.TryChangeKey()) { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Change API key and continue."); } // Use another API key from next time return; } else { Debug.LogError( $"[YouTubeLiveStreamingClient] Failed to change API key."); return; } } case IUncertainRetryableResult<VideosAPIResponse> retryable: { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Retryable failed to get live chat ID because -> {retryable.Message}."); } return; } case IUncertainFailureResult<VideosAPIResponse> failure: { Debug.LogError( $"[YouTubeLiveStreamingClient] Failed to get live chat ID because -> {failure.Message}"); return; } default: throw new UncertainResultPatternMatchException(nameof(result)); } if (response.Items.Count == 0) { if (verbose) { Debug.Log($"[YouTubeLiveStreamingClient] No items are found in response from video ID:{videoID}."); } return; } var liveChatID = response.Items[0].LiveStreamingDetails.ActiveLiveChatId; if (!string.IsNullOrEmpty(liveChatID)) { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Succeeded to get live chat ID:{liveChatID} from video ID:{videoID}."); } this.liveChatID = liveChatID; onVideoInformationUpdated.OnNext(response); } else { Debug.LogError($"[YouTubeLiveStreamingClient] LiveChatID is null or empty from video ID:{videoID}."); } } private async UniTask PollLiveChatMessagesAsync( string liveChatID, CancellationToken cancellationToken) { if (verbose) { Debug.Log($"[YouTubeLiveStreamingClient] Polling live chat messages..."); } var result = await LiveChatMessagesAPI.GetLiveChatMessagesAsync( httpClient, apiKeyProvider.APIKey, liveChatID, cancellationToken, pageToken: nextPageToken, maxResults: maxResultsOfMessages); LiveChatMessagesAPIResponse response; switch (result) { case IUncertainSuccessResult<LiveChatMessagesAPIResponse> success: { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Succeeded to get live chat messages: {success.Result.Items.Count} messages with next page token:{success.Result.NextPageToken}."); } response = success.Result; this.nextPageToken = response.NextPageToken; if (dynamicInterval) { this.intervalSeconds = response.PollingIntervalMillis / 1000f; } break; } case LimitExceededResult<LiveChatMessagesAPIResponse> limitExceeded: { if (verbose) { Debug.LogWarning( $"[YouTubeLiveStreamingClient] Failed to get live chat messages because -> {limitExceeded.Message}."); } if (apiKeyProvider.TryChangeKey()) { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Change API key and continue."); } // Use another API key from next time return; } else { Debug.LogError( $"[YouTubeLiveStreamingClient] Failed to change API key."); return; } } case IUncertainRetryableResult<LiveChatMessagesAPIResponse> retryable: { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Retryable failed to get live chat messages because -> {retryable.Message}."); } return; } case IUncertainFailureResult<LiveChatMessagesAPIResponse> failure: { Debug.LogError( $"[YouTubeLiveStreamingClient] Failed to get live chat messages because -> {failure.Message}"); return; } default: throw new UncertainResultPatternMatchException(nameof(result)); } // NOTE: Publish event on the main thread. await UniTask.SwitchToMainThread(cancellationToken); foreach (var item in response.Items) { if (verbose) { Debug.Log( $"[YouTubeLiveStreamingClient] Collected live chat message: {item.Snippet.DisplayMessage} from {item.AuthorDetails.DisplayName} at {item.Snippet.PublishedAt}."); } onMessageCollected.OnNext(item); } await UniTask.SwitchToThreadPool(); } } }
Assets/Mochineko/YouTubeLiveStreamingClient/LiveChatMessagesCollector.cs
mochi-neko-youtube-live-streaming-client-unity-b712d77
[ { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient.Samples/LiveChatMessagesCollectionDemo.cs", "retrieved_chunk": " {\n [SerializeField]\n private string apiKeyPath = string.Empty;\n [SerializeField]\n private string videoIDOrURL = string.Empty;\n [SerializeField, Range(200, 2000)]\n private uint maxResultsOfMessages = 500;\n [SerializeField]\n private float intervalSeconds = 5f;\n private static readonly HttpClient HttpClient = new();", "score": 0.8268278241157532 }, { "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.809220552444458 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient.Samples/LiveChatMessagesCollectionDemo.cs", "retrieved_chunk": " .Subscribe(OnSuperStickerMessageCollected)\n .AddTo(this);\n // Begin collection\n collector.BeginCollection();\n }\n private void OnDestroy()\n {\n collector?.Dispose();\n }\n private void OnVideoInformationUpdated(VideosAPIResponse response)", "score": 0.7881491184234619 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveStreamingDetails.cs", "retrieved_chunk": " [JsonProperty(\"scheduledStartTime\")]\n public DateTime? ScheduledStartTime { get; private set; }\n [JsonProperty(\"concurrentViewers\")]\n public uint? ConcurrentViewers { get; private set; }\n [JsonProperty(\"activeLiveChatId\"), JsonRequired]\n public string ActiveLiveChatId { get; private set; } = string.Empty;\n }\n}", "score": 0.7878390550613403 }, { "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.7789473533630371 } ]
csharp
LiveChatMessageItem> onMessageCollected = new();
using System.Collections; using System.Collections.Generic; using UnityEngine; using QuestSystem.SaveSystem; using System.Linq; namespace QuestSystem { [CreateAssetMenu(fileName = "New Quest", menuName = "QuestSystem/QuestLog")] [System.Serializable] public class QuestLog : ScriptableObject { public List<Quest> curentQuests = new List<Quest>(); public List<
Quest> doneQuest = new List<Quest>();
public List<Quest> failedQuest = new List<Quest>(); public int businessDay; public bool IsCurrent(Quest q) => curentQuests.Contains(q); public bool IsDoned(Quest q) => doneQuest.Contains(q); public bool IsFailed(Quest q) => failedQuest.Contains(q); public void LoadUpdate(QuestLogSaveData qls) { //Coger el dia businessDay = qls.dia; //Actualizar currents curentQuests = new List<Quest>(); foreach (QuestSaveData qs in qls.currentQuestSave) { Quest q = Resources.Load(QuestConstants.MISIONS_NAME + "/" + qs.name + "/" + qs.name) as Quest; q.state = qs.states; q.AdvanceToCurrentNode(); q.nodeActual.nodeObjectives = qs.actualNodeData.objectives; curentQuests.Add(q); } //Done i failed add doneQuest = new List<Quest>(); foreach (QuestSaveData qs in qls.doneQuestSave) { Quest q = Resources.Load(QuestConstants.MISIONS_NAME + "/" + qs.name + "/" + qs.name) as Quest; doneQuest.Add(q); } failedQuest = new List<Quest>(); foreach (QuestSaveData qs in qls.failedQuestSave) { Quest q = Resources.Load(QuestConstants.MISIONS_NAME + "/" + qs.name + "/" + qs.name) as Quest; failedQuest.Add(q); } } public void RemoveQuest(Quest q) { if (IsCurrent(q)) curentQuests.Remove(q); else if (IsDoned(q)) doneQuest.Remove(q); else if (IsFailed(q)) failedQuest.Remove(q); } public void ResetAllQuest() { List<Quest> quests = curentQuests.Concat(doneQuest).Concat(failedQuest).ToList(); foreach (Quest q in quests) { q.Reset(); RemoveQuest(q); } } } }
Runtime/QuestLog.cs
lluispalerm-QuestSystem-cd836cc
[ { "filename": "Runtime/NodeQuest.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace QuestSystem\n{\n [CreateAssetMenu(fileName = \"New NodeQuest\", menuName = \"QuestSystem/NodeQuest\")]\n [System.Serializable]\n public class NodeQuest : ScriptableObject\n {\n public List<NodeQuest> nextNode = new List<NodeQuest>();", "score": 0.8960690498352051 }, { "filename": "Runtime/Quest.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\nnamespace QuestSystem\n{\n [CreateAssetMenu(fileName = \"New Quest\", menuName = \"QuestSystem/Quest\")]\n [System.Serializable]\n public class Quest : ScriptableObject\n {", "score": 0.8572618365287781 }, { "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.817801296710968 }, { "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.8124104738235474 }, { "filename": "Editor/CustomInspector/QuestLogEditor.cs", "retrieved_chunk": "using UnityEngine;\nusing UnityEditor;\nnamespace QuestSystem.QuestEditor\n{\n [CustomEditor(typeof(QuestLog))]\n public class QuestLogEditor : Editor\n {\n public override void OnInspectorGUI()\n {\n QuestLog questLog = (QuestLog)target;", "score": 0.8105394840240479 } ]
csharp
Quest> doneQuest = new List<Quest>();
// Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using Newtonsoft.Json; namespace BlockadeLabs.Skyboxes { public sealed class SkyboxHistory { [JsonConstructor] public SkyboxHistory( [JsonProperty("data")] List<
SkyboxInfo> skyboxes, [JsonProperty("totalCount")] int totalCount, [JsonProperty("has_more")] bool hasMore) {
Skyboxes = skyboxes; TotalCount = totalCount; HasMore = hasMore; } [JsonProperty("data")] public IReadOnlyList<SkyboxInfo> Skyboxes { get; } [JsonProperty("totalCount")] public int TotalCount { get; } [JsonProperty("has_more")] public bool HasMore { get; } } }
BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxHistory.cs
RageAgainstThePixel-com.rest.blockadelabs-aa2142f
[ { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxInfo.cs", "retrieved_chunk": "{\n public sealed class SkyboxInfo\n {\n [JsonConstructor]\n public SkyboxInfo(\n [JsonProperty(\"id\")] int id,\n [JsonProperty(\"skybox_style_id\")] int skyboxStyleId,\n [JsonProperty(\"skybox_style_name\")] string skyboxStyleName,\n [JsonProperty(\"status\")] Status status,\n [JsonProperty(\"queue_position\")] int queuePosition,", "score": 0.8590359687805176 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxEndpoint.cs", "retrieved_chunk": "namespace BlockadeLabs.Skyboxes\n{\n public sealed class SkyboxEndpoint : BlockadeLabsBaseEndpoint\n {\n [Preserve]\n private class SkyboxInfoRequest\n {\n [Preserve]\n [JsonConstructor]\n public SkyboxInfoRequest([JsonProperty(\"request\")] SkyboxInfo skyboxInfo)", "score": 0.8357540369033813 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxEndpoint.cs", "retrieved_chunk": " [Preserve]\n [JsonConstructor]\n public SkyboxOperation(\n [JsonProperty(\"success\")] string success,\n [JsonProperty(\"error\")] string error)\n {\n Success = success;\n Error = error;\n }\n [Preserve]", "score": 0.8004601001739502 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxInfo.cs", "retrieved_chunk": " }\n [JsonProperty(\"id\")]\n public int Id { get; }\n [JsonProperty(\"skybox_style_id\")]\n public int SkyboxStyleId { get; }\n [JsonProperty(\"skybox_style_name\")]\n public string SkyboxStyleName { get; }\n [JsonProperty(\"status\")]\n [JsonConverter(typeof(StringEnumConverter))]\n public Status Status { get; }", "score": 0.7999307513237 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxEndpoint.cs", "retrieved_chunk": " {\n SkyboxInfo = skyboxInfo;\n }\n [Preserve]\n [JsonProperty(\"request\")]\n public SkyboxInfo SkyboxInfo { get; }\n }\n [Preserve]\n private class SkyboxOperation\n {", "score": 0.7973339557647705 } ]
csharp
SkyboxInfo> skyboxes, [JsonProperty("totalCount")] int totalCount, [JsonProperty("has_more")] bool hasMore) {
using Microsoft.Xna.Framework; using System; using VeilsClaim.Classes.Enums; using VeilsClaim.Classes.Managers; using VeilsClaim.Classes.Objects.Entities; using VeilsClaim.Classes.Objects.Entities.Weapons; using VeilsClaim.Classes.Objects.Particles; using VeilsClaim.Classes.Objects.Projectiles; namespace VeilsClaim.Classes.Objects.Weapons { public class Chaingun : Weapon { public Chaingun() : base() { Loaded = 256; Capacity = 256; FireRate = 0.2f; ReloadTime = 1f; MuzzleVelocity = 750f; Spread = 0.03f; Projectile = new Bolt(); ShotCount = new Point(1); FireMode = FireMode.Automatic; } public override void Fire(Entity parent) { base.Fire(parent); } public override void Reload() { base.Reload(); } public override void CreateProjectile(Entity parent) { base.CreateProjectile(parent); } public override void
CreateFireEffects(Entity parent) {
for (int i = 0; i < Main.Random.Next(8, 16); i++) { float rotation = (Main.Random.NextSingle() - 0.5f); ParticleManager.particles.Add(new SparkParticle() { Position = parent.Position + Vector2.Transform(Barrels[barrelIndex], Matrix.CreateRotationZ(parent.Rotation)), Velocity = new Vector2(MathF.Cos(parent.Rotation + rotation), MathF.Sin(parent.Rotation + rotation)) * Main.Random.Next(100, 300), Size = 15f, StartSize = 15f, EndSize = 5f, Colour = Color.LightSkyBlue, StartColour = Color.LightSkyBlue, EndColour = Color.RoyalBlue, Friction = 0.1f, Mass = 0.005f, WindStrength = 2f, MaxLifespan = 0.15f + Main.Random.NextSingle() / 5f, }); } } } }
VeilsClaim/Classes/Objects/Weapons/Chaingun.cs
IsCactus0-Veils-Claim-de09cef
[ { "filename": "VeilsClaim/Classes/Objects/Weapons/Weapon.cs", "retrieved_chunk": " }\n public virtual void Reload()\n {\n if (lastReloaded < ReloadTime)\n return;\n lastReloaded = 0;\n Loaded = Capacity;\n }\n public virtual void CreateProjectile(Entity parent)\n {", "score": 0.8786160945892334 }, { "filename": "VeilsClaim/Classes/Objects/Projectiles/Projectile.cs", "retrieved_chunk": " {\n Destroy();\n break;\n }\n }\n base.CheckCollisions(lastPos);\n }\n public override Projectile Clone()\n {\n return (Projectile)MemberwiseClone();", "score": 0.8685770034790039 }, { "filename": "VeilsClaim/Classes/Managers/ProjectileManager.cs", "retrieved_chunk": " public ProjectileManager(Game game)\n : base(game)\n {\n spriteBatch = new SpriteBatch(game.GraphicsDevice);\n projectiles = new List<Projectile>();\n }\n public static SpriteBatch spriteBatch;\n public static QuadTree quadTree;\n public static List<Projectile> projectiles;\n public override void Update(GameTime gameTime)", "score": 0.8538222908973694 }, { "filename": "VeilsClaim/Classes/Objects/Weapons/Weapon.cs", "retrieved_chunk": " parent.Force += -force;\n CreateFireEffects(parent);\n }\n public abstract void CreateFireEffects(Entity parent);\n public virtual void Update(float delta)\n {\n lastFired += delta;\n lastReloaded += delta;\n }\n }", "score": 0.8502862453460693 }, { "filename": "VeilsClaim/Classes/Objects/Projectiles/Bolt.cs", "retrieved_chunk": " base.Update(delta);\n }\n public override void Draw(SpriteBatch spriteBatch)\n {\n Trail.Draw(spriteBatch);\n }\n public override Bolt Clone()\n {\n return new Bolt(this);\n }", "score": 0.8309782147407532 } ]
csharp
CreateFireEffects(Entity parent) {
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 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.8593249320983887 }, { "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.8573596477508545 }, { "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.8522411584854126 }, { "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.8333530426025391 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": " }\n }\n class VirtueFlag : MonoBehaviour\n {\n public AudioSource lighningBoltSFX;\n public GameObject ligtningBoltAud;\n public Transform windupObj;\n private EnemyIdentifier eid;\n public Drone virtue;\n public void Awake()", "score": 0.8321343660354614 } ]
csharp
GameObject explosionWaveKnuckleblaster;
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": " }\n dataTable.Rows.Add(columns);\n }\n return dataTable;\n }\n public List<JXLExtractedRow> GetJXLExtractedRows()\n {\n List<JXLWorkbookData> data = GetWorkbooksData();\n List<JXLExtractedRow> extractedRows = data\n .SelectMany(workbookData => workbookData.WorksheetsData", "score": 0.8859206438064575 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " }\n workbookData.WorksheetsData.AddRange(worksheetsData);\n workbooksData.Add(workbookData);\n }\n }\n return workbooksData;\n }\n private Func<string, ExcelPackage, List<JXLWorksheetData>> ResolveGettingWorksheetsMethod()\n {\n if (ReadAllWorksheets)", "score": 0.8811647891998291 }, { "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.8632379770278931 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " .SelectMany(worksheetData => worksheetData.Rows))\n .ToList();\n return extractedRows;\n }\n public List<JXLWorkbookData> GetWorkbooksData()\n {\n List<JXLWorkbookData> workbooksData = new List<JXLWorkbookData>();\n foreach (string workbook in Workbooks)\n {\n using (ExcelPackage excel = new ExcelPackage(DataReaderHelpers.GetFileStream(workbook)))", "score": 0.8568705320358276 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " if (worksheetData != null)\n {\n worksheetsData.Add(worksheetData);\n }\n }\n return worksheetsData;\n }\n private List<JXLWorksheetData> GetWorksheetsDataByIndex(string workbook, ExcelPackage excel)\n {\n List<JXLWorksheetData> worksheetsData = new List<JXLWorksheetData>();", "score": 0.8482028841972351 } ]
csharp
JXLExtractedRow> GetExtractedRows() {
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/github/WebhookService.cs", "retrieved_chunk": " MessageType = messageType;\n }\n }\n public class WebhookService : IService\n {\n public static Thread ListenerThread = new(new ParameterizedThreadStart(Listening));\n public static event EventHandler<WebhookMessageEvent>? MessageEvent;\n public static WebhookService Instance { get; private set; } = new();\n public NodeBot? NodeBot { get; private set; }\n static WebhookService()", "score": 0.8757361769676208 }, { "filename": "NodeBot/github/WebhookService.cs", "retrieved_chunk": "using System.Threading.Tasks;\nnamespace NodeBot.github\n{\n public class WebhookMessageEvent : EventArgs\n {\n public string Message { get; set; }\n public string MessageType { get; set; }\n public WebhookMessageEvent(string message, string messageType)\n {\n Message = message;", "score": 0.8717184066772461 }, { "filename": "NodeBot/Command/ConsoleCommandSender.cs", "retrieved_chunk": "{\n public class ConsoleCommandSender : ICommandSender\n {\n public CqWsSession Session;\n public NodeBot Bot;\n public ConsoleCommandSender(CqWsSession session, NodeBot bot)\n {\n Session = session;\n Bot = bot;\n }", "score": 0.869477391242981 }, { "filename": "NodeBot/BTD6/BTD6_RoundCheck.cs", "retrieved_chunk": "using System.Text;\nusing System.Threading.Tasks;\nnamespace NodeBot.BTD6\n{\n public class BTD6_RoundCheck : ICommand\n {\n public bool Execute(ICommandSender sender, string commandLine)\n {\n string msg = string.Empty;\n int round;", "score": 0.8623074293136597 }, { "filename": "NodeBot/Classes/IQQSender.cs", "retrieved_chunk": " {\n Bot.SendGroupMessage(GroupNumber, msgs);\n }\n }\n public class UserQQSender : IQQSender\n {\n public long QQNumber;\n public CqWsSession Session;\n public NodeBot Bot;\n public UserQQSender(CqWsSession session,NodeBot bot, long QQNumber)", "score": 0.8477609753608704 } ]
csharp
ConsoleInputEvent>? ConsoleInputEvent;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Ryan.DependencyInjection; using Ryan.EntityFrameworkCore.Builder; using Ryan.EntityFrameworkCore.Proxy; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Ryan.EntityFrameworkCore { /// <summary> /// 分表上下文 /// </summary> public class ShardDbContext : DbContext { /// <summary> /// 分表实体 /// </summary> private List<Type> ShardEntityTypes { get; set; } = new List<Type>(); /// <summary> /// 分表依赖 /// </summary> public IShardDependency Dependencies { get; } /// <summary> /// 创建分表上下文 /// </summary> public ShardDbContext(IShardDependency shardDependency) { InitShardConfiguration(); Dependencies = shardDependency; } /// <summary> /// 初始化分表配置 /// </summary> private void InitShardConfiguration() { // 获取分表类型 var shardAttribute = GetType().GetCustomAttribute<ShardAttribute>(); if (shardAttribute == null) { return; } ShardEntityTypes.AddRange(shardAttribute.GetShardEntities()); } /// <summary> /// 配置 /// </summary> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } /// <summary> /// 构建实体 /// </summary> protected override void OnModelCreating(ModelBuilder modelBuilder) { // 构建 ModelBuilder foreach (var shardEntity in ShardEntityTypes) { Dependencies.EntityModelBuilderAccessorGenerator.Create(shardEntity).Accessor(shardEntity, modelBuilder); } } /// <summary> /// 创建非查询代理 /// </summary> internal
EntityProxy CreateEntityProxy(object entity, EntityProxyType type) {
// 上下文代理 var dbContextProxy = Dependencies.DbContextEntityProxyLookupGenerator .Create(this) .GetOrDefault(entity.GetType().BaseType!, this); // 创建代理 var proxy = dbContextProxy.EntityProxies.FirstOrDefault(x => x.Entity == entity); if (proxy != null) { return proxy; } // 创建代理 dbContextProxy.EntityProxies.Add( proxy = Dependencies.EntityProxyGenerator.Create(entity, EntityProxyType.NonQuery, this)); return proxy; } /// <summary> /// 分表查询 /// </summary> public virtual IQueryable<TEntity> AsQueryable<TEntity>(Expression<Func<TEntity, bool>> expression) where TEntity : class { if (!ShardEntityTypes.Contains(typeof(TEntity))) { throw new InvalidOperationException(); } // 获取实现 var queryables = Dependencies.ExpressionImplementationFinder .Find<TEntity>(expression) .Select(x => Dependencies.QueryableFinder.Find<TEntity>(this, x)); // 组合查询 var queryable = queryables.FirstOrDefault(); foreach (var nextQueryable in queryables.Skip(1)) { queryable = queryable.Union(nextQueryable); } return queryable; } /// <summary> /// 分表查询 /// </summary> public virtual IEnumerable<TEntity> AsQueryable<TEntity>(Expression<Func<TEntity, bool>> expression, Expression<Func<TEntity, bool>> predicate) where TEntity : class { if (!ShardEntityTypes.Contains(typeof(TEntity))) { throw new InvalidOperationException(); } // 获取实现 var queryables = Dependencies.ExpressionImplementationFinder .Find<TEntity>(expression) .Select(x => Dependencies.QueryableFinder.Find<TEntity>(this, x)); // 组合查询 return queryables.SelectMany(x => x.Where(predicate).ToList()); } /// <inheritdoc/> public override EntityEntry Add(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Add(entity); } // 将实现添加入状态管理 return base.Add(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override ValueTask<EntityEntry> AddAsync(object entity, CancellationToken cancellationToken = default) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.AddAsync(entity, cancellationToken); } // 将实现添加入状态管理 return base.AddAsync(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation, cancellationToken); } /// <inheritdoc/> public override EntityEntry<TEntity> Add<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Add(entity); } // 将实现添加入状态管理 return base.Add((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override ValueTask<EntityEntry<TEntity>> AddAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = default) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.AddAsync(entity, cancellationToken); } // 将实现添加入状态管理 return base.AddAsync((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation, cancellationToken); } /// <inheritdoc/> public override EntityEntry Attach(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Attach(entity); } return base.Attach(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry<TEntity> Attach<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Attach(entity); } return base.Attach((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry Entry(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Entry(entity); } return base.Entry(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry<TEntity> Entry<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Entry(entity); } return base.Entry((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry Remove(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Remove(entity); } return base.Remove(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry<TEntity> Remove<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Remove(entity); } return base.Remove((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry Update(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Update(entity); } return base.Update(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry<TEntity> Update<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Update(entity); } return base.Update((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override int SaveChanges(bool acceptAllChangesOnSuccess) { var lookup = Dependencies.DbContextEntityProxyLookupGenerator.Create(this); lookup.Changes(); var result = base.SaveChanges(acceptAllChangesOnSuccess); lookup.Changed(); return result; } /// <inheritdoc/> public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) { var lookup = Dependencies.DbContextEntityProxyLookupGenerator.Create(this); lookup.Changes(); var result = base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); lookup.Changed(); return result; } public override void Dispose() { Dependencies.DbContextEntityProxyLookupGenerator.Delete(this); base.Dispose(); } } }
src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/ShardDbContext.cs
c-y-r-Ryan.EntityFrameworkCore.Shard-f15124c
[ { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Expressions/ExpressionImplementationFinder.cs", "retrieved_chunk": " /// <summary>\n /// 访问器生成器\n /// </summary>\n public IEntityModelBuilderAccessorGenerator EntityModelBuilderAccessorGenerator { get; }\n /// <summary>\n /// 创建表达式实现查询器\n /// </summary>\n public ExpressionImplementationFinder(IEntityModelBuilderAccessorGenerator entityModelBuilderAccessorGenerator)\n {\n EntityModelBuilderAccessorGenerator = entityModelBuilderAccessorGenerator;", "score": 0.8599828481674194 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilder.cs", "retrieved_chunk": " /// </summary>\n string GetTableName(Dictionary<string, string> value);\n }\n /// <summary>\n /// 实体模型构造器\n /// </summary>\n public abstract class EntityModelBuilder<TEntity> : IEntityModelBuilder where TEntity : class\n {\n /// <summary>\n /// 访问器", "score": 0.8539867401123047 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilder.cs", "retrieved_chunk": " /// </summary>\n private List<Func<EntityExpressionVisitor>> Visitors { get; } = new List<Func<EntityExpressionVisitor>>();\n /// <summary>\n /// 创建实体模型构建器\n /// </summary>\n public EntityModelBuilder()\n {\n EntityConfiguration();\n }\n /// <summary>", "score": 0.8527746796607971 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityShardConfiguration.cs", "retrieved_chunk": " /// 动态类型创建\n /// </summary>\n public IDynamicTypeGenerator DynamicTypeGenerator { get; }\n /// <summary>\n /// 创建实体分表配置\n /// </summary>\n public EntityShardConfiguration(\n IEntityImplementationDictionaryGenerator entityImplementationDictionaryGenerator\n , IDynamicTypeGenerator dynamicTypeGenerator)\n {", "score": 0.8523234128952026 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilderGenerator.cs", "retrieved_chunk": " /// 创建实体模型构建对象生成器\n /// </summary>\n public EntityModelBuilderGenerator(IServiceProvider serviceProvider)\n {\n ServiceProvider = serviceProvider;\n MemoryCache = new InternalMemoryCache();\n }\n /// <summary>\n /// 创建实体模块构建器\n /// </summary>", "score": 0.8479050993919373 } ]
csharp
EntityProxy CreateEntityProxy(object entity, EntityProxyType type) {
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/Helpers/SchemaHelper.cs", "retrieved_chunk": " schemaName = schemaAttribute.SchemaName;\n }\n else\n {\n schemaName = type.Name;\n }\n return schemaName;\n }\n public static List<string> GetPropertyNamesFromExpression<T>(Expression<Func<T, bool>> predicate) where T : class\n {", "score": 0.8409587740898132 }, { "filename": "Magic.IndexedDb/Helpers/SchemaHelper.cs", "retrieved_chunk": " }\n break;\n }\n }\n }\n return columnName;\n }\n public static string GetPropertyColumnName<T>(this PropertyInfo prop) where T : Attribute\n {\n T? attribute = (T?)Attribute.GetCustomAttribute(prop, typeof(T));", "score": 0.8112989664077759 }, { "filename": "Magic.IndexedDb/Helpers/SchemaHelper.cs", "retrieved_chunk": " }\n }\n }\n }\n return schemas;\n }\n public static StoreSchema GetStoreSchema<T>(string name = null, bool PrimaryKeyAuto = true) where T : class\n {\n Type type = typeof(T);\n return GetStoreSchema(type, name, PrimaryKeyAuto);", "score": 0.8087359070777893 }, { "filename": "Magic.IndexedDb/Models/MagicQuery.cs", "retrieved_chunk": " return num;\n }\n // Not currently available in Dexie version 1,2, or 3\n public MagicQuery<T> OrderBy(Expression<Func<T, object>> predicate)\n {\n var memberExpression = GetMemberExpressionFromLambda(predicate);\n var propertyInfo = memberExpression.Member as PropertyInfo;\n if (propertyInfo == null)\n {\n throw new ArgumentException(\"The expression must represent a single property access.\");", "score": 0.8009387254714966 }, { "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.7890920639038086 } ]
csharp
MagicQuery<T> Where<T>(Expression<Func<T, bool>> predicate) where T : class {
using FayElf.Plugins.WeChat.Applets.Model; using FayElf.Plugins.WeChat.Model; using System; using System.Collections.Generic; using System.Drawing; using System.IO; 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:18:22 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.Applets { /// <summary> /// 小程序主类 /// </summary> public class Applets { #region 无参构造器 /// <summary> /// 无参构造器 /// </summary> public Applets() { this.Config = Config.Current; } /// <summary> /// 设置配置 /// </summary> /// <param name="config">配置</param> public Applets(Config config) { this.Config = config; } /// <summary> /// 设置配置 /// </summary> /// <param name="appID">AppID</param> /// <param name="appSecret">密钥</param> public Applets(string appID, string appSecret) { this.Config.AppID = appID; this.Config.AppSecret = appSecret; } #endregion #region 属性 /// <summary> /// 配置 /// </summary> public Config Config { get; set; } = new Config(); #endregion #region 方法 #region 登录凭证校验 /// <summary> /// 登录凭证校验 /// </summary> /// <param name="code">登录时获取的 code</param> /// <returns></returns> public JsCodeSessionData JsCode2Session(string code) { var session = new JsCodeSessionData(); var config = this.Config.GetConfig(WeChatType.Applets); var result = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Get, Address = $"{HttpApi.HOST}/sns/jscode2session?appid={config.AppID}&secret={config.AppSecret}&js_code={code}&grant_type=authorization_code" }); if (result.StatusCode == System.Net.HttpStatusCode.OK) { session = result.Html.JsonToObject<JsCodeSessionData>(); } else { session.ErrMsg = "请求出错."; session.ErrCode = 500; } return session; } #endregion #region 下发小程序和公众号统一的服务消息 /// <summary> /// 下发小程序和公众号统一的服务消息 /// </summary> /// <param name="data">下发数据</param> /// <returns></returns> public
BaseResult UniformSend(UniformSendData data) {
var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"{HttpApi.HOST}/cgi-bin/message/wxopen/template/uniform_send?access_token={token.AccessToken}", BodyData = data.ToJson() }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<BaseResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {40037,"模板id不正确,weapp_template_msg.template_id或者mp_template_msg.template_id" }, {41028,"weapp_template_msg.form_id过期或者不正确" }, {41029,"weapp_template_msg.form_id已被使用" }, {41030,"weapp_template_msg.page不正确" }, {45009,"接口调用超过限额" }, {40003,"touser不是正确的openid" }, {40013,"appid不正确,或者不符合绑定关系要求" } }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求出错." }; } }); } #endregion #region 获取用户手机号 /// <summary> /// 获取用户手机号 /// </summary> /// <param name="code">手机号获取凭证</param> /// <returns></returns> public UserPhoneData GetUserPhone(string code) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"{HttpApi.HOST}/wxa/business/getuserphonenumber?access_token={token.AccessToken}", BodyData = $"{{\"code\":\"{code}\"}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<UserPhoneData>(); if (result.ErrCode != 0) { result.ErrMsg += "[" + result.ErrCode + "]"; } return result; } else { return new UserPhoneData { ErrCode = 500, ErrMsg = "请求出错." }; } }); } #endregion #region 获取用户encryptKey /// <summary> /// 获取用户encryptKey /// </summary> /// <param name="session">Session数据</param> /// <returns></returns> public UserEncryptKeyData GetUserEncryptKey(JsCodeSessionData session) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"{HttpApi.HOST}/wxa/business/getuserencryptkey?access_token={token.AccessToken}", BodyData = $"{{\"openid\":\"{session.OpenID}\",\"signature\":\"{"".HMACSHA256Encrypt(session.SessionKey)}\",\"sig_method\":\"hmac_sha256\"}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<UserEncryptKeyData>(); if (result.ErrCode != 0) { result.ErrMsg += "[" + result.ErrCode + "]"; } return result; } else { return new UserEncryptKeyData { ErrCode = 500, ErrMsg = "请求出错." }; } }); } #endregion #region 获取小程序码 /// <summary> /// 获取小程序码 /// </summary> /// <param name="path">扫码进入的小程序页面路径,最大长度 128 字节,不能为空;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar",即可在 wx.getLaunchOptionsSync 接口中的 query 参数获取到 {foo:"bar"}。</param> /// <param name="width">二维码的宽度,单位 px。默认值为430,最小 280px,最大 1280px</param> /// <param name="autoColor">默认值false;自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调</param> /// <param name="color">默认值{"r":0,"g":0,"b":0} ;auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示</param> /// <param name="ishyaline">背景是否透明</param> /// <returns></returns> public QrCodeResult GetQRCode(string path, int width, Boolean autoColor = false, Color? color = null, Boolean ishyaline = false) { if (!color.HasValue) color = Color.Black; var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var result = new HttpRequest { Address = $"{HttpApi.HOST}/wxa/getwxacode?access_token={token.AccessToken}", Method = HttpMethod.Post, BodyData = $@"{{ ""path"":""{path}"", ""width"":{width}, ""auto_color"":{autoColor.ToString().ToLower()}, ""line_color"":{{""r"":{color?.R},""g"":{color?.G},""b"":{color?.B}}}, ""is_hyaline"":{ishyaline.ToString().ToLower()} }}" }.GetResponse(); if (result.StatusCode == System.Net.HttpStatusCode.OK) { if (result.Html.IndexOf("errcode") == -1) { return new QrCodeResult { ErrCode = 0, ContentType = result.ContentType, Buffer = result.Data.ToBase64String() }; } } return new QrCodeResult { ErrCode = 500, ErrMsg = result.Html }; }); } #endregion #region 获取不限制的小程序码 /// <summary> /// 获取不限制的小程序码 /// </summary> /// <param name="page">默认是主页,页面 page,例如 pages/index/index,根路径前不要填加 /,不能携带参数(参数请放在 scene 字段里),如果不填写这个字段,默认跳主页面。</param> /// <param name="scene">最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式)</param> /// <param name="checkPath">默认是true,检查page 是否存在,为 true 时 page 必须是已经发布的小程序存在的页面(否则报错);为 false 时允许小程序未发布或者 page 不存在, 但page 有数量上限(60000个)请勿滥用。</param> /// <param name="envVersion">要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。</param> /// <param name="width">默认430,二维码的宽度,单位 px,最小 280px,最大 1280px</param> /// <param name="autoColor">自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false</param> /// <param name="color">默认是{"r":0,"g":0,"b":0} 。auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示</param> /// <param name="ishyaline">默认是false,是否需要透明底色,为 true 时,生成透明底色的小程序</param> /// <returns></returns> public QrCodeResult GetUnlimitedQRCode(string page, string scene, Boolean checkPath, AppletEnvVersion envVersion, int width, Boolean autoColor = false, Color? color = null, Boolean ishyaline = false) { if (!color.HasValue) color = Color.Black; var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var result = new HttpRequest { Address = $"{HttpApi.HOST}/wxa/getwxacodeunlimit?access_token={token.AccessToken}", Method = HttpMethod.Post, BodyData = $@"{{ ""page"":""{page}"", ""scene"":""{scene}"", ""check_path"":{checkPath.ToString().ToLower()}, ""env_version"":""{envVersion.ToString().ToLower()}"", ""width"":{width}, ""auto_color"":{autoColor.ToString().ToLower()}, ""line_color"":{{""r"":{color?.R},""g"":{color?.G},""b"":{color?.B}}}, ""is_hyaline"":{ishyaline.ToString().ToLower()} }}" }.GetResponse(); if (result.StatusCode == System.Net.HttpStatusCode.OK) { if (result.Html.IndexOf("errcode") == -1) { return new QrCodeResult { ErrCode = 0, ContentType = result.ContentType, Buffer = result.Data.ToBase64String() }; } } return new QrCodeResult { ErrCode = 500, ErrMsg = result.Html }; }); } #endregion #region 获取小程序二维码 /// <summary> /// 获取小程序二维码 /// </summary> /// <param name="path">扫码进入的小程序页面路径,最大长度 128 字节,不能为空;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar",即可在 wx.getLaunchOptionsSync 接口中的 query 参数获取到 {foo:"bar"}。</param> /// <param name="width">二维码的宽度,单位 px。最小 280px,最大 1280px;默认是430</param> /// <returns></returns> public QrCodeResult CreateQRCode(string path, int width) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var result = new HttpRequest { Address = $"{HttpApi.HOST}/cgi-bin/wxaapp/createwxaqrcode?access_token={token.AccessToken}", Method = HttpMethod.Post, BodyData = $@"{{ ""path"":""{path}"", ""width"":{width} }}" }.GetResponse(); if (result.StatusCode == System.Net.HttpStatusCode.OK) { if (result.Html.IndexOf("errcode") == -1) { return new QrCodeResult { ErrCode = 0, ContentType = result.ContentType, Buffer = result.Data.ToBase64String() }; } } return new QrCodeResult { ErrCode = 500, ErrMsg = result.Html }; }); } #endregion #endregion } }
Applets/Applets.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "Applets/Model/UniformSendData.cs", "retrieved_chunk": " /// </summary>\n public string url { get; set; }\n /// <summary>\n /// 公众号模板消息所要跳转的小程序,小程序的必须与公众号具有绑定关系\n /// </summary>\n [OmitEmptyNode]\n public MiniProgram miniprogram { get; set; }\n /// <summary>\n /// 公众号模板消息的数据\n /// </summary>", "score": 0.8398221135139465 }, { "filename": "Common.cs", "retrieved_chunk": " /// <summary>\n /// 通用类\n /// </summary>\n public static class Common\n {\n #region 获取全局唯一后台接口调用凭据\n /// <summary>\n /// 获取全局唯一后台接口调用凭据\n /// </summary>\n /// <param name=\"appID\">App ID</param>", "score": 0.8354030847549438 }, { "filename": "OfficialAccount/Template.cs", "retrieved_chunk": " return result.ErrCode == 0;\n }\n #endregion\n #region 发送模板消息\n /// <summary>\n /// 发送模板消息\n /// </summary>\n /// <param name=\"data\">发送数据</param>\n /// <returns></returns>\n public IndustryTemplateSendDataResult Send(IndustryTemplateSendData data)", "score": 0.8191940188407898 }, { "filename": "Applets/Model/UniformSendData.cs", "retrieved_chunk": " public string touser { get; set; }\n /// <summary>\n /// 公众号模板消息\n /// </summary>\n public MPTemplateMsg mp_template_msg { get; set; }\n }\n /// <summary>\n /// 公众号模板消息相关的信息,可以参考公众号模板消息接口\n /// </summary>\n public class MPTemplateMsg", "score": 0.8190426230430603 }, { "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.8178989887237549 } ]
csharp
BaseResult UniformSend(UniformSendData data) {
using Microsoft.Extensions.Caching.Memory; using Ryan.EntityFrameworkCore.Infrastructure; using System; namespace Ryan.EntityFrameworkCore.Builder { /// <inheritdoc cref="IEntityModelBuilderAccessorGenerator"/> public class EntityModelBuilderAccessorGenerator : IEntityModelBuilderAccessorGenerator { /// <summary> /// 实体模型构建生成器 /// </summary> public IEntityModelBuilderGenerator EntityModelBuilderGenerator { get; } /// <summary> /// 实体实现字典生成器 /// </summary> public IEntityImplementationDictionaryGenerator ImplementationDictionaryGenerator { get; } /// <summary> /// 缓存 /// </summary> public IMemoryCache MemoryCache { get; } /// <summary> /// 创建实体模型构建访问器 /// </summary> public EntityModelBuilderAccessorGenerator( IEntityModelBuilderGenerator entityModelBuilderGenerator ,
IEntityImplementationDictionaryGenerator implementationDictionaryGenerator) {
EntityModelBuilderGenerator = entityModelBuilderGenerator; ImplementationDictionaryGenerator = implementationDictionaryGenerator; MemoryCache = new InternalMemoryCache(); } /// <inheritdoc/> public EntityModelBuilderAccessor Create(Type entityType) { return (MemoryCache.GetOrCreate(entityType, (entry) => { var entityModelBulder = EntityModelBuilderGenerator.Create(entityType)!; var entityImplementationDictionary = ImplementationDictionaryGenerator.Create(entityType)!; return entry.SetSize(1).SetValue( new EntityModelBuilderAccessor(entityType, entityImplementationDictionary, entityModelBulder) ).Value; }) as EntityModelBuilderAccessor)!; } } }
src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilderAccessorGenerator.cs
c-y-r-Ryan.EntityFrameworkCore.Shard-f15124c
[ { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Expressions/ExpressionImplementationFinder.cs", "retrieved_chunk": " /// <summary>\n /// 访问器生成器\n /// </summary>\n public IEntityModelBuilderAccessorGenerator EntityModelBuilderAccessorGenerator { get; }\n /// <summary>\n /// 创建表达式实现查询器\n /// </summary>\n public ExpressionImplementationFinder(IEntityModelBuilderAccessorGenerator entityModelBuilderAccessorGenerator)\n {\n EntityModelBuilderAccessorGenerator = entityModelBuilderAccessorGenerator;", "score": 0.9388729929924011 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Proxy/EntityProxyGenerator.cs", "retrieved_chunk": " /// <inheritdoc cref=\"IEntityModelBuilderGenerator\"/>\n public IEntityModelBuilderGenerator EntityModelBuilderGenerator { get; }\n /// <inheritdoc cref=\"IEntityImplementationDictionaryGenerator\"/>\n public IEntityImplementationDictionaryGenerator EntityImplementationDictionaryGenerator { get; }\n /// <summary>\n /// 创建实体代理\n /// </summary>\n public EntityProxyGenerator(\n IEntityModelBuilderGenerator entityModelBuilderGenerator\n , IEntityImplementationDictionaryGenerator entityImplementationDictionaryGenerator)", "score": 0.9369271993637085 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityShardConfiguration.cs", "retrieved_chunk": " /// 动态类型创建\n /// </summary>\n public IDynamicTypeGenerator DynamicTypeGenerator { get; }\n /// <summary>\n /// 创建实体分表配置\n /// </summary>\n public EntityShardConfiguration(\n IEntityImplementationDictionaryGenerator entityImplementationDictionaryGenerator\n , IDynamicTypeGenerator dynamicTypeGenerator)\n {", "score": 0.9290500283241272 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilderAccessor.cs", "retrieved_chunk": " /// </summary>\n public object EntityModelBuilder { get; }\n /// <summary>\n /// 访问器\n /// </summary>\n public Action<Type, ModelBuilder> Accessor { get; protected set; }\n /// <summary>\n /// 创建实体模型构建访问器\n /// </summary>\n public EntityModelBuilderAccessor(Type entityType, EntityImplementationDictionary dictionary, object entityModelBuilder)", "score": 0.921017050743103 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilderGenerator.cs", "retrieved_chunk": " /// 创建实体模型构建对象生成器\n /// </summary>\n public EntityModelBuilderGenerator(IServiceProvider serviceProvider)\n {\n ServiceProvider = serviceProvider;\n MemoryCache = new InternalMemoryCache();\n }\n /// <summary>\n /// 创建实体模块构建器\n /// </summary>", "score": 0.9114470481872559 } ]
csharp
IEntityImplementationDictionaryGenerator implementationDictionaryGenerator) {
using System; using System.Collections.Generic; using System.Text; using FayElf.Plugins.WeChat.OfficialAccount.Model; using XiaoFeng; using XiaoFeng.Http; /**************************************************************** * Copyright © (2022) www.fayelf.com All Rights Reserved. * * Author : jacky * * QQ : 7092734 * * Email : [email protected] * * Site : www.fayelf.com * * Create Time : 2022-03-11 09:34:31 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.OfficialAccount { /// <summary> /// 订阅通知操作类 /// </summary> public class Subscribe { #region 无参构造器 /// <summary> /// 无参构造器 /// </summary> public Subscribe() { this.Config = Config.Current; } /// <summary> /// 设置配置 /// </summary> /// <param name="config">配置</param> public Subscribe(Config config) { this.Config = config; } /// <summary> /// 设置配置 /// </summary> /// <param name="appID">AppID</param> /// <param name="appSecret">密钥</param> public Subscribe(string appID, string appSecret) { this.Config.AppID = appID; this.Config.AppSecret = appSecret; } #endregion #region 属性 /// <summary> /// 配置 /// </summary> public Config Config { get; set; } = new Config(); #endregion #region 方法 #region 选用模板 /// <summary> /// 选用模板 /// </summary> /// <param name="tid">模板标题 id,可通过getPubTemplateTitleList接口获取,也可登录公众号后台查看获取</param> /// <param name="kidList">开发者自行组合好的模板关键词列表,关键词顺序可以自由搭配(例如 [3,5,4] 或 [4,5,3]),最多支持5个,最少2个关键词组合</param> /// <param name="sceneDesc">服务场景描述,15个字以内</param> /// <returns></returns> public AddTemplateResult AddTemplate(string tid, int kidList, string sceneDesc) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token={token.AccessToken}", BodyData = new { access_token = token.AccessToken, tid = tid, kidList = kidList, sceneDesc = sceneDesc }.ToJson() }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<AddTemplateResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {200011,"此账号已被封禁,无法操作" }, {200012,"私有模板数已达上限,上限 50 个" }, {200013,"此模版已被封禁,无法选用" }, {200014,"模版 tid 参数错误" }, {200020,"关键词列表 kidList 参数错误" }, {200021,"场景描述 sceneDesc 参数错误" } }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new AddTemplateResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 删除模板 /// <summary> /// 删除模板 /// </summary> /// <param name="priTmplId">要删除的模板id</param> /// <returns></returns> public BaseResult DeleteTemplate(string priTmplId) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate?access_token={token.AccessToken}", BodyData = $@"{{priTmplId:""{priTmplId}""}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<AddTemplateResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {20001,"系统错误(包含该账号下无该模板等)" }, {20002,"参数错误" }, {200014,"模版 tid 参数错误" } }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new AddTemplateResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取公众号类目 /// <summary> /// 获取公众号类目 /// </summary> /// <returns></returns> public
TemplateCategoryResult GetCategory() {
var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Get, Address = $"https://api.weixin.qq.com/wxaapi/newtmpl/getcategory?access_token={token.AccessToken}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<TemplateCategoryResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {20001,"系统错误(包含该账号下无该模板等)" }, {20002,"参数错误" }, {200014,"模版 tid 参数错误" } }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new TemplateCategoryResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取模板中的关键词 /// <summary> /// 获取模板中的关键词 /// </summary> /// <param name="tid">模板标题 id,可通过接口获取</param> /// <returns></returns> public TemplateKeywordResult GetPubTemplateKeyWordsById(string tid) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Get, Address = $"https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatekeywords?access_token={token.AccessToken}&tid={tid}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<TemplateKeywordResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {20001,"系统错误" } }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new TemplateKeywordResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取类目下的公共模板 /// <summary> /// 获取类目下的公共模板 /// </summary> /// <param name="ids">类目 id,多个用逗号隔开</param> /// <param name="start">用于分页,表示从 start 开始,从 0 开始计数</param> /// <param name="limit">用于分页,表示拉取 limit 条记录,最大为 30</param> /// <returns></returns> public PubTemplateResult GetPubTemplateTitleList(string ids, int start, int limit) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Get, Address = $@"https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatetitles?access_token={token.AccessToken}&ids=""{ids}""&start={start}&limit={limit}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<PubTemplateResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {20001,"系统错误" } }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new PubTemplateResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取私有模板列表 /// <summary> /// 获取私有模板列表 /// </summary> /// <returns></returns> public TemplateResult GetTemplateList() { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Get, Address = $"https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token={token.AccessToken}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<TemplateResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {20001,"系统错误" } }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new TemplateResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 发送订阅通知 /// <summary> /// 发送订阅通知 /// </summary> /// <param name="touser">接收者(用户)的 openid</param> /// <param name="template_id">所需下发的订阅模板id</param> /// <param name="page">跳转网页时填写</param> /// <param name="miniprogram">跳转小程序时填写,格式如{ "appid": "", "pagepath": { "value": any } }</param> /// <param name="data">模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }</param> /// <returns></returns> public BaseResult Send(string touser, string template_id, string page, MiniProgram miniprogram, Dictionary<string, ValueColor> data) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var _data = new Dictionary<string, object>() { {"touser",touser }, {"template_id",template_id} }; if (page.IsNotNullOrEmpty()) _data.Add("page", page); if (miniprogram != null) _data.Add("mimiprogram", miniprogram); _data.Add("data", data); var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token={token.AccessToken}", BodyData = _data.ToJson() }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<BaseResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {40003,"touser字段openid为空或者不正确" }, {40037,"订阅模板id为空不正确" }, {43101,"用户拒绝接受消息,如果用户之前曾经订阅过,则表示用户取消了订阅关系" }, {47003,"模板参数不准确,可能为空或者不满足规则,errmsg会提示具体是哪个字段出错" }, {41030,"page路径不正确" }, }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #endregion } }
OfficialAccount/Subscribe.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "OfficialAccount/Model/TemplateResult.cs", "retrieved_chunk": " /// 个人模板列表\n /// </summary>\n public TemplateData data { get; set; }\n #endregion\n #region 方法\n #endregion\n }\n /// <summary>\n /// 模板信息\n /// </summary>", "score": 0.8884473443031311 }, { "filename": "OfficialAccount/Model/TemplateCategoryResult.cs", "retrieved_chunk": " /// 类目\n /// </summary>\n public List<TemplateCategory> data { get; set; }\n #endregion\n #region 方法\n #endregion\n }\n /// <summary>\n /// 模板类目\n /// </summary>", "score": 0.885725736618042 }, { "filename": "OfficialAccount/Model/TemplateCategoryResult.cs", "retrieved_chunk": " #region 构造器\n /// <summary>\n /// 无参构造器\n /// </summary>\n public TemplateCategoryResult()\n {\n }\n #endregion\n #region 属性\n /// <summary>", "score": 0.8762609958648682 }, { "filename": "Model/ArticleModel.cs", "retrieved_chunk": " /// 无参构造器\n /// </summary>\n public ArticleModel()\n {\n }\n #endregion\n #region 属性\n /// <summary>\n /// 图文消息标题\n /// </summary>", "score": 0.8740506768226624 }, { "filename": "OfficialAccount/Model/AddTemplateResult.cs", "retrieved_chunk": " #region 构造器\n /// <summary>\n /// 无参构造器\n /// </summary>\n public AddTemplateResult()\n {\n }\n #endregion\n #region 属性\n /// <summary>", "score": 0.8623414039611816 } ]
csharp
TemplateCategoryResult GetCategory() {
using EF012.CodeFirstMigration.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; namespace EF012.CodeFirstMigration.Data { public class AppDbContext : DbContext { public DbSet<Course> Courses { get; set; } public DbSet<
Instructor> Instructors {
get; set; } public DbSet<Office> Offices { get; set; } public DbSet<Section> Sections { get; set; } public DbSet<Schedule> Schedules { get; set; } public DbSet<Student> Students { get; set; } public DbSet<Enrollment> Enrollments { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); var config = new ConfigurationBuilder().AddJsonFile("appsettings.json") .Build(); var connectionString = config.GetSection("constr").Value; optionsBuilder.UseSqlServer(connectionString); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // modelBuilder.ApplyConfiguration(new CourseConfiguration()); // not best practice modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly); } } }
EF012.CodeFirstMigration/Data/AppDbContext.cs
metigator-EF012-054d65d
[ { "filename": "EF012.CodeFirstMigration/Program.cs", "retrieved_chunk": "using EF012.CodeFirstMigration.Data;\nusing Microsoft.EntityFrameworkCore;\nnamespace EF012.CodeFirstMigration\n{\n class Program\n {\n public static void Main(string[] args)\n {\n using (var context = new AppDbContext())\n {", "score": 0.873471736907959 }, { "filename": "EF012.CodeFirstMigration/Data/Config/CourseConfiguration.cs", "retrieved_chunk": "using EF012.CodeFirstMigration.Entities;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.EntityFrameworkCore.Metadata.Builders;\nnamespace EF012.CodeFirstMigration.Data.Config\n{\n public class CourseConfiguration : IEntityTypeConfiguration<Course>\n {\n public void Configure(EntityTypeBuilder<Course> builder)\n {\n builder.HasKey(x => x.Id);", "score": 0.8603260517120361 }, { "filename": "EF012.CodeFirstMigration/Data/Config/InstructorConfiguration.cs", "retrieved_chunk": "using EF012.CodeFirstMigration.Entities;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.EntityFrameworkCore.Metadata.Builders;\nnamespace EF012.CodeFirstMigration.Data.Config\n{\n public class InstructorConfiguration : IEntityTypeConfiguration<Instructor>\n {\n public void Configure(EntityTypeBuilder<Instructor> builder)\n {\n builder.HasKey(x => x.Id);", "score": 0.8561199903488159 }, { "filename": "EF012.CodeFirstMigration/Data/Config/OfficeConfiguration.cs", "retrieved_chunk": "using EF012.CodeFirstMigration.Entities;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.EntityFrameworkCore.Metadata.Builders;\nnamespace EF012.CodeFirstMigration.Data.Config\n{\n public class OfficeConfiguration : IEntityTypeConfiguration<Office>\n {\n public void Configure(EntityTypeBuilder<Office> builder)\n {\n builder.HasKey(x => x.Id);", "score": 0.8498786091804504 }, { "filename": "EF012.CodeFirstMigration/Data/Config/StudentConfiguration.cs", "retrieved_chunk": "using EF012.CodeFirstMigration.Entities;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.EntityFrameworkCore.Metadata.Builders;\nnamespace EF012.CodeFirstMigration.Data.Config\n{\n public class StudentConfiguration : IEntityTypeConfiguration<Student>\n {\n public void Configure(EntityTypeBuilder<Student> builder)\n {\n builder.HasKey(x => x.Id);", "score": 0.8483504056930542 } ]
csharp
Instructor> Instructors {
using HarmonyLib; using Mono.Cecil; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using UnityEngine; namespace Ultrapain.Patches { /* u = initial, f = final, d = delta, s = speed multiplier u = 40f * Time.deltaTime f = 40f * S * Time.deltaTime d = 40f * Time.deltaTime * (S - 1) revCharge += 40f * Time.deltaTime * (S - 1f) * (alt ? 0.5f : 1f) */ class Revolver_Update { static bool Prefix(Revolver __instance) { if(__instance.gunVariation == 0 && __instance.pierceCharge < 100f) { __instance.pierceCharge = Mathf.Min(100f, __instance.pierceCharge + 40f * Time.deltaTime * (ConfigManager.chargedRevRegSpeedMulti.value - 1f) * (__instance.altVersion ? 0.5f : 1f)); } return true; } } public class Revolver_Shoot { public static void RevolverBeamEdit(RevolverBeam beam) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.revolverAltDamage.value : ConfigManager.revolverDamage.value; } public static void RevolverBeamSuperEdit(RevolverBeam beam) { if (beam.gunVariation == 0) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.chargedAltRevDamage.value : ConfigManager.chargedRevDamage.value; beam.hitAmount = beam.strongAlt ? ConfigManager.chargedAltRevTotalHits.value : ConfigManager.chargedRevTotalHits.value; beam.maxHitsPerTarget = beam.strongAlt ? ConfigManager.chargedAltRevMaxHitsPerTarget.value : ConfigManager.chargedRevMaxHitsPerTarget.value; } else if (beam.gunVariation == 2) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.sharpshooterAltDamage.value : ConfigManager.sharpshooterDamage.value; beam.maxHitsPerTarget = beam.strongAlt ? ConfigManager.sharpshooterAltMaxHitsPerTarget.value : ConfigManager.sharpshooterMaxHitsPerTarget.value; } } static FieldInfo f_RevolverBeam_gunVariation = typeof(RevolverBeam).GetField("gunVariation", UnityUtils.instanceFlag); static MethodInfo m_Revolver_Shoot_RevolverBeamEdit = typeof(Revolver_Shoot).GetMethod("RevolverBeamEdit", UnityUtils.staticFlag); static MethodInfo m_Revolver_Shoot_RevolverBeamSuperEdit = typeof(Revolver_Shoot).GetMethod("RevolverBeamSuperEdit", UnityUtils.staticFlag); static MethodInfo m_GameObject_GetComponent_RevolverBeam = typeof(GameObject).GetMethod("GetComponent", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(RevolverBeam) }); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); object normalBeamLocalIndex = null; object superBeamLocalIndex = null; // Get local indexes of components for RevolverBeam references for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_GameObject_GetComponent_RevolverBeam)) { object localIndex = ILUtils.GetLocalIndex(code[i + 1]); if (localIndex == null) continue; if (normalBeamLocalIndex == null) { normalBeamLocalIndex = localIndex; } else { superBeamLocalIndex = localIndex; break; } } } Debug.Log($"Normal beam index: {normalBeamLocalIndex}"); Debug.Log($"Super beam index: {superBeamLocalIndex}"); // Modify normal beam for (int i = 3; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_RevolverBeam_gunVariation)) { object localIndex = ILUtils.GetLocalIndex(code[i - 3]); if (localIndex == null) continue; if (localIndex.Equals(normalBeamLocalIndex)) { Debug.Log($"Patching normal beam"); i += 1; code.Insert(i, ILUtils.LoadLocalInstruction(localIndex)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Call, m_Revolver_Shoot_RevolverBeamEdit)); break; } } } // Modify super beam for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_RevolverBeam_gunVariation)) { object localIndex = ILUtils.GetLocalIndex(code[i - 3]); if (localIndex == null) continue; if (localIndex.Equals(superBeamLocalIndex)) { Debug.Log($"Patching super beam"); i += 1; code.Insert(i, ILUtils.LoadLocalInstruction(localIndex)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Call, m_Revolver_Shoot_RevolverBeamSuperEdit)); break; } } } return code.AsEnumerable(); } } public class Shotgun_Shoot { public static void ModifyShotgunPellet(Projectile proj, Shotgun shotgun, int primaryCharge) { if (shotgun.variation == 0) { proj.damage = ConfigManager.shotgunBlueDamagePerPellet.value; } else { if (primaryCharge == 0) proj.damage = ConfigManager.shotgunGreenPump1Damage.value; else if (primaryCharge == 1) proj.damage = ConfigManager.shotgunGreenPump2Damage.value; else if (primaryCharge == 2) proj.damage = ConfigManager.shotgunGreenPump3Damage.value; } } public static void ModifyPumpExplosion(Explosion exp) { exp.damage = ConfigManager.shotgunGreenExplosionDamage.value; exp.playerDamageOverride = ConfigManager.shotgunGreenExplosionPlayerDamage.value; float sizeMulti = ConfigManager.shotgunGreenExplosionSize.value / 9f; exp.maxSize *= sizeMulti; exp.speed *= sizeMulti; exp.speed *= ConfigManager.shotgunGreenExplosionSpeed.value; } static MethodInfo m_GameObject_GetComponent_Projectile = typeof(GameObject).GetMethod("GetComponent", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(Projectile) }); static MethodInfo m_GameObject_GetComponentsInChildren_Explosion = typeof(GameObject).GetMethod("GetComponentsInChildren", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(Explosion) }); static MethodInfo m_Shotgun_Shoot_ModifyShotgunPellet = typeof(Shotgun_Shoot).GetMethod("ModifyShotgunPellet", UnityUtils.staticFlag); static MethodInfo m_Shotgun_Shoot_ModifyPumpExplosion = typeof(Shotgun_Shoot).GetMethod("ModifyPumpExplosion", UnityUtils.staticFlag); static FieldInfo f_Shotgun_primaryCharge = typeof(Shotgun).GetField("primaryCharge", UnityUtils.instanceFlag); static FieldInfo f_Explosion_damage = typeof(Explosion).GetField("damage", UnityUtils.instanceFlag); static bool Prefix(Shotgun __instance, int ___primaryCharge) { if (__instance.variation == 0) { __instance.spread = ConfigManager.shotgunBlueSpreadAngle.value; } else { if (___primaryCharge == 0) __instance.spread = ConfigManager.shotgunGreenPump1Spread.value * 1.5f; else if (___primaryCharge == 1) __instance.spread = ConfigManager.shotgunGreenPump2Spread.value; else if (___primaryCharge == 2) __instance.spread = ConfigManager.shotgunGreenPump3Spread.value / 2f; } return true; } static void Postfix(Shotgun __instance) { __instance.spread = 10f; } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction pelletStoreInst = new CodeInstruction(OpCodes.Stloc_0); int pelletCodeIndex = 0; // Find pellet local variable index for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldc_I4_S && code[i].OperandIs(12)) { if (ConfigManager.shotgunBluePelletCount.value > sbyte.MaxValue) code[i].opcode = OpCodes.Ldc_I4; code[i].operand = ConfigManager.shotgunBluePelletCount.value; i += 1; pelletCodeIndex = i; pelletStoreInst = code[i]; break; } } // Debug.Log($"Pellet store instruction: {ILUtils.TurnInstToString(pelletStoreInst)}"); // Modify pellet counts for (int i = pelletCodeIndex + 1; i < code.Count; i++) { if (code[i].opcode == pelletStoreInst.opcode && (pelletStoreInst.operand == null ? true : pelletStoreInst.operand.Equals(code[i].operand)) && ILUtils.IsConstI4LoadWithOperand(code[i - 1].opcode)) { int constIndex = i - 1; int pelletCount = ILUtils.GetI4LoadOperand(code[constIndex]); if (pelletCount == 10) pelletCount = ConfigManager.shotgunGreenPump1Count.value; else if (pelletCount == 16) pelletCount = ConfigManager.shotgunGreenPump2Count.value; else if (pelletCount == 24) pelletCount = ConfigManager.shotgunGreenPump3Count.value; if (ILUtils.TryEfficientLoadI4(pelletCount, out OpCode efficientOpcode)) { code[constIndex].operand = null; code[constIndex].opcode = efficientOpcode; } else { if (pelletCount > sbyte.MaxValue) code[constIndex].opcode = OpCodes.Ldc_I4; else code[constIndex].opcode = OpCodes.Ldc_I4_S; code[constIndex].operand = pelletCount; } } } // Modify projectile damage for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_GameObject_GetComponent_Projectile)) { i += 1; // Duplicate component (arg 0) code.Insert(i, new CodeInstruction(OpCodes.Dup)); i += 1; // Add instance to stack (arg 1) code.Insert(i, new CodeInstruction(OpCodes.Ldarg_0)); i += 1; // Load instance then get primary field (arg 2) code.Insert(i, new CodeInstruction(OpCodes.Ldarg_0)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Ldfld, f_Shotgun_primaryCharge)); i += 1; // Call the static method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_Shoot_ModifyShotgunPellet)); break; } } // Modify pump explosion int pumpExplosionIndex = 0; while (code[pumpExplosionIndex].opcode != OpCodes.Callvirt && !code[pumpExplosionIndex].OperandIs(m_GameObject_GetComponentsInChildren_Explosion)) pumpExplosionIndex += 1; for (int i = pumpExplosionIndex; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld) { if (code[i].OperandIs(f_Explosion_damage)) { // Duplicate before damage assignment code.Insert(i - 1, new CodeInstruction(OpCodes.Dup)); i += 2; // Argument 0 already loaded, call the method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_Shoot_ModifyPumpExplosion)); // Stack is now clear break; } } } return code.AsEnumerable(); } } // Core eject class Shotgun_ShootSinks { public static void ModifyCoreEject(GameObject core) { GrenadeExplosionOverride ovr = core.AddComponent<GrenadeExplosionOverride>(); ovr.normalMod = true; ovr.normalDamage = (float)ConfigManager.shotgunCoreExplosionDamage.value / 35f; ovr.normalSize = (float)ConfigManager.shotgunCoreExplosionSize.value / 6f * ConfigManager.shotgunCoreExplosionSpeed.value; ovr.normalPlayerDamageOverride = ConfigManager.shotgunCoreExplosionPlayerDamage.value; ovr.superMod = true; ovr.superDamage = (float)ConfigManager.shotgunCoreExplosionDamage.value / 35f; ovr.superSize = (float)ConfigManager.shotgunCoreExplosionSize.value / 6f * ConfigManager.shotgunCoreExplosionSpeed.value; ovr.superPlayerDamageOverride = ConfigManager.shotgunCoreExplosionPlayerDamage.value; } static FieldInfo f_Grenade_sourceWeapon = typeof(Grenade).GetField("sourceWeapon", UnityUtils.instanceFlag); static MethodInfo m_Shotgun_ShootSinks_ModifyCoreEject = typeof(Shotgun_ShootSinks).GetMethod("ModifyCoreEject", UnityUtils.staticFlag); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_Grenade_sourceWeapon)) { i += 1; // Add arg 0 code.Insert(i, new CodeInstruction(OpCodes.Dup)); i += 1; // Call mod method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_ShootSinks_ModifyCoreEject)); break; } } return code.AsEnumerable(); } } class Nailgun_Shoot { static FieldInfo f_Nailgun_heatSinks = typeof(Nailgun).GetField("heatSinks", UnityUtils.instanceFlag); static FieldInfo f_Nailgun_heatUp = typeof(Nailgun).GetField("heatUp", UnityUtils.instanceFlag); public static void ModifyNail(Nailgun inst, GameObject nail) { Nail comp = nail.GetComponent<Nail>(); if (inst.altVersion) { // Blue saw launcher if (inst.variation == 1) { comp.damage = ConfigManager.sawBlueDamage.value; comp.hitAmount = ConfigManager.sawBlueHitAmount.value; } // Green saw launcher else { comp.damage = ConfigManager.sawGreenDamage.value; float maxHit = ConfigManager.sawGreenHitAmount.value; float heatSinks = (float)f_Nailgun_heatSinks.GetValue(inst); float heatUp = (float)f_Nailgun_heatUp.GetValue(inst); if (heatSinks >= 1) comp.hitAmount = Mathf.Lerp(maxHit, Mathf.Max(1f, maxHit), (maxHit - 2f) * heatUp); else comp.hitAmount = 1f; } } else { // Blue nailgun if (inst.variation == 1) { comp.damage = ConfigManager.nailgunBlueDamage.value; } else { if (comp.heated) comp.damage = ConfigManager.nailgunGreenBurningDamage.value; else comp.damage = ConfigManager.nailgunGreenDamage.value; } } } static FieldInfo f_Nailgun_nail = typeof(Nailgun).GetField("nail", UnityUtils.instanceFlag); static MethodInfo m_Nailgun_Shoot_ModifyNail = typeof(Nailgun_Shoot).GetMethod("ModifyNail", UnityUtils.staticFlag); static MethodInfo m_Transform_set_forward = typeof(Transform).GetProperty("forward", UnityUtils.instanceFlag).GetSetMethod(); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction localObjectStoreInst = null; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && code[i].OperandIs(f_Nailgun_nail)) { for (; i < code.Count; i++) if (ILUtils.IsStoreLocalOpcode(code[i].opcode)) break; localObjectStoreInst = code[i]; } } Debug.Log($"Nail local reference: {ILUtils.TurnInstToString(localObjectStoreInst)}"); int insertIndex = 0; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_Transform_set_forward)) { insertIndex = i + 1; break; } } // Push instance reference code.Insert(insertIndex, new CodeInstruction(OpCodes.Ldarg_0)); insertIndex += 1; // Push local nail object code.Insert(insertIndex, new CodeInstruction(ILUtils.GetLoadLocalFromStoreLocal(localObjectStoreInst.opcode), localObjectStoreInst.operand)); insertIndex += 1; // Call the method code.Insert(insertIndex, new CodeInstruction(OpCodes.Call, m_Nailgun_Shoot_ModifyNail)); return code.AsEnumerable(); } } class Nailgun_SuperSaw { public static void ModifySupersaw(
GameObject supersaw) {
Nail saw = supersaw.GetComponent<Nail>(); saw.damage = ConfigManager.sawGreenBurningDamage.value; saw.hitAmount = ConfigManager.sawGreenBurningHitAmount.value; } static FieldInfo f_Nailgun_heatedNail = typeof(Nailgun).GetField("heatedNail", UnityUtils.instanceFlag); static MethodInfo m_Nailgun_SuperSaw_ModifySupersaw = typeof(Nailgun_SuperSaw).GetMethod("ModifySupersaw", UnityUtils.staticFlag); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction localObjectStoreInst = null; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && code[i].OperandIs(f_Nailgun_heatedNail)) { for (; i < code.Count; i++) if (ILUtils.IsStoreLocalOpcode(code[i].opcode)) break; localObjectStoreInst = code[i]; } } Debug.Log($"Supersaw local reference: {ILUtils.TurnInstToString(localObjectStoreInst)}"); int insertIndex = code.Count - 1; // Push local nail object code.Insert(insertIndex, new CodeInstruction(ILUtils.GetLoadLocalFromStoreLocal(localObjectStoreInst.opcode), localObjectStoreInst.operand)); insertIndex += 1; // Call the method code.Insert(insertIndex, new CodeInstruction(OpCodes.Call, m_Nailgun_SuperSaw_ModifySupersaw)); return code.AsEnumerable(); } } class NailGun_Update { static bool Prefix(Nailgun __instance, ref float ___heatSinks) { if(__instance.variation == 0) { float maxSinks = (__instance.altVersion ? 1f : 2f); float multi = (__instance.altVersion ? ConfigManager.sawHeatsinkRegSpeedMulti.value : ConfigManager.nailgunHeatsinkRegSpeedMulti.value); float rate = 0.125f; if (___heatSinks < maxSinks && multi != 1) ___heatSinks = Mathf.Min(maxSinks, ___heatSinks + Time.deltaTime * rate * (multi - 1f)); } return true; } } class NewMovement_Update { static bool Prefix(NewMovement __instance, int ___difficulty) { if (__instance.boostCharge < 300f && !__instance.sliding && !__instance.slowMode) { float multi = 1f; if (___difficulty == 1) multi = 1.5f; else if (___difficulty == 0f) multi = 2f; __instance.boostCharge = Mathf.Min(300f, __instance.boostCharge + Time.deltaTime * 70f * multi * (ConfigManager.staminaRegSpeedMulti.value - 1f)); } return true; } } class WeaponCharges_Charge { static bool Prefix(WeaponCharges __instance, float __0) { if (__instance.rev1charge < 400f) __instance.rev1charge = Mathf.Min(400f, __instance.rev1charge + 25f * __0 * (ConfigManager.coinRegSpeedMulti.value - 1f)); if (__instance.rev2charge < 300f) __instance.rev2charge = Mathf.Min(300f, __instance.rev2charge + (__instance.rev2alt ? 35f : 15f) * __0 * (ConfigManager.sharpshooterRegSpeedMulti.value - 1f)); if(!__instance.naiAmmoDontCharge) { if (__instance.naiAmmo < 100f) __instance.naiAmmo = Mathf.Min(100f, __instance.naiAmmo + __0 * 3.5f * (ConfigManager.nailgunAmmoRegSpeedMulti.value - 1f)); ; if (__instance.naiSaws < 10f) __instance.naiSaws = Mathf.Min(10f, __instance.naiSaws + __0 * 0.5f * (ConfigManager.sawAmmoRegSpeedMulti.value - 1f)); } if (__instance.raicharge < 5f) __instance.raicharge = Mathf.Min(5f, __instance.raicharge + __0 * 0.25f * (ConfigManager.railcannonRegSpeedMulti.value - 1f)); if (!__instance.rocketFrozen && __instance.rocketFreezeTime < 5f) __instance.rocketFreezeTime = Mathf.Min(5f, __instance.rocketFreezeTime + __0 * 0.5f * (ConfigManager.rocketFreezeRegSpeedMulti.value - 1f)); if (__instance.rocketCannonballCharge < 1f) __instance.rocketCannonballCharge = Mathf.Min(1f, __instance.rocketCannonballCharge + __0 * 0.125f * (ConfigManager.rocketCannonballRegSpeedMulti.value - 1f)); return true; } } class NewMovement_GetHurt { static bool Prefix(NewMovement __instance, out float __state) { __state = __instance.antiHp; return true; } static void Postfix(NewMovement __instance, float __state) { float deltaAnti = __instance.antiHp - __state; if (deltaAnti <= 0) return; deltaAnti *= ConfigManager.hardDamagePercent.normalizedValue; __instance.antiHp = __state + deltaAnti; } static FieldInfo hpField = typeof(NewMovement).GetField("hp"); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && (FieldInfo)code[i].operand == hpField) { i += 1; if (code[i].opcode == OpCodes.Ldc_I4_S) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == (Single)99f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.maxPlayerHp.value - 1)); } } return code.AsEnumerable(); } } class HookArm_FixedUpdate { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 66f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(66f * (ConfigManager.maxPlayerHp.value / 100f) * ConfigManager.whiplashHardDamageSpeed.value)); } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 50f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.whiplashHardDamageCap.value)); } } return code.AsEnumerable(); } } class NewMovement_ForceAntiHP { static FieldInfo hpField = typeof(NewMovement).GetField("hp"); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && (FieldInfo)code[i].operand == hpField) { i += 1; if (i < code.Count && code[i].opcode == OpCodes.Ldc_I4_S && (SByte)code[i].operand == (SByte)100) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } else if (code[i].opcode == OpCodes.Ldarg_1) { i += 2; if (i < code.Count && code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 99f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.maxPlayerHp.value - 1)); } } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 100f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)ConfigManager.maxPlayerHp.value); } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 50f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)ConfigManager.maxPlayerHp.value / 2); } else if (code[i].opcode == OpCodes.Ldc_I4_S && (SByte)code[i].operand == (SByte)100) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } return code.AsEnumerable(); } } class NewMovement_GetHealth { static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud) { if (__instance.dead || __instance.exploded) return false; int maxHp = Mathf.RoundToInt(ConfigManager.maxPlayerHp.value - __instance.antiHp); int maxDelta = maxHp - __instance.hp; if (maxDelta <= 0) return true; if (!__1 && __0 > 5 && MonoSingleton<PrefsManager>.Instance.GetBoolLocal("bloodEnabled", false)) { GameObject.Instantiate<GameObject>(__instance.scrnBlood, ___fullHud.transform); } __instance.hp = Mathf.Min(maxHp, __instance.hp + __0); __instance.hpFlash.Flash(1f); if (!__1 && __0 > 5) { if (___greenHpAud == null) { ___greenHpAud = __instance.hpFlash.GetComponent<AudioSource>(); } ___greenHpAud.Play(); } return false; } } class NewMovement_SuperCharge { static bool Prefix(NewMovement __instance) { __instance.hp = Mathf.Max(ConfigManager.maxPlayerHp.value, ConfigManager.playerHpSupercharge.value); return false; } } class NewMovement_Respawn { static void Postfix(NewMovement __instance) { __instance.hp = ConfigManager.maxPlayerHp.value; } } class NewMovement_DeltaHpComp : MonoBehaviour { public static NewMovement_DeltaHpComp instance; private NewMovement player; private AudioSource hurtAud; private bool levelMap = false; private void Awake() { instance = this; player = NewMovement.Instance; hurtAud = player.hurtScreen.GetComponent<AudioSource>(); levelMap = SceneHelper.CurrentLevelNumber > 0; UpdateEnabled(); } public void UpdateEnabled() { if (!ConfigManager.playerHpDeltaToggle.value) enabled = false; if (SceneHelper.CurrentScene == "uk_construct") enabled = ConfigManager.playerHpDeltaSandbox.value; else if (SceneHelper.CurrentScene == "Endless") enabled = ConfigManager.playerHpDeltaCybergrind.value; else { enabled = SceneHelper.CurrentLevelNumber > 0; } } public void ResetCooldown() { deltaCooldown = ConfigManager.playerHpDeltaDelay.value; } public float deltaCooldown = ConfigManager.playerHpDeltaDelay.value; public void Update() { if (player.dead || !ConfigManager.playerHpDeltaToggle.value || !StatsManager.Instance.timer) { ResetCooldown(); return; } if (levelMap) { // Calm if (MusicManager.Instance.requestedThemes == 0) { if (!ConfigManager.playerHpDeltaCalm.value) { ResetCooldown(); return; } } // Combat else { if (!ConfigManager.playerHpDeltaCombat.value) { ResetCooldown(); return; } } } deltaCooldown = Mathf.MoveTowards(deltaCooldown, 0f, Time.deltaTime); if (deltaCooldown == 0f) { ResetCooldown(); int deltaHp = ConfigManager.playerHpDeltaAmount.value; int limit = ConfigManager.playerHpDeltaLimit.value; if (deltaHp == 0) return; if (deltaHp > 0) { if (player.hp > limit) return; player.GetHealth(deltaHp, true); } else { if (player.hp < limit) return; if (player.hp - deltaHp <= 0) player.GetHurt(-deltaHp, false, 0, false, false); else { player.hp += deltaHp; if (ConfigManager.playerHpDeltaHurtAudio.value) { hurtAud.pitch = UnityEngine.Random.Range(0.8f, 1f); hurtAud.PlayOneShot(hurtAud.clip); } } } } } } class NewMovement_Start { static void Postfix(NewMovement __instance) { __instance.gameObject.AddComponent<NewMovement_DeltaHpComp>(); __instance.hp = ConfigManager.maxPlayerHp.value; } } class HealthBarTracker : MonoBehaviour { public static List<HealthBarTracker> instances = new List<HealthBarTracker>(); private HealthBar hb; private void Awake() { if (hb == null) hb = GetComponent<HealthBar>(); instances.Add(this); for (int i = instances.Count - 1; i >= 0; i--) { if (instances[i] == null) instances.RemoveAt(i); } } private void OnDestroy() { if (instances.Contains(this)) instances.Remove(this); } public void SetSliderRange() { if (hb == null) hb = GetComponent<HealthBar>(); if (hb.hpSliders.Length != 0) { hb.hpSliders[0].maxValue = hb.afterImageSliders[0].maxValue = ConfigManager.maxPlayerHp.value; hb.hpSliders[1].minValue = hb.afterImageSliders[1].minValue = ConfigManager.maxPlayerHp.value; hb.hpSliders[1].maxValue = hb.afterImageSliders[1].maxValue = Mathf.Max(ConfigManager.maxPlayerHp.value, ConfigManager.playerHpSupercharge.value); hb.antiHpSlider.maxValue = ConfigManager.maxPlayerHp.value; } } } class HealthBar_Start { static void Postfix(HealthBar __instance) { __instance.gameObject.AddComponent<HealthBarTracker>().SetSliderRange(); } } class HealthBar_Update { static FieldInfo f_HealthBar_hp = typeof(HealthBar).GetField("hp", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); static FieldInfo f_HealthBar_antiHp = typeof(HealthBar).GetField("antiHp", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { CodeInstruction inst = code[i]; if (inst.opcode == OpCodes.Ldc_R4 && code[i - 1].OperandIs(f_HealthBar_hp)) { float operand = (Single)inst.operand; if (operand == 30f) code[i].operand = (Single)(ConfigManager.maxPlayerHp.value * 0.3f); else if (operand == 50f) code[i].operand = (Single)(ConfigManager.maxPlayerHp.value * 0.5f); } else if (inst.opcode == OpCodes.Ldstr) { string operand = (string)inst.operand; if (operand == "/200") code[i].operand = $"/{ConfigManager.playerHpSupercharge}"; } else if (inst.opcode == OpCodes.Ldc_R4 && i + 2 < code.Count && code[i + 2].OperandIs(f_HealthBar_antiHp)) { code[i].operand = (Single)ConfigManager.maxPlayerHp.value; } } return code.AsEnumerable(); } } }
Ultrapain/Patches/PlayerStatTweaks.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.7949020862579346 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " //readonly static FieldInfo maliciousIgnorePlayer = typeof(RevolverBeam).GetField(\"maliciousIgnorePlayer\", BindingFlags.NonPublic | BindingFlags.Instance);\n Transform shootPoint;\n public Transform v2trans;\n public float cooldown = 0f;\n static readonly string debugTag = \"[V2][MalCannonShoot]\";\n void Awake()\n {\n shootPoint = UnityUtils.GetChildByNameRecursively(transform, \"Shootpoint\");\n }\n void PrepareFire()", "score": 0.7926267385482788 }, { "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.7894701957702637 }, { "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.7852051854133606 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " }\n }\n class StatueBoss_Start_Patch\n {\n static void Postfix(StatueBoss __instance)\n {\n __instance.gameObject.AddComponent<CerberusFlag>();\n }\n }\n}", "score": 0.7835893630981445 } ]
csharp
GameObject supersaw) {
using System.Text.Json.Serialization; namespace LibreDteDotNet.RestRequest.Models.Response { public class ResLibroResumen { [JsonPropertyName("data")] public
ResDataLibroResumen? Data {
get; set; } [JsonPropertyName("metaData")] public ResMetaDataLibroResumen? MetaData { get; set; } [JsonPropertyName("respEstado")] public RespEstado? RespEstado { get; set; } } }
LibreDteDotNet.RestRequest/Models/Response/ResLibroResumen.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Models/Request/ReqLibroResumenCsv.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nusing LibreDteDotNet.RestRequest.Models.Response;\nnamespace LibreDteDotNet.RestRequest.Models.Request\n{\n public class ReqLibroResumenCsv\n {\n [JsonPropertyName(\"data\")]\n public List<string>? Data { get; set; }\n [JsonPropertyName(\"metaData\")]\n public ResMetaDataLibroResumen? MetaData { get; set; }", "score": 0.9221160411834717 }, { "filename": "LibreDteDotNet.RestRequest/Models/Response/ResDataLibroResumen.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace LibreDteDotNet.RestRequest.Models.Response\n{\n public class ResDataLibroResumen\n {\n [JsonPropertyName(\"resumenDte\")]\n public List<ResResumenDte>? ResumenDte { get; set; }\n [JsonPropertyName(\"datosAsync\")]\n public object? DatosAsync { get; set; }\n }", "score": 0.9040482044219971 }, { "filename": "LibreDteDotNet.RestRequest/Models/Request/ReqLibroResumen.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace LibreDteDotNet.RestRequest.Models.Request\n{\n internal class ReqLibroResumen\n {\n // Root myDeserializedClass = JsonSerializer.Deserialize<Root>(myJsonResponse);\n [JsonPropertyName(\"metaData\")]\n public ReqMetaDataLibroResumen? MetaData { get; set; }\n [JsonPropertyName(\"data\")]\n public ReqDataLibroResumen? Data { get; set; }", "score": 0.8995466828346252 }, { "filename": "LibreDteDotNet.RestRequest/Models/Response/ResLibroDetalle.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace LibreDteDotNet.RestRequest.Models.Response\n{\n public class ResLibroDetalle\n {\n [JsonPropertyName(\"data\")]\n public object Data { get; set; }\n [JsonPropertyName(\"dataResp\")]\n public DataResp DataResp { get; set; }\n [JsonPropertyName(\"dataReferencias\")]", "score": 0.881874144077301 }, { "filename": "LibreDteDotNet.RestRequest/Models/Response/ResMetaDataLibroResumen.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace LibreDteDotNet.RestRequest.Models.Response\n{\n public class ResMetaDataLibroResumen\n {\n [JsonPropertyName(\"conversationId\")]\n public string? ConversationId { get; set; }\n [JsonPropertyName(\"transactionId\")]\n public string? TransactionId { get; set; }\n [JsonPropertyName(\"namespace\")]", "score": 0.8446230888366699 } ]
csharp
ResDataLibroResumen? Data {
using objective.Core; using objective.Core.Enums; using objective.Models; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace objective.Forms.UI.Units { public class CellField : CellFieldBase { public static readonly DependencyProperty TypeProperty = DependencyProperty.Register("Type", typeof(CellType), typeof(CellField), new PropertyMetadata(CellType.Label)); public static readonly DependencyProperty ColumnSpanProperty = DependencyProperty.Register("ColumnSpan", typeof(int), typeof(CellField), new PropertyMetadata(1, ColumnSpanPropertyChanged)); public static readonly DependencyProperty RowSpanProperty = DependencyProperty.Register("RowSpan", typeof(int), typeof(CellField), new PropertyMetadata(1, RowSpanPropertyChanged)); public CellType Type { get { return (CellType)GetValue(TypeProperty); } set { SetValue(TypeProperty, value); } } public int ColumnSpan { get { return (int)GetValue(ColumnSpanProperty); } set { SetValue(ColumnSpanProperty, value); } } public int RowSpan { get { return (int)GetValue(RowSpanProperty); } set { SetValue(RowSpanProperty, value); } } static CellField() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CellField), new FrameworkPropertyMetadata(typeof(CellField))); } private static void ColumnSpanPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CellField control = (CellField)d; control.SetValue(Grid.ColumnSpanProperty, control.ColumnSpan); } private static void RowSpanPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CellField control = (CellField)d; control.SetValue(Grid.RowSpanProperty, control.RowSpan); } public override ReportObjectModel
GetProperties() {
ReportObjectModel obj = new(); obj.Width = Width; obj.CellType = Type; obj.FontWeight = FontWeight; obj.FontSize = FontSize; obj.Width = Width; obj.Height = Height; obj.RowSpan = RowSpan; obj.ColumnSpan = ColumnSpan; obj.Content = Content; return obj; } public CellField SetProperties(ReportObjectModel obj) { Width = obj.Width; Height = obj.Height; FontWeight = obj.FontWeight; FontSize = obj.FontSize; FontSize = obj.FontSize; Width = obj.Width; Height = obj.Height; RowSpan = obj.RowSpan; ColumnSpan = obj.ColumnSpan; Content = obj.Content; Type = obj.CellType; return this; } public override void SetLeft(double d) { throw new System.NotImplementedException (); } public override void SetTop(double d) { throw new System.NotImplementedException (); } public override void WidthSync(double d) { throw new System.NotImplementedException (); } } }
objective/objective/objective.Forms/UI/Units/CellField.cs
jamesnet214-objective-0e60b6f
[ { "filename": "objective/objective/objective.Forms/UI/Units/PageCanvas.cs", "retrieved_chunk": " AllowDrop = true;\n Drop += ListBox_Drop;\n }\n public override void OnApplyTemplate()\n {\n base.OnApplyTemplate();\n _canvas = GetTemplateChild(\"PART_Canvas\") as Canvas;\n }\n private static void ReportDataPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {", "score": 0.8130048513412476 }, { "filename": "objective/objective/objective.Core/ReportObject.cs", "retrieved_chunk": " {\n base.OnPropertyChanged(e);\n }\n public abstract void SetLeft(double d);\n public abstract void SetTop(double d);\n public abstract void WidthSync(double d);\n\t\t\t\tpublic T FindParent<T>(DependencyObject child) where T : IReportCanvas\n {\n DependencyObject parent = VisualTreeHelper.GetParent(child);\n if (parent == null)", "score": 0.8052232265472412 }, { "filename": "objective/objective/objective.Forms/UI/Units/PageCanvas.cs", "retrieved_chunk": " {\n get { return (ObservableCollection<ReportObject>)GetValue(ReportDataProperty); }\n set { SetValue(ReportDataProperty, value); }\n }\n static PageCanvas()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(PageCanvas), new FrameworkPropertyMetadata(typeof(PageCanvas)));\n }\n public PageCanvas()\n {", "score": 0.7960673570632935 }, { "filename": "objective/objective/objective.Forms/UI/Units/HorizontalLine.cs", "retrieved_chunk": "\t\t\t\t{\n\t\t\t\t\t\tDefaultStyleKeyProperty.OverrideMetadata (typeof (HorizontalLine), new FrameworkPropertyMetadata (typeof (HorizontalLine)));\n\t\t\t\t}\n\t\t\t\tpublic HorizontalLine()\n\t\t\t\t{\n\t\t\t\t\t\tWidth = 700;\n\t\t\t\t\t\tBorderThickness = new Thickness (0, 0, 0, 1);\n\t\t\t\t\t\tBackground = new SolidColorBrush ((Color)ColorConverter.ConvertFromString (\"#000000\"));\n\t\t\t\t}\n\t\t\t\tpublic override ReportObjectModel GetProperties()", "score": 0.7914927005767822 }, { "filename": "objective/objective/objective.Forms/UI/Units/ToolGrid.cs", "retrieved_chunk": "\t\t\t\t\t\tget { return (IEnumerable)GetValue (SelectItemSourceProperty); }\n\t\t\t\t\t\tset { SetValue (SelectItemSourceProperty, value); }\n\t\t\t\t}\n\t\t\t\t// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...\n\t\t\t\tpublic static readonly DependencyProperty SelectItemSourceProperty =\n\t\t\t\t\tDependencyProperty.Register (\"SelectItemSource\", typeof (IEnumerable), typeof (ToolGrid), new PropertyMetadata (null));\n\t\t\t\tstatic ToolGrid()\n\t\t\t\t{\n\t\t\t\t\t\tDefaultStyleKeyProperty.OverrideMetadata (typeof (ToolGrid), new FrameworkPropertyMetadata (typeof (ToolGrid)));\n\t\t\t\t}", "score": 0.7837824821472168 } ]
csharp
GetProperties() {
using ProcessHelpers; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; namespace ACCWindowManager { public class ACCWindowController : INotifyPropertyChanged { public enum ErrorCode { NoError, SteamNotFound, ACCAlreadyRunning, ACCIsNotRunning, ACCMainWindowNotFound, } public Action ACCDetected; public Action ACCResized; public Action SelectedWindowPropertiesChanged; public List<KeyValuePair<string, WindowProperties>> Settings { get { return m_settings; } set { m_settings = value; OnPropertyChanged(nameof(Settings)); } } public KeyValuePair<string, WindowProperties> SelectedWindowProperties { get { return m_selectedWindowProperties; } set { m_selectedWindowProperties = value; OnPropertyChanged(nameof(SelectedWindowProperties)); SelectedWindowPropertiesChanged?.Invoke(); Properties.Settings.Default.SelectedProperty = SelectedWindowProperties.Key; } } public KeyValuePair<string,
WindowProperties> CustomWindowProperties {
get { return m_customWindowProperties; } set { m_customWindowProperties = value; OnPropertyChanged(nameof(CustomWindowProperties)); Properties.Settings.Default.CustomWindowProperties = CustomWindowProperties.Value; } } public ACCWindowController() { Settings = ACCData.DefaultWindowSettings.AllSettings.ToList(); var customProperties = Properties.Settings.Default.CustomWindowProperties; if (customProperties == null) { customProperties = Settings.First().Value; } CustomWindowProperties = new KeyValuePair<string, WindowProperties>(ACCData.DefaultWindowSettings.CustomSettingsName, customProperties); Settings.Add(CustomWindowProperties); KeyValuePair<string, WindowProperties>? selectedProperty = Settings.Find(setting => setting.Key == Properties.Settings.Default.SelectedProperty); if (selectedProperty == null) { selectedProperty = Settings.First(); } SelectedWindowProperties = (KeyValuePair<string, WindowProperties>)selectedProperty; m_winEventDelegate = new WinAPIHelpers.WinAPI.WinEventDelegate(WinEventProc); WinAPIHelpers.WinAPI.SetWinEventHook(WinAPIHelpers.WinAPI.EVENT_SYSTEM_FOREGROUND, WinAPIHelpers.WinAPI.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, m_winEventDelegate, 0, 0, WinAPIHelpers.WinAPI.EVENT_OUTOFCONTEXT); } public void Initialize() { Window accMainWindow; var errorCode = GetACCWindow(out accMainWindow); if (errorCode != ErrorCode.NoError) { return; } ACCDetected?.Invoke(); ResizeACCWindow(); } public ErrorCode LaunchACC() { var accProcess = Process.FindProcess(ACCData.ProcessInfo.AppName); if (accProcess != null) { return ErrorCode.ACCAlreadyRunning; } var accStarterProcess = new System.Diagnostics.Process(); accStarterProcess.StartInfo.FileName = "steam://rungameid/" + ACCData.ProcessInfo.AppID; accStarterProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; accStarterProcess.Start(); return ErrorCode.NoError; } public ErrorCode ResizeACCWindow() { Window accMainWindow; var errorCode = GetACCWindow(out accMainWindow); if (errorCode != ErrorCode.NoError) { return errorCode; } ResizeACCWindow(accMainWindow); return ErrorCode.NoError; } private ErrorCode GetACCWindow(out Window mainWindow) { mainWindow = null; var accProcess = Process.FindProcess(ACCData.ProcessInfo.AppName); if (accProcess == null) { return ErrorCode.ACCIsNotRunning; } var accWindows = WinAPIHelpers.WindowFinder.GetProcessWindows(accProcess); if (accWindows == null) { return ErrorCode.ACCIsNotRunning; } mainWindow = accWindows.FirstOrDefault(w => w.Name.Contains(ACCData.ProcessInfo.MainWindowName)); if (mainWindow == null) { return ErrorCode.ACCMainWindowNotFound; } return ErrorCode.NoError; } private void ResizeACCWindow(Window mainWindow) { if (!mainWindow.WindowInfo.ToProperties().Equals(m_selectedWindowProperties.Value)) { WindowManager.ApplyChanges(mainWindow, m_selectedWindowProperties.Value); } ACCResized?.Invoke(); } public void OnACCDetected() { Window accMainWindow; var errorCode = GetACCWindow(out accMainWindow); if (errorCode != ErrorCode.NoError) { return; } if (!accMainWindow.WindowInfo.ToProperties().Equals(m_selectedWindowProperties.Value)) { ACCDetected?.Invoke(); Task.Delay(10000).ContinueWith(_ => ResizeACCWindow(accMainWindow)); } } private List<KeyValuePair<string, WindowProperties>> m_settings; private KeyValuePair<string, WindowProperties> m_selectedWindowProperties; private KeyValuePair<string, WindowProperties> m_customWindowProperties; public void WinEventProc(IntPtr hWinEventHook, int eventType, int hWnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) { string activeWindowTitle = WinAPIHelpers.WindowFinder.GetActiveWindowTitle(); if (activeWindowTitle != null && activeWindowTitle.Contains(ACCData.ProcessInfo.AppName)) { OnACCDetected(); } } WinAPIHelpers.WinAPI.WinEventDelegate m_winEventDelegate; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
ACCWindowController.cs
kristofkerekes-acc-windowmanager-46578f1
[ { "filename": "MainWindow.xaml.cs", "retrieved_chunk": "\t\t\tget { return m_widthInput; }\n\t\t\tset {\n\t\t\t\tm_widthInput = value;\n\t\t\t\tOnPropertyChanged(nameof(WidthInput));\n\t\t\t\t// Invoke setter after modifying nested property\n\t\t\t\tWindowController.CustomWindowProperties.Value.Width = value;\n\t\t\t\tWindowController.CustomWindowProperties = WindowController.CustomWindowProperties;\n\t\t\t}\n\t\t}\n\t\tpublic int HeightInput {", "score": 0.8885880708694458 }, { "filename": "MainWindow.xaml.cs", "retrieved_chunk": "\t\t\tget { return m_heightInput; }\n\t\t\tset {\n\t\t\t\tm_heightInput = value;\n\t\t\t\tOnPropertyChanged(nameof(HeightInput));\n\t\t\t\tWindowController.CustomWindowProperties.Value.Height = value;\n\t\t\t\tWindowController.CustomWindowProperties = WindowController.CustomWindowProperties;\n\t\t\t}\n\t\t}\n\t\tpublic int PosXInput {\n\t\t\tget { return m_posXInput; }", "score": 0.8646116256713867 }, { "filename": "MainWindow.xaml.cs", "retrieved_chunk": "\t\t\tset {\n\t\t\t\tm_posXInput = value;\n\t\t\t\tOnPropertyChanged(nameof(PosXInput));\n\t\t\t\tWindowController.CustomWindowProperties.Value.PosX = value;\n\t\t\t\tWindowController.CustomWindowProperties = WindowController.CustomWindowProperties;\n\t\t\t}\n\t\t}\n\t\tpublic int PosYInput {\n\t\t\tget { return m_posYInput; }\n\t\t\tset {", "score": 0.845933735370636 }, { "filename": "MainWindow.xaml.cs", "retrieved_chunk": "\t\t\tPosXInput = WindowController.CustomWindowProperties.Value.PosX;\n\t\t\tPosYInput = WindowController.CustomWindowProperties.Value.PosY;\n\t\t}\n\t\tpublic event PropertyChangedEventHandler PropertyChanged;\n\t\tprivate void OnPropertyChanged(string propertyName) {\n\t\t\tif (PropertyChanged != null) {\n\t\t\t\tPropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n\t\t\t}\n\t\t}\n\t}", "score": 0.8341943025588989 }, { "filename": "MainWindow.xaml.cs", "retrieved_chunk": "\t\t\t}\n\t\t}\n\t\tpublic Visibility CustomSettingsVisible {\n\t\t\tget { return m_customSettingsVisible; }\n\t\t\tset {\n\t\t\t\tm_customSettingsVisible = value;\n\t\t\t\tOnPropertyChanged(nameof(CustomSettingsVisible));\n\t\t\t}\n\t\t}\n\t\tpublic int WidthInput {", "score": 0.8262957334518433 } ]
csharp
WindowProperties> CustomWindowProperties {
#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": "#nullable enable\nusing System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing Cysharp.Threading.Tasks;\nusing Mochineko.Relent.Result;\nnamespace Mochineko.RelentStateMachine\n{\n public sealed class StackStateMachine<TContext>\n : IStackStateMachine<TContext>", "score": 0.9078274965286255 }, { "filename": "Assets/Mochineko/RelentStateMachine/FiniteStateMachine.cs", "retrieved_chunk": "#nullable enable\nusing System;\nusing System.Threading;\nusing Cysharp.Threading.Tasks;\nusing Mochineko.Relent.Result;\nnamespace Mochineko.RelentStateMachine\n{\n public sealed class FiniteStateMachine<TEvent, TContext>\n : IFiniteStateMachine<TEvent, TContext>\n {", "score": 0.9021233320236206 }, { "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.8982861042022705 }, { "filename": "Assets/Mochineko/RelentStateMachine.Tests/MockStackContext.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nnamespace Mochineko.RelentStateMachine.Tests\n{\n internal sealed class MockStackContext\n {\n public Stack<IPopToken> PopTokenStack = new();\n }\n}", "score": 0.8839242458343506 }, { "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.8677539229393005 } ]
csharp
IStateStoreBuilder<TContext> {
using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Text; using ULTRAKILL.Cheats; using UnityEngine; namespace Ultrapain.Patches { class Leviathan_Flag : MonoBehaviour { private LeviathanHead comp; private Animator anim; //private Collider col; private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 }; public float playerRocketRideTracker = 0; private GameObject currentProjectileEffect; private AudioSource currentProjectileAud; private Transform shootPoint; public float currentProjectileSize = 0; public float beamChargeRate = 12f / 1f; public int beamRemaining = 0; public int projectilesRemaining = 0; public float projectileDelayRemaining = 0f; private static FieldInfo ___inAction = typeof(LeviathanHead).GetField("inAction", BindingFlags.NonPublic | BindingFlags.Instance); private void Awake() { comp = GetComponent<LeviathanHead>(); anim = GetComponent<Animator>(); //col = GetComponent<Collider>(); } public bool beamAttack = false; public bool projectileAttack = false; public bool charging = false; private void Update() { if (currentProjectileEffect != null && (charging || currentProjectileSize < 11.9f)) { currentProjectileSize += beamChargeRate * Time.deltaTime; currentProjectileEffect.transform.localScale = Vector3.one * currentProjectileSize; currentProjectileAud.pitch = currentProjectileSize / 2; } } public void ChargeBeam(Transform shootPoint) { if (currentProjectileEffect != null) return; this.shootPoint = shootPoint; charging = true; currentProjectileSize = 0; currentProjectileEffect = GameObject.Instantiate(Plugin.chargeEffect, shootPoint); currentProjectileAud = currentProjectileEffect.GetComponent<AudioSource>(); currentProjectileEffect.transform.localPosition = new Vector3(0, 0, 6); currentProjectileEffect.transform.localScale = Vector3.zero; beamRemaining = ConfigManager.leviathanChargeCount.value; beamChargeRate = 11.9f / ConfigManager.leviathanChargeDelay.value; Invoke("PrepareForFire", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } private Grenade FindTargetGrenade() { List<Grenade> list = GrenadeList.Instance.grenadeList; Grenade targetGrenade = null; Vector3 playerPos = PlayerTracker.Instance.GetTarget().position; foreach (Grenade grn in list) { if (Vector3.Distance(grn.transform.position, playerPos) <= 10f) { targetGrenade = grn; break; } } return targetGrenade; } private Grenade targetGrenade = null; public void PrepareForFire() { charging = false; // OLD PREDICTION //targetShootPoint = NewMovement.Instance.playerCollider.bounds.center; //if (Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out RaycastHit hit, float.MaxValue, envMask)) // targetShootPoint = hit.point; // Malicious face beam prediction GameObject player = MonoSingleton<PlayerTracker>.Instance.GetPlayer().gameObject; Vector3 a = new Vector3(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().x, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().y / (float)(MonoSingleton<NewMovement>.Instance.ridingRocket ? 1 : 2), MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().z); targetShootPoint = (MonoSingleton<NewMovement>.Instance.ridingRocket ? MonoSingleton<NewMovement>.Instance.ridingRocket.transform.position : player.transform.position) + a / (1f / ConfigManager.leviathanChargeDelay.value) / comp.lcon.eid.totalSpeedModifier; RaycastHit raycastHit; // I guess this was in case player is approaching the malface, but it is very unlikely with leviathan /*if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude > 0f && col.Raycast(new Ray(player.transform.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity()), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.5f / comp.lcon.eid.totalSpeedModifier)) { targetShootPoint = player.transform.position; } else */if (Physics.Raycast(player.transform.position, targetShootPoint - player.transform.position, out raycastHit, Vector3.Distance(targetShootPoint, player.transform.position), LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { targetShootPoint = raycastHit.point; } Invoke("Shoot", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } private Vector3 RandomVector(float min, float max) { return new Vector3(UnityEngine.Random.Range(min, max), UnityEngine.Random.Range(min, max), UnityEngine.Random.Range(min, max)); } public Vector3 targetShootPoint; private void Shoot() { Debug.Log("Attempting to shoot projectile for leviathan"); GameObject proj = GameObject.Instantiate(Plugin.maliciousFaceProjectile, shootPoint.transform.position, Quaternion.identity); if (targetGrenade == null) targetGrenade = FindTargetGrenade(); if (targetGrenade != null) { //NewMovement.Instance.playerCollider.bounds.center //proj.transform.rotation = Quaternion.LookRotation(targetGrenade.transform.position - shootPoint.transform.position); proj.transform.rotation = Quaternion.LookRotation(targetGrenade.transform.position - shootPoint.transform.position); } else { proj.transform.rotation = Quaternion.LookRotation(targetShootPoint - proj.transform.position); //proj.transform.rotation = Quaternion.LookRotation(NewMovement.Instance.playerCollider.bounds.center - proj.transform.position); //proj.transform.eulerAngles += RandomVector(-5f, 5f); } proj.transform.localScale = new Vector3(2f, 1f, 2f); if (proj.TryGetComponent(out RevolverBeam projComp)) { GameObject expClone = GameObject.Instantiate(projComp.hitParticle, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); foreach (Explosion exp in expClone.GetComponentsInChildren<Explosion>()) { exp.maxSize *= ConfigManager.leviathanChargeSizeMulti.value; exp.speed *= ConfigManager.leviathanChargeSizeMulti.value; exp.damage = (int)(exp.damage * ConfigManager.leviathanChargeDamageMulti.value * comp.lcon.eid.totalDamageModifier); exp.toIgnore.Add(EnemyType.Leviathan); } projComp.damage *= 2 * comp.lcon.eid.totalDamageModifier; projComp.hitParticle = expClone; } beamRemaining -= 1; if (beamRemaining <= 0) { Destroy(currentProjectileEffect); currentProjectileSize = 0; beamAttack = false; if (projectilesRemaining <= 0) { comp.lookAtPlayer = false; anim.SetBool("ProjectileBurst", false); ___inAction.SetValue(comp, false); targetGrenade = null; } else { comp.lookAtPlayer = true; projectileAttack = true; } } else { targetShootPoint = NewMovement.Instance.playerCollider.bounds.center; if (Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out RaycastHit hit, float.MaxValue, envMask)) targetShootPoint = hit.point; comp.lookAtPlayer = true; Invoke("PrepareForFire", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } } private void SwitchToSecondPhase() { comp.lcon.phaseChangeHealth = comp.lcon.stat.health; } } class LeviathanTail_Flag : MonoBehaviour { public int swingCount = 0; private Animator ___anim; private void Awake() { ___anim = GetComponent<Animator>(); } public static float crossfadeDuration = 0.05f; private void SwingAgain() { ___anim.CrossFade("TailWhip", crossfadeDuration, 0, LeviathanTail_SwingEnd.targetStartNormalized); } } class Leviathan_Start { static void Postfix(LeviathanHead __instance) { Leviathan_Flag flag = __instance.gameObject.AddComponent<Leviathan_Flag>(); if(ConfigManager.leviathanSecondPhaseBegin.value) flag.Invoke("SwitchToSecondPhase", 2f / __instance.lcon.eid.totalSpeedModifier); } } class Leviathan_FixedUpdate { public static float projectileForward = 10f; static bool Roll(float chancePercent) { return UnityEngine.Random.Range(0, 99.9f) <= chancePercent; } static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown,
Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack) {
if (!__instance.active) { return false; } Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (___projectileBursting && flag.projectileAttack) { if (flag.projectileDelayRemaining > 0f) { flag.projectileDelayRemaining = Mathf.MoveTowards(flag.projectileDelayRemaining, 0f, Time.deltaTime * __instance.lcon.eid.totalSpeedModifier); } else { flag.projectilesRemaining -= 1; flag.projectileDelayRemaining = (1f / ConfigManager.leviathanProjectileDensity.value) / __instance.lcon.eid.totalSpeedModifier; GameObject proj = null; Projectile comp = null; if (Roll(ConfigManager.leviathanProjectileYellowChance.value) && ConfigManager.leviathanProjectileMixToggle.value) { proj = GameObject.Instantiate(Plugin.hideousMassProjectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); comp.safeEnemyType = EnemyType.Leviathan; // values from p2 flesh prison comp.turnSpeed *= 4f; comp.turningSpeedMultiplier *= 4f; comp.predictiveHomingMultiplier = 1.25f; } else if (Roll(ConfigManager.leviathanProjectileBlueChance.value) && ConfigManager.leviathanProjectileMixToggle.value) { proj = GameObject.Instantiate(Plugin.homingProjectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); comp.safeEnemyType = EnemyType.Leviathan; // values from mindflayer comp.turningSpeedMultiplier = 0.5f; comp.speed = 20f; comp.speed *= ___lcon.eid.totalSpeedModifier; comp.damage *= ___lcon.eid.totalDamageModifier; } else { proj = GameObject.Instantiate<GameObject>(MonoSingleton<DefaultReferenceManager>.Instance.projectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.safeEnemyType = EnemyType.Leviathan; comp.speed *= 2f; comp.enemyDamageMultiplier = 0.5f; } comp.speed *= __instance.lcon.eid.totalSpeedModifier; comp.damage *= __instance.lcon.eid.totalDamageModifier; comp.safeEnemyType = EnemyType.Leviathan; comp.enemyDamageMultiplier = ConfigManager.leviathanProjectileFriendlyFireDamageMultiplier.normalizedValue; proj.transform.localScale *= 2f; proj.transform.position += proj.transform.forward * projectileForward; } } if (___projectileBursting) { if (flag.projectilesRemaining <= 0 || BlindEnemies.Blind) { flag.projectileAttack = false; if (!flag.beamAttack) { ___projectileBursting = false; ___trackerIgnoreLimits = false; ___anim.SetBool("ProjectileBurst", false); } } else { if (NewMovement.Instance.ridingRocket != null && ConfigManager.leviathanChargeAttack.value && ConfigManager.leviathanChargeHauntRocketRiding.value) { flag.playerRocketRideTracker += Time.deltaTime; if (flag.playerRocketRideTracker >= 1 && !flag.beamAttack) { flag.projectileAttack = false; flag.beamAttack = true; __instance.lookAtPlayer = true; flag.ChargeBeam(___shootPoint); flag.beamRemaining = 1; return false; } } else { flag.playerRocketRideTracker = 0; } } } return false; } } class Leviathan_ProjectileBurst { static bool Prefix(LeviathanHead __instance, Animator ___anim, ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction) { if (!__instance.active) { return false; } Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (flag.beamAttack || flag.projectileAttack) return false; flag.beamAttack = false; if (ConfigManager.leviathanChargeAttack.value) { if (NewMovement.Instance.ridingRocket != null && ConfigManager.leviathanChargeHauntRocketRiding.value) { flag.beamAttack = true; } else if (UnityEngine.Random.Range(0, 99.9f) <= ConfigManager.leviathanChargeChance.value && ConfigManager.leviathanChargeAttack.value) { flag.beamAttack = true; } } flag.projectileAttack = true; return true; /*if (!beamAttack) { flag.projectileAttack = true; return true; }*/ /*if(flag.beamAttack) { Debug.Log("Attempting to prepare beam for leviathan"); ___anim.SetBool("ProjectileBurst", true); //___projectilesLeftInBurst = 1; //___projectileBurstCooldown = 100f; ___inAction = true; return true; }*/ } } class Leviathan_ProjectileBurstStart { static bool Prefix(LeviathanHead __instance, Transform ___shootPoint) { Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (flag.projectileAttack) { if(flag.projectilesRemaining <= 0) { flag.projectilesRemaining = ConfigManager.leviathanProjectileCount.value; flag.projectileDelayRemaining = 0; } } if (flag.beamAttack) { if (!flag.charging) { Debug.Log("Attempting to charge beam for leviathan"); __instance.lookAtPlayer = true; flag.ChargeBeam(___shootPoint); } } return true; } } class LeviathanTail_Start { static void Postfix(LeviathanTail __instance) { __instance.gameObject.AddComponent<LeviathanTail_Flag>(); } } // This is the tail attack animation begin // fires at n=3.138 // l=5.3333 // 0.336 // 0.88 class LeviathanTail_BigSplash { static bool Prefix(LeviathanTail __instance) { LeviathanTail_Flag flag = __instance.gameObject.GetComponent<LeviathanTail_Flag>(); if (flag == null) return true; flag.swingCount = ConfigManager.leviathanTailComboCount.value; return true; } } class LeviathanTail_SwingEnd { public static float targetEndNormalized = 0.7344f; public static float targetStartNormalized = 0.41f; static bool Prefix(LeviathanTail __instance, Animator ___anim) { LeviathanTail_Flag flag = __instance.gameObject.GetComponent<LeviathanTail_Flag>(); if (flag == null) return true; flag.swingCount -= 1; if (flag.swingCount == 0) return true; flag.Invoke("SwingAgain", Mathf.Max(0f, 5.3333f * (0.88f - targetEndNormalized) * (1f / ___anim.speed))); return false; } } }
Ultrapain/Patches/Leviathan.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.8679111003875732 }, { "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.8478441834449768 }, { "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.8459437489509583 }, { "filename": "Ultrapain/Patches/Screwdriver.cs", "retrieved_chunk": " {\n public static float forwardForce = 10f;\n public static float upwardForce = 10f;\n static LayerMask envLayer = new LayerMask() { m_Mask = 16777472 };\n private static Harpoon lastHarpoon;\n static bool Prefix(Harpoon __instance, Collider __0)\n {\n if (!__instance.drill)\n return true;\n if(__0.TryGetComponent(out EnemyIdentifierIdentifier eii))", "score": 0.8456364870071411 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " }\n class V2SecondFastCoin\n {\n static MethodInfo switchWeapon = typeof(V2).GetMethod(\"SwitchWeapon\", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);\n static bool Prefix(V2 __instance, ref int ___coinsToThrow, ref bool ___aboutToShoot, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb,\n ref Transform ___target, Animator ___anim, ref bool ___shootingForCoin, ref int ___currentWeapon, ref float ___shootCooldown, ref bool ___aiming)\n {\n if (___coinsToThrow == 0)\n {\n return false;", "score": 0.8409042358398438 } ]
csharp
Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack) {
using VRC.SDK3.Data; using Koyashiro.GenericDataContainer.Internal; namespace Koyashiro.GenericDataContainer { public static class DataListExt { public static int Capacity<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return dataList.Capacity; } public static int Count<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return dataList.Count; } public static void Add<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.Add(token); } public static void AddRange<T>(this
DataList<T> list, T[] collection) {
foreach (var item in collection) { list.Add(item); } } public static void AddRange<T>(this DataList<T> list, DataList<T> collection) { var dataList = (DataList)(object)(list); var tokens = (DataList)(object)collection; dataList.AddRange(tokens); } public static void BinarySearch<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.BinarySearch(token); } public static void BinarySearch<T>(this DataList<T> list, int index, int count, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.BinarySearch(index, count, token); } public static void Clear<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Clear(); } public static bool Contains<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.Contains(token); } public static DataList<T> DeepClone<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.DeepClone(); } public static DataList<T> GetRange<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.GetRange(index, count); } public static int IndexOf<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token); } public static int IndexOf<T>(this DataList<T> list, T item, int index) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token, index); } public static int IndexOf<T>(this DataList<T> list, T item, int index, int count) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token, index, count); } public static void Insert<T>(this DataList<T> list, int index, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.Insert(index, token); } public static void InsertRange<T>(this DataList<T> list, int index, T[] collection) { for (var i = index; i < collection.Length; i++) { list.Insert(i, collection[i]); } } public static void InsertRange<T>(this DataList<T> list, int index, DataList<T> collection) { var dataList = (DataList)(object)(list); var tokens = (DataList)(object)collection; dataList.InsertRange(index, tokens); } public static int LastIndexOf<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token); } public static int LastIndexOf<T>(this DataList<T> list, T item, int index) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token, index); } public static int LastIndexOf<T>(this DataList<T> list, T item, int index, int count) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token, index, count); } public static bool Remove<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.Remove(token); } public static bool RemoveAll<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.RemoveAll(token); } public static void RemoveAt<T>(this DataList<T> list, int index) { var dataList = (DataList)(object)(list); dataList.RemoveAt(index); } public static void RemoveRange<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.RemoveRange(index, count); } public static void Reverse<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Reverse(); } public static void Reverse<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.Reverse(index, count); } public static void SetValue<T>(this DataList<T> list, int index, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.SetValue(index, token); } public static DataList<T> ShallowClone<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.ShallowClone(); } public static void Sort<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Sort(); } public static void Sort<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.Sort(index, count); } public static T[] ToArray<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); var length = dataList.Count; var array = new T[length]; for (var i = 0; i < length; i++) { var token = dataList[i]; switch (token.TokenType) { case TokenType.Reference: array[i] = (T)token.Reference; break; default: array[i] = (T)(object)token; break; } } return array; } public static object[] ToObjectArray<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); var length = dataList.Count; var array = new object[length]; for (var i = 0; i < length; i++) { var token = dataList[i]; switch (token.TokenType) { case TokenType.Reference: array[i] = (T)token.Reference; break; default: array[i] = (T)(object)token; break; } } return array; } public static void TrimExcess<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.TrimExcess(); } public static bool TryGetValue<T>(this DataList<T> list, int index, out T value) { var dataList = (DataList)(object)(list); if (!dataList.TryGetValue(index, out var token)) { value = default; return false; } switch (token.TokenType) { case TokenType.Reference: value = (T)token.Reference; break; default: value = (T)(object)token; break; } return true; } public static T GetValue<T>(this DataList<T> list, int index) { var dataList = (DataList)(object)(list); var token = dataList[index]; switch (token.TokenType) { case TokenType.Reference: return (T)token.Reference; default: return (T)(object)token; } } } }
Packages/net.koyashiro.genericdatacontainer/Runtime/DataListExt.cs
koyashiro-generic-data-container-1aef372
[ { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataList.cs", "retrieved_chunk": " {\n return (DataList<T>)(object)new DataList();\n }\n public static DataList<T> New(params T[] array)\n {\n var tokens = DataTokenUtil.NewDataTokens(array);\n return (DataList<T>)(object)new DataList(tokens);\n }\n }\n}", "score": 0.890123724937439 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " }\n public static void Add<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, TValue value)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n var valueToken = DataTokenUtil.NewDataToken(value);\n dataDictionary.Add(keyToken, valueToken);\n }\n public static void Clear<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary)\n {", "score": 0.8712003231048584 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " return result;\n }\n public static void SetValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, TValue value)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n var keyValue = DataTokenUtil.NewDataToken(value);\n dataDictionary.SetValue(keyToken, keyValue);\n }\n public static DataDictionary<TKey, TValue> ShallowClone<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary)", "score": 0.8498222827911377 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " var dataDictionary = (DataDictionary)(object)(dictionary);\n dataDictionary.Clear();\n }\n public static bool ContainsKey<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n return dataDictionary.ContainsKey(keyToken);\n }\n public static bool ContainsValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TValue value)", "score": 0.8427997827529907 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " break;\n }\n return true;\n }\n public static TValue GetValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n var valueToken = dataDictionary[keyToken];\n switch (valueToken.TokenType)", "score": 0.8309763669967651 } ]
csharp
DataList<T> list, T[] collection) {
using System.Linq; using Sandland.SceneTool.Editor.Common.Data; using Sandland.SceneTool.Editor.Common.Utils; using Sandland.SceneTool.Editor.Services; using Sandland.SceneTool.Editor.Views.Base; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace Sandland.SceneTool.Editor.Views { internal class SceneSelectorWindow : SceneToolsWindowBase { private const string WindowNameInternal = "Scene Selector"; private const string KeyboardShortcut = " %g"; private const string WindowMenuItem = MenuItems.Tools.Root + WindowNameInternal + KeyboardShortcut; public override float
MinWidth => 460;
public override float MinHeight => 600; public override string WindowName => WindowNameInternal; public override string VisualTreeName => nameof(SceneSelectorWindow); public override string StyleSheetName => nameof(SceneSelectorWindow); private SceneInfo[] _sceneInfos; private SceneInfo[] _filteredSceneInfos; private ListView _sceneList; private TextField _searchField; [MenuItem(WindowMenuItem)] public static void ShowWindow() { var window = GetWindow<SceneSelectorWindow>(); window.InitWindow(); window._searchField?.Focus(); } protected override void OnEnable() { base.OnEnable(); FavoritesService.FavoritesChanged += OnFavoritesChanged; } protected override void OnDisable() { base.OnDisable(); FavoritesService.FavoritesChanged -= OnFavoritesChanged; } protected override void InitGui() { _sceneInfos = AssetDatabaseUtils.FindScenes(); _filteredSceneInfos = GetFilteredSceneInfos(); _sceneList = rootVisualElement.Q<ListView>("scenes-list"); _sceneList.makeItem = () => new SceneItemView(); _sceneList.bindItem = InitListItem; _sceneList.fixedItemHeight = SceneItemView.FixedHeight; _sceneList.itemsSource = _filteredSceneInfos; _searchField = rootVisualElement.Q<TextField>("scenes-search"); _searchField.RegisterValueChangedCallback(OnSearchValueChanged); _searchField.Focus(); _searchField.SelectAll(); } private void OnSearchValueChanged(ChangeEvent<string> @event) => RebuildItems(@event.newValue); private void OnFavoritesChanged() => RebuildItems(); private void RebuildItems(string filter = null) { _filteredSceneInfos = GetFilteredSceneInfos(filter); _sceneList.itemsSource = _filteredSceneInfos; _sceneList.Rebuild(); } private SceneInfo[] GetFilteredSceneInfos(string filter = null) { var isFilterEmpty = string.IsNullOrWhiteSpace(filter); return _sceneInfos .Where(s => isFilterEmpty || s.Name.ToUpper().Contains(filter.ToUpper())) .OrderByFavorites() .ThenByDescending(s => s.ImportType == SceneImportType.BuildSettings) .ThenByDescending(s => s.ImportType == SceneImportType.Addressables) .ThenByDescending(s => s.ImportType == SceneImportType.AssetBundle) .ToArray(); } private void InitListItem(VisualElement element, int dataIndex) { var sceneView = (SceneItemView)element; sceneView.Init(_filteredSceneInfos[dataIndex]); } } }
Assets/SceneTools/Editor/Views/SceneSelectorWindow/SceneSelectorWindow.cs
migus88-Sandland.SceneTools-64e9f8c
[ { "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.9106249809265137 }, { "filename": "Assets/SceneTools/Editor/Common/Utils/MenuItems.cs", "retrieved_chunk": "namespace Sandland.SceneTool.Editor.Common.Utils\n{\n internal static class MenuItems\n {\n public static class Tools\n {\n public const string Root = \"Tools/Sandland Games/\";\n public const string Actions = Root + \"Actions/\";\n }\n public static class Creation", "score": 0.8990117311477661 }, { "filename": "Assets/SceneTools/Editor/Listeners/SceneClassGenerationListener.cs", "retrieved_chunk": "using UnityEditor.AddressableAssets.Settings;\n#endif\nnamespace Sandland.SceneTool.Editor.Listeners\n{\n internal static class SceneClassGenerationListener\n {\n [InitializeOnLoadMethod]\n private static void Initialize()\n {\n EditorBuildSettings.sceneListChanged += GenerateScenesClass;", "score": 0.8400002121925354 }, { "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.8311184048652649 }, { "filename": "Assets/SceneTools/Editor/Common/Data/SceneInfo.cs", "retrieved_chunk": "using System.Collections.Generic;\nnamespace Sandland.SceneTool.Editor.Common.Data\n{\n internal class SceneInfo : AssetFileInfo\n {\n public int BuildIndex { get; set; }\n public string Address { get; set; }\n public SceneImportType ImportType { get; set; }\n private SceneInfo(string name, string path, string guid, string bundleName, List<string> labels) : base(name, path, guid, bundleName, labels)\n {", "score": 0.8290756940841675 } ]
csharp
MinWidth => 460;
#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.9007003307342529 }, { "filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs", "retrieved_chunk": " BuildReadonlyTransitionMap(),\n anyTransitionMap);\n // Cannot reuse builder after build.\n this.Dispose();\n return result;\n }\n private IReadOnlyDictionary<\n IState<TEvent, TContext>,\n IReadOnlyDictionary<TEvent, IState<TEvent, TContext>>>\n BuildReadonlyTransitionMap()", "score": 0.8645638227462769 }, { "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.8630362749099731 }, { "filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs", "retrieved_chunk": " }\n else\n {\n transitions.Add(@event, toState);\n }\n }\n else\n {\n var newTransitions = new Dictionary<TEvent, IState<TEvent, TContext>>();\n newTransitions.Add(@event, toState);", "score": 0.8626829385757446 }, { "filename": "Assets/Mochineko/RelentStateMachine/TransitionMapBuilder.cs", "retrieved_chunk": " transitionMap.Add(fromState, newTransitions);\n }\n }\n public void RegisterAnyTransition<TToState>(TEvent @event)\n where TToState : IState<TEvent, TContext>, new()\n {\n if (disposed)\n {\n throw new ObjectDisposedException(nameof(TransitionMapBuilder<TEvent, TContext>));\n }", "score": 0.8550323247909546 } ]
csharp
ITransitionMap<TEvent, TContext>.InitialState => initialState;
using UnityEditor; using UnityEditor.Timeline; using UnityEngine; using UnityEngine.Timeline; namespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor { internal static class AbstractFloatValueControlTrackEditorUtility { internal static Color PrimaryColor = new(1f, 0.5f, 0.5f); } [CustomTimelineEditor(typeof(AbstractFloatValueControlTrack))] public class AbstractFloatValueControlTrackCustomEditor : TrackEditor { public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding) { track.name = "CustomTrack"; var options = base.GetTrackOptions(track, binding); options.trackColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor; return options; } } [CustomTimelineEditor(typeof(AbstractFloatValueControlClip))] public class AbstractFloatValueControlCustomEditor : ClipEditor { public override ClipDrawOptions GetClipOptions(TimelineClip clip) { var clipOptions = base.GetClipOptions(clip); clipOptions.icons = null; clipOptions.highlightColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor; return clipOptions; } } [CanEditMultipleObjects] [CustomEditor(typeof(
AbstractFloatValueControlClip))] public class AbstractFloatValueControlClipEditor : UnityEditor.Editor {
public override void OnInspectorGUI() { DrawDefaultInspector(); } } }
Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs
nmxi-Unity_AbstractTimelineExtention-b518049
[ { "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.8950591087341309 }, { "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.8943959474563599 }, { "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.891287088394165 }, { "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.8823099136352539 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs", "retrieved_chunk": " }\n [CanEditMultipleObjects]\n [CustomEditor(typeof(AbstractBoolValueControlClip))]\n public class AbstractBoolValueControlClipEditor : UnityEditor.Editor\n {\n public override void OnInspectorGUI()\n {\n DrawDefaultInspector();\n }\n }", "score": 0.876338005065918 } ]
csharp
AbstractFloatValueControlClip))] public class AbstractFloatValueControlClipEditor : UnityEditor.Editor {
using SupernoteDesktopClient.Core.Win32Api; using System.Collections.Generic; namespace SupernoteDesktopClient.Models { public class Settings { public int LatestVersion { get { return 1; } } public int CurrentVersion { get; set; } = 1; public Dictionary<string, SupernoteInfo> DeviceProfiles { get; set; } = new Dictionary<string, SupernoteInfo>(); public General General { get; set; } public Sync Sync { get; set; } public Settings() { CurrentVersion = LatestVersion; // sections General = new General(); Sync = new Sync(); } } public class General { public bool RememberAppWindowPlacement { get; set; } = true; public
WindowPlacement AppWindowPlacement {
get; set; } public bool MinimizeToTrayEnabled { get; set; } = false; public string CurrentTheme { get; set; } = "Light"; // Light or Dark public bool DiagnosticLogEnabled { get; set; } = false; public bool AutomaticUpdateCheckEnabled { get; set; } = true; } public class Sync { public bool ShowNotificationOnDeviceStateChange { get; set; } = true; public bool AutomaticSyncOnConnect { get; set; } = false; public int MaxDeviceArchives { get; set; } = 7; } }
Models/Settings.cs
nelinory-SupernoteDesktopClient-e527602
[ { "filename": "Services/Contracts/ISyncService.cs", "retrieved_chunk": "namespace SupernoteDesktopClient.Services.Contracts\n{\n public interface ISyncService\n {\n bool IsBusy { get; }\n public string SourceFolder { get; }\n public string BackupFolder { get; }\n public string ArchiveFolder { get; }\n bool Sync();\n }", "score": 0.8726307153701782 }, { "filename": "Core/SettingsManager.cs", "retrieved_chunk": " private static readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions { WriteIndented = true };\n private static readonly string _settingsFileLocation = Path.Combine(FileSystemManager.GetApplicationFolder(), \"SupernoteDesktopClient.config\");\n public static SettingsManager Instance { get { return _instance.Value; } }\n public Settings Settings { get; private set; }\n private SettingsManager()\n {\n Settings = new Settings();\n Load();\n }\n public void Load()", "score": 0.8607352375984192 }, { "filename": "Models/ArchiveFileAttributes.cs", "retrieved_chunk": "using SupernoteDesktopClient.Extensions;\nusing System;\nnamespace SupernoteDesktopClient.Models\n{\n public class ArchiveFileAttributes\n {\n public string Name { get; private set; }\n public string Path { get; private set; }\n public DateTime CreateDateTime { get; private set; }\n public long SizeBytes { get; private set; }", "score": 0.8473923206329346 }, { "filename": "Messages/MediaDeviceChangedMessage.cs", "retrieved_chunk": " public bool IsConnected { get; private set; }\n public DeviceInfo(string deviceId, bool isConnected)\n {\n Deviceid = deviceId;\n IsConnected = isConnected;\n }\n }\n}", "score": 0.8463613390922546 }, { "filename": "Services/MediaDeviceService.cs", "retrieved_chunk": " get { return _supernoteInfo; }\n }\n private MediaDevice _supernoteManager;\n public MediaDevice SupernoteManager\n {\n get { return _supernoteManager; }\n }\n public MediaDeviceService()\n {\n RefreshMediaDeviceInfo();", "score": 0.8428073525428772 } ]
csharp
WindowPlacement AppWindowPlacement {
/* * Copyright (C) Antony Vitillo (aka Skarredghost), Perpetual eMotion 2023. * Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ using System; using UnityEngine; using vrroom.Dynaimic.Common; namespace vrroom.CubicMusic.Audio { /// <summary> /// Manages the audio in the application /// </summary> public class AudioManager : Singleton<AudioManager> { /// <summary> /// The microphone manager to be used by the application /// </summary> public MicrophoneManager MicrophoneManager { get; private set; } /// <summary> /// Analyzer of data of the background music. Can be null if there is no background music set. /// Use <see cref="SetBackgroundMusic(AudioSource)"/> to set the background music. /// </summary> public
IAudioAnalyzer BackgroundMusicAnalyzer {
get; private set; } /// <summary> /// Analyzer of data of the microphone /// </summary> public IAudioAnalyzer MicrophoneAnalyzer { get; private set; } /// <summary> /// Constructor with initialization /// </summary> public AudioManager() { MicrophoneManager = new MicrophoneManager(); MicrophoneManager.StartRecording(); MicrophoneManager.OnRecordingEnded += OnMicrophoneRecordingEnded; MicrophoneAnalyzer = new AudioAnalyzer(new MicrophoneAudioDataSource(MicrophoneManager), 15); } /// <summary> /// Called when the microphone recording ends. It restarts the recording automatically /// to keep the microphone analysis going on always /// </summary> /// <param name="deviceName">Ignored</param> /// <param name="recordedAudioClip">Ignored</param> private void OnMicrophoneRecordingEnded(string deviceName, AudioClip recordedAudioClip) { MicrophoneManager.StartRecording(); } /// <summary> /// Set the background music to be analyzed /// </summary> /// <param name="audioSource">Audiosource of the background music</param> public void SetBackgroundMusic(AudioSource audioSource) { BackgroundMusicAnalyzer = new AudioAnalyzer(new AudioSourceDataSource(audioSource)); } } }
CubicMusic/Assets/_CubicMusic/Runtime/AudioManagement/AudioManager.cs
Perpetual-eMotion-DynaimicApps-46c94e0
[ { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/AudioManagement/MicrophoneManager.cs", "retrieved_chunk": " /// </summary>\n public class MicrophoneManager\n {\n /// <summary>\n /// The audio clip of the microphone. It may be still recording, or the\n /// clip from the previous recording\n /// </summary>\n public AudioClip MicAudioClip { get; private set; }\n /// <summary>\n /// The name of the device to use for recording.", "score": 0.9228389859199524 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/AudioManagement/AudioAnalyzer.cs", "retrieved_chunk": " /// Interface for elements that analyze some audio source\n /// </summary>\n public abstract class IAudioAnalyzer\n {\n /// <summary>\n /// The sensitivity of the volume detection. \n /// The higher this value, the higher the <see cref=\"CurrentVolume\"/>\n /// </summary>\n public abstract float VolumeSensitivity { get; set; }\n /// <summary>", "score": 0.8969722986221313 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/AudioManagement/AudioAnalyzer.cs", "retrieved_chunk": " /// The current volume of the audio, in the range [0, 1]\n /// </summary>\n public abstract float CurrentVolume { get; }\n }\n /// <summary>\n /// Analyzes the audio output of an audio source that is playing\n /// </summary>\n public class AudioAnalyzer : IAudioAnalyzer\n {\n /// <summary>", "score": 0.8963518738746643 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/AudioManagement/AudioDataSources.cs", "retrieved_chunk": " /// Interface for elements that provide audio data\n /// </summary>\n public interface IAudioDataSource\n {\n /// <summary>\n /// True if the audio source is playing (so data is available), false otherwise\n /// </summary>\n abstract bool IsPlaying { get; }\n /// <summary>\n /// The number of channels of the audio source", "score": 0.8904803395271301 }, { "filename": "CubicMusic/Assets/_CubicMusic/Runtime/AudioManagement/MicrophoneManager.cs", "retrieved_chunk": " /// null to use the default microphone\n /// </summary>\n private string m_deviceName;\n /// <summary>\n /// Get the position in samples of the recording\n /// </summary>\n public int Position => Microphone.GetPosition(m_deviceName);\n /// <summary>\n /// True if the microphone is recording, false otherwise\n /// </summary>", "score": 0.8883469700813293 } ]
csharp
IAudioAnalyzer BackgroundMusicAnalyzer {
using System.Diagnostics; using System.Text; using Gum.Blackboards; using Gum.Utilities; namespace Gum.InnerThoughts { [DebuggerDisplay("{DebuggerDisplay(),nq}")] public class DialogAction { public readonly Fact Fact = new(); public readonly
BlackboardActionKind Kind = BlackboardActionKind.Set;
public readonly string? StrValue = null; public readonly int? IntValue = null; public readonly bool? BoolValue = null; public readonly string? ComponentValue = null; public DialogAction() { } public DialogAction(Fact fact, BlackboardActionKind kind, object value) { bool? @bool = null; int? @int = null; string? @string = null; string? component = null; // Do not propagate previous values. switch (fact.Kind) { case FactKind.Bool: @bool = (bool)value; break; case FactKind.Int: @int = (int)value; break; case FactKind.String: @string = (string)value; break; case FactKind.Component: component = (string)value; break; } (Fact, Kind, StrValue, IntValue, BoolValue, ComponentValue) = (fact, kind, @string, @int, @bool, component); } public string DebuggerDisplay() { StringBuilder result = new(); if (Fact.Kind == FactKind.Component) { result = result.Append($"[c:"); } else { result = result.Append($"[{Fact.Name} {OutputHelpers.ToCustomString(Kind)} "); } switch (Fact.Kind) { case FactKind.Bool: result = result.Append(BoolValue); break; case FactKind.Int: result = result.Append(IntValue); break; case FactKind.String: result = result.Append(StrValue); break; case FactKind.Component: result = result.Append(ComponentValue); break; } result = result.Append(']'); return result.ToString(); } } }
src/Gum/InnerThoughts/DialogAction.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum/InnerThoughts/Criterion.cs", "retrieved_chunk": "using System.Text;\nusing System.Diagnostics;\nusing Gum.Utilities;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{DebuggerDisplay(),nq}\")]\n public readonly struct Criterion\n {\n public readonly Fact Fact = new();\n public readonly CriterionKind Kind = CriterionKind.Is;", "score": 0.8754894733428955 }, { "filename": "src/Gum/InnerThoughts/Situation.cs", "retrieved_chunk": "using Gum.Utilities;\nusing Newtonsoft.Json;\nusing System.Diagnostics;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{Name}\")]\n public class Situation\n {\n [JsonProperty]\n public readonly int Id = 0;", "score": 0.8626265525817871 }, { "filename": "src/Gum/InnerThoughts/Block.cs", "retrieved_chunk": "using System;\nusing System.Diagnostics;\nusing System.Text;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{DebuggerDisplay(),nq}\")]\n public class Block\n {\n public readonly int Id = 0;\n /// <summary>", "score": 0.8584232926368713 }, { "filename": "src/Gum/InnerThoughts/CriterionNode.cs", "retrieved_chunk": "using System.Diagnostics;\nusing Gum.Utilities;\nnamespace Gum.InnerThoughts\n{\n [DebuggerDisplay(\"{DebuggerDisplay(),nq}\")]\n public readonly struct CriterionNode\n {\n public readonly Criterion Criterion = new();\n public readonly CriterionNodeKind Kind = CriterionNodeKind.And;\n public CriterionNode() { }", "score": 0.8269740343093872 }, { "filename": "src/Gum/Blackboards/BlackboardActionKind.cs", "retrieved_chunk": "using Gum.Attributes;\nnamespace Gum.Blackboards\n{\n public enum BlackboardActionKind\n {\n [TokenName(\"=\")]\n Set, // All\n [TokenName(\"+=\")]\n Add, // Integer\n [TokenName(\"-=\")]", "score": 0.805597186088562 } ]
csharp
BlackboardActionKind Kind = BlackboardActionKind.Set;
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/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.9004019498825073 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Virtue_Start_Patch\n {\n static void Postfix(Drone __instance, ref EnemyIdentifier ___eid)\n {\n VirtueFlag flag = __instance.gameObject.AddComponent<VirtueFlag>();\n flag.virtue = __instance;", "score": 0.8788547515869141 }, { "filename": "Ultrapain/Patches/SwordsMachine.cs", "retrieved_chunk": " }\n anim.speed = speed;\n }\n }\n }\n class SwordsMachine_Start\n {\n static void Postfix(SwordsMachine __instance)\n {\n SwordsMachineFlag flag = __instance.gameObject.AddComponent<SwordsMachineFlag>();", "score": 0.8677898645401001 }, { "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.8637702465057373 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " }\n }\n class StatueBoss_Start_Patch\n {\n static void Postfix(StatueBoss __instance)\n {\n __instance.gameObject.AddComponent<CerberusFlag>();\n }\n }\n}", "score": 0.8631440997123718 } ]
csharp
Harpoon __instance, EnemyIdentifierIdentifier ___target) {
using LassoProcessManager.Models.Rules; using Newtonsoft.Json; using ProcessManager.Models.Configs; using System.Reflection; namespace ProcessManager.Providers { public class ConfigProvider : IConfigProvider { private const string ConfigFileName = "Config.json"; private ManagerConfig managerConfig; private ILogProvider LogProvider { get; set; } public ConfigProvider(ILogProvider logProvider) => this.LogProvider = logProvider; public ManagerConfig GetManagerConfig() { if (managerConfig != null) return managerConfig; string configPath = GetConfigFilePath(); try { managerConfig = JsonConvert.DeserializeObject<ManagerConfig>(File.ReadAllText(GetConfigFilePath())); return managerConfig; } catch { LogProvider.Log($"Failed to load config at '{configPath}'."); } return null; } public List<
BaseRule> GetRules() {
List<BaseRule> rules = new List<BaseRule>(); rules.AddRange(managerConfig.ProcessRules); rules.AddRange(managerConfig.FolderRules); return rules; } public Dictionary<string, LassoProfile> GetLassoProfiles() { Dictionary<string, LassoProfile> lassoProfiles = new Dictionary<string, LassoProfile>(); // Load lasso profiles foreach (var profile in managerConfig.Profiles) { if (!lassoProfiles.ContainsKey(profile.Name)) { lassoProfiles.Add(profile.Name, profile); } } return lassoProfiles; } private string GetConfigFilePath() => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName); } }
ProcessManager/Providers/ConfigProvider.cs
kenshinakh1-LassoProcessManager-bcc481f
[ { "filename": "ProcessManager/Managers/LassoManager.cs", "retrieved_chunk": " {\n try\n {\n LoadConfig();\n SetupProfilesForAllProcesses();\n SetupEventWatcher();\n }\n catch\n {\n LogProvider.Log(\"Exception with initial setup. Cannot continue. Check for errors.\");", "score": 0.845187246799469 }, { "filename": "ProcessManager/Managers/LassoManager.cs", "retrieved_chunk": " profileName = null;\n return false;\n }\n if (lassoProfile is null)\n {\n LogProvider.Log($\"No profile applied on Process '{process.ProcessName}' (ID:{process.Id}).\");\n profileName = null;\n return false;\n }\n try", "score": 0.8298875689506531 }, { "filename": "ProcessManager/Models/Rules/FolderRule.cs", "retrieved_chunk": "using System.Diagnostics;\nnamespace LassoProcessManager.Models.Rules\n{\n public class FolderRule : BaseRule\n {\n public string FolderPath { get; set; }\n public override bool IsMatchForRule(Process process)\n {\n try\n {", "score": 0.8037558794021606 }, { "filename": "ProcessManager/Providers/LogProvider.cs", "retrieved_chunk": "namespace ProcessManager.Providers\n{\n public class LogProvider : ILogProvider\n {\n public void Log(string message)\n {\n Console.WriteLine(message);\n }\n }\n}", "score": 0.798099160194397 }, { "filename": "ProcessManager/Managers/LassoManager.cs", "retrieved_chunk": " }\n return false;\n }\n private void LoadConfig()\n {\n config = ConfigProvider.GetManagerConfig();\n rules = ConfigProvider.GetRules();\n lassoProfiles = ConfigProvider.GetLassoProfiles();\n }\n private void SetupProfilesForAllProcesses()", "score": 0.7882440090179443 } ]
csharp
BaseRule> GetRules() {
using System.Collections.Generic; using System.Xml.Linq; using System.Xml.XPath; using SQLServerCoverage.Objects; namespace SQLServerCoverage.Parsers { public class EventsParser { private readonly List<string> _xmlEvents; private XDocument _doc; private int _stringNumber; public EventsParser(List<string> xmlEvents) { _xmlEvents = xmlEvents; if (_xmlEvents == null || _xmlEvents.Count == 0) { _xmlEvents = new List<string>(); return; } _doc = XDocument.Parse(xmlEvents[_stringNumber++]); } public
CoveredStatement GetNextStatement() {
if (_stringNumber > _xmlEvents.Count || _xmlEvents.Count == 0) return null; var statement = new CoveredStatement(); statement.Offset = GetOffset(); statement.OffsetEnd = GetOffsetEnd(); statement.ObjectId = GetIntValue("object_id"); if (_stringNumber < _xmlEvents.Count) _doc = XDocument.Parse(_xmlEvents[_stringNumber++]); else _stringNumber++; return statement; } private int GetOffset() { var value = GetStringValue("offset"); if (value == null) { value = Get2008StyleString("offsetStart"); } return int.Parse(value); } private int GetOffsetEnd() { var value = GetStringValue("offset_end"); if (value == null) { value = Get2008StyleString("offsetEnd"); } var offset = int.Parse(value); return offset; } private string Get2008StyleString(string name) { var node = _doc.XPathSelectElement("//action[@name='tsql_stack']/value"); var newDocument = XDocument.Parse(string.Format("<Root>{0}</Root>", node.Value)); var frame = newDocument.Element("Root").FirstNode; if (frame == null) { return null; } var element = frame as XElement; return element.Attribute(name).Value; } private int GetIntValue(string name) { var value = GetStringValue(name); return int.Parse(value); } private string GetStringValue(string name) { var node = _doc.XPathSelectElement(string.Format("//data[@name='{0}']/value", name)); return node?.Value; } } }
src/SQLServerCoverageLib/Parsers/EventsParser.cs
sayantandey-SQLServerCoverage-aea57e3
[ { "filename": "src/SQLServerCoverageLib/CodeCoverage.cs", "retrieved_chunk": " }\n }\n private List<string> StopInternal()\n {\n var events = _trace.ReadTrace();\n _trace.Stop();\n _trace.Drop();\n return events;\n }\n public CoverageResult Stop()", "score": 0.802800178527832 }, { "filename": "src/SQLServerCoverageLib/CodeCoverage.cs", "retrieved_chunk": " }\n private void GenerateResults(List<string> filter, List<string> xml, List<string> sqlExceptions, string commandDetail)\n {\n var batches = _source.GetBatches(filter);\n _result = new CoverageResult(batches, xml, _databaseName, _database.DataSource, sqlExceptions, commandDetail);\n }\n public CoverageResult Results()\n {\n return _result;\n }", "score": 0.7946298122406006 }, { "filename": "src/SQLServerCoverageLib/CoverageResult.cs", "retrieved_chunk": " public CoverageResult(IEnumerable<Batch> batches, List<string> xml, string database, string dataSource, List<string> sqlExceptions, string commandDetail)\n {\n _batches = batches;\n _sqlExceptions = sqlExceptions;\n _commandDetail = $\"{commandDetail} at {DateTime.Now}\";\n DatabaseName = database;\n DataSource = dataSource;\n var parser = new EventsParser(xml);\n var statement = parser.GetNextStatement();\n while (statement != null)", "score": 0.7943543195724487 }, { "filename": "src/SQLServerCoverageLib/Parsers/StatementParser.cs", "retrieved_chunk": " public readonly List<Statement> Statements = new List<Statement>();\n private bool _stopEnumerating = false;\n public StatementVisitor(string script)\n {\n _script = script;\n }\n public override void Visit(TSqlStatement statement)\n {\n if (_stopEnumerating)\n return;", "score": 0.7935205101966858 }, { "filename": "src/SQLServerCoverageLib/Trace/SqlTraceController.cs", "retrieved_chunk": " var events = new List<string>();\n foreach (DataRow row in data.Rows)\n {\n events.Add(row.ItemArray[0].ToString());\n }\n return events;\n }\n public override void Drop()\n {\n RunScript(DropTraceFormat, \"Error dropping the extended events trace, error: {0}\");", "score": 0.7822654843330383 } ]
csharp
CoveredStatement GetNextStatement() {
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Ryan.DependencyInjection; using Ryan.EntityFrameworkCore.Builder; using Ryan.EntityFrameworkCore.Proxy; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Ryan.EntityFrameworkCore { /// <summary> /// 分表上下文 /// </summary> public class ShardDbContext : DbContext { /// <summary> /// 分表实体 /// </summary> private List<Type> ShardEntityTypes { get; set; } = new List<Type>(); /// <summary> /// 分表依赖 /// </summary> public
IShardDependency Dependencies {
get; } /// <summary> /// 创建分表上下文 /// </summary> public ShardDbContext(IShardDependency shardDependency) { InitShardConfiguration(); Dependencies = shardDependency; } /// <summary> /// 初始化分表配置 /// </summary> private void InitShardConfiguration() { // 获取分表类型 var shardAttribute = GetType().GetCustomAttribute<ShardAttribute>(); if (shardAttribute == null) { return; } ShardEntityTypes.AddRange(shardAttribute.GetShardEntities()); } /// <summary> /// 配置 /// </summary> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } /// <summary> /// 构建实体 /// </summary> protected override void OnModelCreating(ModelBuilder modelBuilder) { // 构建 ModelBuilder foreach (var shardEntity in ShardEntityTypes) { Dependencies.EntityModelBuilderAccessorGenerator.Create(shardEntity).Accessor(shardEntity, modelBuilder); } } /// <summary> /// 创建非查询代理 /// </summary> internal EntityProxy CreateEntityProxy(object entity, EntityProxyType type) { // 上下文代理 var dbContextProxy = Dependencies.DbContextEntityProxyLookupGenerator .Create(this) .GetOrDefault(entity.GetType().BaseType!, this); // 创建代理 var proxy = dbContextProxy.EntityProxies.FirstOrDefault(x => x.Entity == entity); if (proxy != null) { return proxy; } // 创建代理 dbContextProxy.EntityProxies.Add( proxy = Dependencies.EntityProxyGenerator.Create(entity, EntityProxyType.NonQuery, this)); return proxy; } /// <summary> /// 分表查询 /// </summary> public virtual IQueryable<TEntity> AsQueryable<TEntity>(Expression<Func<TEntity, bool>> expression) where TEntity : class { if (!ShardEntityTypes.Contains(typeof(TEntity))) { throw new InvalidOperationException(); } // 获取实现 var queryables = Dependencies.ExpressionImplementationFinder .Find<TEntity>(expression) .Select(x => Dependencies.QueryableFinder.Find<TEntity>(this, x)); // 组合查询 var queryable = queryables.FirstOrDefault(); foreach (var nextQueryable in queryables.Skip(1)) { queryable = queryable.Union(nextQueryable); } return queryable; } /// <summary> /// 分表查询 /// </summary> public virtual IEnumerable<TEntity> AsQueryable<TEntity>(Expression<Func<TEntity, bool>> expression, Expression<Func<TEntity, bool>> predicate) where TEntity : class { if (!ShardEntityTypes.Contains(typeof(TEntity))) { throw new InvalidOperationException(); } // 获取实现 var queryables = Dependencies.ExpressionImplementationFinder .Find<TEntity>(expression) .Select(x => Dependencies.QueryableFinder.Find<TEntity>(this, x)); // 组合查询 return queryables.SelectMany(x => x.Where(predicate).ToList()); } /// <inheritdoc/> public override EntityEntry Add(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Add(entity); } // 将实现添加入状态管理 return base.Add(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override ValueTask<EntityEntry> AddAsync(object entity, CancellationToken cancellationToken = default) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.AddAsync(entity, cancellationToken); } // 将实现添加入状态管理 return base.AddAsync(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation, cancellationToken); } /// <inheritdoc/> public override EntityEntry<TEntity> Add<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Add(entity); } // 将实现添加入状态管理 return base.Add((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override ValueTask<EntityEntry<TEntity>> AddAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = default) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.AddAsync(entity, cancellationToken); } // 将实现添加入状态管理 return base.AddAsync((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation, cancellationToken); } /// <inheritdoc/> public override EntityEntry Attach(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Attach(entity); } return base.Attach(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry<TEntity> Attach<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Attach(entity); } return base.Attach((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry Entry(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Entry(entity); } return base.Entry(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry<TEntity> Entry<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Entry(entity); } return base.Entry((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry Remove(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Remove(entity); } return base.Remove(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry<TEntity> Remove<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Remove(entity); } return base.Remove((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry Update(object entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Update(entity); } return base.Update(CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override EntityEntry<TEntity> Update<TEntity>(TEntity entity) { if (!ShardEntityTypes.Contains(entity.GetType())) { return base.Update(entity); } return base.Update((TEntity)CreateEntityProxy(entity, EntityProxyType.NonQuery).Implementation); } /// <inheritdoc/> public override int SaveChanges(bool acceptAllChangesOnSuccess) { var lookup = Dependencies.DbContextEntityProxyLookupGenerator.Create(this); lookup.Changes(); var result = base.SaveChanges(acceptAllChangesOnSuccess); lookup.Changed(); return result; } /// <inheritdoc/> public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) { var lookup = Dependencies.DbContextEntityProxyLookupGenerator.Create(this); lookup.Changes(); var result = base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); lookup.Changed(); return result; } public override void Dispose() { Dependencies.DbContextEntityProxyLookupGenerator.Delete(this); base.Dispose(); } } }
src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/ShardDbContext.cs
c-y-r-Ryan.EntityFrameworkCore.Shard-f15124c
[ { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilderAccessor.cs", "retrieved_chunk": " /// <summary>\n /// 实体类型\n /// </summary>\n public Type EntityType { get; }\n /// <summary>\n /// 实体实现字典\n /// </summary>\n public EntityImplementationDictionary Dictionary { get; }\n /// <summary>\n /// 实体模型构建", "score": 0.9073924422264099 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/ShardAttribute.cs", "retrieved_chunk": " /// <summary>\n /// 创建分表特性\n /// </summary>\n public ShardAttribute(params Type[] shardEntities)\n {\n _shardEntities = shardEntities;\n }\n /// <summary>\n /// 获取分表实体\n /// </summary>", "score": 0.8998774886131287 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityImplementationDictionary.cs", "retrieved_chunk": " /// 实体类型\n /// </summary>\n public Type EntityType { get; }\n /// <summary>\n /// 创建实体实现字典\n /// </summary>\n public EntityImplementationDictionary(Type entityType)\n {\n EntityType = entityType;\n }", "score": 0.8963766694068909 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Proxy/DbContextEntityProxy.cs", "retrieved_chunk": " /// 上下文\n /// </summary>\n public DbContext Context { get; }\n /// <summary>\n /// 实体代理\n /// </summary>\n public List<EntityProxy> EntityProxies { get; }\n /// <summary>\n /// 创建上下文实体代理\n /// </summary>", "score": 0.8926998376846313 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilderGenerator.cs", "retrieved_chunk": " {\n /// <summary>\n /// 容器\n /// </summary>\n public IServiceProvider ServiceProvider { get; }\n /// <summary>\n /// 内存缓存\n /// </summary>\n public IMemoryCache MemoryCache { get; }\n /// <summary>", "score": 0.8888548016548157 } ]
csharp
IShardDependency Dependencies {
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/NodeQuest.cs", "retrieved_chunk": " public TextAsset extraText;\n public List<GameObject> objectsActivated;\n public bool isFinal;\n public QuestObjective[] nodeObjectives;\n [Header(\"Graph Part\")]\n public string GUID;\n public Vector2 position;\n public void AddObject(GameObject g)\n {\n if (g == null) Debug.Log(\"Object is null\");", "score": 0.8492050170898438 }, { "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.8311867713928223 }, { "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.8274955153465271 }, { "filename": "Editor/GraphEditor/QuestObjectiveGraph.cs", "retrieved_chunk": " public string keyName;\n public int maxItems;\n public int actualItems;\n public string description;\n public bool hiddenObjective;\n public bool autoExitOnCompleted;\n public QuestObjectiveGraph(string key = \"\", int max = 0, int actual = 0, string des = \"\", bool hiddenObjectiveDefault = false, bool autoExitOnCompletedDefault = false)\n {\n //keyName\n var propertyKeyNameField = new TextField(\"keyName:\")", "score": 0.8222934007644653 }, { "filename": "Editor/GraphEditor/NodeQuestGraph.cs", "retrieved_chunk": " {\n public string GUID;\n public TextAsset extraText;\n public VisualElement objectivesRef;\n public List<QuestObjectiveGraph> questObjectives;\n public bool isFinal;\n public bool entryPoint = false;\n public int limitDay;\n public int startDay;\n public string misionName;", "score": 0.8219175338745117 } ]
csharp
NodeQuestGraph CreateNodeQuest(string nodeName, Vector2 position, TextAsset ta = null, bool end = false) {
using LibreDteDotNet.RestRequest.Interfaces; namespace LibreDteDotNet.RestRequest.Infraestructure { public class RestRequest { public ILibro Libro { get; } public IContribuyente Contribuyente { get; } public IFolioCaf FolioCaf { get; } public IBoleta Boleta { get; } public IDTE DocumentoTributario { get; } public RestRequest( ILibro libroService, IContribuyente contribuyenteService, IFolioCaf folioCafService, IBoleta boletaService,
IDTE dTEService ) {
Libro = libroService; Contribuyente = contribuyenteService; FolioCaf = folioCafService; Boleta = boletaService; DocumentoTributario = dTEService; } } }
LibreDteDotNet.RestRequest/Infraestructure/RestRequest.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Interfaces/IBoleta.cs", "retrieved_chunk": "namespace LibreDteDotNet.RestRequest.Interfaces\n{\n public interface IBoleta\n {\n Task<IBoleta> SetCookieCertificado();\n Task<string> GetConsumoByFecha(\n string anoIni,\n string mesIni,\n string anoFin,\n string mesFin,", "score": 0.8331670761108398 }, { "filename": "LibreDteDotNet.RestRequest/Interfaces/IFolioCaf.cs", "retrieved_chunk": " string rut,\n string dv,\n string cant,\n string cantmax,\n TipoDoc tipodoc\n );\n Task<XDocument> Descargar();\n Task<IFolioCaf> SetCookieCertificado();\n Task<Dictionary<string, string>> GetRangoMax(string rut, string dv, TipoDoc tipodoc);\n Task<IFolioCaf> Confirmar();", "score": 0.825432300567627 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/DTEExtension.cs", "retrieved_chunk": " public static async Task<string> Enviar(\n this Task<IDTE> folioService,\n string rutCompany,\n string DvCompany\n )\n {\n IDTE instance = await folioService;\n return await instance.Enviar(rutCompany, DvCompany);\n }\n }", "score": 0.8241344094276428 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/BoletaExtension.cs", "retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class BoletaExtension\n {\n public static IBoleta Conectar(this IBoleta folioService)\n {\n IBoleta instance = folioService;\n return instance.SetCookieCertificado().Result;\n }", "score": 0.8170495629310608 }, { "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.8141237497329712 } ]
csharp
IDTE dTEService ) {
/* 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_3 : MonoFlux { [SerializeField] private int _life; public int Life { [Flux("Get_Life")] get => _life; [
Flux("Set_Life")] set {
_life = value; "OnChange_Life".Dispatch(value); } } private void Start() { "Set_Life".Dispatch(10); } private void Update() { (Time.frameCount % 60).Dispatch(); } [Flux(0)] private void OnUpdate() { if("Get_Life".Dispatch<int>() > 0) { "Set_Life".Dispatch("Get_Life".Dispatch<int>()-1); } } [Flux("OnChange_Life")] private void OnChange_Life(int life) { if(life == 0) { "OnDeath".Dispatch(); } } [Flux("OnDeath")] private void OnDeath() { Debug.Log("You're Dead !"); } } }
Samples/UniFlux.Sample.3/Sample_3.cs
xavierarpa-UniFlux-a2d46de
[ { "filename": "Samples/UniFlux.Sample.4/Sample_4.cs", "retrieved_chunk": "{\n public sealed class Sample_4 : MonoFlux\n {\n [SerializeField] private int _shots;\n private void Update()\n {\n Kingdox.UniFlux.Core.Flux.Dispatch(_shots < 10);\n }\n [Flux(true)]private void CanShot()\n {", "score": 0.8618424534797668 }, { "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.8617891073226929 }, { "filename": "Samples/UniFlux.Sample.Experimental/UniFlux_Exp_S_1_A.cs", "retrieved_chunk": "{\n public class UniFlux_Exp_S_1_A : MonoFlux\n {\n [SerializeField] KeyFluxBase k_doSample;\n private void Start() => k_doSample.Dispatch();\n }\n}", "score": 0.8404073715209961 }, { "filename": "Samples/UniFlux.Sample.5/Sample_5.cs", "retrieved_chunk": "namespace Kingdox.UniFlux.Sample\n{\n public sealed class Sample_5 : MonoFlux\n {\n public const string K_Primary = \"primary\";\n [SerializeField] private Color color_1;\n [SerializeField] private Color color_2;\n [Space]\n [SerializeField] private Color color_current;\n [Space]", "score": 0.838027834892273 }, { "filename": "Benchmark/Nest/Benchmark_Nest_UniFlux.cs", "retrieved_chunk": "using System;\nusing UnityEngine;\nnamespace Kingdox.UniFlux.Benchmark\n{\n public sealed class Benchmark_Nest_UniFlux : MonoFlux\n {\n [SerializeField] private Marker _mark_fluxAttribute = new Marker()\n {\n K = \"NestedModel Flux Attribute\"\n };", "score": 0.8355761766433716 } ]
csharp
Flux("Set_Life")] set {
#nullable enable using System; using System.IO; using System.Threading; using Cysharp.Threading.Tasks; using Mochineko.ChatGPT_API; using Mochineko.FacialExpressions.Blink; using Mochineko.FacialExpressions.Emotion; using Mochineko.FacialExpressions.Extensions.VRM; using Mochineko.FacialExpressions.LipSync; using Mochineko.FacialExpressions.Samples; using Mochineko.LLMAgent.Chat; using Mochineko.LLMAgent.Emotion; using Mochineko.LLMAgent.Memory; using Mochineko.LLMAgent.Speech; using Mochineko.LLMAgent.Summarization; using Mochineko.Relent.Extensions.NewtonsoftJson; using Mochineko.Relent.Result; using Mochineko.RelentStateMachine; using Mochineko.VOICEVOX_API.QueryCreation; using UnityEngine; using UniVRM10; using VRMShaders; namespace Mochineko.LLMAgent.Operation { internal sealed class DemoOperator : MonoBehaviour { [SerializeField] private Model model = Model.Turbo; [SerializeField, TextArea] private string prompt = string.Empty; [SerializeField, TextArea] private string defaultConversations = string.Empty; [SerializeField, TextArea] private string message = string.Empty; [SerializeField] private int speakerID; [SerializeField] private string vrmAvatarPath = string.Empty; [SerializeField] private float emotionFollowingTime = 1f; [SerializeField] private float emotionWeight = 1f; [SerializeField] private AudioSource? audioSource = null; [SerializeField] private RuntimeAnimatorController? animatorController = null; private IChatMemoryStore? store; private LongTermChatMemory? memory; internal
LongTermChatMemory? Memory => memory;
private ChatCompletion? chatCompletion; private ChatCompletion? stateCompletion; private VoiceVoxSpeechSynthesis? speechSynthesis; private IFiniteStateMachine<AgentEvent, AgentContext>? agentStateMachine; private async void Start() { await SetupAgentAsync(this.GetCancellationTokenOnDestroy()); } private async void Update() { if (agentStateMachine == null) { return; } var updateResult = await agentStateMachine .UpdateAsync(this.GetCancellationTokenOnDestroy()); if (updateResult is IFailureResult updateFailure) { Debug.LogError($"Failed to update agent state machine because -> {updateFailure.Message}."); } } private void OnDestroy() { agentStateMachine?.Dispose(); } private async UniTask SetupAgentAsync(CancellationToken cancellationToken) { if (audioSource == null) { throw new NullReferenceException(nameof(audioSource)); } if (animatorController == null) { throw new NullReferenceException(nameof(animatorController)); } var apiKeyPath = Path.Combine( Application.dataPath, "Mochineko/LLMAgent/Operation/OpenAI_API_Key.txt"); var apiKey = await File.ReadAllTextAsync(apiKeyPath, cancellationToken); if (string.IsNullOrEmpty(apiKey)) { throw new Exception($"[LLMAgent.Operation] Loaded API Key is empty from path:{apiKeyPath}"); } store = new NullChatMemoryStore(); memory = await LongTermChatMemory.InstantiateAsync( maxShortTermMemoriesTokenLength: 1000, maxBufferMemoriesTokenLength: 1000, apiKey, model, store, cancellationToken); chatCompletion = new ChatCompletion( apiKey, model, prompt + PromptTemplate.MessageResponseWithEmotion, memory); if (!string.IsNullOrEmpty(defaultConversations)) { var conversationsDeserializeResult = RelentJsonSerializer .Deserialize<ConversationCollection>(defaultConversations); if (conversationsDeserializeResult is ISuccessResult<ConversationCollection> successResult) { for (var i = 0; i < successResult.Result.Conversations.Count; i++) { await memory.AddMessageAsync( successResult.Result.Conversations[i], cancellationToken); } } else if (conversationsDeserializeResult is IFailureResult<ConversationCollection> failureResult) { Debug.LogError( $"[LLMAgent.Operation] Failed to deserialize default conversations because -> {failureResult.Message}"); } } speechSynthesis = new VoiceVoxSpeechSynthesis(speakerID); var binary = await File.ReadAllBytesAsync( vrmAvatarPath, cancellationToken); var instance = await LoadVRMAsync( binary, cancellationToken); var lipMorpher = new VRMLipMorpher(instance.Runtime.Expression); var lipAnimator = new FollowingLipAnimator(lipMorpher); var emotionMorpher = new VRMEmotionMorpher(instance.Runtime.Expression); var emotionAnimator = new ExclusiveFollowingEmotionAnimator<FacialExpressions.Emotion.Emotion>( emotionMorpher, followingTime: emotionFollowingTime); var eyelidMorpher = new VRMEyelidMorpher(instance.Runtime.Expression); var eyelidAnimator = new SequentialEyelidAnimator(eyelidMorpher); var eyelidAnimationFrames = ProbabilisticEyelidAnimationGenerator.Generate( Eyelid.Both, blinkCount: 20); var agentContext = new AgentContext( eyelidAnimator, eyelidAnimationFrames, lipMorpher, lipAnimator, audioSource, emotionAnimator); agentStateMachine = await AgentStateMachineFactory.CreateAsync( agentContext, cancellationToken); instance .GetComponent<Animator>() .runtimeAnimatorController = animatorController; } // ReSharper disable once InconsistentNaming private static async UniTask<Vrm10Instance> LoadVRMAsync( byte[] binaryData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await Vrm10.LoadBytesAsync( bytes: binaryData, canLoadVrm0X: true, controlRigGenerationOption: ControlRigGenerationOption.Generate, showMeshes: true, awaitCaller: new RuntimeOnlyAwaitCaller(), ct: cancellationToken ); } [ContextMenu(nameof(StartChatAsync))] public void StartChatAsync() { ChatAsync(message, this.GetCancellationTokenOnDestroy()) .Forget(); } public async UniTask ChatAsync(string message, CancellationToken cancellationToken) { if (chatCompletion == null) { throw new NullReferenceException(nameof(chatCompletion)); } if (speechSynthesis == null) { throw new NullReferenceException(nameof(speechSynthesis)); } if (agentStateMachine == null) { throw new NullReferenceException(nameof(agentStateMachine)); } string chatResponse; var chatResult = await chatCompletion.CompleteChatAsync(message, cancellationToken); switch (chatResult) { case ISuccessResult<string> chatSuccess: { Debug.Log($"[LLMAgent.Operation] Complete chat message:{chatSuccess.Result}."); chatResponse = chatSuccess.Result; break; } case IFailureResult<string> chatFailure: { Debug.LogError($"[LLMAgent.Operation] Failed to complete chat because of {chatFailure.Message}."); return; } default: throw new ResultPatternMatchException(nameof(chatResult)); } EmotionalMessage emotionalMessage; var deserializeResult = RelentJsonSerializer.Deserialize<EmotionalMessage>(chatResponse); switch (deserializeResult) { case ISuccessResult<EmotionalMessage> deserializeSuccess: { emotionalMessage = deserializeSuccess.Result; break; } case IFailureResult<EmotionalMessage> deserializeFailure: { Debug.LogError( $"[LLMAgent.Operation] Failed to deserialize emotional message:{chatResponse} because of {deserializeFailure.Message}."); return; } default: throw new ResultPatternMatchException(nameof(deserializeResult)); } var emotion = EmotionConverter.ExcludeHighestEmotion(emotionalMessage.Emotion); Debug.Log($"[LLMAgent.Operation] Exclude emotion:{emotion}."); var synthesisResult = await speechSynthesis.SynthesisSpeechAsync( HttpClientPool.PooledClient, emotionalMessage.Message, cancellationToken); switch (synthesisResult) { case ISuccessResult<(AudioQuery query, AudioClip clip)> synthesisSuccess: { agentStateMachine.Context.SpeechQueue.Enqueue(new SpeechCommand( synthesisSuccess.Result.query, synthesisSuccess.Result.clip, new EmotionSample<FacialExpressions.Emotion.Emotion>(emotion, emotionWeight))); if (agentStateMachine.IsCurrentState<AgentIdleState>()) { var sendEventResult = await agentStateMachine.SendEventAsync( AgentEvent.BeginSpeaking, cancellationToken); if (sendEventResult is IFailureResult sendEventFailure) { Debug.LogError( $"[LLMAgent.Operation] Failed to send event because of {sendEventFailure.Message}."); } } break; } case IFailureResult<(AudioQuery query, AudioClip clip)> synthesisFailure: { Debug.Log( $"[LLMAgent.Operation] Failed to synthesis speech because of {synthesisFailure.Message}."); return; } default: return; } } } }
Assets/Mochineko/LLMAgent/Operation/DemoOperator.cs
mochi-neko-llm-agent-sandbox-unity-6521c0b
[ { "filename": "Assets/Mochineko/KoeiromapAPI.Samples/KoeiromapAPISample.cs", "retrieved_chunk": "using UnityEngine.Assertions;\nnamespace Mochineko.KoeiromapAPI.Samples\n{\n internal sealed class KoeiromapAPISample : MonoBehaviour\n {\n [SerializeField, Range(-3f, 3f)] private float speakerX;\n [SerializeField, Range(-3f, 3f)] private float speakerY;\n [SerializeField] private bool useSeed;\n [SerializeField] private ulong seed;\n [SerializeField, TextArea] private string text = string.Empty;", "score": 0.8477622270584106 }, { "filename": "Assets/Mochineko/LLMAgent/Memory/LongTermChatMemory.cs", "retrieved_chunk": " private readonly Queue<Message> shortTermMemories = new();\n internal IEnumerable<Message> ShortTermMemories => shortTermMemories.ToArray();\n private readonly Queue<Message> bufferMemories = new();\n internal IEnumerable<Message> BufferMemories => bufferMemories.ToArray();\n private readonly Summarizer summarizer;\n private readonly IChatMemoryStore store;\n private Message summary;\n internal Message Summary => summary;\n private readonly object lockObject = new();\n public static async UniTask<LongTermChatMemory> InstantiateAsync(", "score": 0.8280960321426392 }, { "filename": "Assets/Mochineko/KoeiromapAPI.Samples/KoeiromapAPISample.cs", "retrieved_chunk": " [SerializeField] private Style style;\n [SerializeField] private AudioSource? audioSource;\n private static readonly HttpClient HttpClient = new();\n private IPolicy<Stream>? policy;\n private void Awake()\n {\n Assert.IsNotNull(audioSource);\n policy = PolicyFactory.BuildPolicy();\n }\n [ContextMenu(nameof(Synthesis))]", "score": 0.8276987671852112 }, { "filename": "Assets/Mochineko/LLMAgent/Summarization/Summarizer.cs", "retrieved_chunk": " public sealed class Summarizer\n {\n private readonly Model model;\n private readonly TikToken tikToken;\n private readonly RelentChatCompletionAPIConnection connection;\n private readonly IChatMemory simpleChatMemory = new SimpleChatMemory();\n private readonly IPolicy<ChatCompletionResponseBody> policy;\n private readonly string summary = string.Empty;\n private const int MaxSummaryTokenLength = 2000;\n public Summarizer(", "score": 0.8121027946472168 }, { "filename": "Assets/Mochineko/LLMAgent/Operation/DemoOperatorUI.cs", "retrieved_chunk": " [SerializeField] private DemoOperator? demoOperator = null;\n [SerializeField] private TMPro.TMP_InputField? messageInput = null;\n [SerializeField] private Button? sendButton = null;\n private void Awake()\n {\n if (demoOperator == null)\n {\n throw new NullReferenceException(nameof(demoOperator));\n }\n if (messageInput == null)", "score": 0.807403564453125 } ]
csharp
LongTermChatMemory? Memory => memory;
using CommunityToolkit.Mvvm.DependencyInjection; using Microsoft.UI.Dispatching; using Microsoft.UI.Input; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Windows.UI.Core; using wingman.Helpers; using wingman.Interfaces; using wingman.ViewModels; namespace wingman.Views { public class GridExposeCursor : Grid { public InputCursor Cursor { get => ProtectedCursor; set => ProtectedCursor = value; } } public sealed partial class MainWindow : Window { public
IEventHandlerService eventsHandler;
private readonly DispatcherQueue _dispatcherQueue; private App _app; public MainWindow(IEventHandlerService eventsHandler) { InitializeComponent(); _dispatcherQueue = DispatcherQueue.GetForCurrentThread(); this.eventsHandler = eventsHandler; eventsHandler.InferenceCallback += HandleInferenceAsync; ExtendsContentIntoTitleBar = true; SetTitleBar(MainTitleBar); ViewModel = Ioc.Default.GetRequiredService<MainWindowViewModel>(); this.SetWindowSize(800, 600); this.SetIsResizable(true); this.Closed += OnClosed; _app = null; this.SetIcon("Assets/wingman.ico"); } public void SetApp(App app) { this._app = app; } public MainWindowViewModel ViewModel { get; } private void OnClosed(object sender, WindowEventArgs e) { // Unsubscribe the event handler eventsHandler.InferenceCallback -= HandleInferenceAsync; // Remove the event handler for the Closed event ((Window)sender).Closed -= OnClosed; if (_app != null) _app.Dispose(); } private async void HandleInferenceAsync(object sender, bool result) { // Your asynchronous code here if (result) { await CommunityToolkit.WinUI.DispatcherQueueExtensions.EnqueueAsync(_dispatcherQueue, () => { // Change the mouse cursor to waiting cursor var cursor = InputCursor.CreateFromCoreCursor(new CoreCursor(CoreCursorType.Wait, 0)); this.MainGrid.Cursor = cursor; //(ThisIsStupid as UIElement).ChangeCursor(InputSystemCursor.Create(InputSystemCursorShape.Wait)); }); } else { await CommunityToolkit.WinUI.DispatcherQueueExtensions.EnqueueAsync(_dispatcherQueue, () => { var cursor = InputCursor.CreateFromCoreCursor(new CoreCursor(CoreCursorType.Arrow, 0)); this.MainGrid.Cursor = cursor; // Change the mouse cursor to arrow cursor //(ThisIsStupid as UIElement).ChangeCursor(InputSystemCursor.Create(InputSystemCursorShape.Arrow)); }); } } } }
Views/MainWindow.xaml.cs
dannyr-git-wingman-41103f3
[ { "filename": "Services/LoggingService.cs", "retrieved_chunk": " public string Response { get; set; }\n }\n public enum VerboseLevel\n {\n Verbose,\n Normal\n }\n public class LoggingService : ILoggingService\n {\n private readonly object _lock = new object();", "score": 0.899111807346344 }, { "filename": "Views/Footer.xaml.cs", "retrieved_chunk": " {\n InitializeComponent();\n ViewModel = Ioc.Default.GetRequiredService<FooterViewModel>();\n DataContext = ViewModel;\n }\n public FooterViewModel ViewModel { get; }\n }\n public static class TextBoxBehavior\n {\n public static readonly DependencyProperty AutoScrollProperty =", "score": 0.8736530542373657 }, { "filename": "Helpers/Extensions.cs", "retrieved_chunk": " }\n public static class UIElementExtensions\n {\n public static void ChangeCursor(this UIElement uiElement, InputCursor cursor)\n {\n Type type = typeof(UIElement);\n type.InvokeMember(\"ProtectedCursor\", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, uiElement, new object[] { cursor });\n }\n }\n public static class Extensions", "score": 0.8670573234558105 }, { "filename": "ViewModels/FooterViewModel.cs", "retrieved_chunk": " }\n public string LogText\n {\n get => _logText;\n set\n {\n SetProperty(ref _logText, value);\n }\n }\n private async Task LogHandler(string logBook)", "score": 0.8556430339813232 }, { "filename": "Helpers/Converters.cs", "retrieved_chunk": " {\n return new SolidColorBrush(Colors.Transparent);\n }\n }\n public object ConvertBack(object value, Type targetType, object parameter, string language)\n {\n throw new NotImplementedException();\n }\n }\n public class BoolToApiKeyValidConverter : IValueConverter", "score": 0.8497498035430908 } ]
csharp
IEventHandlerService eventsHandler;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.Memory.Qdrant; using Microsoft.SemanticKernel.CoreSkills; using Microsoft.SemanticKernel.KernelExtensions; using Microsoft.SemanticKernel.Memory; using Microsoft.SemanticKernel.Orchestration; using Microsoft.SemanticKernel.SkillDefinition; using SKernel.Factory; using SKernel.Factory.Config; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace SKernel { public static partial class Extensions { internal static ISKFunction CreatePlan(this IKernel kernel) => kernel.Skills.GetFunction("plannerskill", "createplan"); internal static ISKFunction ExecutePlan(this IKernel kernel) => kernel.Skills.GetFunction("plannerskill", "executeplan"); internal static ContextVariables ToContext(this IEnumerable<KeyValuePair<string, string>> variables) { var context = new ContextVariables(); foreach (var variable in variables) context[variable.Key] = variable.Value; return context; } internal static IKernel RegisterSemanticSkills(this IKernel kernel, string skill, IList<string> skills, ILogger logger) { foreach (var prompt in Directory.EnumerateFiles(skill, "*.txt", SearchOption.AllDirectories) .Select(_ => new FileInfo(_))) { logger.LogDebug($"{prompt} === "); logger.LogDebug($"{skill} === "); logger.LogDebug($"{prompt.Directory?.Parent} === "); var skillName = FunctionName(new DirectoryInfo(skill), prompt.Directory); logger.LogDebug($"{skillName} === "); if (skills.Count != 0 && !skills.Contains(skillName.ToLower())) continue; logger.LogDebug($"Importing semantic skill ${skill}/${skillName}"); kernel.ImportSemanticSkillFromDirectory(skill, skillName); } return kernel; } private static string FunctionName(DirectoryInfo skill, DirectoryInfo? folder) { while (!skill.FullName.Equals(folder?.Parent?.FullName)) folder = folder?.Parent; return folder.Name; } internal static KernelBuilder WithOpenAI(this KernelBuilder builder, SKConfig config,
ApiKey api) => builder.Configure(_ => {
if (api.Text != null) _.AddOpenAITextCompletionService("text", config.Models.Text, api.Text); if (api.Embedding != null) _.AddOpenAIEmbeddingGenerationService("embedding", config.Models.Embedding, api.Embedding); if (api.Chat != null) _.AddOpenAIChatCompletionService("chat", config.Models.Chat, api.Chat); }); internal static IKernel Register(this IKernel kernel, ISkillsImporter importer, IList<string> skills) { importer.ImportSkills(kernel, skills); return kernel; } public static IKernel RegistryCoreSkills(this IKernel kernel, IList<string> skills) { if (ShouldLoad(skills, nameof(FileIOSkill))) kernel.ImportSkill(new FileIOSkill(), nameof(FileIOSkill)); if (ShouldLoad(skills, nameof(HttpSkill))) kernel.ImportSkill(new HttpSkill(), nameof(HttpSkill)); if (ShouldLoad(skills, nameof(TextSkill))) kernel.ImportSkill(new TextSkill(), nameof(TextSkill)); if (ShouldLoad(skills, nameof(TextMemorySkill))) kernel.ImportSkill(new TextMemorySkill(), nameof(TextMemorySkill)); if (ShouldLoad(skills, nameof(ConversationSummarySkill))) kernel.ImportSkill(new ConversationSummarySkill(kernel), nameof(ConversationSummarySkill)); if (ShouldLoad(skills, nameof(TimeSkill))) kernel.ImportSkill(new TimeSkill(), nameof(TimeSkill)); kernel.ImportSkill(new PlannerSkill(kernel), nameof(PlannerSkill)); return kernel; } private static bool ShouldLoad(IList<string> skills, string skill) => skills.Count == 0 || skills.Contains(skill.ToLower()); public static IHostBuilder ConfigureAdventKernelDefaults(this IHostBuilder builder, IConfiguration configuration) => builder.ConfigureServices(services => { services.AddSemanticKernelFactory(configuration); services.AddConsoleLogger(configuration); }); public static IServiceCollection AddSemanticKernelFactory(this IServiceCollection services, IConfiguration configuration) { var config = new SKConfig(); configuration.Bind(config); var options = config.Skills.ToSkillOptions(); foreach (var skillType in options.NativeSkillTypes) services.AddSingleton(skillType); services.AddSingleton(options); services.AddSingleton(config); services.AddSingleton<NativeSkillsImporter>(); services.AddSingleton<SemanticSkillsImporter>(); services.AddSingleton<SemanticKernelFactory>(); services.AddSingleton(typeof(IPlanExecutor), typeof(DefaultPlanExecutor)); services.AddSingleton<IMemoryStore>( config.Memory.Type == "Volatile" ? new VolatileMemoryStore() : new QdrantMemoryStore(config.Memory.Host, config.Memory.Port, config.Memory.VectorSize)); return services; } public static IServiceCollection AddConsoleLogger(this IServiceCollection services, IConfiguration configuration) { var factory = LoggerFactory.Create(builder => { builder.AddConfiguration(configuration.GetSection("Logging")); builder.AddConsole(); }); services.AddSingleton(factory); services.AddSingleton<ILogger>(factory.CreateLogger<object>()); return services; } public static IList<FunctionView> ToSkills(this IKernel kernel) { var view = kernel.Skills.GetFunctionsView(); return view.NativeFunctions.Values.SelectMany(Enumerable.ToList) .Union(view.SemanticFunctions.Values.SelectMany(Enumerable.ToList)).ToList(); } public static async Task<SKContext> InvokePipedFunctions(this IKernel kernel, Message message) => await kernel.RunAsync(message.Variables.ToContext(), (message.Pipeline?.Select(_ => kernel.Skills.GetFunction(_.Skill, _.Name)) ?? Array.Empty<ISKFunction>()) .ToArray()); public static SkillOptions ToSkillOptions(this string[] directories) => new() { SemanticSkillsFolders = directories, NativeSkillTypes = directories.SelectMany(_ => Directory .EnumerateFiles(_, "*.dll", SearchOption.AllDirectories) .SelectMany(file => Assembly.LoadFrom(file).GetTypes().Where(_ => _.GetMethods().Any(m => m.GetCustomAttribute<SKFunctionAttribute>() != null)))).ToList() }; /// <summary> /// 加密 /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <returns></returns> public static string AesEncryption(this string data, string key) { byte[] keyArr = Encoding.UTF8.GetBytes(key); byte[] dataArr = Encoding.UTF8.GetBytes(data); using var aes = Aes.Create(); aes.Key = keyArr; aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; using var cryptoTransform = aes.CreateEncryptor(); byte[] result = cryptoTransform.TransformFinalBlock(dataArr, 0, dataArr.Length); return Convert.ToBase64String(result); } /// <summary> /// 解密 /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <returns></returns> public static string AesDecryption(this string data, string key) { byte[] keyArr = Encoding.UTF8.GetBytes(key); byte[] dataArr = Convert.FromBase64String(data); using var aes = Aes.Create(); aes.Key = keyArr; aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; using var cryptoTransform = aes.CreateDecryptor(); byte[] result = cryptoTransform.TransformFinalBlock(dataArr, 0, dataArr.Length); return Convert.ToBase64String(result); } } }
src/SKernel/KernelExtensions.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.8051947355270386 }, { "filename": "src/SKernel.WebApi/Program.cs", "retrieved_chunk": " {\n public static void Main(string[] args)\n {\n var builder = WebApplication.CreateBuilder(args);\n var skills = builder.Configuration.GetSection(\"SKConfig:Skills\").Get<string[]>() ?? new[] { \"./skills\" };\n foreach (var folder in skills)\n {\n if (!Directory.Exists(folder))\n Directory.CreateDirectory(folder);\n }", "score": 0.7912769913673401 }, { "filename": "src/SKernel.Services/Extensions.cs", "retrieved_chunk": " return apiConfig;\n }\n public static bool TryGetKernel(this HttpRequest request, SemanticKernelFactory factory,\n out IKernel? kernel, IList<string>? selected = null)\n {\n var api = request.ToApiKeyConfig();\n kernel = api is { Text: { }, Embedding: { } } ? factory.Create(api, selected) : null;\n return kernel != null;\n }\n public static IResult ToResult(this SKContext result, IList<string>? skills) => (result.ErrorOccurred)", "score": 0.7875372171401978 }, { "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.7764424085617065 }, { "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.7598945498466492 } ]
csharp
ApiKey api) => builder.Configure(_ => {
using HarmonyLib; using ULTRAKILL.Cheats; using UnityEngine; namespace Ultrapain.Patches { public class Stalker_SandExplode_Patch { static bool Prefix(Stalker __instance, ref int ___difficulty, ref EnemyIdentifier ___eid, int __0, ref bool ___exploding, ref float ___countDownAmount, ref float ___explosionCharge, ref Color ___currentColor, Color[] ___lightColors, AudioSource ___lightAud,
AudioClip[] ___lightSounds, ref bool ___blinking, Machine ___mach, ref bool ___exploded, Transform ___target) {
bool removeStalker = true; if (!(StockMapInfo.Instance != null && StockMapInfo.Instance.levelName == "GOD DAMN THE SUN" && __instance.transform.parent != null && __instance.transform.parent.name == "Wave 1" && __instance.transform.parent.parent != null && __instance.transform.parent.parent.name.StartsWith("5 Stuff"))) { removeStalker = false; } GameObject explosion = Object.Instantiate<GameObject>(__instance.explosion, __instance.transform.position + Vector3.up * 2.5f, Quaternion.identity); if (__0 != 1) { explosion.transform.localScale *= 1.5f; } if (___eid.stuckMagnets.Count > 0) { float num = 0.75f; if (___eid.stuckMagnets.Count > 1) { num -= 0.125f * (float)(___eid.stuckMagnets.Count - 1); } explosion.transform.localScale *= num; } SandificationZone zone = explosion.GetComponentInChildren<SandificationZone>(); zone.buffDamage = zone.buffHealth = zone.buffSpeed = false; if (ConfigManager.stalkerSpreadHealthRad.value) zone.healthBuff = ___eid.healthBuffModifier + ConfigManager.stalkerSpreadHealthAddition.value; else zone.healthBuff = 0; if (ConfigManager.stalkerSpreadDamageRad.value) zone.damageBuff = ___eid.damageBuffModifier + ConfigManager.stalkerSpreadDamageAddition.value; else zone.damageBuff = 0; if (ConfigManager.stalkerSpreadSpeedRad.value) zone.speedBuff = ___eid.speedBuffModifier + ConfigManager.stalkerSpreadSpeedAddition.value; else zone.speedBuff = 0; if ((!removeStalker || ___eid.blessed || InvincibleEnemies.Enabled) && __0 != 1) { ___exploding = false; ___countDownAmount = 0f; ___explosionCharge = 0f; ___currentColor = ___lightColors[0]; ___lightAud.clip = ___lightSounds[0]; ___blinking = false; return false; } ___exploded = true; if (!___mach.limp) { ___mach.GoLimp(); ___eid.Death(); } if (___target != null) { if (MonoSingleton<StalkerController>.Instance.CheckIfTargetTaken(___target)) { MonoSingleton<StalkerController>.Instance.targets.Remove(___target); } EnemyIdentifier enemyIdentifier; if (___target.TryGetComponent<EnemyIdentifier>(out enemyIdentifier) && enemyIdentifier.buffTargeter == ___eid) { enemyIdentifier.buffTargeter = null; } } if (___eid.drillers.Count != 0) { for (int i = ___eid.drillers.Count - 1; i >= 0; i--) { Object.Destroy(___eid.drillers[i].gameObject); } } __instance.gameObject.SetActive(false); Object.Destroy(__instance.gameObject); return false; } } public class SandificationZone_Enter_Patch { static void Postfix(SandificationZone __instance, Collider __0) { if (__0.gameObject.layer == 10 || __0.gameObject.layer == 11) { EnemyIdentifierIdentifier component = __0.gameObject.GetComponent<EnemyIdentifierIdentifier>(); if (component && component.eid && !component.eid.dead && component.eid.enemyType != EnemyType.Stalker) { EnemyIdentifier eid = component.eid; if (eid.damageBuffModifier < __instance.damageBuff) eid.DamageBuff(__instance.damageBuff); if (eid.speedBuffModifier < __instance.speedBuff) eid.SpeedBuff(__instance.speedBuff); if (eid.healthBuffModifier < __instance.healthBuff) eid.HealthBuff(__instance.healthBuff); } } } } }
Ultrapain/Patches/Stalker.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " }\n else\n patch.swingComboLeft = 2;*/\n }\n }\n class Mindflayer_MeleeTeleport_Patch\n {\n public static Vector3 deltaPosition = new Vector3(0, -10, 0);\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged)\n {", "score": 0.8230044841766357 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " }\n class V2SecondFastCoin\n {\n static MethodInfo switchWeapon = typeof(V2).GetMethod(\"SwitchWeapon\", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);\n static bool Prefix(V2 __instance, ref int ___coinsToThrow, ref bool ___aboutToShoot, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb,\n ref Transform ___target, Animator ___anim, ref bool ___shootingForCoin, ref int ___currentWeapon, ref float ___shootCooldown, ref bool ___aiming)\n {\n if (___coinsToThrow == 0)\n {\n return false;", "score": 0.8229718208312988 }, { "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.8191878795623779 }, { "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.8191120624542236 }, { "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.8188749551773071 } ]
csharp
AudioClip[] ___lightSounds, ref bool ___blinking, Machine ___mach, ref bool ___exploded, Transform ___target) {
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/QuestNodeSearchWindow.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEditor;\nusing UnityEditor.Experimental.GraphView;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nnamespace QuestSystem.QuestEditor\n{\n public class QuestNodeSearchWindow : ScriptableObject, ISearchWindowProvider\n {", "score": 0.9176694750785828 }, { "filename": "Editor/GraphEditor/NodeQuestGraph.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEditor.Experimental.GraphView;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nusing UnityEditor;\nnamespace QuestSystem.QuestEditor\n{\n [System.Serializable]\n public class NodeQuestGraph : UnityEditor.Experimental.GraphView.Node", "score": 0.9041051268577576 }, { "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.8847296833992004 }, { "filename": "Editor/CustomInspector/QuestOnObjectWorldEditor.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\nnamespace QuestSystem.QuestEditor\n{\n [CustomEditor(typeof(QuestOnObjectWorld))]\n public class QuestOnObjectWorldEditor : Editor\n {\n public override void OnInspectorGUI()", "score": 0.8834264278411865 }, { "filename": "Editor/CustomInspector/QuestObjectiveUpdaterEditor.cs", "retrieved_chunk": "using UnityEngine;\nusing UnityEditor;\nusing System;\nusing System.Collections.Generic;\nnamespace QuestSystem.QuestEditor\n{\n [CustomEditor(typeof(QuestObjectiveUpdater))]\n public class QuestObjectiveUpdaterEditor : Editor\n { \n private int selectedValue = 0;", "score": 0.8797557353973389 } ]
csharp
QuestGraphView _targetGraphView;
#nullable enable using System; using System.Collections.Generic; using System.Threading; using Cysharp.Threading.Tasks; using Mochineko.Relent.Extensions.UniTask; namespace Mochineko.FacialExpressions.Blink { /// <summary> /// A sequential eyelid animator that animates eyelid sequentially by frame collection. /// </summary> public sealed class SequentialEyelidAnimator : ISequentialEyelidAnimator { private readonly
IEyelidMorpher morpher;
/// <summary> /// Creates a new instance of <see cref="SequentialEyelidAnimator"/>. /// </summary> /// <param name="morpher">Target morpher.</param> public SequentialEyelidAnimator(IEyelidMorpher morpher) { this.morpher = morpher; } public async UniTask AnimateAsync( IEnumerable<EyelidAnimationFrame> frames, CancellationToken cancellationToken) { morpher.Reset(); while (!cancellationToken.IsCancellationRequested) { foreach (var frame in frames) { if (cancellationToken.IsCancellationRequested) { break; } morpher.MorphInto(frame.sample); var result = await RelentUniTask.Delay( TimeSpan.FromSeconds(frame.durationSeconds), delayTiming: PlayerLoopTiming.Update, cancellationToken: cancellationToken); // Cancelled if (result.Failure) { break; } } } morpher.Reset(); } } }
Assets/Mochineko/FacialExpressions/Blink/SequentialEyelidAnimator.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "filename": "Assets/Mochineko/FacialExpressions/Blink/ISequentialEyelidAnimator.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing System.Threading;\nusing Cysharp.Threading.Tasks;\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// Defines an animator to animate eyelid sequentially by frame collection.\n /// </summary>\n public interface ISequentialEyelidAnimator", "score": 0.8898707628250122 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/CompositeEyelidMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// Composition of some <see cref=\"IEyelidMorpher\"/>s.\n /// </summary>\n public sealed class CompositeEyelidMorpher : IEyelidMorpher\n {\n private readonly IReadOnlyList<IEyelidMorpher> morphers;", "score": 0.8883662223815918 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/IFramewiseEyelidAnimator.cs", "retrieved_chunk": "#nullable enable\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// Defines an animator to update eyelid animation per game engine frame.\n /// </summary>\n public interface IFramewiseEyelidAnimator\n {\n /// <summary>\n /// Updates animation.", "score": 0.8795033097267151 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/LinearEyelidAnimationGenerator.cs", "retrieved_chunk": "#nullable enable\nusing System;\nusing System.Collections.Generic;\nusing Random = UnityEngine.Random;\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// A generator of <see cref=\"EyelidAnimationFrame\"/> for linear eyelid animation.\n /// </summary>\n public static class LinearEyelidAnimationGenerator", "score": 0.8754974603652954 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/IEyelidMorpher.cs", "retrieved_chunk": "#nullable enable\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// Defines a morpher of eyelid.\n /// </summary>\n public interface IEyelidMorpher\n {\n /// <summary>\n /// Morphs specified eyelid into specified weight. ", "score": 0.872838020324707 } ]
csharp
IEyelidMorpher morpher;
using System.Diagnostics; namespace OGXbdmDumper { /// <summary> /// TODO: description /// </summary> [DebuggerDisplay("{" + nameof(Name) + "}")] public class Module { /// <summary> /// Name of the module that was loaded. /// </summary> public string? Name; /// <summary> /// Address that the module was loaded to. /// </summary> public uint BaseAddress; /// <summary> /// Size of the module. /// </summary> public int Size; /// <summary> /// Time stamp of the module. /// </summary> public DateTime TimeStamp; /// <summary> /// Checksum of the module. /// </summary> public uint Checksum; /// <summary> /// Sections contained within the module. /// </summary> public List<
ModuleSection>? Sections;
/// <summary> /// Indicates whether or not the module uses TLS. /// </summary> public bool HasTls; /// <summary> /// Indicates whether or not the module is an Xbox executable. /// </summary> public bool IsXbe; /// <summary> /// Gets an Xbox module section by name. /// </summary> /// <param name="name"></param> /// <returns></returns> public ModuleSection? GetSection(string name) { return Sections?.FirstOrDefault(section => name.Equals(section?.Name)); } } }
src/OGXbdmDumper/Module.cs
Ernegien-OGXbdmDumper-07a1e82
[ { "filename": "src/OGXbdmDumper/XboxFileInformation.cs", "retrieved_chunk": " public string FullName;\n /// <summary>\n /// The file size.\n /// </summary>\n public long Size;\n /// <summary>\n /// The file attributes.\n /// </summary>\n public FileAttributes Attributes;\n /// <summary>", "score": 0.9355999827384949 }, { "filename": "src/OGXbdmDumper/Kernel.cs", "retrieved_chunk": " /// The kernel module information. Note: Internally caches result for future use.\n /// </summary>\n public readonly Module Module;\n /// <summary>\n /// The kernel image size. NOTE: May not be contiguous memory.\n /// </summary>\n public int Size => Module.Size;\n /// <summary>\n /// The kernel base address in memory.\n /// </summary>", "score": 0.9076142907142639 }, { "filename": "src/OGXbdmDumper/Kernel.cs", "retrieved_chunk": " public long Address => Module.BaseAddress;\n /// <summary>\n /// The kernel build time in UTC.\n /// </summary>\n public DateTime Date => Module.TimeStamp;\n /// <summary>\n /// The Xbox kernel build version.\n /// </summary>\n public Version Version { get; private set; }\n /// <summary>", "score": 0.9050196409225464 }, { "filename": "src/OGXbdmDumper/Thread.cs", "retrieved_chunk": " public uint Base;\n /// <summary>\n /// TODO: description\n /// </summary>\n public uint Limit;\n /// <summary>\n /// TODO: description\n /// </summary>\n public DateTime CreationTime;\n }", "score": 0.9027446508407593 }, { "filename": "src/OGXbdmDumper/CommandResponse.cs", "retrieved_chunk": " /// </summary>\n public string Full { get; }\n /// <summary>\n /// The command response code.\n /// </summary>\n public int Code { get; }\n /// <summary>\n /// The message portion of the command response.\n /// </summary>\n public string Message { get; }", "score": 0.9019263982772827 } ]
csharp
ModuleSection>? Sections;
//#define PRINT_DEBUG using System; using Godot; using System.Collections.Generic; using System.IO; using System.Linq; using Path = System.IO.Path; using File = System.IO.File; namespace GodotLauncher { public partial class LauncherManager : Control { [Export] private bool useLocalData; private CheckBox installedOnlyToggle; private CheckBox classicToggle; private CheckBox monoToggle; private CheckBox preReleaseToggle; private FileDialog fileDialog; private MenuButton newProjectVersion; private string newProjectVersionKey; private Node projectsEntriesNode; private Node installersEntriesNode; private Control infoNode; private double infoNodeTimer; private bool showExtracting; private const string ConfigFileName = "config.json"; private const string ProjectsFileName = "projects.json"; private
Downloader installersDownloader;
private const string InstallersJson = "https://raw.githubusercontent.com/NathanWarden/ready-to-launch/master/godot-project/Data/installers.json"; private const string LastInstallerList = "last-installers.json"; private List<ProjectEntryData> projectEntries = new (); private Dictionary<string, InstallerEntryData> installerEntries = new (); private Dictionary<string, InstallerEntryData> previousInstallers = new (); private Dictionary<string, Downloader> downloaders = new (); private Config config; public override void _Ready() { GetWindow().Title = "Ready To Launch (Alpha)"; GetWindow().FilesDropped += _onFilesDropped; DataPaths.CreateInstallationDirectory(); var configJson = DataPaths.ReadFile(ConfigFileName, "{}"); config = DataBuilder.LoadConfigFromJson(configJson); var projectsJson = DataPaths.ReadFile(ProjectsFileName, "[]"); projectEntries = DataBuilder.LoadProjectListFromJson(projectsJson); fileDialog = GetNode<FileDialog>("FileDialog"); newProjectVersion = GetNode<MenuButton>("ProjectsPanel/AddProjectsContainer/NewProjectVersionMenu"); projectsEntriesNode = GetNode("ProjectsPanel/ProjectsList/ProjectEntries"); installersEntriesNode = GetNode("InstallersPanel/InstallersList/InstallerEntries"); infoNode = GetNode<Control>("Info"); SetupToggles(); if (OS.IsDebugBuild() && useLocalData) { installerEntries = DataBuilder.BuildInstallerData(); BuildLists(false); } else { var json = DataPaths.ReadFile(LastInstallerList); installerEntries = DataBuilder.LoadInstallerData(json); BuildLists(false); installersDownloader = new Downloader(InstallersJson, this); installersDownloader.Start(); } } public override void _Process(double delta) { if (CheckForQuit()) return; if (infoNodeTimer > 0) { infoNodeTimer -= delta; if (infoNodeTimer <= 0) infoNode.Visible = false; } if (installersDownloader != null && installersDownloader.IsDone) { // If the downloader failed, use the last downloaded json data var previousJson = DataPaths.ReadFile(LastInstallerList); if (string.IsNullOrEmpty(previousJson)) { // If that doesn't exist, use the builtin one previousJson = FileHelper.ReadAllText("res://Data/installers.json"); } var json = installersDownloader.HasError ? previousJson : installersDownloader.ReadText(); DataPaths.WriteFile(LastInstallerList, json); installerEntries = DataBuilder.LoadInstallerData(json); previousInstallers = DataBuilder.LoadInstallerData(previousJson); BuildLists(true); installersDownloader = null; } foreach (var dlPair in downloaders) { var key = dlPair.Key; var downloader = dlPair.Value; var entry = installerEntries[key]; if (downloader == null) continue; if (!downloader.IsDone) { infoNode.Call("show_message", "Downloading Godot " + entry.version + $" ({entry.BuildType}) ...\n" + downloader.SizeInMb.ToString("F2") + " MB"); continue; } if (!showExtracting) { infoNode.Call("show_message", "Extracting...\n\nThis may take a few minutes."); showExtracting = true; return; } var data = downloader.ReadData(); if (data != null) { string fileName = $"{key}.zip"; DataPaths.WriteFile(fileName, data); DataPaths.ExtractArchive(fileName, entry); if (!GetNode<Control>("InstallersPanel").Visible) { BuildInstallersList(false); } bool installerExists = DataPaths.ExecutableExists(entry); installersEntriesNode.Call("_update_installer_button", entry.version, entry.BuildType, installerExists); downloaders.Remove(key); infoNode.Visible = false; showExtracting = false; BuildProjectsList(); break; } if (downloader.HasError) { GD.Print(downloader.ErrorMessage); infoNode.Call("show_message", downloader.ErrorMessage); downloaders.Remove(key); infoNodeTimer = 3; break; } GD.Print("Data was null!"); } } private bool CheckForQuit() { if (Input.IsActionPressed("Control") && Input.IsActionJustPressed("Quit")) { GetTree().Quit(); return true; } return false; } private void SetupToggles() { var rootNode = GetNode("InstallersPanel/HBoxContainer"); installedOnlyToggle = rootNode.GetNode<CheckBox>("InstalledOnlyToggle"); classicToggle = rootNode.GetNode<CheckBox>("ClassicToggle"); monoToggle = rootNode.GetNode<CheckBox>("MonoToggle"); preReleaseToggle = rootNode.GetNode<CheckBox>("PreReleaseToggle"); installedOnlyToggle.ButtonPressed = config.installedOnlyToggled; classicToggle.ButtonPressed = config.classicToggled; monoToggle.ButtonPressed = config.monoToggled; preReleaseToggle.ButtonPressed = config.preReleaseToggled; } void BuildProjectsList() { var installers = GetInstalledVersions(); var installerKeysList = new List<string>(); var installerNamesList = new List<string>(); foreach (var installer in installers) { installerKeysList.Add(installer.VersionKey); installerNamesList.Add(installer.version + " " + installer.BuildType); } var installerKeys = installerKeysList.ToArray(); var installerNames = installerNamesList.ToArray(); projectsEntriesNode.Call("_clear_project_buttons"); projectEntries.Sort((x, y) => { if (x.timestamp == y.timestamp) return 0; return x.timestamp < y.timestamp ? 1 : -1; }); newProjectVersion.Call("_setup", "", installerKeys, installerNames); foreach (var entry in projectEntries) { string version = ""; string buildType = ""; if (installerEntries.TryGetValue(entry.versionKey, out var installer)) { version = installer.version; buildType = installer.BuildType; } projectsEntriesNode.Call("_add_project_button", entry.path, version, buildType, false, installerKeys, installerNames); } } List<InstallerEntryData> GetInstalledVersions() { var results = new List<InstallerEntryData>(); foreach (var entry in installerEntries.Values) { bool installerExists = DataPaths.ExecutableExists(entry); if (installerExists) results.Add(entry); } return results; } void BuildLists(bool showNewInstallers) { BuildInstallersList(showNewInstallers); BuildProjectsList(); } void BuildInstallersList(bool showNewInstallers) { installersEntriesNode.Call("_clear_installer_buttons"); if (showNewInstallers) { foreach (var entry in installerEntries) { if (!previousInstallers.ContainsKey(entry.Key)) { projectsEntriesNode.Call("_new_installer_available", entry.Value.version, entry.Value.BuildType); } } } foreach (var entry in GetFilteredEntries()) { bool installerExists = DataPaths.ExecutableExists(entry); var path = DataPaths.GetExecutablePath(entry); installersEntriesNode.Call("_add_installer_button", entry.version, entry.BuildType, path, installerExists); } } IEnumerable<InstallerEntryData> GetFilteredEntries() { foreach (var entry in installerEntries.Values) { if (config.installedOnlyToggled && !DataPaths.ExecutableExists(entry)) continue; if (!config.preReleaseToggled && entry.preRelease) continue; if (!config.monoToggled && entry.mono) continue; if (!config.classicToggled && !entry.mono) continue; yield return entry; } } void _onNewProjectPressed() { fileDialog.Visible = true; } void _onNewProjectVersionChanged(string versionKey) { newProjectVersionKey = versionKey; } void _onFileDialogDirSelected(string directoryPath) { if (string.IsNullOrEmpty(newProjectVersionKey)) { var installers = GetInstalledVersions(); if (installers.Count == 0) { GD.Print("No version selected!!!"); return; } newProjectVersionKey = installers[0].VersionKey; } DataPaths.EnsureProjectExists(directoryPath); var project = new ProjectEntryData { path = directoryPath, versionKey = newProjectVersionKey, timestamp = DateTime.UtcNow.Ticks }; projectEntries.Add(project); LaunchProject(directoryPath, false); } void _onFilesDropped(string[] files) { for (int i = 0; i < files.Length; i++) { string path = DataPaths.SanitizeProjectPath(files[i]); // Check for duplicates if (projectEntries.Any(t => t.path.Equals(path))) continue; var versionKey = File.ReadAllText(GodotVersionPath(path)); projectEntries.Add(new ProjectEntryData { path = path, versionKey = versionKey, timestamp = 0 }); InstallVersion(versionKey); } SaveProjectsList(); BuildProjectsList(); } void SaveConfig() { var json = DataBuilder.GetConfigJson(config); DataPaths.WriteFile(ConfigFileName, json); } void SaveProjectsList() { var json = DataBuilder.GetProjectListJson(projectEntries); DataPaths.WriteFile(ProjectsFileName, json); } string GodotVersionPath(string basePath) => Path.Combine(basePath, "godotversion.txt"); void _onProjectEntryPressed(string path) { LaunchProject(path, false); } void _onRunProject(string path) { LaunchProject(path, true); } void LaunchProject(string path, bool run) { for (int i = 0; i < projectEntries.Count; i++) { if (projectEntries[i].path.Equals(path) && installerEntries.TryGetValue(projectEntries[i].versionKey, out var entry)) { var project = projectEntries[i]; #if PRINT_DEBUG GD.Print("Launch " + path); #endif if (!run) { File.WriteAllText(GodotVersionPath(path), project.versionKey); } project.timestamp = DateTime.UtcNow.Ticks; SaveProjectsList(); BuildProjectsList(); if (entry.version.StartsWith("1.") || entry.version.StartsWith("2.")) { LaunchInstaller(entry); return; } var additionalFlags = run ? "" : "-e"; DataPaths.LaunchGodot(entry, additionalFlags + " --path \"" + path + "\""); //OS.WindowMinimized = config.minimizeOnLaunch; return; } } } void _onProjectVersionChanged(string path, string versionKey) { foreach (var entry in projectEntries) { if (entry.path.Equals(path)) { entry.versionKey = versionKey; break; } } SaveProjectsList(); } void _onShowInFolder(string path) { var fileInfo = new FileInfo(path); if (fileInfo.Exists) { path = fileInfo.DirectoryName; } DataPaths.ShowInFolder(path); } void _onProjectDeletePressed(string path) { for (int i = 0; i < projectEntries.Count; i++) { if (!projectEntries[i].path.Equals(path)) continue; projectEntries.RemoveAt(i); break; } SaveProjectsList(); BuildProjectsList(); } void _onInstallerEntryPressed(string version, string buildType) { InstallVersion(version + buildType); } void InstallVersion(string key) { var installerEntry = installerEntries[key]; if (LaunchInstaller(installerEntry) || downloaders.ContainsKey(key)) return; var entry = installerEntries[key]; downloaders[key] = new Downloader(entry.Url, this); downloaders[key].Start(); infoNode.Call("show_message", "Downloading Godot " + installerEntry.version + $" ({installerEntry.BuildType}) ..."); } bool LaunchInstaller(InstallerEntryData installerEntry) { bool installerExists = DataPaths.ExecutableExists(installerEntry); if (installerExists) { DataPaths.LaunchGodot(installerEntry); //OS.WindowMinimized = config.minimizeOnLaunch; return true; } return false; } void _onInstallerDeletePressed(string version, string buildType) { DataPaths.DeleteVersion(version, buildType); BuildLists(false); } void _onInstalledOnlyToggled(bool state) { config.installedOnlyToggled = state; BuildInstallersList(false); SaveConfig(); } void _onClassicToggled(bool state) { config.classicToggled = state; BuildInstallersList(false); SaveConfig(); } void _onMonoToggled(bool state) { config.monoToggled = state; BuildInstallersList(false); SaveConfig(); } void _onPreReleaseToggled(bool state) { config.preReleaseToggled = state; BuildInstallersList(false); SaveConfig(); } void _onDebugOsSelected(string os) { DataPaths.platformOverride = os; BuildInstallersList(false); } void _onDownloadAllPressed() { foreach (var entry in installerEntries.Values) { if (DataPaths.ExecutableExists(entry) || string.IsNullOrEmpty(entry.Url)) continue; var key = entry.VersionKey; downloaders[key] = new Downloader(entry.Url, this); downloaders[key].Start(); } } } }
godot-project/Scripts/DataManagement/LauncherManager.cs
NathanWarden-ready-to-launch-58eba6d
[ { "filename": "godot-project/Scripts/DataManagement/Downloader.cs", "retrieved_chunk": "using System.Net;\nusing System.Text;\nusing Godot;\nnamespace GodotLauncher\n{\n\tpublic partial class Downloader : Node\n\t{\n\t\tprivate string url;\n\t\tprivate HttpRequest downloader;\n\t\tprivate HttpClient client;", "score": 0.6712629795074463 }, { "filename": "godot-project/Scripts/DataManagement/Downloader.cs", "retrieved_chunk": "\t\tprivate byte[] data;\n\t\tprivate bool done;\n\t\tprivate string error;\n\t\tpublic Downloader(string url, Node downloaderParent)\n\t\t{\n\t\t\tthis.url = url;\n\t\t\tdownloaderParent.AddChild(this);\n\t\t\tdownloader = new HttpRequest();\n\t\t\tdownloader.UseThreads = true;\n\t\t\tAddChild(downloader);", "score": 0.667462170124054 }, { "filename": "godot-project/addons/PostBuild/BuildData.cs", "retrieved_chunk": "using System;\nusing Newtonsoft.Json;\n[Serializable]\npublic class BuildData\n{\n\tpublic const string BuildDataPath = \"res://Data/BuildData.json\";\n\tpublic int buildNumber;\n\tpublic string version;\n\tpublic string storeFlag;\n\tpublic static BuildData Load()", "score": 0.6642072200775146 }, { "filename": "godot-project/Scripts/DataManagement/InstallerEntryData.cs", "retrieved_chunk": "\t\tpublic PlatformData linux;\n\t\tpublic PlatformData mac;\n\t\tpublic PlatformData win;\n\t\t[JsonIgnore] public string VersionKey => version + BuildType;\n\t\t[JsonIgnore] public string BuildType => mono ? \"mono\" : \"classic\";\n\t\t[JsonIgnore] public PlatformData PlatformData\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tswitch (DataPaths.GetPlatformName())", "score": 0.6560758352279663 }, { "filename": "godot-project/Scripts/DataManagement/DataBuilder.cs", "retrieved_chunk": "using System.Collections.Generic;\nusing GodotLauncher;\nusing Newtonsoft.Json;\npublic static class DataBuilder\n{\n\tpublic static Dictionary<string, InstallerEntryData> BuildInstallerData()\n\t{\n\t\tvar json = FileHelper.ReadAllText(\"res://Data/installers.json\");\n\t\tvar entries = LoadInstallerData(json);\n\t\treturn entries;", "score": 0.6507129669189453 } ]
csharp
Downloader installersDownloader;
using System; using System.Collections.Generic; using UnityEngine; using Str=System.ReadOnlySpan<char>; namespace ZimGui.Demo { public enum LogTimeType { None, Seconds, MilliSeconds } public static class SimpleConsole { static object _lock = new object(); static
RingBuffer<(TimeOfDay Time ,string Text ,UiColor Color)> _elements;
public static int Capacity { get { lock (_lock) { return _elements.Capacity; } } } public static void Init(int capacity=32,bool receiveLog=true) { _elements=new (capacity); if(receiveLog) Application.logMessageReceivedThreaded += ReceivedLog; } static void ReceivedLog(string logString, string stackTrace, LogType logType) { switch (logType) { case LogType.Log:Log(logString); return; case LogType.Warning: case LogType.Assert: Log(logString,UiColor.Yellow); return; case LogType.Error: case LogType.Exception: Log(logString,UiColor.Red); return; default: return; } } public static void Clear() { _elements.Clear(); Application.logMessageReceivedThreaded -= ReceivedLog; } public static void Log(string text) { if (_inLock) return; lock (_lock) { _elements.Add((new TimeOfDay(DateTime.Now),text,IMStyle.FontColor)); } } public static void Log(string text,UiColor color) { if (_inLock) return; lock (_lock) { _elements.Add((new TimeOfDay(DateTime.Now), text, color)); } } static float scrollValue=0; static bool _inLock=false; public static bool Draw() { lock (_lock) { _inLock = true; try { var count = _elements.Count; if (IM.Button("Clear")) { _elements.Clear(); return true; } if (count == 0) return true; if (!IM.Current.TryGetRemainRect(out var rect)) return true; var height = rect.height; var elementHeight = IMStyle.SpacedTextHeight * 1.1f; var elementsHeight = elementHeight * count; var elementRect = new Rect(rect.xMin, rect.yMax - elementHeight, rect.width, IMStyle.SpacedTextHeight); if (height < IMStyle.SpacedTextHeight) { return true; } if (elementsHeight < height) { scrollValue = 0; Span<char> timeLabel = stackalloc char[11]; timeLabel[0] = '['; timeLabel[9] = ']'; timeLabel[10] = ' '; var timeRange = timeLabel[1..9]; foreach (var element in _elements) { element.Time.FormatHoursToSeconds(timeRange); IM.Label(elementRect, timeLabel, element.Text, element.Color); elementRect.MoveY(-elementHeight); } return true; } else { var barRect = rect; barRect.xMin += rect.width - 10f; IM.VerticalScroll(barRect, ref scrollValue, height / elementsHeight, out var top, out var bottom); elementRect.xMax -= 10f; var topIndex = (int) (Mathf.Ceil(count * top)); topIndex = Mathf.Clamp(topIndex, 0, count - 1); elementRect.MoveY((count * top - topIndex) * elementHeight); Span<char> timeLabel = stackalloc char[11]; timeLabel[0] = '['; timeLabel[9] = ']'; timeLabel[10] = ' '; var timeRange = timeLabel[1..9]; foreach (var element in _elements.Slice(topIndex, (int) (height / elementHeight))) { element.Time.FormatHoursToSeconds(timeRange); IM.Label(elementRect, timeLabel, element.Text, element.Color); elementRect.MoveY(-elementHeight); } return true; } } finally { _inLock = false; } } } } }
Assets/ZimGui/Demo/SimpleConsole.cs
Akeit0-ZimGui-Unity-cc82fb9
[ { "filename": "Assets/ZimGui/IMInput.cs", "retrieved_chunk": "using UnityEngine;\nnamespace ZimGui {\n public enum FocusState {\n NotFocus,\n NewFocus,\n Focus,\n }\n public static class IMInput {\n public struct ModalWindowData {\n public bool IsActive;", "score": 0.8779129385948181 }, { "filename": "Assets/ZimGui/Window.cs", "retrieved_chunk": "using System;\nusing UnityEngine;\nnamespace ZimGui {\n public class Window {\n public string Name;\n public readonly int WindowID;\n static int _lastWindowID;\n public Rect Rect;\n public Vector2 NextPosition;\n public bool Opened;", "score": 0.8640751838684082 }, { "filename": "Assets/ZimGui/Coordinate.cs", "retrieved_chunk": "namespace ZimGui {\n public enum Coordinate {\n TopLeft,\n /// <summary>\n /// Default\n /// </summary>\n BottomLeft,\n }\n}", "score": 0.8500000238418579 }, { "filename": "Assets/ZimGui/Text/RefDataMap.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nnamespace ZimGui.Text {\n public class RefDataMap<TValue> {\n public struct Entry {\n public int hashCode;\n public int next;\n public TValue value;\n }\n int[] buckets;", "score": 0.8395228385925293 }, { "filename": "Assets/ZimGui/Core/Quad.cs", "retrieved_chunk": " public byte Padding1;\n public byte Padding2;\n }\n [StructLayout(LayoutKind.Sequential)]\n public struct VertexData {\n /// <summary>\n /// Screen Position\n /// </summary>\n public Vector2 Position;\n public UiColor Color;", "score": 0.8369754552841187 } ]
csharp
RingBuffer<(TimeOfDay Time ,string Text ,UiColor Color)> _elements;
using Gum.InnerThoughts; using Gum.Utilities; using Murder.Serialization; using Newtonsoft.Json; using System.Reflection; using System.Text; namespace Gum { /// <summary> /// This is the parser entrypoint when converting .gum -> metadata. /// </summary> public class Reader { /// <param name="arguments"> /// This expects the following arguments: /// `.\Gum <input-path> <output-path>` /// <input-path> can be the path of a directory or a single file. /// <output-path> is where the output should be created. /// </param> internal static void Main(string[] arguments) { // If this got called from the msbuild command, for example, // it might group different arguments into the same string. // We manually split them if there's such a case. // // Regex stringParser = new Regex(@"([^""]+)""|\s*([^\""\s]+)"); Console.OutputEncoding = Encoding.UTF8; if (arguments.Length != 2) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("This expects the following arguments:\n" + "\t.\\Whispers <input-path> <output-path>\n\n" + "\t - <input-path> can be the path of a directory or a single file.\n" + "\t - <output-path> is where the output should be created.\n"); Console.ResetColor(); throw new ArgumentException(nameof(arguments)); } string outputPath = ToRootPath(arguments[1]); if (!Directory.Exists(outputPath)) { OutputHelpers.WriteError($"Unable to find output path '{outputPath}'"); return; } CharacterScript[] scripts = ParseImplementation(inputPath: arguments[0], lastModified: null, DiagnosticLevel.All); foreach (CharacterScript script in scripts) { _ = Save(script, outputPath); } if (scripts.Length > 0) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"🪄 Success! Successfully saved output at {outputPath}."); Console.ResetColor(); } } internal static bool Save(CharacterScript script, string path) { string json = JsonConvert.SerializeObject(script, Settings); File.WriteAllText(path: Path.Join(path, $"{script.Name}.json"), contents: json); return true; } internal static CharacterScript? Retrieve(string filepath) { if (!File.Exists(filepath)) { OutputHelpers.WriteError($"Unable to find file at '{filepath}'"); return null; } string json = File.ReadAllText(filepath); return JsonConvert.DeserializeObject<CharacterScript>(json); } /// <summary> /// This will parse all the documents in <paramref name="inputPath"/>. /// </summary> public static CharacterScript[] Parse(string inputPath, DateTime? lastModified, out string errors) { StringWriter writer = new(); Console.SetOut(writer); CharacterScript[] result = ParseImplementation(inputPath, lastModified, DiagnosticLevel.ErrorsOnly); errors = writer.ToString(); return result; } /// <summary> /// This will parse all the documents in <paramref name="inputPath"/>. /// </summary> private static CharacterScript[] ParseImplementation(string inputPath, DateTime? lastModified,
DiagnosticLevel level) {
OutputHelpers.Level = level; inputPath = ToRootPath(inputPath); List<CharacterScript> scripts = new List<CharacterScript>(); IEnumerable<string> files = GetAllLibrariesInPath(inputPath, lastModified); foreach (string file in files) { OutputHelpers.Log($"✨ Compiling {Path.GetFileName(file)}..."); CharacterScript? script = Parser.Parse(file); if (script is not null) { scripts.Add(script); } } return scripts.ToArray(); } internal readonly static JsonSerializerSettings Settings = new() { TypeNameHandling = TypeNameHandling.None, ContractResolver = new WritablePropertiesOnlyResolver(), Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }; /// <summary> /// Handles any relative path to the executable. /// </summary> private static string ToRootPath(string s) => Path.IsPathRooted(s) ? s : Path.GetFullPath(Path.Join(Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location), s)); /// <summary> /// Look recursively for all the files in <paramref name="path"/>. /// </summary> /// <param name="path">Rooted path to the binaries folder. This must be a valid directory.</param> private static IEnumerable<string> GetAllLibrariesInPath(in string path, DateTime? lastModified) { if (File.Exists(path)) { return new string[] { path }; } if (!Path.Exists(path)) { OutputHelpers.WriteError($"Unable to find input path '{path}'"); return new string[0]; } // 1. Filter all files that has a "*.gum" extension. // 2. Distinguish the file names. IEnumerable<string> paths = Directory.EnumerateFiles(path, "*.gum", SearchOption.AllDirectories) .GroupBy(s => Path.GetFileName(s)) .Select(s => s.First()); if (lastModified is not null) { // Only select files that have been modifier prior to a specific date. paths = paths.Where(s => File.GetLastWriteTime(s) > lastModified); } return paths; } } }
src/Gum/Reader.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum.Tests/Bungee.cs", "retrieved_chunk": " {\n string[] lines = Regex.Split(input, @\"\\r?\\n|\\r\");\n Parser parser = new(\"Test\", lines);\n return parser.Start();\n }\n [TestMethod]\n public void TestSerialization()\n {\n const string path = \"./resources\";\n CharacterScript[] results = Reader.Parse(path, lastModified: null, out string errors);", "score": 0.850598931312561 }, { "filename": "src/Gum/Parser.cs", "retrieved_chunk": " _playUntil = -1;\n return playUntil;\n }\n //\n // Post-analysis variables.\n // \n /// <summary>\n /// This is for validating all the goto destination statements.\n /// </summary>\n private readonly List<(Block Block, string Location, int Line)> _gotoDestinations = new();", "score": 0.838951826095581 }, { "filename": "src/Gum/Parser.cs", "retrieved_chunk": " line = line.Slice(end);\n word = GetNextWord(line, out end).TrimStart();\n }\n return false;\n }\n /// <summary>\n /// Check whether the first character of a line has a token defined.\n /// </summary>\n private bool Defines(ReadOnlySpan<char> line, TokenChar[] tokens)\n {", "score": 0.8342989683151245 }, { "filename": "src/Gum/Parser_Actions.cs", "retrieved_chunk": " /// </summary>\n /// <returns>Whether it succeeded parsing the action.</returns>\n private bool ParseAction(ReadOnlySpan<char> line, int lineIndex, int currentColumn)\n {\n if (line.IsEmpty)\n {\n // We saw something like a (and) condition. This is not really valid for us.\n OutputHelpers.WriteWarning($\"Empty action ('[]') found at line {lineIndex}. \" +\n \"Was this on purpose? Because it will be ignored.\");\n return true;", "score": 0.8254386186599731 }, { "filename": "src/Gum/Parser.cs", "retrieved_chunk": " /// Keep tack of the latest index of each line.\n /// </summary>\n private int _lastIndentationIndex = 0;\n /// <summary>\n /// If applicable, tracks the first token of the last line.\n /// This is used to tweak our own indentation rules.\n /// </summary>\n private TokenChar? _lastLineToken = null;\n private int _indentationIndex = 0;\n /// <summary>", "score": 0.8230728507041931 } ]
csharp
DiagnosticLevel level) {
using GraphNotifications.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Graph; namespace GraphNotifications.Services { public class GraphNotificationService : IGraphNotificationService { private readonly ILogger _logger; private readonly string _notificationUrl; private readonly IGraphClientService _graphClientService; private readonly ICertificateService _certificateService; public GraphNotificationService(
IGraphClientService graphClientService, ICertificateService certificateService, IOptions<AppSettings> settings, ILogger<GraphNotificationService> logger) {
_graphClientService = graphClientService; _certificateService = certificateService ?? throw new ArgumentException(nameof(certificateService)); _logger = logger; _notificationUrl = settings.Value.NotificationUrl ?? throw new ArgumentException(nameof(settings.Value.NotificationUrl)); } public async Task<Subscription> AddSubscriptionAsync(string userAccessToken, SubscriptionDefinition subscriptionDefinition) { // Create the subscription request var subscription = new Subscription { ChangeType = string.Join(',', subscriptionDefinition.ChangeTypes), //"created", NotificationUrl = _notificationUrl, Resource = subscriptionDefinition.Resource, // "me/mailfolders/inbox/messages", ClientState = Guid.NewGuid().ToString(), IncludeResourceData = subscriptionDefinition.ResourceData, ExpirationDateTime = subscriptionDefinition.ExpirationTime }; if (subscriptionDefinition.ResourceData) { // Get the encryption certificate (public key) var encryptionCertificate = await _certificateService.GetEncryptionCertificate(); subscription.EncryptionCertificateId = encryptionCertificate.Subject; // To get resource data, we must provide a public key that // Microsoft Graph will use to encrypt their key // See https://docs.microsoft.com/graph/webhooks-with-resource-data#creating-a-subscription subscription.AddPublicEncryptionCertificate(encryptionCertificate); } _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation("Create graph subscription"); return await graphUserClient.Subscriptions.Request().AddAsync(subscription); } public async Task<Subscription> RenewSubscriptionAsync(string userAccessToken, string subscriptionId, DateTimeOffset expirationTime) { var subscription = new Subscription { ExpirationDateTime = expirationTime }; _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation($"Renew graph subscription: {subscriptionId}"); return await graphUserClient.Subscriptions[subscriptionId].Request().UpdateAsync(subscription); } public async Task<Subscription> GetSubscriptionAsync(string userAccessToken, string subscriptionId) { _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation($"Get graph subscription: {subscriptionId}"); return await graphUserClient.Subscriptions[subscriptionId].Request().GetAsync(); } } }
Services/GraphNotificationService.cs
microsoft-GraphNotificationBroker-b1564aa
[ { "filename": "Services/GraphClientService.cs", "retrieved_chunk": " {\n private readonly AppSettings _settings;\n private readonly ILogger _logger;\n public GraphClientService(IOptions<AppSettings> options, ILogger<GraphClientService> logger)\n {\n _settings = options.Value;\n _logger = logger;\n }\n public GraphServiceClient GetUserGraphClient(string userAssertion)\n {", "score": 0.9054337739944458 }, { "filename": "Functions/GraphNotificationsHub.cs", "retrieved_chunk": " private readonly ICertificateService _certificateService;\n private readonly ICacheService _cacheService;\n private readonly ILogger _logger;\n private readonly AppSettings _settings;\n private const string MicrosoftGraphChangeTrackingSpId = \"0bf30f3b-4a52-48df-9a82-234910c4a086\";\n public GraphNotificationsHub(\n ITokenValidationService tokenValidationService,\n IGraphNotificationService graphNotificationService,\n ICacheService cacheService,\n ICertificateService certificateService,", "score": 0.8876277208328247 }, { "filename": "Functions/GraphNotificationsHub.cs", "retrieved_chunk": " ILogger<GraphNotificationsHub> logger,\n IOptions<AppSettings> options)\n {\n _tokenValidationService = tokenValidationService;\n _graphNotificationService = graphNotificationService;\n _certificateService = certificateService ?? throw new ArgumentException(nameof(certificateService));\n _cacheService = cacheService ?? throw new ArgumentException(nameof(cacheService));\n _logger = logger;\n _settings = options.Value;\n }", "score": 0.8477421402931213 }, { "filename": "Services/CacheService.cs", "retrieved_chunk": " /// <summary>\n /// Implements connection to Redis\n /// </summary> \n public class CacheService : ICacheService\n {\n private readonly ILogger<CacheService> _logger;\n private readonly IRedisFactory _redisFactory;\n private static readonly Encoding encoding = Encoding.UTF8;\n public CacheService(IRedisFactory redisFactory, ILogger<CacheService> logger)\n {", "score": 0.8459003567695618 }, { "filename": "Services/CertificateService.cs", "retrieved_chunk": "namespace GraphNotifications.Services\n{\n /// <summary>\n /// Implements methods to retrieve certificates from Azure Key Vault\n /// </summary>\n public class CertificateService : ICertificateService\n {\n private readonly AppSettings _settings;\n private readonly ILogger _logger;\n private readonly Uri _keyVaultUrl;", "score": 0.8319236040115356 } ]
csharp
IGraphClientService graphClientService, ICertificateService certificateService, IOptions<AppSettings> settings, ILogger<GraphNotificationService> logger) {
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": "Common.cs", "retrieved_chunk": " #region 运行\n /// <summary>\n /// 运行\n /// </summary>\n /// <typeparam name=\"T\">类型</typeparam>\n /// <param name=\"appID\">appid</param>\n /// <param name=\"appSecret\">密钥</param>\n /// <param name=\"fun\">委托</param>\n /// <returns></returns>\n public static T Execute<T>(string appID, string appSecret, Func<AccessTokenData, T> fun) where T : BaseResult, new()", "score": 0.8541826009750366 }, { "filename": "Applets/Applets.cs", "retrieved_chunk": " }\n });\n }\n #endregion\n #region 获取用户手机号\n /// <summary>\n /// 获取用户手机号\n /// </summary>\n /// <param name=\"code\">手机号获取凭证</param>\n /// <returns></returns>", "score": 0.8404883742332458 }, { "filename": "Common.cs", "retrieved_chunk": " /// <param name=\"config\">配置</param>\n /// <returns></returns>\n public static AccessTokenData GetAccessToken(WeChatConfig config) => GetAccessToken(config.AppID, config.AppSecret);\n /// <summary>\n /// 获取全局唯一后台接口调用凭据\n /// </summary>\n /// <param name=\"weChatType\">微信类型</param>\n /// <returns></returns>\n public static AccessTokenData GetAccessToken(WeChatType weChatType = WeChatType.OfficeAccount) => GetAccessToken(new Config().GetConfig(weChatType));\n #endregion", "score": 0.8382308483123779 }, { "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.8360902070999146 }, { "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.8356175422668457 } ]
csharp
AccessTokenModel GetAccessToken(string appID, string appSecret, string code) {
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using Microsoft.Build.Shared; using Microsoft.Build.Shared.FileSystem; using Microsoft.Build.Utilities; namespace Microsoft.Build.Shared { internal static class FileUtilities { private static readonly
IFileSystem DefaultFileSystem = FileSystems.Default;
internal static readonly char[] Slashes = new char[2] { '/', '\\' }; // Linux大小写敏感 private static readonly ConcurrentDictionary<string, bool> FileExistenceCache = new ConcurrentDictionary<string, bool>(StringComparer.Ordinal); internal static bool IsSlash(char c) { if (c != Path.DirectorySeparatorChar) { return c == Path.AltDirectorySeparatorChar; } return true; } internal static string TrimTrailingSlashes(this string s) { return s.TrimEnd(Slashes); } internal static string FixFilePath(string path) { if (!string.IsNullOrEmpty(path) && Path.DirectorySeparatorChar != '\\') { return path.Replace('\\', '/'); } return path; } /// <summary> /// If the given path doesn't have a trailing slash then add one. /// If the path is an empty string, does not modify it. /// </summary> /// <param name="fileSpec">The path to check.</param> /// <returns>A path with a slash.</returns> internal static string EnsureTrailingSlash(string fileSpec) { fileSpec = FixFilePath(fileSpec); if (fileSpec.Length > 0 && !IsSlash(fileSpec[fileSpec.Length - 1])) { fileSpec += Path.DirectorySeparatorChar; } return fileSpec; } internal static string NormalizePath(string path) { ErrorUtilities.VerifyThrowArgumentLength(path, "path"); return FixFilePath(GetFullPath(path)); } private static string GetFullPath(string path) { #if __ if (NativeMethods.IsWindows) { string fullPath = NativeMethods.GetFullPath(path); if (IsPathTooLong(fullPath)) { throw new PathTooLongException(ResourceUtilities.FormatString(AssemblyResources.GetString("Shared.PathTooLong"), path, NativeMethods.MaxPath)); } Path.HasExtension(fullPath); if (!IsUNCPath(fullPath)) { return fullPath; } return Path.GetFullPath(fullPath); } #endif return Path.GetFullPath(path); } internal static string EnsureNoTrailingSlash(string path) { path = FixFilePath(path); if (EndsWithSlash(path)) { path = path.Substring(0, path.Length - 1); } return path; } internal static bool EndsWithSlash(string fileSpec) { if (fileSpec.Length <= 0) { return false; } return IsSlash(fileSpec[fileSpec.Length - 1]); } internal static string GetDirectoryNameOfFullPath(string fullPath) { if (fullPath != null) { int num = fullPath.Length; while (num > 0 && fullPath[--num] != Path.DirectorySeparatorChar && fullPath[num] != Path.AltDirectorySeparatorChar) { } return FixFilePath(fullPath.Substring(0, num)); } return null; } internal static string AttemptToShortenPath(string path) { #if __ if (IsPathTooLong(path) || IsPathTooLongIfRooted(path)) { path = GetFullPathNoThrow(path); } #endif return FixFilePath(path); } internal static bool PathsEqual(string path1, string path2) { if (path1 == null && path2 == null) { return true; } if (path1 == null || path2 == null) { return false; } int num = path1.Length - 1; int num2 = path2.Length - 1; for (int num3 = num; num3 >= 0; num3--) { char c = path1[num3]; if (c != '/' && c != '\\') { break; } num--; } for (int num4 = num2; num4 >= 0; num4--) { char c2 = path2[num4]; if (c2 != '/' && c2 != '\\') { break; } num2--; } if (num != num2) { return false; } for (int i = 0; i <= num; i++) { uint num5 = path1[i]; uint num6 = path2[i]; if ((num5 | num6) > 127) { return PathsEqualNonAscii(path1, path2, i, num - i + 1); } if (num5 - 97 <= 25) { num5 -= 32; } if (num6 - 97 <= 25) { num6 -= 32; } if (num5 == 92) { num5 = 47u; } if (num6 == 92) { num6 = 47u; } if (num5 != num6) { return false; } } return true; } private static bool PathsEqualNonAscii(string strA, string strB, int i, int length) { if (string.Compare(strA, i, strB, i, length, StringComparison.OrdinalIgnoreCase) == 0) { return true; } string strA2 = strA.ToSlash(); string strB2 = strB.ToSlash(); if (string.Compare(strA2, i, strB2, i, length, StringComparison.OrdinalIgnoreCase) == 0) { return true; } return false; } internal static string ToSlash(this string s) { return s.Replace('\\', '/'); } internal static bool FileExistsNoThrow(string fullPath, IFileSystem fileSystem = null) { fullPath = AttemptToShortenPath(fullPath); try { if (fileSystem == null) { fileSystem = DefaultFileSystem; } return /*Traits.Instance.CacheFileExistence*/true ? FileExistenceCache.GetOrAdd(fullPath, (string fullPath) => fileSystem.FileExists(fullPath)) : fileSystem.FileExists(fullPath); } catch { return false; } } internal static StreamWriter OpenWrite(string path, bool append, Encoding encoding = null) { FileMode mode = (append ? FileMode.Append : FileMode.Create); Stream stream = new FileStream(path, mode, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan); if (stream != null) FileExistenceCache[path] = true; if (encoding == null) { return new StreamWriter(stream); } return new StreamWriter(stream, encoding); } internal static bool IsAnySlash(char c) { if (c != '/') { return c == '\\'; } return true; } internal static void ClearFileExistenceCache() { FileExistenceCache.Clear(); } internal static void UpdateFileExistenceCache(string path) { bool value; FileExistenceCache.Remove(path, out value); } } }
Microsoft.Build.Shared/FileUtilities.cs
Chuyu-Team-MSBuildCppCrossToolset-6c84a69
[ { "filename": "Microsoft.Build.Shared/FileMatcher.cs", "retrieved_chunk": "using Microsoft.Build.Shared;\nusing Microsoft.Build.Shared.FileSystem;\nusing Microsoft.Build.Utilities;\nusing Microsoft.VisualBasic.FileIO;\nnamespace Microsoft.Build.Shared\n{\n internal class FileMatcher\n {\n private class TaskOptions\n {", "score": 0.936830461025238 }, { "filename": "Microsoft.Build.Shared/FileSystem/ManagedFileSystem.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing Microsoft.Build.Shared.FileSystem;\nnamespace Microsoft.Build.Shared.FileSystem\n{\n internal class ManagedFileSystem : IFileSystem\n {\n private static readonly ManagedFileSystem Instance = new ManagedFileSystem();\n public static ManagedFileSystem Singleton()", "score": 0.9312975406646729 }, { "filename": "Microsoft.Build.Utilities/CanonicalTrackedFilesHelper.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing Microsoft.Build.Framework;\nusing Microsoft.Build.Shared;\nusing Microsoft.Build.Utilities;\nnamespace Microsoft.Build.Utilities\n{\n internal static class CanonicalTrackedFilesHelper\n {\n internal const int MaxLogCount = 100;", "score": 0.9140711426734924 }, { "filename": "Microsoft.Build.Utilities/TrackedDependencies.cs", "retrieved_chunk": "using System.Collections.Generic;\nusing System.IO;\nusing Microsoft.Build.Framework;\nusing Microsoft.Build.Shared;\nusing Microsoft.Build.Shared.FileSystem;\nusing Microsoft.Build.Utilities;\nnamespace Microsoft.Build.Utilities\n{\n public static class TrackedDependencies\n {", "score": 0.9115883111953735 }, { "filename": "Microsoft.Build.Shared/FileTracker.cs", "retrieved_chunk": "using Microsoft.Build.Framework;\nusing Microsoft.Build.Tasks;\nusing Microsoft.Build.Utilities;\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace Microsoft.Build.Shared\n{\n internal class FileTracker\n {", "score": 0.9074937105178833 } ]
csharp
IFileSystem DefaultFileSystem = FileSystems.Default;
using Aas = AasCore.Aas3_0; // renamed using System.Collections.Generic; // can't alias namespace EnvironmentFromCsvConceptDescriptions { internal static class ParsingConceptDescriptions { internal static class ColumnNames { internal const string Id = "ID"; internal const string PreferredName = "Preferred Name"; internal const string ShortName = "Short Name"; internal const string Unit = "Unit"; internal const string Symbol = "Symbol"; internal const string Definition = "Definition"; internal const string SourceOfDefinition = "Source of Definition"; } internal static readonly List<string> ExpectedHeader = new() { ColumnNames.Id, ColumnNames.PreferredName, ColumnNames.ShortName, ColumnNames.Unit, ColumnNames.Symbol, ColumnNames.Definition, ColumnNames.SourceOfDefinition }; internal static ( Registering.
TypedRegistry<Aas.IConceptDescription>?, List<string>? ) ParseTable(CsvParsing.CsvDictionaryReader csv) {
var error = csv.ReadHeader(); if (error != null) { return ( null, new List<string>() { $"Failed to parse the header: {error}" } ); } var errors = CsvParsing.Parsing.CheckHeader( ExpectedHeader, csv.Header ); if (errors != null) { return (null, errors); } // First row corresponds to the header. var rowIndex = 1; errors = new List<string>(); var registry = new Registering.TypedRegistry<Aas.IConceptDescription>(); while (true) { error = csv.ReadRow(); rowIndex++; if (error != null) { errors.Add($"In row {rowIndex}: {error}"); return (null, errors); } if (csv.Row == null) { break; } List<string>? rowErrors = null; var id = csv.Row[ColumnNames.Id]; if (id == "") { rowErrors ??= new List<string>(); rowErrors.Add( $"In row {rowIndex} " + $"and column {ColumnNames.Id}: " + "Unexpected empty" ); } var preferredName = csv.Row[ColumnNames.PreferredName]; if (preferredName == "") { rowErrors ??= new List<string>(); rowErrors.Add( $"In row {rowIndex} " + $"and column {ColumnNames.PreferredName}: " + "Unexpected empty" ); } if (rowErrors != null) { errors.AddRange(rowErrors); continue; } var shortName = csv.Row[ColumnNames.ShortName]; var unit = csv.Row[ColumnNames.Unit]; var symbol = csv.Row[ColumnNames.Symbol]; var definition = csv.Row[ColumnNames.Definition]; var sourceOfDefinition = csv.Row[ColumnNames.SourceOfDefinition]; var dataSpecificationContent = new Aas.DataSpecificationIec61360( new List<Aas.ILangStringPreferredNameTypeIec61360> { new Aas.LangStringPreferredNameTypeIec61360( "en", preferredName ) } ) { ShortName = (shortName.Length > 0) ? new List<Aas.ILangStringShortNameTypeIec61360> { new Aas.LangStringShortNameTypeIec61360( "en", shortName ) } : null, Unit = (unit.Length > 0) ? unit : null, Symbol = (symbol.Length > 0) ? symbol : null, Definition = (definition.Length > 0) ? new List<Aas.ILangStringDefinitionTypeIec61360> { new Aas.LangStringDefinitionTypeIec61360( "en", definition ) } : null, SourceOfDefinition = (sourceOfDefinition.Length > 0) ? sourceOfDefinition : null, }; var conceptDescription = new Aas.ConceptDescription(id) { EmbeddedDataSpecifications = new() { new Aas.EmbeddedDataSpecification( new Aas.Reference( Aas.ReferenceTypes.ExternalReference, new List<Aas.IKey> { new Aas.Key( Aas.KeyTypes.GlobalReference, id ) } ), dataSpecificationContent ) } }; registry.Add(conceptDescription); } if (errors.Count > 0) { return (null, errors); } return (registry, null); } } }
src/EnvironmentFromCsvConceptDescriptions/ParsingConceptDescriptions.cs
aas-core-works-aas-core3.0-cli-swiss-knife-eb9a3ef
[ { "filename": "src/EnvironmentFromCsvConceptDescriptions/Program.cs", "retrieved_chunk": " var csv = new CsvParsing.CsvDictionaryReader(\n new CsvParsing.CsvReader(reader)\n );\n return ParsingConceptDescriptions.ParseTable(\n csv\n );\n }\n public static int Execute(\n List<string> conceptDescriptionPaths,\n string output,", "score": 0.857853889465332 }, { "filename": "src/EnvironmentFromCsvShellsAndSubmodels/ParsingAssetAdministrationShellsAndSubmodels.cs", "retrieved_chunk": " new()\n {\n ColumnNames.Max,\n ColumnNames.Min,\n ColumnNames.DataType,\n };\n private static (Aas.ISubmodelElement?, List<string>?) ParseFile(\n IReadOnlyDictionary<string, string> row,\n int rowIndex\n )", "score": 0.8546134233474731 }, { "filename": "src/EnvironmentFromCsvShellsAndSubmodels/ParsingAssetAdministrationShellsAndSubmodels.cs", "retrieved_chunk": " ColumnNames.Max,\n ColumnNames.Min,\n ColumnNames.ContentType\n };\n private static (Aas.ISubmodelElement?, List<string>?) ParseProperty(\n IReadOnlyDictionary<string, string> row,\n int rowIndex\n )\n {\n List<string>? errors = null;", "score": 0.8483898043632507 }, { "filename": "src/EnvironmentFromCsvShellsAndSubmodels/ParsingAssetAdministrationShellsAndSubmodels.cs", "retrieved_chunk": " }\n private static readonly List<string> ExpectedEmptyColumnsInRange =\n new()\n {\n ColumnNames.Value,\n ColumnNames.ContentType\n };\n private static (Aas.ISubmodelElement?, List<string>?) ParseRange(\n IReadOnlyDictionary<string, string> row,\n int rowIndex", "score": 0.8405765295028687 }, { "filename": "src/EnvironmentFromCsvShellsAndSubmodels/ParsingAssetAdministrationShellsAndSubmodels.cs", "retrieved_chunk": " ColumnNames.Value,\n ColumnNames.DataType,\n ColumnNames.ContentType,\n ColumnNames.Min,\n ColumnNames.Max,\n ColumnNames.SemanticId,\n };\n internal static (\n Registering.TypedRegistry<Aas.IAssetAdministrationShell>?,\n Registering.TypedRegistry<Aas.ISubmodel>?,", "score": 0.8375262022018433 } ]
csharp
TypedRegistry<Aas.IConceptDescription>?, List<string>? ) ParseTable(CsvParsing.CsvDictionaryReader csv) {
using UserManagement.Api.Services; using UserManagement.Data.Models; using Microsoft.AspNetCore.Mvc; namespace BloggingApis.Controllers { [Route("api/[controller]")] [ApiController] public class AuthenticationController : ControllerBase { private readonly IAuthService _authService; private readonly ILogger<AuthenticationController> _logger; public AuthenticationController(IAuthService authService, ILogger<AuthenticationController> logger) { _authService = authService; _logger = logger; } [HttpPost] [Route("login")] public async Task<IActionResult> Login(LoginModel model) { try { if (!ModelState.IsValid) return BadRequest("Invalid payload"); var (status, message) = await _authService.Login(model); if (status == 0) return BadRequest(message); return Ok(message); } catch(Exception ex) { _logger.LogError(ex.Message); return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpPost] [Route("registeration")] public async Task<IActionResult> Register(
RegistrationModel model) {
try { if (!ModelState.IsValid) return BadRequest("Invalid payload"); var (status, message) = await _authService.Registeration(model, UserRoles.Admin); if (status == 0) { return BadRequest(message); } return CreatedAtAction(nameof(Register), model); } catch (Exception ex) { _logger.LogError(ex.Message); return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } } }
UserManagement.Api/Controllers/AuthenticationController.cs
shahedbd-API.UserManagement-dcce5cc
[ { "filename": "UserManagement.Api/Services/IAuthService.cs", "retrieved_chunk": "using UserManagement.Data.Models;\nnamespace UserManagement.Api.Services\n{\n public interface IAuthService\n {\n Task<(int, string)> Registeration(RegistrationModel model, string role);\n Task<(int, string)> Login(LoginModel model);\n }\n}", "score": 0.7745292782783508 }, { "filename": "UserManagement.Api/Controllers/UserListController.cs", "retrieved_chunk": " [HttpGet]\n public async Task<IActionResult> Get()\n {\n var uerlist= await Task.FromResult(new string[] { \"Virat\", \"Messi\", \"Ozil\", \"Lara\", \"MS Dhoni\" });\n return Ok(uerlist);\n }\n }\n}", "score": 0.7500361204147339 }, { "filename": "UserManagement.Data/Migrations/ApplicationDbContextModelSnapshot.cs", "retrieved_chunk": " [DbContext(typeof(ApplicationDbContext))]\n partial class ApplicationDbContextModelSnapshot : ModelSnapshot\n {\n protected override void BuildModel(ModelBuilder modelBuilder)\n {\n#pragma warning disable 612, 618\n modelBuilder\n .HasAnnotation(\"ProductVersion\", \"7.0.4\")\n .HasAnnotation(\"Relational:MaxIdentifierLength\", 128);\n SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);", "score": 0.7442865967750549 }, { "filename": "UserManagement.Data/Migrations/20230328162524_initcreate.Designer.cs", "retrieved_chunk": "{\n [DbContext(typeof(ApplicationDbContext))]\n [Migration(\"20230328162524_initcreate\")]\n partial class initcreate\n {\n /// <inheritdoc />\n protected override void BuildTargetModel(ModelBuilder modelBuilder)\n {\n#pragma warning disable 612, 618\n modelBuilder", "score": 0.7328075170516968 }, { "filename": "UserManagement.Data/Models/LoginModel.cs", "retrieved_chunk": " [Required(ErrorMessage = \"User Name is required\")]\n public string? Username { get; set; }\n [Required(ErrorMessage = \"Password is required\")]\n public string? Password { get; set; }\n }\n}", "score": 0.7038487792015076 } ]
csharp
RegistrationModel model) {
/* 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 `FuncFluxParam` class represents a flux that stores functions with one parameter of type `TParam` 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="TParam">The type of the parameter passed to the functions stored in the dictionary.</typeparam> /// <typeparam name="TReturn">The return type of the functions stored in the dictionary.</typeparam> internal sealed class FuncFluxParam<TKey, TParam, TReturn> :
IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>> {
/// <summary> /// A dictionary that stores functions with one parameter of type `TParam` and a return value of type `TReturn`. /// </summary> internal readonly Dictionary<TKey, Func<TParam, TReturn>> dictionary = new Dictionary<TKey, Func<TParam, 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<TParam, TReturn>>.Store(in bool condition, TKey key, Func<TParam, 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 parameter, and returns its return value. /// If the dictionary does not contain the specified key, returns the default value of type `TReturn`. /// </summary> TReturn IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>>.Dispatch(TKey key, TParam param) { if(dictionary.TryGetValue(key, out var _actions)) { return _actions.Invoke(param); } return default; } } }
Runtime/Core/Internal/FuncFluxParam.cs
xavierarpa-UniFlux-a2d46de
[ { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": "namespace Kingdox.UniFlux.Core.Internal\n{\n /// <summary>\n /// The `FuncFlux` class represents a flux that stores functions with no parameters 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=\"TReturn\">The return type of the functions stored in the dictionary.</typeparam>\n internal sealed class FuncFlux<TKey, TReturn> : IFluxReturn<TKey, TReturn, Func<TReturn>>\n {", "score": 0.9702043533325195 }, { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": " /// <summary>\n /// A dictionary that stores functions with no parameters and a return value of type `TReturn`.\n /// </summary>\n internal readonly Dictionary<TKey, Func<TReturn>> dictionary = new Dictionary<TKey, Func<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<TReturn>>.Store(in bool condition, TKey key, Func<TReturn> func) \n {", "score": 0.9042541980743408 }, { "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.8861973285675049 }, { "filename": "Runtime/Core/Internal/IFlux.cs", "retrieved_chunk": " /// <summary>\n /// TKey TParam\n /// </summary>\n internal interface IFluxParam<in TKey, in TParam, in TStorage> : IStore<TKey, TStorage>\n {\n /// <summary>\n /// Dispatch the TKey with TParam\n /// </summary>\n void Dispatch(TKey key, TParam param);\n }", "score": 0.8754024505615234 }, { "filename": "Runtime/Core/Internal/IFlux.cs", "retrieved_chunk": " /// <summary>\n /// TKey TParam TReturn\n /// </summary>\n internal interface IFluxParamReturn<in TKey, in TParam, out TReturn, in TStorage> : IStore<TKey, TStorage>\n {\n /// <summary>\n /// Dispatch the TKey with TParam and return TReturn\n /// </summary>\n TReturn Dispatch(TKey key, TParam param);\n }", "score": 0.8747603297233582 } ]
csharp
IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>> {
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using SQLServerCoverage.Gateway; using SQLServerCoverage.Source; using SQLServerCoverage.Trace; namespace SQLServerCoverage { public class CodeCoverage { private const int MAX_DISPATCH_LATENCY = 1000; private readonly DatabaseGateway _database; private readonly string _databaseName; private readonly bool _debugger; private readonly
TraceControllerType _traceType;
private readonly List<string> _excludeFilter; private readonly bool _logging; private readonly SourceGateway _source; private CoverageResult _result; public const short TIMEOUT_EXPIRED = -2; //From TdsEnums public SQLServerCoverageException Exception { get; private set; } = null; public bool IsStarted { get; private set; } = false; private TraceController _trace; //This is to better support powershell and optional parameters public CodeCoverage(string connectionString, string databaseName) : this(connectionString, databaseName, null, false, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter) : this(connectionString, databaseName, excludeFilter, false, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging) : this(connectionString, databaseName, excludeFilter, logging, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging, bool debugger) : this(connectionString, databaseName, excludeFilter, logging, debugger, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging, bool debugger, TraceControllerType traceType) { if (debugger) Debugger.Launch(); _databaseName = databaseName; if (excludeFilter == null) excludeFilter = new string[0]; _excludeFilter = excludeFilter.ToList(); _logging = logging; _debugger = debugger; _traceType = traceType; _database = new DatabaseGateway(connectionString, databaseName); _source = new DatabaseSourceGateway(_database); } public bool Start(int timeOut = 30) { Exception = null; try { _database.TimeOut = timeOut; _trace = new TraceControllerBuilder().GetTraceController(_database, _databaseName, _traceType); _trace.Start(); IsStarted = true; return true; } catch (Exception ex) { Debug("Error starting trace: {0}", ex); Exception = new SQLServerCoverageException("SQL Cover failed to start.", ex); IsStarted = false; return false; } } private List<string> StopInternal() { var events = _trace.ReadTrace(); _trace.Stop(); _trace.Drop(); return events; } public CoverageResult Stop() { if (!IsStarted) throw new SQLServerCoverageException("SQL Cover was not started, or did not start correctly."); IsStarted = false; WaitForTraceMaxLatency(); var results = StopInternal(); GenerateResults(_excludeFilter, results, new List<string>(), "SQLServerCoverage result of running external process"); return _result; } private void Debug(string message, params object[] args) { if (_logging) Console.WriteLine(message, args); } public CoverageResult Cover(string command, int timeOut = 30) { Debug("Starting Code Coverage"); _database.TimeOut = timeOut; if (!Start()) { throw new SQLServerCoverageException("Unable to start the trace - errors are recorded in the debug output"); } Debug("Executing Command: {0}", command); var sqlExceptions = new List<string>(); try { _database.Execute(command, timeOut, true); } catch (System.Data.SqlClient.SqlException e) { if (e.Number == -2) { throw; } sqlExceptions.Add(e.Message); } catch (Exception e) { Console.WriteLine("Exception running command: {0} - error: {1}", command, e.Message); } Debug("Executing Command: {0}...done", command); WaitForTraceMaxLatency(); Debug("Stopping Code Coverage"); try { var rawEvents = StopInternal(); Debug("Getting Code Coverage Result"); GenerateResults(_excludeFilter, rawEvents, sqlExceptions, $"SQLServerCoverage result of running '{command}'"); Debug("Result generated"); } catch (Exception e) { Console.Write(e.StackTrace); throw new SQLServerCoverageException("Exception gathering the results", e); } return _result; } private static void WaitForTraceMaxLatency() { Thread.Sleep(MAX_DISPATCH_LATENCY); } private void GenerateResults(List<string> filter, List<string> xml, List<string> sqlExceptions, string commandDetail) { var batches = _source.GetBatches(filter); _result = new CoverageResult(batches, xml, _databaseName, _database.DataSource, sqlExceptions, commandDetail); } public CoverageResult Results() { return _result; } } }
src/SQLServerCoverageLib/CodeCoverage.cs
sayantandey-SQLServerCoverage-aea57e3
[ { "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.8718293905258179 }, { "filename": "src/SQLServerCoverageLib/CoverageResult.cs", "retrieved_chunk": "using Palmmedia.ReportGenerator.Core;\nusing ReportGenerator;\nnamespace SQLServerCoverage\n{\n public class CoverageResult : CoverageSummary\n {\n private readonly IEnumerable<Batch> _batches;\n private readonly List<string> _sqlExceptions;\n private readonly string _commandDetail;\n public string DatabaseName { get; }", "score": 0.8708730936050415 }, { "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.8581744432449341 }, { "filename": "src/SQLServerCoverageLib/Objects/CoveredStatement.cs", "retrieved_chunk": "namespace SQLServerCoverage.Objects\n{\n public class CoveredStatement\n {\n public int Offset;\n public int OffsetEnd;\n public int ObjectId;\n }\n}", "score": 0.8542032241821289 }, { "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.848965585231781 } ]
csharp
TraceControllerType _traceType;
namespace CalloutInterfaceAPI.Records { using System; using LSPD_First_Response.Engine.Scripting.Entities; /// <summary> /// Represents a ped record. /// </summary> public class PedRecord :
EntityRecord<Rage.Ped> {
/// <summary> /// Initializes a new instance of the <see cref="PedRecord"/> class. /// </summary> /// <param name="ped">The underlying ped.</param> public PedRecord(Rage.Ped ped) : base(ped) { } /// <summary> /// Gets the advisory text. /// </summary> public string Advisory { get; internal set; } = string.Empty; /// <summary> /// Gets the ped's birthday. /// </summary> public DateTime Birthday { get; internal set; } = DateTime.MinValue; /// <summary> /// Gets the number of citations. /// </summary> public int Citations { get; internal set; } = 0; /// <summary> /// Gets the ped's first name. /// </summary> public string First { get; internal set; } = "John"; /// <summary> /// Gets a value indicating whether or not the ped is male. /// </summary> public bool IsMale { get; internal set; } = true; /// <summary> /// Gets a value indicating whether or not the ped is wanted. /// </summary> public bool IsWanted { get; internal set; } = false; /// <summary> /// Gets the peds last name. /// </summary> public string Last { get; internal set; } = "Doe"; /// <summary> /// Gets the license state. /// </summary> public ELicenseState LicenseState { get; internal set; } = ELicenseState.Valid; /// <summary> /// Gets the persona for the Ped. /// </summary> public Persona Persona { get; internal set; } = null; } }
CalloutInterfaceAPI/Records/PedRecord.cs
Immersive-Plugins-Team-CalloutInterfaceAPI-2c5a303
[ { "filename": "CalloutInterfaceAPI/Records/PedDatabase.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using System;\n using System.Collections.Generic;\n using LSPD_First_Response.Engine.Scripting.Entities;\n /// <summary>\n /// Represents a database of ped records.\n /// </summary>\n internal class PedDatabase : RecordDatabase<Rage.Ped, PedRecord>\n {", "score": 0.95030277967453 }, { "filename": "CalloutInterfaceAPI/Records/Computer.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using LSPD_First_Response.Engine.Scripting.Entities;\n /// <summary>\n /// The police computer.\n /// </summary>\n public static class Computer\n {\n private static readonly PedDatabase PedDatabase = new PedDatabase();\n private static readonly VehicleDatabase VehicleDatabase = new VehicleDatabase();", "score": 0.8884536623954773 }, { "filename": "CalloutInterfaceAPI/Records/VehicleRecord.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using LSPD_First_Response.Engine.Scripting.Entities;\n /// <summary>\n /// Represents a vehicle record looked up on the computer.\n /// </summary>\n public class VehicleRecord : EntityRecord<Rage.Vehicle>\n {\n /// <summary>\n /// Initializes a new instance of the <see cref=\"VehicleRecord\"/> class.", "score": 0.8880178332328796 }, { "filename": "CalloutInterfaceAPI/Records/RecordDatabase.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using System.Collections.Generic;\n using System.Diagnostics;\n /// <summary>\n /// Represents a database of records.\n /// </summary>\n /// <typeparam name=\"TEntity\">The type of Rage.Entity.</typeparam>\n /// <typeparam name=\"TRecord\">The type of EntityRecord.</typeparam>\n internal abstract class RecordDatabase<TEntity, TRecord>", "score": 0.860340416431427 }, { "filename": "CalloutInterfaceAPI/Records/EntityRecord.cs", "retrieved_chunk": "namespace CalloutInterfaceAPI.Records\n{\n using System;\n /// <summary>\n /// Represents a single entity.\n /// </summary>\n /// <typeparam name=\"TEntity\">The type of entity for the record.</typeparam>\n public abstract class EntityRecord<TEntity>\n where TEntity : Rage.Entity\n {", "score": 0.8597168922424316 } ]
csharp
EntityRecord<Rage.Ped> {
using HarmonyLib; using UnityEngine; namespace Ultrapain.Patches { class Solider_Start_Patch { static void Postfix(ZombieProjectiles __instance, ref GameObject ___decProjectile, ref GameObject ___projectile, ref EnemyIdentifier ___eid, ref Animator ___anim) { if (___eid.enemyType != EnemyType.Soldier) return; /*___projectile = Plugin.soliderBullet; if (Plugin.decorativeProjectile2.gameObject != null) ___decProjectile = Plugin.decorativeProjectile2.gameObject;*/ __instance.gameObject.AddComponent<SoliderShootCounter>(); } } class Solider_SpawnProjectile_Patch { static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP) { if (___eid.enemyType != EnemyType.Soldier) return; ___eid.weakPoint = null; } } class SoliderGrenadeFlag : MonoBehaviour { public GameObject tempExplosion; } class Solider_ThrowProjectile_Patch { static void Postfix(
ZombieProjectiles __instance, ref GameObject ___currentProjectile, ref EnemyIdentifier ___eid, ref GameObject ___player, ref Animator ___anim, ref float ___coolDown) {
if (___eid.enemyType != EnemyType.Soldier) return; ___currentProjectile.GetComponent<ProjectileSpread>().spreadAmount = 10; ___currentProjectile.SetActive(true); SoliderShootCounter counter = __instance.gameObject.GetComponent<SoliderShootCounter>(); if (counter.remainingShots > 0) { counter.remainingShots -= 1; if (counter.remainingShots != 0) { ___anim.Play("Shoot", 0, Plugin.SoliderShootAnimationStart / 2f); ___anim.fireEvents = true; __instance.DamageStart(); ___coolDown = 0; } else { counter.remainingShots = ConfigManager.soliderShootCount.value; if (ConfigManager.soliderShootGrenadeToggle.value) { GameObject grenade = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject, ___currentProjectile.transform.position, ___currentProjectile.transform.rotation); grenade.transform.Translate(Vector3.forward * 0.5f); Vector3 targetPos = Plugin.PredictPlayerPosition(__instance.GetComponent<Collider>(), ___eid.totalSpeedModifier); grenade.transform.LookAt(targetPos); Rigidbody rb = grenade.GetComponent<Rigidbody>(); //rb.maxAngularVelocity = 10000; //foreach (Rigidbody r in grenade.GetComponentsInChildren<Rigidbody>()) // r.maxAngularVelocity = 10000; rb.AddForce(grenade.transform.forward * Plugin.SoliderGrenadeForce); //rb.velocity = ___currentProjectile.transform.forward * Plugin.instance.SoliderGrenadeForce; rb.useGravity = false; grenade.GetComponent<Grenade>().enemy = true; grenade.GetComponent<Grenade>().CanCollideWithPlayer(true); grenade.AddComponent<SoliderGrenadeFlag>(); } } } //counter.remainingShots = ConfigManager.soliderShootCount.value; } } class Grenade_Explode_Patch { static bool Prefix(Grenade __instance, out bool __state) { __state = false; SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>(); if (flag == null) return true; flag.tempExplosion = GameObject.Instantiate(__instance.explosion); __state = true; foreach(Explosion e in flag.tempExplosion.GetComponentsInChildren<Explosion>()) { e.damage = ConfigManager.soliderGrenadeDamage.value; e.maxSize *= ConfigManager.soliderGrenadeSize.value; e.speed *= ConfigManager.soliderGrenadeSize.value; } __instance.explosion = flag.tempExplosion; return true; } static void Postfix(Grenade __instance, bool __state) { if (!__state) return; SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>(); GameObject.Destroy(flag.tempExplosion); } } class SoliderShootCounter : MonoBehaviour { public int remainingShots = ConfigManager.soliderShootCount.value; } }
Ultrapain/Patches/Solider.cs
eternalUnion-UltraPain-ad924af
[ { "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.8764358758926392 }, { "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.8752352595329285 }, { "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.8732805252075195 }, { "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.8679319620132446 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " }\n else\n patch.swingComboLeft = 2;*/\n }\n }\n class Mindflayer_MeleeTeleport_Patch\n {\n public static Vector3 deltaPosition = new Vector3(0, -10, 0);\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged)\n {", "score": 0.8662758469581604 } ]
csharp
ZombieProjectiles __instance, ref GameObject ___currentProjectile, ref EnemyIdentifier ___eid, ref GameObject ___player, ref Animator ___anim, ref float ___coolDown) {
using NowPlaying.Utils; using NowPlaying.Models; using System; using System.Collections.Generic; using System.IO; namespace NowPlaying.ViewModels { public class GameCacheViewModel : ObservableObject { private readonly NowPlaying plugin; public readonly GameCacheManagerViewModel manager; public readonly GameCacheEntry entry; public CacheRootViewModel cacheRoot; public string Title => entry.Title; public string Root => entry.CacheRoot; public string Device => Directory.GetDirectoryRoot(Root); public string Id => entry.Id; public string CacheDir => entry.CacheDir; public string InstallDir => entry.InstallDir; public string ExePath => entry.ExePath; public string XtraArgs => entry.XtraArgs; public long InstallSize => entry.InstallSize; public long InstallFiles => entry.InstallFiles; public long CacheSize => entry.CacheSize; public long CacheSizeOnDisk => entry.CacheSizeOnDisk; public GameCacheState State => entry.State; public GameCachePlatform Platform => entry.Platform; private string installQueueStatus; private string uninstallQueueStatus; private bool nowInstalling; private bool nowUninstalling; private string formatStringXofY; private int bytesScale; private string bytesToCopy; private string cacheInstalledSize; public string InstallQueueStatus => installQueueStatus; public string UninstallQueueStatus => uninstallQueueStatus; public bool NowInstalling => nowInstalling; public bool NowUninstalling => nowUninstalling; public string Status => GetStatus ( entry.State, installQueueStatus, uninstallQueueStatus, nowInstalling, plugin.SpeedLimitIpg > 0, nowUninstalling ); public string StatusColor => ( State == GameCacheState.Unknown || State == GameCacheState.Invalid ? "WarningBrush" : Status == plugin.GetResourceString("LOCNowPlayingTermsUninstalled") ? "TextBrushDarker" : NowInstalling ? (plugin.SpeedLimitIpg > 0 ? "SlowInstallBrush" : "InstallBrush") : "TextBrush" ); public string CacheInstalledSize => cacheInstalledSize; public string CacheInstalledSizeColor => ( CanInstallCache == plugin.GetResourceString("LOCNowPlayingTermsNo") ? "WarningBrush" : State == GameCacheState.Empty ? "TextBrushDarker" : "TextBrush" ); public bool CacheWillFit { get; private set; } public string CanInstallCache => ( (entry.State==GameCacheState.Empty || entry.State==GameCacheState.InProgress) ? plugin.GetResourceString(CacheWillFit ? "LOCNowPlayingTermsYes" : "LOCNowPlayingTermsNo") : "-" ); public string CanInstallCacheColor => CanInstallCache == plugin.GetResourceString("LOCNowPlayingTermsNo") ? "WarningBrush" : "TextBrush"; public TimeSpan InstallEtaTimeSpan { get; private set; } public string InstallEta { get; private set; } public string CacheRootSpaceAvailable { get; private set; } public string CacheRootSpaceAvailableColor => cacheRoot.BytesAvailableForCaches > 0 ? "TextBrush" : "WarningBrush"; public bool PartialFileResume { get; set; } public GameCacheViewModel(GameCacheManagerViewModel manager, GameCacheEntry entry, CacheRootViewModel cacheRoot) { this.manager = manager; this.plugin = manager.plugin; this.entry = entry; this.cacheRoot = cacheRoot; this.nowInstalling = manager.IsPopulateInProgess(entry.Id); this.PartialFileResume = false; this.formatStringXofY = plugin.GetResourceFormatString("LOCNowPlayingProgressXofYFmt2", 2) ?? "{0} of {1}"; this.cacheInstalledSize = GetCacheInstalledSize(entry); this.bytesScale = SmartUnits.GetBytesAutoScale(entry.InstallSize); this.bytesToCopy = SmartUnits.Bytes(entry.InstallSize, decimals: 1, userScale: bytesScale); UpdateInstallEta(); } public bool IsUninstalled() { return State == GameCacheState.Empty; } public void UpdateCacheRoot() { OnPropertyChanged(nameof(Root)); OnPropertyChanged(nameof(Device)); OnPropertyChanged(nameof(CacheDir)); UpdateStatus(); UpdateCacheSize(); UpdateCacheSpaceWillFit(); UpdateInstallEta(); } public void UpdateStatus() { OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); OnPropertyChanged(nameof(CanInstallCache)); OnPropertyChanged(nameof(CanInstallCacheColor)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); cacheRoot.UpdateGameCaches(); } public void UpdateInstallQueueStatus(string value = null) { if (installQueueStatus != value) { installQueueStatus = value; OnPropertyChanged(nameof(InstallQueueStatus)); OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); } } public void UpdateUninstallQueueStatus(string value = null) { if (uninstallQueueStatus != value) { uninstallQueueStatus = value; OnPropertyChanged(nameof(UninstallQueueStatus)); OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); } } public void UpdateNowInstalling(bool value) { if (value) { // . update auto scale for and bake "OfBytes" to copy string. this.bytesScale = SmartUnits.GetBytesAutoScale(entry.InstallSize); this.bytesToCopy = SmartUnits.Bytes(entry.InstallSize, decimals: 1, userScale: bytesScale); } nowInstalling = value; nowUninstalling &= !nowInstalling; UpdateInstallEta(); OnPropertyChanged(nameof(NowInstalling)); OnPropertyChanged(nameof(NowUninstalling)); OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); OnPropertyChanged(nameof(CanInstallCache)); OnPropertyChanged(nameof(CanInstallCacheColor)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); } public void UpdateNowUninstalling(bool value) { if (nowUninstalling != value) { nowUninstalling = value; nowInstalling &= !nowUninstalling; OnPropertyChanged(nameof(NowInstalling)); OnPropertyChanged(nameof(NowUninstalling)); OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); OnPropertyChanged(nameof(CanInstallCache)); OnPropertyChanged(nameof(CanInstallCacheColor)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); } } public void UpdateCacheSize() { OnPropertyChanged(nameof(CacheSize)); string value = GetCacheInstalledSize(entry); if (cacheInstalledSize != value) { cacheInstalledSize = value; OnPropertyChanged(nameof(CacheInstalledSize)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); cacheRoot.UpdateCachesInstalled(); cacheRoot.UpdateSpaceAvailableForCaches(); } } public void UpdateCacheSpaceWillFit() { bool bval = cacheRoot.BytesAvailableForCaches > (InstallSize - CacheSizeOnDisk); if (CacheWillFit != bval) { CacheWillFit = bval; OnPropertyChanged(nameof(CacheWillFit)); OnPropertyChanged(nameof(CanInstallCache)); OnPropertyChanged(nameof(CanInstallCacheColor)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); } string sval = SmartUnits.Bytes(cacheRoot.BytesAvailableForCaches, decimals: 1); if (CacheRootSpaceAvailable != sval || cacheRoot.BytesAvailableForCaches <= 0) { CacheRootSpaceAvailable = sval; OnPropertyChanged(nameof(CacheRootSpaceAvailable)); OnPropertyChanged(nameof(CacheRootSpaceAvailableColor)); } } public void UpdateInstallEta(TimeSpan? value = null) { if (value == null) { var avgBytesPerFile = entry.InstallSize / entry.InstallFiles; var avgBps = manager.GetInstallAverageBps(entry.InstallDir, avgBytesPerFile, plugin.SpeedLimitIpg); value = GetInstallEtaTimeSpan(entry, avgBps); } if (InstallEtaTimeSpan != value || InstallEta == null) { InstallEtaTimeSpan = (TimeSpan)value; InstallEta = GetInstallEta(InstallEtaTimeSpan); OnPropertyChanged(nameof(InstallEtaTimeSpan)); OnPropertyChanged(nameof(InstallEta)); } } private TimeSpan GetInstallEtaTimeSpan(
GameCacheEntry entry, long averageBps) {
bool notInstalled = entry.State == GameCacheState.Empty || entry.State == GameCacheState.InProgress; if (notInstalled) { if (averageBps > 0) { long bytesLeftToInstall = entry.InstallSize - entry.CacheSize; return TimeSpan.FromSeconds((1.0 * bytesLeftToInstall) / averageBps); } else { return TimeSpan.FromMilliseconds(-1); // Infinite } } else { return TimeSpan.Zero; } } private string GetInstallEta(TimeSpan etaTimeSpan) { return etaTimeSpan > TimeSpan.Zero ? SmartUnits.Duration(etaTimeSpan) : etaTimeSpan == TimeSpan.Zero ? "-" : "∞"; } private string GetCacheInstalledSize(GameCacheEntry entry) { switch (entry.State) { case GameCacheState.Played: case GameCacheState.Populated: return SmartUnits.Bytes(entry.CacheSize, decimals: 1); case GameCacheState.InProgress: return string.Format ( formatStringXofY, SmartUnits.Bytes(entry.CacheSize, userScale: bytesScale, decimals: 1, showUnits: false), bytesToCopy ); case GameCacheState.Empty: return plugin.FormatResourceString ( "LOCNowPlayingGameCacheSizeNeededFmt", SmartUnits.Bytes(entry.InstallSize, decimals:1) ); default: return "-"; } } private string GetStatus ( GameCacheState state, string installQueueStatus, string uninstallQueueStatus, bool nowInstalling, bool isSpeedLimited, bool nowUninstalling ) { if (installQueueStatus != null) { return plugin.GetResourceString("LOCNowPlayingTermsQueuedForInstall") + $" ({installQueueStatus})"; } else if (uninstallQueueStatus != null) { return plugin.GetResourceString("LOCNowPlayingTermsQueuedForUninstall") + $" ({uninstallQueueStatus})"; } else if (nowInstalling) { return plugin.GetResourceString(isSpeedLimited ? "LOCNowPlayingTermsInstallSpeedLimit" : "LOCNowPlayingTermsInstalling") + "..."; } else if (nowUninstalling) { return plugin.GetResourceString("LOCNowPlayingTermsUninstalling") + "..."; } else { switch (state) { case GameCacheState.Played: case GameCacheState.Populated: return plugin.GetResourceString("LOCNowPlayingTermsInstalled"); case GameCacheState.InProgress: return plugin.GetResourceString("LOCNowPlayingTermsPaused"); case GameCacheState.Empty: return plugin.GetResourceString("LOCNowPlayingTermsUninstalled"); default: return "** " + plugin.GetResourceString("LOCNowPlayingTermsInvalid") + " **"; } } } } }
source/ViewModels/GameCacheViewModel.cs
gittromney-Playnite-NowPlaying-23eec41
[ { "filename": "source/ViewModels/TopPanelViewModel.cs", "retrieved_chunk": " totalBytesToInstall -= installSize;\n queuedInstallEta -= eta;\n UpdateStatus();\n }\n public void NowInstalling(GameCacheViewModel gameCache, bool isSpeedLimited = false)\n {\n nowInstallingCache = gameCache;\n queuedInstallEta -= gameCache.InstallEtaTimeSpan;\n isSlowInstall = isSpeedLimited;\n plugin.cacheManager.gameCacheManager.eJobStatsUpdated += OnJobStatsUpdated;", "score": 0.7873748540878296 }, { "filename": "source/ViewModels/NowPlayingPanelViewModel.cs", "retrieved_chunk": " }\n public class CustomEtaSorter : IComparer\n {\n public int Compare(object x, object y)\n {\n double etaX = ((GameCacheViewModel)x).InstallEtaTimeSpan.TotalSeconds;\n double etaY = ((GameCacheViewModel)y).InstallEtaTimeSpan.TotalSeconds;\n return etaX.CompareTo(etaY);\n }\n }", "score": 0.7788262367248535 }, { "filename": "source/ViewModels/InstallProgressViewModel.cs", "retrieved_chunk": " gameCache.UpdateInstallEta(timeSpanRemaining);\n }\n sval = SmartUnits.Bytes(averageAvgBps, decimals: 1) + \"/s\";\n if (averageSpeed != sval)\n {\n averageSpeed = sval;\n OnPropertyChanged(nameof(SpeedDurationEta));\n }\n }\n /// <summary>", "score": 0.7758326530456543 }, { "filename": "source/ViewModels/InstallProgressViewModel.cs", "retrieved_chunk": " OnPropertyChanged(nameof(CurrentFile));\n OnPropertyChanged(nameof(SpeedDurationEta));\n OnPropertyChanged(nameof(ProgressBgBrush));\n OnPropertyChanged(nameof(ProgressValue));\n }\n }\n }\n private int speedLimitIpg;\n public int SpeedLimitIpg\n {", "score": 0.7710636258125305 }, { "filename": "source/NowPlaying.cs", "retrieved_chunk": " var gameCache = cacheManager.FindGameCache(cacheId);\n gameCache.UpdateInstallQueueStatus(null);\n UpdateInstallQueueStatuses();\n topPanelViewModel.CancelledFromInstallQueue(gameCache.InstallSize, gameCache.InstallEtaTimeSpan);\n panelViewModel.RefreshGameCaches();\n }\n }\n public async void DequeueInstallerAndInvokeNextAsync(string cacheId)\n {\n // Dequeue the controller (and sanity check it was ours)", "score": 0.7570925951004028 } ]
csharp
GameCacheEntry entry, long averageBps) {
using HarmonyLib; using System; using System.Collections.Generic; using System.Text; using UnityEngine; using static Ultrapain.ConfigManager; namespace Ultrapain.Patches { // EID class EnemyIdentifier_UpdateModifiers { static void Postfix(
EnemyIdentifier __instance) {
EidStatContainer container = ConfigManager.enemyStats[__instance.enemyType]; if(__instance.enemyType == EnemyType.V2) { V2 comp = __instance.GetComponent<V2>(); if(comp != null && comp.secondEncounter) { container = ConfigManager.enemyStats[EnemyType.V2Second]; } } __instance.totalHealthModifier *= container.health.value; __instance.totalDamageModifier *= container.damage.value; __instance.totalSpeedModifier *= container.speed.value; List<string> weakness = new List<string>(); List<float> weaknessMulti = new List<float>(); foreach(KeyValuePair<string, float> weaknessPair in container.resistanceDict) { weakness.Add(weaknessPair.Key); int index = Array.IndexOf(__instance.weaknesses, weaknessPair.Key); if(index >= 0) { float defaultResistance = 1f / __instance.weaknessMultipliers[index]; if (defaultResistance > weaknessPair.Value) weaknessMulti.Add(1f / defaultResistance); else weaknessMulti.Add(1f / weaknessPair.Value); } else weaknessMulti.Add(1f / weaknessPair.Value); } for(int i = 0; i < __instance.weaknessMultipliers.Length; i++) { if (container.resistanceDict.ContainsKey(__instance.weaknesses[i])) continue; weakness.Add(__instance.weaknesses[i]); weaknessMulti.Add(__instance.weaknessMultipliers[i]); } __instance.weaknesses = weakness.ToArray(); __instance.weaknessMultipliers = weaknessMulti.ToArray(); } } // DETECT DAMAGE TYPE class Explosion_Collide_FF { static bool Prefix(Explosion __instance) { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Explosion; if ((__instance.enemy || __instance.friendlyFire) && __instance.canHit != AffectedSubjects.PlayerOnly) EnemyIdentifier_DeliverDamage_FF.friendlyBurn = true; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; EnemyIdentifier_DeliverDamage_FF.friendlyBurn = false; } } class PhysicalShockwave_CheckCollision_FF { static bool Prefix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Explosion; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; } } class VirtueInsignia_OnTriggerEnter_FF { static bool Prefix(VirtueInsignia __instance) { if (__instance.gameObject.name == "PlayerSpawned") return true; EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Fire; EnemyIdentifier_DeliverDamage_FF.friendlyBurn = true; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; EnemyIdentifier_DeliverDamage_FF.friendlyBurn = false; } } class SwingCheck2_CheckCollision_FF { static bool Prefix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Melee; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; } } class Projectile_Collided_FF { static bool Prefix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Projectile; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; } } class EnemyIdentifier_DeliverDamage_FF { public enum DamageCause { Explosion, Projectile, Fire, Melee, Unknown } public static DamageCause currentCause = DamageCause.Unknown; public static bool friendlyBurn = false; [HarmonyBefore] static bool Prefix(EnemyIdentifier __instance, ref float __3) { if (currentCause != DamageCause.Unknown && (__instance.hitter == "enemy" || __instance.hitter == "ffexplosion")) { switch(currentCause) { case DamageCause.Projectile: //if (ConfigManager.friendlyFireDamageOverrideProjectile.normalizedValue == 0) // return false; __3 *= ConfigManager.friendlyFireDamageOverrideProjectile.normalizedValue; break; case DamageCause.Explosion: //if (ConfigManager.friendlyFireDamageOverrideProjectile.normalizedValue == 0) // return false; __3 *= ConfigManager.friendlyFireDamageOverrideExplosion.normalizedValue; break; case DamageCause.Melee: //if (ConfigManager.friendlyFireDamageOverrideProjectile.normalizedValue == 0) // return false; __3 *= ConfigManager.friendlyFireDamageOverrideMelee.normalizedValue; break; } } return true; } } class Flammable_Burn_FF { static bool Prefix(Flammable __instance, ref float __0) { if (EnemyIdentifier_DeliverDamage_FF.friendlyBurn) { if (ConfigManager.friendlyFireDamageOverrideFire.normalizedValue == 0) return false; __0 *= ConfigManager.friendlyFireDamageOverrideFire.normalizedValue; } return true; } } class StreetCleaner_Fire_FF { static bool Prefix(FireZone __instance) { if (__instance.source != FlameSource.Streetcleaner) return true; EnemyIdentifier_DeliverDamage_FF.friendlyBurn = true; return true; } static void Postfix(FireZone __instance) { if (__instance.source == FlameSource.Streetcleaner) EnemyIdentifier_DeliverDamage_FF.friendlyBurn = false; } } }
Ultrapain/Patches/GlobalEnemyTweaks.cs
eternalUnion-UltraPain-ad924af
[ { "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.8665699362754822 }, { "filename": "Ultrapain/Patches/Idol.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Idol_Death_Patch\n {\n static void Postfix(Idol __instance)\n {", "score": 0.8622758984565735 }, { "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.8459130525588989 }, { "filename": "Ultrapain/Patches/Panopticon.cs", "retrieved_chunk": "using UnityEngine.UIElements;\nnamespace Ultrapain.Patches\n{\n class Panopticon_Start\n {\n static void Postfix(FleshPrison __instance)\n {\n if (__instance.altVersion)\n __instance.onFirstHeal = new UltrakillEvent();\n }", "score": 0.8399146795272827 }, { "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.8398146033287048 } ]
csharp
EnemyIdentifier __instance) {
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 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.8696674108505249 }, { "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.8528801202774048 }, { "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.833311915397644 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": " }\n }\n class VirtueFlag : MonoBehaviour\n {\n public AudioSource lighningBoltSFX;\n public GameObject ligtningBoltAud;\n public Transform windupObj;\n private EnemyIdentifier eid;\n public Drone virtue;\n public void Awake()", "score": 0.8221200108528137 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " }\n // ROOT PANEL\n public static BoolField enemyTweakToggle;\n private static ConfigPanel enemyPanel;\n public static BoolField playerTweakToggle;\n private static ConfigPanel playerPanel;\n public static BoolField discordRichPresenceToggle;\n public static BoolField steamRichPresenceToggle;\n public static StringField pluginName;\n public static StringMultilineField pluginInfo;", "score": 0.8192429542541504 } ]
csharp
GameObject sisyphiusExplosion;
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/QuestNodeSearchWindow.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEditor;\nusing UnityEditor.Experimental.GraphView;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nnamespace QuestSystem.QuestEditor\n{\n public class QuestNodeSearchWindow : ScriptableObject, ISearchWindowProvider\n {", "score": 0.9013000726699829 }, { "filename": "Editor/CustomInspector/QuestOnObjectWorldEditor.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\nnamespace QuestSystem.QuestEditor\n{\n [CustomEditor(typeof(QuestOnObjectWorld))]\n public class QuestOnObjectWorldEditor : Editor\n {\n public override void OnInspectorGUI()", "score": 0.8850847482681274 }, { "filename": "Editor/GraphEditor/NodeQuestGraph.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEditor.Experimental.GraphView;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nusing UnityEditor;\nnamespace QuestSystem.QuestEditor\n{\n [System.Serializable]\n public class NodeQuestGraph : UnityEditor.Experimental.GraphView.Node", "score": 0.8825631141662598 }, { "filename": "Editor/CustomInspector/QuestObjectiveUpdaterEditor.cs", "retrieved_chunk": "using UnityEngine;\nusing UnityEditor;\nusing System;\nusing System.Collections.Generic;\nnamespace QuestSystem.QuestEditor\n{\n [CustomEditor(typeof(QuestObjectiveUpdater))]\n public class QuestObjectiveUpdaterEditor : Editor\n { \n private int selectedValue = 0;", "score": 0.8814030885696411 }, { "filename": "Editor/GraphEditor/QuestObjectiveGraph.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nusing UnityEditor.UIElements;\nnamespace QuestSystem.QuestEditor\n{\n [System.Serializable]\n public class QuestObjectiveGraph : VisualElement\n {", "score": 0.8769224286079407 } ]
csharp
QuestNodeSearchWindow _searchWindow;
using DotNetDevBadgeWeb.Common; using Newtonsoft.Json; namespace DotNetDevBadgeWeb.Model { public class User { private const int AVATAR_SIZE = 128; [JsonProperty("id")] public int Id { get; set; } [JsonProperty("username")] public string Username { get; set; } [JsonProperty("name")] public string Name { get; set; } [
JsonProperty("avatar_template")] public string AvatarTemplate {
get; set; } [JsonProperty("flair_name")] public object FlairName { get; set; } [JsonProperty("trust_level")] public int TrustLevel { get; set; } [JsonProperty("admin")] public bool? Admin { get; set; } [JsonProperty("moderator")] public bool? Moderator { get; set; } public ELevel Level => TrustLevel switch { 3 => ELevel.Silver, 4 => ELevel.Gold, _ => ELevel.Bronze, }; public string AvatarEndPoint => AvatarTemplate?.Replace("{size}", AVATAR_SIZE.ToString()) ?? string.Empty; } }
src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs
chanos-dev-dotnetdev-badge-5740a40
[ { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "retrieved_chunk": " public int TimeRead { get; set; }\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }", "score": 0.8458383083343506 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "retrieved_chunk": " public int TopicsEntered { get; set; }\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n [JsonProperty(\"time_read\")]", "score": 0.8243749737739563 }, { "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.8224432468414307 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "retrieved_chunk": "using Newtonsoft.Json;\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [JsonProperty(\"likes_given\")]\n public int LikesGiven { get; set; }\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n [JsonProperty(\"topics_entered\")]", "score": 0.8002774715423584 }, { "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.7690387964248657 } ]
csharp
JsonProperty("avatar_template")] public string AvatarTemplate {
namespace DotNetDevBadgeWeb.Common { internal static class Palette { private static readonly
Dictionary<ETheme, ColorSet> _colorSets;
static Palette() { _colorSets = new() { { ETheme.Light, new ColorSet("222222", "FFFFFF") }, { ETheme.Dark, new ColorSet("FFFFFF", "222222") }, { ETheme.Dotnet, new ColorSet("FFFFFF", "6E20A0") }, }; } public static ColorSet GetColorSet(ETheme theme) => _colorSets[theme]; public static string GetTrustColor(ELevel level) => level switch { ELevel.Bronze => "CD7F32", ELevel.Silver => "C0C0C0", ELevel.Gold => "E7C300", _ => "CD7F32", }; } internal class ColorSet { internal string FontColor { get; private set; } internal string BackgroundColor { get; private set; } internal ColorSet(string fontColor, string backgroundColor) { FontColor = fontColor; BackgroundColor = backgroundColor; } } }
src/dotnetdev-badge/dotnetdev-badge.web/Common/Palette.cs
chanos-dev-dotnetdev-badge-5740a40
[ { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Common/Defines.cs", "retrieved_chunk": "namespace DotNetDevBadgeWeb.Common\n{\n public enum ELevel\n {\n Bronze,\n Silver,\n Gold,\n }\n public enum ETheme\n {", "score": 0.7875968813896179 }, { "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.7511158585548401 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs", "retrieved_chunk": "using DotNetDevBadgeWeb.Common;\nusing DotNetDevBadgeWeb.Interfaces;\nusing DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Core.Badge\n{\n internal class BadgeCreatorV1 : IBadgeV1\n {\n private const float MAX_WIDTH = 193f; \n private const float LOGO_X = 164.5f;\n private const float TEXT_X = 75.5f;", "score": 0.7454304099082947 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IMeasureText.cs", "retrieved_chunk": "namespace DotNetDevBadgeWeb.Interfaces\n{\n interface IMeasureText\n {\n bool IsMediumIdWidthGreater(string id, out float addedWidth);\n }\n interface IMeasureTextV1 : IMeasureText { }\n}", "score": 0.7379308342933655 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Middleware/BadgeIdValidatorMiddleware.cs", "retrieved_chunk": "namespace DotNetDevBadgeWeb.Middleware\n{\n public class BadgeIdValidatorMiddleware\n {\n private readonly RequestDelegate _next;\n public BadgeIdValidatorMiddleware(RequestDelegate next)\n {\n _next = next;\n }\n public async Task InvokeAsync(HttpContext context)", "score": 0.7373393774032593 } ]
csharp
Dictionary<ETheme, ColorSet> _colorSets;
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using SQLServerCoverage.Gateway; using SQLServerCoverage.Source; using SQLServerCoverage.Trace; namespace SQLServerCoverage { public class CodeCoverage { private const int MAX_DISPATCH_LATENCY = 1000; private readonly DatabaseGateway _database; private readonly string _databaseName; private readonly bool _debugger; private readonly TraceControllerType _traceType; private readonly List<string> _excludeFilter; private readonly bool _logging; private readonly
SourceGateway _source;
private CoverageResult _result; public const short TIMEOUT_EXPIRED = -2; //From TdsEnums public SQLServerCoverageException Exception { get; private set; } = null; public bool IsStarted { get; private set; } = false; private TraceController _trace; //This is to better support powershell and optional parameters public CodeCoverage(string connectionString, string databaseName) : this(connectionString, databaseName, null, false, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter) : this(connectionString, databaseName, excludeFilter, false, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging) : this(connectionString, databaseName, excludeFilter, logging, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging, bool debugger) : this(connectionString, databaseName, excludeFilter, logging, debugger, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging, bool debugger, TraceControllerType traceType) { if (debugger) Debugger.Launch(); _databaseName = databaseName; if (excludeFilter == null) excludeFilter = new string[0]; _excludeFilter = excludeFilter.ToList(); _logging = logging; _debugger = debugger; _traceType = traceType; _database = new DatabaseGateway(connectionString, databaseName); _source = new DatabaseSourceGateway(_database); } public bool Start(int timeOut = 30) { Exception = null; try { _database.TimeOut = timeOut; _trace = new TraceControllerBuilder().GetTraceController(_database, _databaseName, _traceType); _trace.Start(); IsStarted = true; return true; } catch (Exception ex) { Debug("Error starting trace: {0}", ex); Exception = new SQLServerCoverageException("SQL Cover failed to start.", ex); IsStarted = false; return false; } } private List<string> StopInternal() { var events = _trace.ReadTrace(); _trace.Stop(); _trace.Drop(); return events; } public CoverageResult Stop() { if (!IsStarted) throw new SQLServerCoverageException("SQL Cover was not started, or did not start correctly."); IsStarted = false; WaitForTraceMaxLatency(); var results = StopInternal(); GenerateResults(_excludeFilter, results, new List<string>(), "SQLServerCoverage result of running external process"); return _result; } private void Debug(string message, params object[] args) { if (_logging) Console.WriteLine(message, args); } public CoverageResult Cover(string command, int timeOut = 30) { Debug("Starting Code Coverage"); _database.TimeOut = timeOut; if (!Start()) { throw new SQLServerCoverageException("Unable to start the trace - errors are recorded in the debug output"); } Debug("Executing Command: {0}", command); var sqlExceptions = new List<string>(); try { _database.Execute(command, timeOut, true); } catch (System.Data.SqlClient.SqlException e) { if (e.Number == -2) { throw; } sqlExceptions.Add(e.Message); } catch (Exception e) { Console.WriteLine("Exception running command: {0} - error: {1}", command, e.Message); } Debug("Executing Command: {0}...done", command); WaitForTraceMaxLatency(); Debug("Stopping Code Coverage"); try { var rawEvents = StopInternal(); Debug("Getting Code Coverage Result"); GenerateResults(_excludeFilter, rawEvents, sqlExceptions, $"SQLServerCoverage result of running '{command}'"); Debug("Result generated"); } catch (Exception e) { Console.Write(e.StackTrace); throw new SQLServerCoverageException("Exception gathering the results", e); } return _result; } private static void WaitForTraceMaxLatency() { Thread.Sleep(MAX_DISPATCH_LATENCY); } private void GenerateResults(List<string> filter, List<string> xml, List<string> sqlExceptions, string commandDetail) { var batches = _source.GetBatches(filter); _result = new CoverageResult(batches, xml, _databaseName, _database.DataSource, sqlExceptions, commandDetail); } public CoverageResult Results() { return _result; } } }
src/SQLServerCoverageLib/CodeCoverage.cs
sayantandey-SQLServerCoverage-aea57e3
[ { "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.8364717364311218 }, { "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.819220244884491 }, { "filename": "src/SQLServerCoverageLib/CoverageResult.cs", "retrieved_chunk": "using Palmmedia.ReportGenerator.Core;\nusing ReportGenerator;\nnamespace SQLServerCoverage\n{\n public class CoverageResult : CoverageSummary\n {\n private readonly IEnumerable<Batch> _batches;\n private readonly List<string> _sqlExceptions;\n private readonly string _commandDetail;\n public string DatabaseName { get; }", "score": 0.8028138875961304 }, { "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.7936305999755859 }, { "filename": "src/SQLServerCoverageLib/CoverageResult.cs", "retrieved_chunk": " public string DataSource { get; }\n public List<string> SqlExceptions\n {\n get { return _sqlExceptions; }\n }\n public IEnumerable<Batch> Batches\n {\n get { return _batches; }\n }\n private readonly StatementChecker _statementChecker = new StatementChecker();", "score": 0.7935295701026917 } ]
csharp
SourceGateway _source;
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/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.8987112641334534 }, { "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.8767520785331726 }, { "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.8620911836624146 }, { "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.8607838749885559 }, { "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.8533667325973511 } ]
csharp
Renderer rend;
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TreeifyTask { public class TaskNode : ITaskNode { private static Random rnd = new Random(); private readonly List<Task> taskObjects = new(); private readonly List<ITaskNode> childTasks = new(); private bool hasCustomAction; private Func<IProgressReporter, CancellationToken, Task> action = async (rep, tok) => await Task.Yield(); public event ProgressReportingEventHandler Reporting; private bool seriesRunnerIsBusy; private bool concurrentRunnerIsBusy; public TaskNode() { this.Id = rnd.Next() + string.Empty; this.Reporting += OnSelfReporting; } public TaskNode(string Id) : this() { this.Id = Id ?? rnd.Next() + string.Empty; } public TaskNode(string Id, Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAsyncFunction) : this(Id) { this.SetAction(cancellableProgressReportingAsyncFunction); } #region Props public string Id { get; set; } public double ProgressValue { get; private set; } public object ProgressState { get; private set; } public TaskStatus TaskStatus { get; private set; } public ITaskNode Parent { get; set; } public IEnumerable<
ITaskNode> ChildTasks => this.childTasks;
#endregion Props public void AddChild(ITaskNode childTask) { childTask = childTask ?? throw new ArgumentNullException(nameof(childTask)); childTask.Parent = this; // Ensure this after setting its parent as this EnsureNoCycles(childTask); childTask.Reporting += OnChildReporting; childTasks.Add(childTask); } private class ActionReport { public ActionReport() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressValue = 0; this.ProgressState = null; } public ActionReport(ITaskNode task) { this.Id = task.Id; this.TaskStatus = task.TaskStatus; this.ProgressState = task.ProgressState; this.ProgressValue = task.ProgressValue; } public string Id { get; set; } public TaskStatus TaskStatus { get; set; } public double ProgressValue { get; set; } public object ProgressState { get; set; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } private ActionReport selfActionReport = new(); private void OnSelfReporting(object sender, ProgressReportingEventArgs eventArgs) { TaskStatus = selfActionReport.TaskStatus = eventArgs.TaskStatus; ProgressValue = selfActionReport.ProgressValue = eventArgs.ProgressValue; ProgressState = selfActionReport.ProgressState = eventArgs.ProgressState; } private void OnChildReporting(object sender, ProgressReportingEventArgs eventArgs) { // Child task that reports var cTask = sender as ITaskNode; var allReports = childTasks.Select(t => new ActionReport(t)); if (hasCustomAction) { allReports = allReports.Append(selfActionReport); } this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.InDeterminate) ? TaskStatus.InDeterminate : TaskStatus.InProgress; this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.Failed) ? TaskStatus.Failed : this.TaskStatus; if (this.TaskStatus == TaskStatus.Failed) { this.ProgressState = new AggregateException($"{Id}: One or more error occurred in child tasks.", childTasks.Where(v => v.TaskStatus == TaskStatus.Failed && v.ProgressState is Exception) .Select(c => c.ProgressState as Exception)); } this.ProgressValue = allReports.Select(t => t.ProgressValue).Average(); SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ProgressValue = this.ProgressValue, TaskStatus = this.TaskStatus, ChildTasksRunningInParallel = concurrentRunnerIsBusy, ProgressState = seriesRunnerIsBusy ? cTask.ProgressState : this.ProgressState }); } public async Task ExecuteConcurrently(CancellationToken cancellationToken, bool throwOnError) { if (concurrentRunnerIsBusy || seriesRunnerIsBusy) return; concurrentRunnerIsBusy = true; ResetChildrenProgressValues(); foreach (var child in childTasks) { taskObjects.Add(child.ExecuteConcurrently(cancellationToken, throwOnError)); } taskObjects.Add(ExceptionHandledAction(cancellationToken, throwOnError)); if (taskObjects.Any()) { await Task.WhenAll(taskObjects); } if (throwOnError && taskObjects.Any(t => t.IsFaulted)) { var exs = taskObjects.Where(t => t.IsFaulted).Select(t => t.Exception); throw new AggregateException($"Internal error occurred while executing task - {Id}.", exs); } concurrentRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } private async Task ExceptionHandledAction(CancellationToken cancellationToken, bool throwOnError) { try { await action(this, cancellationToken); } catch (OperationCanceledException) { // Don't throw this as an error as we have to come out of await. } catch (Exception ex) { this.Report(TaskStatus.Failed, this.ProgressValue, ex); if (throwOnError) { throw new AggregateException($"Internal error occurred while executing the action of task - {Id}.", ex); } } } public async Task ExecuteInSeries(CancellationToken cancellationToken, bool throwOnError) { if (seriesRunnerIsBusy || concurrentRunnerIsBusy) return; seriesRunnerIsBusy = true; ResetChildrenProgressValues(); try { foreach (var child in childTasks) { if (cancellationToken.IsCancellationRequested) break; await child.ExecuteInSeries(cancellationToken, throwOnError); } await ExceptionHandledAction(cancellationToken, throwOnError); } catch (Exception ex) { if (throwOnError) { throw new AggregateException($"Internal error occurred while executing task - {Id}.", ex); } } seriesRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } public IEnumerable<ITaskNode> ToFlatList() { return FlatList(this); } private void SafeRaiseReportingEvent(object sender, ProgressReportingEventArgs args) { this.Reporting?.Invoke(sender, args); } private void ResetChildrenProgressValues() { taskObjects.Clear(); foreach (var task in childTasks) { task.ResetStatus(); } } /// <summary> /// Throws <see cref="AsyncTasksCycleDetectedException"/> /// </summary> /// <param name="newTask"></param> private void EnsureNoCycles(ITaskNode newTask) { var thisNode = this as ITaskNode; HashSet<ITaskNode> hSet = new HashSet<ITaskNode>(); while (true) { if (thisNode.Parent is null) { break; } if (hSet.Contains(thisNode)) { throw new TaskNodeCycleDetectedException(thisNode, newTask); } hSet.Add(thisNode); thisNode = thisNode.Parent; } var existingTask = FlatList(thisNode).FirstOrDefault(t => t == newTask); if (existingTask != null) { throw new TaskNodeCycleDetectedException(newTask, existingTask.Parent); } } private IEnumerable<ITaskNode> FlatList(ITaskNode root) { yield return root; foreach (var ct in root.ChildTasks) { foreach (var item in FlatList(ct)) yield return item; } } public void RemoveChild(ITaskNode childTask) { childTask.Reporting -= OnChildReporting; childTasks.Remove(childTask); } public void Report(TaskStatus taskStatus, double progressValue, object progressState = null) { SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ChildTasksRunningInParallel = concurrentRunnerIsBusy, TaskStatus = taskStatus, ProgressValue = progressValue, ProgressState = progressState }); } public void SetAction(Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAction) { cancellableProgressReportingAction = cancellableProgressReportingAction ?? throw new ArgumentNullException(nameof(cancellableProgressReportingAction)); hasCustomAction = true; action = cancellableProgressReportingAction; } public void ResetStatus() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressState = null; this.ProgressValue = 0; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } }
Source/TreeifyTask/TaskTree/TaskNode.cs
intuit-TreeifyTask-4b124d4
[ { "filename": "Source/TreeifyTask/TaskTree/ProgressReportingEventArgs.cs", "retrieved_chunk": "using System;\nnamespace TreeifyTask\n{\n public class ProgressReportingEventArgs : EventArgs\n {\n public TaskStatus TaskStatus { get; set; }\n public double ProgressValue { get; set; }\n public object ProgressState { get; set; }\n public bool ChildTasksRunningInParallel { get; set; }\n }", "score": 0.8980610966682434 }, { "filename": "Source/TreeifyTask.BlazorSample/TaskDataModel/code.cs", "retrieved_chunk": " Children = children;\n }\n public string Id { get; }\n public CancellableAsyncActionDelegate Action { get; }\n public AT[] Children { get; }\n }\n public class CodeTry\n {\n public void SyntaxCheck()\n {", "score": 0.8843288421630859 }, { "filename": "Source/TreeifyTask.BlazorSample/Data/CodeBehavior.cs", "retrieved_chunk": "namespace TreeifyTask.BlazorSample\n{\n public record CodeBehavior\n {\n public bool ShouldHangInAnInDeterminateState { get; set; }\n public bool ShouldPerformAnInDeterminateAction { get; set; }\n public bool ShouldHangDuringProgress { get; set; }\n public bool ShouldThrowException { get; set; }\n public bool ShouldThrowExceptionDuringProgress { get; set; }\n public int IntervalDelay { get; set; } = 10;", "score": 0.8814182281494141 }, { "filename": "Source/TreeifyTask.WpfSample/CodeBehavior.cs", "retrieved_chunk": "using System;\nnamespace TreeifyTask.Sample\n{\n public record CodeBehavior\n {\n public bool ShouldHangInAnInDeterminateState { get; set; }\n public bool ShouldPerformAnInDeterminateAction { get; set; }\n public bool ShouldHangDuringProgress { get; set; }\n public bool ShouldThrowException { get; set; }\n public bool ShouldThrowExceptionDuringProgress { get; set; }", "score": 0.8560878038406372 }, { "filename": "Source/TreeifyTask.WpfSample/TaskNodeViewModel.cs", "retrieved_chunk": " public string Id\n {\n get => baseTaskNode.Id;\n }\n public TaskStatus TaskStatus\n {\n get => _taskStatus;\n set\n {\n _taskStatus = value;", "score": 0.8371008634567261 } ]
csharp
ITaskNode> ChildTasks => this.childTasks;
namespace Library.QAPortal { using System; using QAPortalAPI.APIHelper; using QAPortalAPI.Models.ReportingModels; using Skyline.DataMiner.Automation; internal class QAPortal { private readonly IEngine engine; private readonly
QaPortalConfiguration configuration;
public QAPortal(IEngine engine) { this.engine = engine; configuration = QaPortalConfiguration.GetConfiguration(out var e); if (e != null) { throw e; } } public void PublishReport(TestReport report) { QaPortalApiHelper helper; if (configuration.ClientId == null) { helper = new QaPortalApiHelper(engine.GenerateInformation, configuration.Path, string.Empty, string.Empty); } else if (configuration.Path.Contains("@")) { helper = new QaPortalApiHelper( engine.GenerateInformation, configuration.Path, configuration.ClientId, configuration.ApiKey, PlainBodyEmail); } else { helper = new QaPortalApiHelper( engine.GenerateInformation, configuration.Path, configuration.ClientId, configuration.ApiKey); } helper.PostResult(report); } private void PlainBodyEmail(string message, string subject, string to) { EmailOptions emailOptions = new EmailOptions(message, subject, to) { SendAsPlainText = true, }; engine.SendEmail(emailOptions); } } }
Library/QAPortal/QAPortal.cs
SkylineCommunications-Skyline.DataMiner.GithubTemplate.RegressionTest-bb57db1
[ { "filename": "RT_Customer_MyFirstRegressionTest_1/TestCases/TestCaseExample.cs", "retrieved_chunk": "namespace RT_Customer_MyFirstRegressionTest_1\n{\n\tusing System;\n\tusing System.Collections.Generic;\n\tusing System.Linq;\n\tusing System.Text;\n\tusing System.Threading.Tasks;\n\tusing Library.Tests.TestCases;\n\tusing QAPortalAPI.Models.ReportingModels;\n\tusing Skyline.DataMiner.Automation;", "score": 0.8173905611038208 }, { "filename": "Library/Tests/ITest.cs", "retrieved_chunk": "namespace Library.Tests\n{\n using QAPortalAPI.Models.ReportingModels;\n using Skyline.DataMiner.Automation;\n internal interface ITest\n {\n TestReport Execute(IEngine engine);\n }\n}", "score": 0.8127403259277344 }, { "filename": "Library/Tests/Test.cs", "retrieved_chunk": "namespace Library.Tests\n{\n\tusing System;\n\tusing System.Collections.Generic;\n\tusing System.Linq;\n\tusing System.Text;\n\tusing Library.Consts;\n\tusing Library.Tests.TestCases;\n\tusing QAPortalAPI.Models.ReportingModels;\n\tusing Skyline.DataMiner.Automation;", "score": 0.8095190525054932 }, { "filename": "RT_Customer_MyFirstRegressionTest_1/RT_Customer_MyFirstRegressionTest_1.cs", "retrieved_chunk": "*/\nusing System;\nusing Library.Tests;\nusing RT_Customer_MyFirstRegressionTest_1;\nusing Skyline.DataMiner.Automation;\n/// <summary>\n/// DataMiner Script Class.\n/// </summary>\npublic class Script\n{", "score": 0.792945146560669 }, { "filename": "Library/Tests/ITestCase.cs", "retrieved_chunk": "namespace Library.Tests.TestCases\n{\n\tusing QAPortalAPI.Models.ReportingModels;\n\tusing Skyline.DataMiner.Automation;\n\tinternal interface ITestCase\n\t{\n\t\tstring Name { get; set; }\n\t\tTestCaseReport TestCaseReport { get; }\n\t\tPerformanceTestCaseReport PerformanceTestCaseReport { get; }\n\t\tvoid Execute(IEngine engine);", "score": 0.7720260620117188 } ]
csharp
QaPortalConfiguration configuration;
/* 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; using UnityEditor; using System.Reflection; using System; using System.Linq; using System.Collections.Generic; namespace Kingdox.UniFlux.Editor { [CustomEditor(typeof(
MonoFlux), true)] public partial class MonoFluxEditor : UnityEditor.Editor {
private MethodInfo[] methods_subscribeAttrb; private Dictionary<MethodInfo, object[]> dic_method_parameters; private static bool showBox = true; private void OnEnable() { Type type = target.GetType(); var methods = type.GetMethods((BindingFlags)(-1)); methods_subscribeAttrb = methods.Where(m => m.GetCustomAttributes(typeof(FluxAttribute), true).Length > 0).ToArray(); dic_method_parameters = methods_subscribeAttrb.Select(m => new { Method = m, Parameters = new object[m.GetParameters().Length] }).ToDictionary(mp => mp.Method, mp => mp.Parameters); } public override void OnInspectorGUI() { DrawDefaultInspector(); if(methods_subscribeAttrb.Length.Equals(0)) { showBox = false; } else { if(GUILayout.Button( showBox ? "Close" : $"Open ({methods_subscribeAttrb.Length})", GUI.skin.box)) { showBox = !showBox; } } if(showBox) { _Draw(); } } private void _Draw() { GUILayout.Space(20); GUIStyle buttonStyle = new GUIStyle(GUI.skin.button) { alignment = TextAnchor.MiddleLeft, richText = true, fontSize = 12 }; GUIStyle style_title = new GUIStyle(EditorStyles.boldLabel) { richText = true }; foreach (var item in methods_subscribeAttrb) { var atribute = item.GetCustomAttribute<FluxAttribute>(); var parameters = item.GetParameters(); var isParameters = parameters.Length > 0; var isErr_return = item.ReturnType != typeof(void); var isErr_static = item.IsStatic; var isError = isParameters || isErr_return || isErr_static; string key_color = isError ? "yellow" : "white"; EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label( $"<color={key_color}>{atribute.key}</color>", style_title); GUILayout.Label(item.ToString(), EditorStyles.whiteMiniLabel); GenerateButton(buttonStyle,item); EditorGUILayout.BeginVertical(); GenerateParameters(item, parameters); EditorGUILayout.EndVertical(); EditorGUILayout.EndVertical(); GUILayout.Space(5); } } // private void GenerateParameters(MethodInfo item, ParameterInfo[] parameters) // { // // var args = dic_method_parameters[item]; // // for (int i = 0; i < parameters.Length; i++) // // { // // EditorGUILayout.BeginHorizontal(EditorStyles.helpBox); // // GUILayout.Label(parameters[i].ToString()); // // EditorGUILayout.EndHorizontal(); // // } // // dic_method_parameters[item] = args; // } private void GenerateParameters(MethodInfo item, ParameterInfo[] parameters) { // var args = dic_method_parameters[item]; // for (int i = 0; i < parameters.Length; i++) // { // var parameter = parameters[i]; // if (parameter.ParameterType.IsValueType) // { // // El parámetro es primitivo // object defaultValue = Activator.CreateInstance(parameter.ParameterType); // object value = args[i] ?? defaultValue; // EditorGUILayout.BeginHorizontal(EditorStyles.helpBox); // GUILayout.Label(parameter.Name, GUILayout.Width(150)); // if (parameter.ParameterType == typeof(int)) // { // value = EditorGUILayout.IntField((int)value); // } // else if (parameter.ParameterType == typeof(float)) // { // value = EditorGUILayout.FloatField((float)value); // } // else if (parameter.ParameterType == typeof(bool)) // { // value = EditorGUILayout.Toggle((bool)value); // } // else if (parameter.ParameterType == typeof(string)) // { // value = EditorGUILayout.TextField((string)value); // } // else if (parameter.ParameterType == typeof(Vector2)) // { // value = EditorGUILayout.Vector2Field("", (Vector2)value); // } // else if (parameter.ParameterType == typeof(Vector3)) // { // value = EditorGUILayout.Vector3Field("", (Vector3)value); // } // else if (parameter.ParameterType == typeof(Vector4)) // { // value = EditorGUILayout.Vector4Field("", (Vector4)value); // } // args[i] = Convert.ChangeType(value, parameter.ParameterType); // EditorGUILayout.EndHorizontal(); // } // else // { // // El parámetro no es primitivo // GUILayout.Label(parameter.Name + " (no primitivo)", EditorStyles.whiteMiniLabel); // } // } // dic_method_parameters[item] = args; } private void GenerateButton(GUIStyle buttonStyle, MethodInfo item) { GUI.enabled = Application.isPlaying; if (dic_method_parameters[item].Length.Equals(0) && GUILayout.Button($"Invoke!", buttonStyle)) { if(item.ReturnType != typeof(void)) { var resp = item.Invoke(target, dic_method_parameters[item]); Debug.Log(resp); } else { item.Invoke(target, dic_method_parameters[item]); } } GUI.enabled = true; } } }
Editor/MonoFluxEditor.cs
xavierarpa-UniFlux-a2d46de
[ { "filename": "Benchmark/General/Benchmark_UniFlux.cs", "retrieved_chunk": "using UnityEngine;\nusing Kingdox.UniFlux.Core;\nnamespace Kingdox.UniFlux.Benchmark\n{\n public class Benchmark_UniFlux : MonoFlux\n {\n [SerializeField] private Marker _m_store_string_add = new Marker()\n {\n K = \"store<string,Action> ADD\"\n };", "score": 0.8215559124946594 }, { "filename": "Tests/EditMode/EditMode_Test_1.cs", "retrieved_chunk": "using System.Collections.Generic;\nusing NUnit.Framework;\nusing UnityEngine;\nusing UnityEngine.TestTools;\nusing Kingdox.UniFlux;\nusing Kingdox.UniFlux.Core;\nnamespace Kingdox.UniFlux.Tests\n{\n public class EditMode_Test_1\n {", "score": 0.8128011226654053 }, { "filename": "Benchmark/Nest/Benchmark_Nest_UniFlux.cs", "retrieved_chunk": "using System;\nusing UnityEngine;\nnamespace Kingdox.UniFlux.Benchmark\n{\n public sealed class Benchmark_Nest_UniFlux : MonoFlux\n {\n [SerializeField] private Marker _mark_fluxAttribute = new Marker()\n {\n K = \"NestedModel Flux Attribute\"\n };", "score": 0.8063074946403503 }, { "filename": "Runtime/MonoFluxExtension.cs", "retrieved_chunk": "using System.Linq;\nusing System.Reflection;\nnamespace Kingdox.UniFlux\n{\n ///<summary>\n /// static class that ensure to handle the FluxAttribute\n ///</summary>\n internal static class MonoFluxExtension\n {\n internal static readonly BindingFlags m_bindingflag_all = (BindingFlags)(-1);", "score": 0.7935020327568054 }, { "filename": "Runtime/UniFlux.String.cs", "retrieved_chunk": "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Kingdox.UniFlux.Core;\n// asmdef Version Defines, enabled when com.cysharp.unitask is imported.\n#if UNIFLUX_UNITASK_SUPPORT\n using Cysharp.Threading.Tasks;\n namespace Kingdox.UniFlux\n {\n public static partial class FluxExtension //Action<UniTask>\n {", "score": 0.7901077270507812 } ]
csharp
MonoFlux), true)] public partial class MonoFluxEditor : UnityEditor.Editor {
using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Text; using ULTRAKILL.Cheats; using UnityEngine; namespace Ultrapain.Patches { class Leviathan_Flag : MonoBehaviour { private LeviathanHead comp; private Animator anim; //private Collider col; private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 }; public float playerRocketRideTracker = 0; private GameObject currentProjectileEffect; private AudioSource currentProjectileAud; private Transform shootPoint; public float currentProjectileSize = 0; public float beamChargeRate = 12f / 1f; public int beamRemaining = 0; public int projectilesRemaining = 0; public float projectileDelayRemaining = 0f; private static FieldInfo ___inAction = typeof(LeviathanHead).GetField("inAction", BindingFlags.NonPublic | BindingFlags.Instance); private void Awake() { comp = GetComponent<LeviathanHead>(); anim = GetComponent<Animator>(); //col = GetComponent<Collider>(); } public bool beamAttack = false; public bool projectileAttack = false; public bool charging = false; private void Update() { if (currentProjectileEffect != null && (charging || currentProjectileSize < 11.9f)) { currentProjectileSize += beamChargeRate * Time.deltaTime; currentProjectileEffect.transform.localScale = Vector3.one * currentProjectileSize; currentProjectileAud.pitch = currentProjectileSize / 2; } } public void ChargeBeam(Transform shootPoint) { if (currentProjectileEffect != null) return; this.shootPoint = shootPoint; charging = true; currentProjectileSize = 0; currentProjectileEffect = GameObject.Instantiate(Plugin.chargeEffect, shootPoint); currentProjectileAud = currentProjectileEffect.GetComponent<AudioSource>(); currentProjectileEffect.transform.localPosition = new Vector3(0, 0, 6); currentProjectileEffect.transform.localScale = Vector3.zero; beamRemaining = ConfigManager.leviathanChargeCount.value; beamChargeRate = 11.9f / ConfigManager.leviathanChargeDelay.value; Invoke("PrepareForFire", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } private Grenade FindTargetGrenade() { List<Grenade> list = GrenadeList.Instance.grenadeList; Grenade targetGrenade = null; Vector3 playerPos = PlayerTracker.Instance.GetTarget().position; foreach (Grenade grn in list) { if (Vector3.Distance(grn.transform.position, playerPos) <= 10f) { targetGrenade = grn; break; } } return targetGrenade; } private Grenade targetGrenade = null; public void PrepareForFire() { charging = false; // OLD PREDICTION //targetShootPoint = NewMovement.Instance.playerCollider.bounds.center; //if (Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out RaycastHit hit, float.MaxValue, envMask)) // targetShootPoint = hit.point; // Malicious face beam prediction GameObject player = MonoSingleton<PlayerTracker>.Instance.GetPlayer().gameObject; Vector3 a = new Vector3(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().x, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().y / (float)(MonoSingleton<NewMovement>.Instance.ridingRocket ? 1 : 2), MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().z); targetShootPoint = (MonoSingleton<NewMovement>.Instance.ridingRocket ? MonoSingleton<NewMovement>.Instance.ridingRocket.transform.position : player.transform.position) + a / (1f / ConfigManager.leviathanChargeDelay.value) / comp.lcon.eid.totalSpeedModifier; RaycastHit raycastHit; // I guess this was in case player is approaching the malface, but it is very unlikely with leviathan /*if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude > 0f && col.Raycast(new Ray(player.transform.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity()), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.5f / comp.lcon.eid.totalSpeedModifier)) { targetShootPoint = player.transform.position; } else */if (Physics.Raycast(player.transform.position, targetShootPoint - player.transform.position, out raycastHit, Vector3.Distance(targetShootPoint, player.transform.position), LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { targetShootPoint = raycastHit.point; } Invoke("Shoot", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } private Vector3 RandomVector(float min, float max) { return new Vector3(UnityEngine.Random.Range(min, max), UnityEngine.Random.Range(min, max), UnityEngine.Random.Range(min, max)); } public
Vector3 targetShootPoint;
private void Shoot() { Debug.Log("Attempting to shoot projectile for leviathan"); GameObject proj = GameObject.Instantiate(Plugin.maliciousFaceProjectile, shootPoint.transform.position, Quaternion.identity); if (targetGrenade == null) targetGrenade = FindTargetGrenade(); if (targetGrenade != null) { //NewMovement.Instance.playerCollider.bounds.center //proj.transform.rotation = Quaternion.LookRotation(targetGrenade.transform.position - shootPoint.transform.position); proj.transform.rotation = Quaternion.LookRotation(targetGrenade.transform.position - shootPoint.transform.position); } else { proj.transform.rotation = Quaternion.LookRotation(targetShootPoint - proj.transform.position); //proj.transform.rotation = Quaternion.LookRotation(NewMovement.Instance.playerCollider.bounds.center - proj.transform.position); //proj.transform.eulerAngles += RandomVector(-5f, 5f); } proj.transform.localScale = new Vector3(2f, 1f, 2f); if (proj.TryGetComponent(out RevolverBeam projComp)) { GameObject expClone = GameObject.Instantiate(projComp.hitParticle, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); foreach (Explosion exp in expClone.GetComponentsInChildren<Explosion>()) { exp.maxSize *= ConfigManager.leviathanChargeSizeMulti.value; exp.speed *= ConfigManager.leviathanChargeSizeMulti.value; exp.damage = (int)(exp.damage * ConfigManager.leviathanChargeDamageMulti.value * comp.lcon.eid.totalDamageModifier); exp.toIgnore.Add(EnemyType.Leviathan); } projComp.damage *= 2 * comp.lcon.eid.totalDamageModifier; projComp.hitParticle = expClone; } beamRemaining -= 1; if (beamRemaining <= 0) { Destroy(currentProjectileEffect); currentProjectileSize = 0; beamAttack = false; if (projectilesRemaining <= 0) { comp.lookAtPlayer = false; anim.SetBool("ProjectileBurst", false); ___inAction.SetValue(comp, false); targetGrenade = null; } else { comp.lookAtPlayer = true; projectileAttack = true; } } else { targetShootPoint = NewMovement.Instance.playerCollider.bounds.center; if (Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out RaycastHit hit, float.MaxValue, envMask)) targetShootPoint = hit.point; comp.lookAtPlayer = true; Invoke("PrepareForFire", ConfigManager.leviathanChargeDelay.value / comp.lcon.eid.totalSpeedModifier); } } private void SwitchToSecondPhase() { comp.lcon.phaseChangeHealth = comp.lcon.stat.health; } } class LeviathanTail_Flag : MonoBehaviour { public int swingCount = 0; private Animator ___anim; private void Awake() { ___anim = GetComponent<Animator>(); } public static float crossfadeDuration = 0.05f; private void SwingAgain() { ___anim.CrossFade("TailWhip", crossfadeDuration, 0, LeviathanTail_SwingEnd.targetStartNormalized); } } class Leviathan_Start { static void Postfix(LeviathanHead __instance) { Leviathan_Flag flag = __instance.gameObject.AddComponent<Leviathan_Flag>(); if(ConfigManager.leviathanSecondPhaseBegin.value) flag.Invoke("SwitchToSecondPhase", 2f / __instance.lcon.eid.totalSpeedModifier); } } class Leviathan_FixedUpdate { public static float projectileForward = 10f; static bool Roll(float chancePercent) { return UnityEngine.Random.Range(0, 99.9f) <= chancePercent; } static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown, Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack) { if (!__instance.active) { return false; } Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (___projectileBursting && flag.projectileAttack) { if (flag.projectileDelayRemaining > 0f) { flag.projectileDelayRemaining = Mathf.MoveTowards(flag.projectileDelayRemaining, 0f, Time.deltaTime * __instance.lcon.eid.totalSpeedModifier); } else { flag.projectilesRemaining -= 1; flag.projectileDelayRemaining = (1f / ConfigManager.leviathanProjectileDensity.value) / __instance.lcon.eid.totalSpeedModifier; GameObject proj = null; Projectile comp = null; if (Roll(ConfigManager.leviathanProjectileYellowChance.value) && ConfigManager.leviathanProjectileMixToggle.value) { proj = GameObject.Instantiate(Plugin.hideousMassProjectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); comp.safeEnemyType = EnemyType.Leviathan; // values from p2 flesh prison comp.turnSpeed *= 4f; comp.turningSpeedMultiplier *= 4f; comp.predictiveHomingMultiplier = 1.25f; } else if (Roll(ConfigManager.leviathanProjectileBlueChance.value) && ConfigManager.leviathanProjectileMixToggle.value) { proj = GameObject.Instantiate(Plugin.homingProjectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); comp.safeEnemyType = EnemyType.Leviathan; // values from mindflayer comp.turningSpeedMultiplier = 0.5f; comp.speed = 20f; comp.speed *= ___lcon.eid.totalSpeedModifier; comp.damage *= ___lcon.eid.totalDamageModifier; } else { proj = GameObject.Instantiate<GameObject>(MonoSingleton<DefaultReferenceManager>.Instance.projectile, ___shootPoint.position, ___shootPoint.rotation); comp = proj.GetComponent<Projectile>(); comp.safeEnemyType = EnemyType.Leviathan; comp.speed *= 2f; comp.enemyDamageMultiplier = 0.5f; } comp.speed *= __instance.lcon.eid.totalSpeedModifier; comp.damage *= __instance.lcon.eid.totalDamageModifier; comp.safeEnemyType = EnemyType.Leviathan; comp.enemyDamageMultiplier = ConfigManager.leviathanProjectileFriendlyFireDamageMultiplier.normalizedValue; proj.transform.localScale *= 2f; proj.transform.position += proj.transform.forward * projectileForward; } } if (___projectileBursting) { if (flag.projectilesRemaining <= 0 || BlindEnemies.Blind) { flag.projectileAttack = false; if (!flag.beamAttack) { ___projectileBursting = false; ___trackerIgnoreLimits = false; ___anim.SetBool("ProjectileBurst", false); } } else { if (NewMovement.Instance.ridingRocket != null && ConfigManager.leviathanChargeAttack.value && ConfigManager.leviathanChargeHauntRocketRiding.value) { flag.playerRocketRideTracker += Time.deltaTime; if (flag.playerRocketRideTracker >= 1 && !flag.beamAttack) { flag.projectileAttack = false; flag.beamAttack = true; __instance.lookAtPlayer = true; flag.ChargeBeam(___shootPoint); flag.beamRemaining = 1; return false; } } else { flag.playerRocketRideTracker = 0; } } } return false; } } class Leviathan_ProjectileBurst { static bool Prefix(LeviathanHead __instance, Animator ___anim, ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction) { if (!__instance.active) { return false; } Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (flag.beamAttack || flag.projectileAttack) return false; flag.beamAttack = false; if (ConfigManager.leviathanChargeAttack.value) { if (NewMovement.Instance.ridingRocket != null && ConfigManager.leviathanChargeHauntRocketRiding.value) { flag.beamAttack = true; } else if (UnityEngine.Random.Range(0, 99.9f) <= ConfigManager.leviathanChargeChance.value && ConfigManager.leviathanChargeAttack.value) { flag.beamAttack = true; } } flag.projectileAttack = true; return true; /*if (!beamAttack) { flag.projectileAttack = true; return true; }*/ /*if(flag.beamAttack) { Debug.Log("Attempting to prepare beam for leviathan"); ___anim.SetBool("ProjectileBurst", true); //___projectilesLeftInBurst = 1; //___projectileBurstCooldown = 100f; ___inAction = true; return true; }*/ } } class Leviathan_ProjectileBurstStart { static bool Prefix(LeviathanHead __instance, Transform ___shootPoint) { Leviathan_Flag flag = __instance.GetComponent<Leviathan_Flag>(); if (flag == null) return true; if (flag.projectileAttack) { if(flag.projectilesRemaining <= 0) { flag.projectilesRemaining = ConfigManager.leviathanProjectileCount.value; flag.projectileDelayRemaining = 0; } } if (flag.beamAttack) { if (!flag.charging) { Debug.Log("Attempting to charge beam for leviathan"); __instance.lookAtPlayer = true; flag.ChargeBeam(___shootPoint); } } return true; } } class LeviathanTail_Start { static void Postfix(LeviathanTail __instance) { __instance.gameObject.AddComponent<LeviathanTail_Flag>(); } } // This is the tail attack animation begin // fires at n=3.138 // l=5.3333 // 0.336 // 0.88 class LeviathanTail_BigSplash { static bool Prefix(LeviathanTail __instance) { LeviathanTail_Flag flag = __instance.gameObject.GetComponent<LeviathanTail_Flag>(); if (flag == null) return true; flag.swingCount = ConfigManager.leviathanTailComboCount.value; return true; } } class LeviathanTail_SwingEnd { public static float targetEndNormalized = 0.7344f; public static float targetStartNormalized = 0.41f; static bool Prefix(LeviathanTail __instance, Animator ___anim) { LeviathanTail_Flag flag = __instance.gameObject.GetComponent<LeviathanTail_Flag>(); if (flag == null) return true; flag.swingCount -= 1; if (flag.swingCount == 0) return true; flag.Invoke("SwingAgain", Mathf.Max(0f, 5.3333f * (0.88f - targetEndNormalized) * (1f / ___anim.speed))); return false; } } }
Ultrapain/Patches/Leviathan.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/MinosPrime.cs", "retrieved_chunk": " string stateName = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name;\n MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>();\n if (stateName == \"Combo\" || (flag != null && flag.throwingProjectile))\n return;\n Transform player = MonoSingleton<PlayerTracker>.Instance.GetPlayer();\n float min = ConfigManager.minosPrimeRandomTeleportMinDistance.value;\n float max = ConfigManager.minosPrimeRandomTeleportMaxDistance.value;\n Vector3 unitSphere = UnityEngine.Random.onUnitSphere;\n unitSphere.y = Mathf.Abs(unitSphere.y);\n float distance = UnityEngine.Random.Range(min, max);", "score": 0.8018776178359985 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " if (___eid.drillers.Count > 0)\n return false;\n Vector3 targetPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.9f) + deltaPosition;\n float distance = Vector3.Distance(__instance.transform.position, targetPosition);\n Ray targetRay = new Ray(__instance.transform.position, targetPosition - __instance.transform.position);\n RaycastHit hit;\n if (Physics.Raycast(targetRay, out hit, distance, ___environmentMask, QueryTriggerInteraction.Ignore))\n {\n targetPosition = targetRay.GetPoint(Mathf.Max(0.0f, hit.distance - 1.0f));\n }", "score": 0.789752185344696 }, { "filename": "Ultrapain/Plugin.cs", "retrieved_chunk": " return raycastHit.point;\n }\n else {\n Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod;\n return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z);\n }\n }\n public static GameObject projectileSpread;\n public static GameObject homingProjectile;\n public static GameObject hideousMassProjectile;", "score": 0.789647102355957 }, { "filename": "Ultrapain/Plugin.cs", "retrieved_chunk": " }\n public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null)\n {\n Vector3 projectedPlayerPos;\n if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f)\n {\n return target.position;\n }\n RaycastHit raycastHit;\n 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)", "score": 0.7803660035133362 }, { "filename": "Ultrapain/Patches/FleshPrison.cs", "retrieved_chunk": " }\n }\n }\n }\n class FleshPrisonProjectile : MonoBehaviour\n {\n void Start()\n {\n GetComponent<Rigidbody>().AddForce(Vector3.up * 50f, ForceMode.VelocityChange);\n }", "score": 0.7791950702667236 } ]
csharp
Vector3 targetShootPoint;
/* 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> /// This class represents an implementation of an IFlux interface with a TKey key and an action without parameters. ///</summary> internal sealed class ActionFlux<TKey> : IFlux<TKey, Action> { /// <summary> /// A dictionary that stores functions with no parameters /// </summary> internal Dictionary<TKey, HashSet<Action>> dictionary = new Dictionary<TKey, HashSet<Action>>(); ///<summary> /// Subscribes an event to the action dictionary if the given condition is met ///</summary> ///<param name="condition">Condition that must be true to subscribe the event</param> ///<param name="key">Key of the event to subscribe</param> ///<param name="action">Action to execute when the event is triggered</param> void
IStore<TKey, Action>.Store(in bool condition, TKey key, Action action) {
if(dictionary.TryGetValue(key, out var values)) { if (condition) values.Add(action); else values.Remove(action); } else if (condition) dictionary.Add(key, new HashSet<Action>(){action}); } ///<summary> /// Triggers the function stored in the dictionary with the specified key. ///</summary> void IFlux<TKey, Action>.Dispatch(TKey key) { if(dictionary.TryGetValue(key, out var _actions)) { foreach (var item in _actions) item.Invoke(); } } } } //Hashtable<TAction>
Runtime/Core/Internal/ActionFlux.cs
xavierarpa-UniFlux-a2d46de
[ { "filename": "Runtime/Core/Internal/ActionFluxParam.cs", "retrieved_chunk": " internal readonly Dictionary<TKey, HashSet<Action<TValue>>> dictionary = new Dictionary<TKey, HashSet<Action<TValue>>>();\n ///<summary>\n /// Subscribes an event to the action dictionary if the given condition is met\n ///</summary>\n ///<param name=\"condition\">Condition that must be true to subscribe the event</param>\n ///<param name=\"key\">Key of the event to subscribe</param>\n ///<param name=\"action\">Action to execute when the event is triggered</param>\n void IStore<TKey, Action<TValue>>.Store(in bool condition, TKey key, Action<TValue> action)\n {\n if(dictionary.TryGetValue(key, out var values))", "score": 0.9670993685722351 }, { "filename": "Runtime/Core/Internal/ActionFluxParam.cs", "retrieved_chunk": " {\n if (condition) values.Add(action);\n else values.Remove(action);\n }\n else if (condition) dictionary.Add(key, new HashSet<Action<TValue>>(){action});\n }\n ///<summary>\n /// Triggers the function stored in the dictionary with the specified key and set the parameter as argument \n ///</summary>\n void IFluxParam<TKey, TValue, Action<TValue>>.Dispatch(TKey key, TValue param)", "score": 0.8642476201057434 }, { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": " /// <summary>\n /// A dictionary that stores functions with no parameters and a return value of type `TReturn`.\n /// </summary>\n internal readonly Dictionary<TKey, Func<TReturn>> dictionary = new Dictionary<TKey, Func<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<TReturn>>.Store(in bool condition, TKey key, Func<TReturn> func) \n {", "score": 0.8590528964996338 }, { "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.8564959764480591 }, { "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.8400952219963074 } ]
csharp
IStore<TKey, Action>.Store(in bool condition, TKey key, Action action) {
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/Parry.cs", "retrieved_chunk": " exp.speed *= ConfigManager.grenadeBoostSizeMultiplier.value;\n }\n __instance.superExplosion = explosion;\n flag.temporaryBigExplosion = explosion;\n }\n }\n return true;\n }\n static void Postfix(Grenade __instance, ref bool ___exploded)\n {", "score": 0.8778294920921326 }, { "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.8474560379981995 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8368473052978516 }, { "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.8367260694503784 }, { "filename": "Ultrapain/Patches/CommonComponents.cs", "retrieved_chunk": " {\n tempHarmless = tempNormal = tempSuper = null;\n }\n }\n [HarmonyBefore]\n static bool Prefix(Grenade __instance, out StateInfo __state)\n {\n __state = new StateInfo();\n GrenadeExplosionOverride flag = __instance.GetComponent<GrenadeExplosionOverride>();\n if (flag == null)", "score": 0.8359988927841187 } ]
csharp
Grenade __instance, StateInfo __state) {
using HarmonyLib; using System; using System.ComponentModel; using UnityEngine; namespace Ultrapain.Patches { class MaliciousFaceFlag : MonoBehaviour { public bool charging = false; } class MaliciousFace_Start_Patch { static void Postfix(SpiderBody __instance, ref GameObject ___proj, ref int ___maxBurst) { __instance.gameObject.AddComponent<MaliciousFaceFlag>(); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { ___proj = Plugin.homingProjectile; ___maxBurst = Math.Max(0, ConfigManager.maliciousFaceHomingProjectileCount.value - 1); } } } class MaliciousFace_ChargeBeam { static void Postfix(SpiderBody __instance) { if (__instance.TryGetComponent<MaliciousFaceFlag>(out MaliciousFaceFlag flag)) flag.charging = true; } } class MaliciousFace_BeamChargeEnd { static bool Prefix(SpiderBody __instance, float ___maxHealth, ref int ___beamsAmount) { if (__instance.TryGetComponent<MaliciousFaceFlag>(out MaliciousFaceFlag flag) && flag.charging) { if (__instance.health < ___maxHealth / 2) ___beamsAmount = ConfigManager.maliciousFaceBeamCountEnraged.value; else ___beamsAmount = ConfigManager.maliciousFaceBeamCountNormal.value; flag.charging = false; } return true; } } class MaliciousFace_ShootProj_Patch { /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state) { __state = false; if (!Plugin.ultrapainDifficulty || !ConfigManager.enemyTweakToggle.value || !ConfigManager.maliciousFaceHomingProjectileToggle.value) return true; ___proj = Plugin.homingProjectile; __state = true; return true; }*/ static void Postfix(SpiderBody __instance, ref
GameObject ___currentProj, EnemyIdentifier ___eid/*, bool __state*/) {
/*if (!__state) return;*/ Projectile proj = ___currentProj.GetComponent<Projectile>(); proj.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); proj.speed = ConfigManager.maliciousFaceHomingProjectileSpeed.value; proj.turningSpeedMultiplier = ConfigManager.maliciousFaceHomingProjectileTurnSpeed.value; proj.damage = ConfigManager.maliciousFaceHomingProjectileDamage.value; proj.safeEnemyType = EnemyType.MaliciousFace; proj.speed *= ___eid.totalSpeedModifier; proj.damage *= ___eid.totalDamageModifier; ___currentProj.SetActive(true); } } class MaliciousFace_Enrage_Patch { static void Postfix(SpiderBody __instance) { EnemyIdentifier comp = __instance.GetComponent<EnemyIdentifier>(); for(int i = 0; i < ConfigManager.maliciousFaceRadianceAmount.value; i++) comp.BuffAll(); comp.UpdateBuffs(false); //__instance.spark = new GameObject(); } } /*[HarmonyPatch(typeof(SpiderBody))] [HarmonyPatch("BeamChargeEnd")] class MaliciousFace_BeamChargeEnd_Patch { static void Postfix(SpiderBody __instance, ref bool ___parryable) { if (__instance.currentEnrageEffect == null) return; ___parryable = false; } }*/ /*[HarmonyPatch(typeof(HookArm))] [HarmonyPatch("FixedUpdate")] class HookArm_FixedUpdate_MaliciousFacePatch { static void Postfix(HookArm __instance, ref EnemyIdentifier ___caughtEid) { if (__instance.state == HookState.Caught && ___caughtEid.enemyType == EnemyType.MaliciousFace) { if (___caughtEid.GetComponent<SpiderBody>().currentEnrageEffect == null) return; //__instance.state = HookState.Pulling; ___caughtEid = null; __instance.StopThrow(); } } }*/ }
Ultrapain/Patches/MaliciousFace.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Schism.cs", "retrieved_chunk": " class ZombieProjectile_Start_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)\n {\n if (___eid.enemyType != EnemyType.Schism)\n return;\n __instance.projectile = Plugin.homingProjectile;\n __instance.decProjectile = Plugin.decorativeProjectile2;\n }\n }*/", "score": 0.8631079196929932 }, { "filename": "Ultrapain/Patches/Stray.cs", "retrieved_chunk": " class Swing\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)\n {\n if (___eid.enemyType != EnemyType.Stray)\n return;\n ___eid.weakPoint = null;\n }\n }\n /*[HarmonyPatch(typeof(ZombieProjectiles), \"Swing\")]", "score": 0.8396205902099609 }, { "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.8335655927658081 }, { "filename": "Ultrapain/Patches/Solider.cs", "retrieved_chunk": " {\n static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, ref EnemyIdentifier ___eid, ref GameObject ___player, ref Animator ___anim, ref float ___coolDown)\n {\n if (___eid.enemyType != EnemyType.Soldier)\n return;\n ___currentProjectile.GetComponent<ProjectileSpread>().spreadAmount = 10;\n ___currentProjectile.SetActive(true);\n SoliderShootCounter counter = __instance.gameObject.GetComponent<SoliderShootCounter>();\n if (counter.remainingShots > 0)\n {", "score": 0.8238064646720886 }, { "filename": "Ultrapain/Patches/HideousMass.cs", "retrieved_chunk": " flag.damageBuf = ___eid.totalDamageModifier;\n flag.speedBuf = ___eid.totalSpeedModifier;\n return true;\n }\n static void Postfix(Mass __instance)\n {\n GameObject.Destroy(__instance.explosiveProjectile);\n __instance.explosiveProjectile = Plugin.hideousMassProjectile;\n }\n }", "score": 0.8231477737426758 } ]
csharp
GameObject ___currentProj, EnemyIdentifier ___eid/*, bool __state*/) {
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/Patches/FleshPrison.cs", "retrieved_chunk": " }\n }\n }\n }\n class FleshPrisonProjectile : MonoBehaviour\n {\n void Start()\n {\n GetComponent<Rigidbody>().AddForce(Vector3.up * 50f, ForceMode.VelocityChange);\n }", "score": 0.7826391458511353 }, { "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.7702245712280273 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " }\n return targetGrenade;\n }\n private Grenade targetGrenade = null;\n public void PrepareForFire()\n {\n charging = false;\n // OLD PREDICTION\n //targetShootPoint = NewMovement.Instance.playerCollider.bounds.center;\n //if (Physics.Raycast(NewMovement.Instance.transform.position, Vector3.down, out RaycastHit hit, float.MaxValue, envMask))", "score": 0.7699393033981323 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " public float beamChargeRate = 12f / 1f;\n public int beamRemaining = 0;\n public int projectilesRemaining = 0;\n public float projectileDelayRemaining = 0f;\n private static FieldInfo ___inAction = typeof(LeviathanHead).GetField(\"inAction\", BindingFlags.NonPublic | BindingFlags.Instance);\n private void Awake()\n {\n comp = GetComponent<LeviathanHead>();\n anim = GetComponent<Animator>();\n //col = GetComponent<Collider>();", "score": 0.7678588628768921 }, { "filename": "Ultrapain/Patches/V2Common.cs", "retrieved_chunk": " public Vector3 shootPoint;\n public Vector3 targetPoint;\n public RaycastHit targetHit;\n public bool alreadyHitPlayer = false;\n public bool alreadyReflected = false;\n private void Awake()\n {\n proj = GetComponent<Projectile>();\n proj.speed = 0;\n GetComponent<Rigidbody>().isKinematic = true;", "score": 0.7670968770980835 } ]
csharp
Collider safeCollider, float speedMod) {
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.9033595323562622 }, { "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.8898056149482727 }, { "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.8718518018722534 }, { "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.8585890531539917 }, { "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.8549362421035767 } ]
csharp
Kernel Kernel {
#nullable enable using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Mochineko.YouTubeLiveStreamingClient.Responses { [JsonObject] public sealed class LiveChatMessageSnippet { [JsonProperty("type"), JsonRequired, JsonConverter(typeof(StringEnumConverter))] public
LiveChatMessageType Type {
get; private set; } [JsonProperty("liveChatId"), JsonRequired] public string LiveChatId { get; private set; } = string.Empty; [JsonProperty("authorChannelId"), JsonRequired] public string AuthorChannelId { get; private set; } = string.Empty; [JsonProperty("publishedAt"), JsonRequired] public DateTime PublishedAt { get; private set; } [JsonProperty("hasDisplayContent"), JsonRequired] public bool HasDisplayContent { get; private set; } [JsonProperty("displayMessage"), JsonRequired] public string DisplayMessage { get; private set; } = string.Empty; [JsonProperty("textMessageDetails")] public TextMessageDetails? TextMessageDetails { get; private set; } [JsonProperty("messageDeletedDetails")] public MessageDeletedDetails? MessageDeletedDetails { get; private set; } [JsonProperty("userBannedDetails")] public UserBannedDetails? UserBannedDetails { get; private set; } [JsonProperty("memberMilestoneChatDetails")] public MemberMilestoneChatDetails? MemberMilestoneChatDetails { get; private set; } [JsonProperty("newSponsorDetails")] public NewSponsorDetails? NewSponsorDetails { get; private set; } [JsonProperty("superChatDetails")] public SuperChatDetails? SuperChatDetails { get; private set; } [JsonProperty("superStickerDetails")] public SuperStickerDetails? SuperStickerDetails { get; private set; } [JsonProperty("membershipGiftingDetails")] public MembershipGiftingDetails? MembershipGiftingDetails { get; private set; } [JsonProperty("giftMembershipReceivedDetails")] public GiftMembershipReceivedDetails? GiftMembershipReceivedDetails { get; private set; } } }
Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessageSnippet.cs
mochi-neko-youtube-live-streaming-client-unity-b712d77
[ { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessagesAPIResponse.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing Newtonsoft.Json;\nnamespace Mochineko.YouTubeLiveStreamingClient.Responses\n{\n [JsonObject]\n public sealed class LiveChatMessagesAPIResponse\n {\n [JsonProperty(\"kind\"), JsonRequired]\n public string Kind { get; private set; } = string.Empty;", "score": 0.9173272848129272 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessageItem.cs", "retrieved_chunk": "#nullable enable\nusing Newtonsoft.Json;\nnamespace Mochineko.YouTubeLiveStreamingClient.Responses\n{\n [JsonObject]\n public sealed class LiveChatMessageItem\n {\n [JsonProperty(\"kind\"), JsonRequired]\n public string Kind { get; private set; } = string.Empty;\n [JsonProperty(\"etag\"), JsonRequired]", "score": 0.908582329750061 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/VideoSnippet.cs", "retrieved_chunk": "#nullable enable\nusing System;\nusing Newtonsoft.Json;\nnamespace Mochineko.YouTubeLiveStreamingClient.Responses\n{\n [JsonObject]\n public sealed class VideoSnippet\n {\n [JsonProperty(\"publishedAt\"), JsonRequired]\n public DateTime PublishedAt { get; private set; }", "score": 0.8999543190002441 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/TextMessageDetails.cs", "retrieved_chunk": "#nullable enable\nusing Newtonsoft.Json;\nnamespace Mochineko.YouTubeLiveStreamingClient.Responses\n{\n [JsonObject]\n public sealed class TextMessageDetails\n {\n [JsonProperty(\"messageText\"), JsonRequired]\n public string MessageText { get; private set; } = string.Empty;\n }", "score": 0.8970657587051392 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/VideosAPIResponse.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing Newtonsoft.Json;\nnamespace Mochineko.YouTubeLiveStreamingClient.Responses\n{\n [JsonObject]\n public sealed class VideosAPIResponse\n {\n [JsonProperty(\"kind\"), JsonRequired]\n public string Kind { get; private set; } = string.Empty;", "score": 0.8937999606132507 } ]
csharp
LiveChatMessageType Type {
using System.Collections.Generic; using System.Threading.Tasks; using Sandland.SceneTool.Editor.Common.Utils; using Sandland.SceneTool.Editor.Views.Base; using Sandland.SceneTool.Editor.Views.Handlers; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace Sandland.SceneTool.Editor.Views { internal class SceneToolsSetupWindow : SceneToolsWindowBase { private const string WindowMenuItem = MenuItems.Tools.Root + "Setup Scene Tools"; public override float MinWidth => 600; public override float MinHeight => 600; public override string WindowName => "Scene Tools Setup"; public override string VisualTreeName => nameof(SceneToolsSetupWindow); public override string
StyleSheetName => nameof(SceneToolsSetupWindow);
private readonly List<ISceneToolsSetupUiHandler> _uiHandlers = new(); private Button _saveAllButton; [MenuItem(WindowMenuItem, priority = 0)] public static void ShowWindow() { var window = GetWindow<SceneToolsSetupWindow>(); window.InitWindow(); window.minSize = new Vector2(window.MinWidth, window.MinHeight); } protected override void InitGui() { _uiHandlers.Add(new SceneClassGenerationUiHandler(rootVisualElement)); _uiHandlers.Add(new ThemesSelectionUiHandler(rootVisualElement)); _saveAllButton = rootVisualElement.Q<Button>("save-button"); _saveAllButton.clicked += OnSaveAllButtonClicked; _uiHandlers.ForEach(handler => handler.SubscribeToEvents()); } private void OnDestroy() { _saveAllButton.clicked -= OnSaveAllButtonClicked; _uiHandlers.ForEach(handler => handler.UnsubscribeFromEvents()); } private async void OnSaveAllButtonClicked() { rootVisualElement.SetEnabled(false); _uiHandlers.ForEach(handler => handler.Apply()); while (EditorApplication.isCompiling) { await Task.Delay(100); // Checking every 100ms } rootVisualElement.SetEnabled(true); } } }
Assets/SceneTools/Editor/Views/SceneToolsSetupWindow/SceneToolsSetupWindow.cs
migus88-Sandland.SceneTools-64e9f8c
[ { "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.9642096757888794 }, { "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.8808590173721313 }, { "filename": "Assets/SceneTools/Editor/Common/Utils/MenuItems.cs", "retrieved_chunk": "namespace Sandland.SceneTool.Editor.Common.Utils\n{\n internal static class MenuItems\n {\n public static class Tools\n {\n public const string Root = \"Tools/Sandland Games/\";\n public const string Actions = Root + \"Actions/\";\n }\n public static class Creation", "score": 0.8736134767532349 }, { "filename": "Assets/SceneTools/Editor/Common/Data/SceneInfo.cs", "retrieved_chunk": " }\n public static class Create\n {\n public static SceneInfo Addressable(string address, string name = null, string path = null, string guid = null, List<string> labels = null)\n {\n return new SceneInfo(name, path, guid, string.Empty, labels)\n {\n ImportType = SceneImportType.Addressables,\n Address = address\n };", "score": 0.8356162309646606 }, { "filename": "Assets/SceneTools/Editor/Services/SceneTools/SceneToolsClassGenerationService.cs", "retrieved_chunk": " private const string DefaultNamespace = \"Sandland\";\n private const string Label = \"sandland-scene-class\";\n public static bool IsEnabled\n {\n get => EditorPrefs.GetBool(MainToggleKey, false);\n set => EditorPrefs.SetBool(MainToggleKey, value);\n }\n public static bool IsAutoGenerateEnabled\n {\n get => EditorPrefs.GetBool(AutogenerateOnChangeToggleKey, true);", "score": 0.8191770911216736 } ]
csharp
StyleSheetName => nameof(SceneToolsSetupWindow);
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Moadian.Dto { public class InvoiceDto : PrimitiveDto { public InvoiceHeaderDto header { get; set; } public List<InvoiceBodyDto> body { get; set; } public List<
InvoicePaymentDto> payments {
get; set; } } }
Dto/InvoiceDto.cs
Torabi-srh-Moadian-482c806
[ { "filename": "Dto/InvoiceHeaderDto.cs", "retrieved_chunk": "namespace Moadian.Dto\n{\n public class InvoiceHeaderDto : PrimitiveDto\n {\n /**\n * unique tax ID (should be generated using InvoiceIdService)\n */\n public string taxid { get; set; }\n /**\n * invoice timestamp (milliseconds from epoch)", "score": 0.8601642847061157 }, { "filename": "Dto/GetTokenDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class GetTokenDto : PrimitiveDto\n {\n public string username { get; set; }", "score": 0.8225544691085815 }, { "filename": "Dto/InvoicePaymentDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class InvoicePaymentDto : PrimitiveDto\n {\n private string? iinn;", "score": 0.821017861366272 }, { "filename": "Dto/InvoiceBodyDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class InvoiceBodyDto : PrimitiveDto\n {\n // service stuff ID", "score": 0.8202044367790222 }, { "filename": "Services/HttpClientService.cs", "retrieved_chunk": "namespace Moadian.Services\n{\n public class HttpClientService\n {\n private readonly HttpClient client;\n private readonly SignatureService signatureService;\n private readonly EncryptionService encryptionService;\n public HttpClientService(SignatureService signatureService, EncryptionService encryptionService, string baseUri = \"https://tp.tax.gov.ir\")\n {\n client = new HttpClient", "score": 0.7803497910499573 } ]
csharp
InvoicePaymentDto> payments {
using System; using System.Collections.Generic; using System.Text; using TaskSummarizer.Shared.Models; using Newtonsoft.Json; using static TaskSummarizer.Shared.Helpers.OpenAiHelpers; namespace TaskSummarizer.Shared.Services { public class OpenAiChatService { private string ApiKey { get; } private string BaseUrl { get; } private string DeploymentId { get; } private HttpDataService HttpDataService { get; } public OpenAiChatService(string apiKey, string baseUrl, string deploymentId) { ApiKey = apiKey; BaseUrl = baseUrl; DeploymentId = deploymentId; var endpointUrl = $"{baseUrl}/openai/deployments/{DeploymentId}/completions?api-version=2022-12-01"; HttpDataService = new HttpDataService(endpointUrl); } public async Task<
OpenAiResponse?> CreateCompletionAsync(string prompt) {
var completion = new OpenAiCompletion() { Prompt = prompt, Temperature = 1, FrequencyPenalty = 0, PresencePenalty = 0, MaxTokens = 1000, TopP = 0.95 }; var content = await HttpDataService.PostAsJsonAsync<OpenAiCompletion>("", completion, ApiKey); if (content == null) return null; var response = JsonConvert.DeserializeObject<OpenAiResponse>(content); return response; } } }
src/TasksSummarizer/TaskSummarizer.Shared/Services/OpenAiChatService.cs
Jcardif-DailyTaskSummary-5d3f785
[ { "filename": "src/TasksSummarizer/TasksSummarizer.Functions/Functions/SummarizeTasksHttpTrigger.cs", "retrieved_chunk": " .AddEnvironmentVariables()\n .Build();\n var apiKey = config.GetValue<string>(\"AzureOpenAI:APIKey\");\n var deploymentId = config.GetValue<string>(\"AzureOpenAI:DeploymentId\");\n var baseUrl = config.GetValue<string>(\"AzureOpenAI:BaseUrl\");\n var filePath = Path.Combine(Environment.CurrentDirectory, \"Prompts\", \"SummarizeText.txt\");\n var baseSystemMessage = await File.ReadAllTextAsync(filePath);\n baseSystemMessage = baseSystemMessage.Replace(\"Peter Parker\", name);\n var chatService = new OpenAiChatService(apiKey, baseUrl, deploymentId);\n var prompt = GetPromptFromTasks(items, baseSystemMessage);", "score": 0.7559842467308044 }, { "filename": "src/TasksSummarizer/TasksSummarizer.Functions/Functions/GenerateAdaptiveCardHttpTrigger.cs", "retrieved_chunk": " var deploymentId = config.GetValue<string>(\"AzureOpenAI:DeploymentId\");\n var baseUrl = config.GetValue<string>(\"AzureOpenAI:BaseUrl\");\n var filePath = Path.Combine(Environment.CurrentDirectory, \"Prompts\", \"GenerateAdaptiveCard.txt\");\n var baseSystemMessage = await File.ReadAllTextAsync(filePath);\n var chatService = new OpenAiChatService(apiKey, baseUrl, deploymentId);\n var prompt = GetAdaptiveCardPrompt(taskSummary, baseSystemMessage);\n var openAiResponse = await chatService.CreateCompletionAsync(prompt);\n var text = openAiResponse?.Choices?.FirstOrDefault()?.Text;\n var card = EnsureBraces(text ?? \"{}\");\n response = req.CreateResponse(HttpStatusCode.OK);", "score": 0.7513695955276489 }, { "filename": "src/TasksSummarizer/TaskSummarizer.Shared/Services/HttpDataService.cs", "retrieved_chunk": " return JsonConvert.DeserializeObject<T>(content);\n }\n throw new HttpRequestException($\"Error calling {uri} - {response.StatusCode}\");\n }\n public async Task<string?> PostAsJsonAsync<T>(string uri, T item, string apiKey)\n {\n var jsonBody = JsonConvert.SerializeObject(item);\n var httpContent = new StringContent(jsonBody, Encoding.UTF8, \"application/json\");\n httpContent.Headers.Add(\"api-key\", apiKey);\n var response = await _client.PostAsync(\"\", httpContent);", "score": 0.723456621170044 }, { "filename": "src/TasksSummarizer/TaskSummarizer.Shared/Services/HttpDataService.cs", "retrieved_chunk": " _client = new HttpClient();\n _client.BaseAddress = new Uri(defaultBaseUrl);\n }\n public async Task<T?> GetAsync<T>(string uri)\n {\n var request = new HttpRequestMessage(HttpMethod.Get, uri);\n var response = await _client.SendAsync(request);\n if (response.IsSuccessStatusCode)\n {\n var content = await response.Content.ReadAsStringAsync();", "score": 0.7143890261650085 }, { "filename": "src/TasksSummarizer/TasksSummarizer.Functions/Functions/SummarizeTasksHttpTrigger.cs", "retrieved_chunk": " var openAiResponse = await chatService.CreateCompletionAsync(prompt);\n var summary = new { taskSummary = openAiResponse?.Choices?.FirstOrDefault()?.Text ?? \"\" };\n response = req.CreateResponse(HttpStatusCode.OK);\n await response.WriteAsJsonAsync(summary); \n return response;\n }\n }\n}", "score": 0.7115087509155273 } ]
csharp
OpenAiResponse?> CreateCompletionAsync(string prompt) {
using FayElf.Plugins.WeChat.Applets.Model; using FayElf.Plugins.WeChat.Model; using System; using System.Collections.Generic; using System.Drawing; using System.IO; 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:18:22 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.Applets { /// <summary> /// 小程序主类 /// </summary> public class Applets { #region 无参构造器 /// <summary> /// 无参构造器 /// </summary> public Applets() { this.Config = Config.Current; } /// <summary> /// 设置配置 /// </summary> /// <param name="config">配置</param> public Applets(Config config) { this.Config = config; } /// <summary> /// 设置配置 /// </summary> /// <param name="appID">AppID</param> /// <param name="appSecret">密钥</param> public Applets(string appID, string appSecret) { this.Config.AppID = appID; this.Config.AppSecret = appSecret; } #endregion #region 属性 /// <summary> /// 配置 /// </summary> public Config Config { get; set; } = new Config(); #endregion #region 方法 #region 登录凭证校验 /// <summary> /// 登录凭证校验 /// </summary> /// <param name="code">登录时获取的 code</param> /// <returns></returns> public JsCodeSessionData JsCode2Session(string code) { var session = new JsCodeSessionData(); var config = this.Config.GetConfig(WeChatType.Applets); var result = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Get, Address = $"{HttpApi.HOST}/sns/jscode2session?appid={config.AppID}&secret={config.AppSecret}&js_code={code}&grant_type=authorization_code" }); if (result.StatusCode == System.Net.HttpStatusCode.OK) { session = result.Html.JsonToObject<JsCodeSessionData>(); } else { session.ErrMsg = "请求出错."; session.ErrCode = 500; } return session; } #endregion #region 下发小程序和公众号统一的服务消息 /// <summary> /// 下发小程序和公众号统一的服务消息 /// </summary> /// <param name="data">下发数据</param> /// <returns></returns> public BaseResult UniformSend(UniformSendData data) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"{HttpApi.HOST}/cgi-bin/message/wxopen/template/uniform_send?access_token={token.AccessToken}", BodyData = data.ToJson() }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<BaseResult>(); if (result.ErrCode != 0) { var dic = new Dictionary<int, string> { {40037,"模板id不正确,weapp_template_msg.template_id或者mp_template_msg.template_id" }, {41028,"weapp_template_msg.form_id过期或者不正确" }, {41029,"weapp_template_msg.form_id已被使用" }, {41030,"weapp_template_msg.page不正确" }, {45009,"接口调用超过限额" }, {40003,"touser不是正确的openid" }, {40013,"appid不正确,或者不符合绑定关系要求" } }; result.ErrMsg += "[" + dic[result.ErrCode] + "]"; } return result; } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求出错." }; } }); } #endregion #region 获取用户手机号 /// <summary> /// 获取用户手机号 /// </summary> /// <param name="code">手机号获取凭证</param> /// <returns></returns> public UserPhoneData GetUserPhone(string code) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"{HttpApi.HOST}/wxa/business/getuserphonenumber?access_token={token.AccessToken}", BodyData = $"{{\"code\":\"{code}\"}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<UserPhoneData>(); if (result.ErrCode != 0) { result.ErrMsg += "[" + result.ErrCode + "]"; } return result; } else { return new UserPhoneData { ErrCode = 500, ErrMsg = "请求出错." }; } }); } #endregion #region 获取用户encryptKey /// <summary> /// 获取用户encryptKey /// </summary> /// <param name="session">Session数据</param> /// <returns></returns> public
UserEncryptKeyData GetUserEncryptKey(JsCodeSessionData session) {
var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"{HttpApi.HOST}/wxa/business/getuserencryptkey?access_token={token.AccessToken}", BodyData = $"{{\"openid\":\"{session.OpenID}\",\"signature\":\"{"".HMACSHA256Encrypt(session.SessionKey)}\",\"sig_method\":\"hmac_sha256\"}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = response.Html.JsonToObject<UserEncryptKeyData>(); if (result.ErrCode != 0) { result.ErrMsg += "[" + result.ErrCode + "]"; } return result; } else { return new UserEncryptKeyData { ErrCode = 500, ErrMsg = "请求出错." }; } }); } #endregion #region 获取小程序码 /// <summary> /// 获取小程序码 /// </summary> /// <param name="path">扫码进入的小程序页面路径,最大长度 128 字节,不能为空;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar",即可在 wx.getLaunchOptionsSync 接口中的 query 参数获取到 {foo:"bar"}。</param> /// <param name="width">二维码的宽度,单位 px。默认值为430,最小 280px,最大 1280px</param> /// <param name="autoColor">默认值false;自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调</param> /// <param name="color">默认值{"r":0,"g":0,"b":0} ;auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示</param> /// <param name="ishyaline">背景是否透明</param> /// <returns></returns> public QrCodeResult GetQRCode(string path, int width, Boolean autoColor = false, Color? color = null, Boolean ishyaline = false) { if (!color.HasValue) color = Color.Black; var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var result = new HttpRequest { Address = $"{HttpApi.HOST}/wxa/getwxacode?access_token={token.AccessToken}", Method = HttpMethod.Post, BodyData = $@"{{ ""path"":""{path}"", ""width"":{width}, ""auto_color"":{autoColor.ToString().ToLower()}, ""line_color"":{{""r"":{color?.R},""g"":{color?.G},""b"":{color?.B}}}, ""is_hyaline"":{ishyaline.ToString().ToLower()} }}" }.GetResponse(); if (result.StatusCode == System.Net.HttpStatusCode.OK) { if (result.Html.IndexOf("errcode") == -1) { return new QrCodeResult { ErrCode = 0, ContentType = result.ContentType, Buffer = result.Data.ToBase64String() }; } } return new QrCodeResult { ErrCode = 500, ErrMsg = result.Html }; }); } #endregion #region 获取不限制的小程序码 /// <summary> /// 获取不限制的小程序码 /// </summary> /// <param name="page">默认是主页,页面 page,例如 pages/index/index,根路径前不要填加 /,不能携带参数(参数请放在 scene 字段里),如果不填写这个字段,默认跳主页面。</param> /// <param name="scene">最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式)</param> /// <param name="checkPath">默认是true,检查page 是否存在,为 true 时 page 必须是已经发布的小程序存在的页面(否则报错);为 false 时允许小程序未发布或者 page 不存在, 但page 有数量上限(60000个)请勿滥用。</param> /// <param name="envVersion">要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。</param> /// <param name="width">默认430,二维码的宽度,单位 px,最小 280px,最大 1280px</param> /// <param name="autoColor">自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false</param> /// <param name="color">默认是{"r":0,"g":0,"b":0} 。auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示</param> /// <param name="ishyaline">默认是false,是否需要透明底色,为 true 时,生成透明底色的小程序</param> /// <returns></returns> public QrCodeResult GetUnlimitedQRCode(string page, string scene, Boolean checkPath, AppletEnvVersion envVersion, int width, Boolean autoColor = false, Color? color = null, Boolean ishyaline = false) { if (!color.HasValue) color = Color.Black; var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var result = new HttpRequest { Address = $"{HttpApi.HOST}/wxa/getwxacodeunlimit?access_token={token.AccessToken}", Method = HttpMethod.Post, BodyData = $@"{{ ""page"":""{page}"", ""scene"":""{scene}"", ""check_path"":{checkPath.ToString().ToLower()}, ""env_version"":""{envVersion.ToString().ToLower()}"", ""width"":{width}, ""auto_color"":{autoColor.ToString().ToLower()}, ""line_color"":{{""r"":{color?.R},""g"":{color?.G},""b"":{color?.B}}}, ""is_hyaline"":{ishyaline.ToString().ToLower()} }}" }.GetResponse(); if (result.StatusCode == System.Net.HttpStatusCode.OK) { if (result.Html.IndexOf("errcode") == -1) { return new QrCodeResult { ErrCode = 0, ContentType = result.ContentType, Buffer = result.Data.ToBase64String() }; } } return new QrCodeResult { ErrCode = 500, ErrMsg = result.Html }; }); } #endregion #region 获取小程序二维码 /// <summary> /// 获取小程序二维码 /// </summary> /// <param name="path">扫码进入的小程序页面路径,最大长度 128 字节,不能为空;对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar",即可在 wx.getLaunchOptionsSync 接口中的 query 参数获取到 {foo:"bar"}。</param> /// <param name="width">二维码的宽度,单位 px。最小 280px,最大 1280px;默认是430</param> /// <returns></returns> public QrCodeResult CreateQRCode(string path, int width) { var config = this.Config.GetConfig(WeChatType.Applets); return Common.Execute(config.AppID, config.AppSecret, token => { var result = new HttpRequest { Address = $"{HttpApi.HOST}/cgi-bin/wxaapp/createwxaqrcode?access_token={token.AccessToken}", Method = HttpMethod.Post, BodyData = $@"{{ ""path"":""{path}"", ""width"":{width} }}" }.GetResponse(); if (result.StatusCode == System.Net.HttpStatusCode.OK) { if (result.Html.IndexOf("errcode") == -1) { return new QrCodeResult { ErrCode = 0, ContentType = result.ContentType, Buffer = result.Data.ToBase64String() }; } } return new QrCodeResult { ErrCode = 500, ErrMsg = result.Html }; }); } #endregion #endregion } }
Applets/Applets.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " #endregion\n #region 删除模板\n /// <summary>\n /// 删除模板\n /// </summary>\n /// <param name=\"priTmplId\">要删除的模板id</param>\n /// <returns></returns>\n public BaseResult DeleteTemplate(string priTmplId)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);", "score": 0.8181033134460449 }, { "filename": "OfficialAccount/Menu.cs", "retrieved_chunk": " #region 创建菜单\n /// <summary>\n /// 创建菜单\n /// </summary>\n /// <param name=\"buttons\">菜单列表</param>\n /// <returns></returns>\n public BaseResult CreateMenu(List<ButtonModel> buttons)\n {\n if (buttons == null || buttons.Count == 0)\n return new BaseResult", "score": 0.80782151222229 }, { "filename": "OfficialAccount/Template.cs", "retrieved_chunk": " return result.ErrCode == 0;\n }\n #endregion\n #region 发送模板消息\n /// <summary>\n /// 发送模板消息\n /// </summary>\n /// <param name=\"data\">发送数据</param>\n /// <returns></returns>\n public IndustryTemplateSendDataResult Send(IndustryTemplateSendData data)", "score": 0.8034499883651733 }, { "filename": "Model/WeChatConfig.cs", "retrieved_chunk": " #endregion\n #region 属性\n /// <summary>\n /// AppID\n /// </summary>\n [Description(\"AppID\")]\n public string AppID { get; set; } = \"\";\n /// <summary>\n /// 密钥\n /// </summary>", "score": 0.8032799363136292 }, { "filename": "Applets/Model/UserEncryptKeyData.cs", "retrieved_chunk": " #endregion\n }\n /// <summary>\n /// 加密 key\n /// </summary>\n public class KeyInfoModel {\n /// <summary>\n /// 加密key\n /// </summary>\n [JsonElement(\"encrypt_key\")]", "score": 0.8019145727157593 } ]
csharp
UserEncryptKeyData GetUserEncryptKey(JsCodeSessionData session) {
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; using VeilsClaim.Classes.Managers; using VeilsClaim.Classes.Objects.Particles; using VeilsClaim.Classes.Utilities; namespace VeilsClaim.Classes.Objects.Projectiles { public class Bolt : Projectile { public Bolt(Bolt copy) : base(copy) { Trail = new Trail( copy.Position, copy.Trail.Joints.Count, copy.Trail.SegmentLength, copy.Trail.StartThickness, copy.Trail.EndThickness, copy.Trail.AllowShrinking, copy.Trail.StartColour, copy.Trail.EndColour); } public Bolt() : base() { Friction = 1f; Penetration = 1; Trail = new Trail( Position, 32, 2f, 5f, 1f, true, Color.White, Color.DodgerBlue); } public
Trail Trail;
public override List<Vector2> CreateShape() { return new List<Vector2>(); } public override void Destroy() { // for (int i = 0; i < (int)(Velocity.Length() / 100); i++) // ParticleManager.particles.Add(new SparkParticle() // { // Position = Position, // Velocity = Velocity, // Size = 15f, // StartSize = 15f, // EndSize = 5f, // Colour = Color.LightSkyBlue, // StartColour = Color.LightSkyBlue, // EndColour = Color.RoyalBlue, // Friction = 0.1f, // Mass = 0.005f, // WindStrength = 20f, // MaxLifespan = 0.5f + Main.Random.NextSingle() / 5f, // }); base.Destroy(); } public override void Update(float delta) { Trail.Limit(Position); if (MathAdditions.Probability(delta, 0.5f)) ParticleManager.particles.Add(new SparkParticle() { Position = Position, Velocity = Velocity, Size = 15f, StartSize = 15f, EndSize = 5f, Colour = Color.LightSkyBlue, StartColour = Color.LightSkyBlue, EndColour = Color.RoyalBlue, Friction = 0.1f, Mass = 0.005f, WindStrength = 2f, MaxLifespan = 0.15f + Main.Random.NextSingle() / 5f, }); base.Update(delta); } public override void Draw(SpriteBatch spriteBatch) { Trail.Draw(spriteBatch); } public override Bolt Clone() { return new Bolt(this); } } }
VeilsClaim/Classes/Objects/Projectiles/Bolt.cs
IsCactus0-Veils-Claim-de09cef
[ { "filename": "VeilsClaim/Classes/Objects/Trail.cs", "retrieved_chunk": " StartThickness = 5f;\n EndThickness = 2f;\n AllowShrinking = true;\n StartColour = Color.White;\n EndColour = Color.RoyalBlue;\n }\n public Trail(Vector2 position, int segmentCount, float length, float thickness)\n {\n Joints = new List<Vector2>();\n for (int i = 0; i < segmentCount; i++)", "score": 0.8660206198692322 }, { "filename": "VeilsClaim/Classes/Objects/Projectiles/Projectile.cs", "retrieved_chunk": " {\n Penetration = 1;\n MinDamage = 1;\n MaxDamage = 2;\n CritChance = 0.1f;\n CritMultiplier = 2f;\n Hitbox = new Rectangle(-3, -3, 6, 6);\n }\n public Projectile(float x, float y)\n : base(x, y)", "score": 0.8547490239143372 }, { "filename": "VeilsClaim/Classes/Objects/Particles/Particle.cs", "retrieved_chunk": " {\n Colour = Color.White;\n StartSize = 10f;\n EndSize = 10f;\n Size = StartSize;\n }\n public Particle(Color colour)\n : base()\n {\n Colour = colour;", "score": 0.8526397347450256 }, { "filename": "VeilsClaim/Classes/Objects/Projectiles/Projectile.cs", "retrieved_chunk": " {\n Penetration = 1;\n MinDamage = 1;\n MaxDamage = 2;\n CritChance = 0.1f;\n CritMultiplier = 2f;\n Hitbox = new Rectangle(-3, -3, 6, 6);\n }\n public Projectile(float x, float y, float vx, float vy)\n : base(x, y, vx, vy)", "score": 0.8508047461509705 }, { "filename": "VeilsClaim/Classes/Objects/Particles/SparkParticle.cs", "retrieved_chunk": " SparkColour = Color.White;\n SparkStartColour = Color.White;\n SparkEndColour = Color.White;\n SparkSize = 10f;\n SparkStartSize = 10f;\n SparkEndSize = 2f;\n }\n public Color SparkStartColour;\n public Color SparkEndColour;\n public Color SparkColour;", "score": 0.8446144461631775 } ]
csharp
Trail Trail;
using NowPlaying.Utils; using NowPlaying.Models; using System; using System.Collections.Generic; using System.IO; namespace NowPlaying.ViewModels { public class GameCacheViewModel : ObservableObject { private readonly NowPlaying plugin; public readonly GameCacheManagerViewModel manager; public readonly GameCacheEntry entry; public CacheRootViewModel cacheRoot; public string Title => entry.Title; public string Root => entry.CacheRoot; public string Device => Directory.GetDirectoryRoot(Root); public string Id => entry.Id; public string CacheDir => entry.CacheDir; public string InstallDir => entry.InstallDir; public string ExePath => entry.ExePath; public string XtraArgs => entry.XtraArgs; public long InstallSize => entry.InstallSize; public long InstallFiles => entry.InstallFiles; public long CacheSize => entry.CacheSize; public long CacheSizeOnDisk => entry.CacheSizeOnDisk; public GameCacheState State => entry.State; public
GameCachePlatform Platform => entry.Platform;
private string installQueueStatus; private string uninstallQueueStatus; private bool nowInstalling; private bool nowUninstalling; private string formatStringXofY; private int bytesScale; private string bytesToCopy; private string cacheInstalledSize; public string InstallQueueStatus => installQueueStatus; public string UninstallQueueStatus => uninstallQueueStatus; public bool NowInstalling => nowInstalling; public bool NowUninstalling => nowUninstalling; public string Status => GetStatus ( entry.State, installQueueStatus, uninstallQueueStatus, nowInstalling, plugin.SpeedLimitIpg > 0, nowUninstalling ); public string StatusColor => ( State == GameCacheState.Unknown || State == GameCacheState.Invalid ? "WarningBrush" : Status == plugin.GetResourceString("LOCNowPlayingTermsUninstalled") ? "TextBrushDarker" : NowInstalling ? (plugin.SpeedLimitIpg > 0 ? "SlowInstallBrush" : "InstallBrush") : "TextBrush" ); public string CacheInstalledSize => cacheInstalledSize; public string CacheInstalledSizeColor => ( CanInstallCache == plugin.GetResourceString("LOCNowPlayingTermsNo") ? "WarningBrush" : State == GameCacheState.Empty ? "TextBrushDarker" : "TextBrush" ); public bool CacheWillFit { get; private set; } public string CanInstallCache => ( (entry.State==GameCacheState.Empty || entry.State==GameCacheState.InProgress) ? plugin.GetResourceString(CacheWillFit ? "LOCNowPlayingTermsYes" : "LOCNowPlayingTermsNo") : "-" ); public string CanInstallCacheColor => CanInstallCache == plugin.GetResourceString("LOCNowPlayingTermsNo") ? "WarningBrush" : "TextBrush"; public TimeSpan InstallEtaTimeSpan { get; private set; } public string InstallEta { get; private set; } public string CacheRootSpaceAvailable { get; private set; } public string CacheRootSpaceAvailableColor => cacheRoot.BytesAvailableForCaches > 0 ? "TextBrush" : "WarningBrush"; public bool PartialFileResume { get; set; } public GameCacheViewModel(GameCacheManagerViewModel manager, GameCacheEntry entry, CacheRootViewModel cacheRoot) { this.manager = manager; this.plugin = manager.plugin; this.entry = entry; this.cacheRoot = cacheRoot; this.nowInstalling = manager.IsPopulateInProgess(entry.Id); this.PartialFileResume = false; this.formatStringXofY = plugin.GetResourceFormatString("LOCNowPlayingProgressXofYFmt2", 2) ?? "{0} of {1}"; this.cacheInstalledSize = GetCacheInstalledSize(entry); this.bytesScale = SmartUnits.GetBytesAutoScale(entry.InstallSize); this.bytesToCopy = SmartUnits.Bytes(entry.InstallSize, decimals: 1, userScale: bytesScale); UpdateInstallEta(); } public bool IsUninstalled() { return State == GameCacheState.Empty; } public void UpdateCacheRoot() { OnPropertyChanged(nameof(Root)); OnPropertyChanged(nameof(Device)); OnPropertyChanged(nameof(CacheDir)); UpdateStatus(); UpdateCacheSize(); UpdateCacheSpaceWillFit(); UpdateInstallEta(); } public void UpdateStatus() { OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); OnPropertyChanged(nameof(CanInstallCache)); OnPropertyChanged(nameof(CanInstallCacheColor)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); cacheRoot.UpdateGameCaches(); } public void UpdateInstallQueueStatus(string value = null) { if (installQueueStatus != value) { installQueueStatus = value; OnPropertyChanged(nameof(InstallQueueStatus)); OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); } } public void UpdateUninstallQueueStatus(string value = null) { if (uninstallQueueStatus != value) { uninstallQueueStatus = value; OnPropertyChanged(nameof(UninstallQueueStatus)); OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); } } public void UpdateNowInstalling(bool value) { if (value) { // . update auto scale for and bake "OfBytes" to copy string. this.bytesScale = SmartUnits.GetBytesAutoScale(entry.InstallSize); this.bytesToCopy = SmartUnits.Bytes(entry.InstallSize, decimals: 1, userScale: bytesScale); } nowInstalling = value; nowUninstalling &= !nowInstalling; UpdateInstallEta(); OnPropertyChanged(nameof(NowInstalling)); OnPropertyChanged(nameof(NowUninstalling)); OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); OnPropertyChanged(nameof(CanInstallCache)); OnPropertyChanged(nameof(CanInstallCacheColor)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); } public void UpdateNowUninstalling(bool value) { if (nowUninstalling != value) { nowUninstalling = value; nowInstalling &= !nowUninstalling; OnPropertyChanged(nameof(NowInstalling)); OnPropertyChanged(nameof(NowUninstalling)); OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(StatusColor)); OnPropertyChanged(nameof(CanInstallCache)); OnPropertyChanged(nameof(CanInstallCacheColor)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); } } public void UpdateCacheSize() { OnPropertyChanged(nameof(CacheSize)); string value = GetCacheInstalledSize(entry); if (cacheInstalledSize != value) { cacheInstalledSize = value; OnPropertyChanged(nameof(CacheInstalledSize)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); cacheRoot.UpdateCachesInstalled(); cacheRoot.UpdateSpaceAvailableForCaches(); } } public void UpdateCacheSpaceWillFit() { bool bval = cacheRoot.BytesAvailableForCaches > (InstallSize - CacheSizeOnDisk); if (CacheWillFit != bval) { CacheWillFit = bval; OnPropertyChanged(nameof(CacheWillFit)); OnPropertyChanged(nameof(CanInstallCache)); OnPropertyChanged(nameof(CanInstallCacheColor)); OnPropertyChanged(nameof(CacheInstalledSizeColor)); } string sval = SmartUnits.Bytes(cacheRoot.BytesAvailableForCaches, decimals: 1); if (CacheRootSpaceAvailable != sval || cacheRoot.BytesAvailableForCaches <= 0) { CacheRootSpaceAvailable = sval; OnPropertyChanged(nameof(CacheRootSpaceAvailable)); OnPropertyChanged(nameof(CacheRootSpaceAvailableColor)); } } public void UpdateInstallEta(TimeSpan? value = null) { if (value == null) { var avgBytesPerFile = entry.InstallSize / entry.InstallFiles; var avgBps = manager.GetInstallAverageBps(entry.InstallDir, avgBytesPerFile, plugin.SpeedLimitIpg); value = GetInstallEtaTimeSpan(entry, avgBps); } if (InstallEtaTimeSpan != value || InstallEta == null) { InstallEtaTimeSpan = (TimeSpan)value; InstallEta = GetInstallEta(InstallEtaTimeSpan); OnPropertyChanged(nameof(InstallEtaTimeSpan)); OnPropertyChanged(nameof(InstallEta)); } } private TimeSpan GetInstallEtaTimeSpan(GameCacheEntry entry, long averageBps) { bool notInstalled = entry.State == GameCacheState.Empty || entry.State == GameCacheState.InProgress; if (notInstalled) { if (averageBps > 0) { long bytesLeftToInstall = entry.InstallSize - entry.CacheSize; return TimeSpan.FromSeconds((1.0 * bytesLeftToInstall) / averageBps); } else { return TimeSpan.FromMilliseconds(-1); // Infinite } } else { return TimeSpan.Zero; } } private string GetInstallEta(TimeSpan etaTimeSpan) { return etaTimeSpan > TimeSpan.Zero ? SmartUnits.Duration(etaTimeSpan) : etaTimeSpan == TimeSpan.Zero ? "-" : "∞"; } private string GetCacheInstalledSize(GameCacheEntry entry) { switch (entry.State) { case GameCacheState.Played: case GameCacheState.Populated: return SmartUnits.Bytes(entry.CacheSize, decimals: 1); case GameCacheState.InProgress: return string.Format ( formatStringXofY, SmartUnits.Bytes(entry.CacheSize, userScale: bytesScale, decimals: 1, showUnits: false), bytesToCopy ); case GameCacheState.Empty: return plugin.FormatResourceString ( "LOCNowPlayingGameCacheSizeNeededFmt", SmartUnits.Bytes(entry.InstallSize, decimals:1) ); default: return "-"; } } private string GetStatus ( GameCacheState state, string installQueueStatus, string uninstallQueueStatus, bool nowInstalling, bool isSpeedLimited, bool nowUninstalling ) { if (installQueueStatus != null) { return plugin.GetResourceString("LOCNowPlayingTermsQueuedForInstall") + $" ({installQueueStatus})"; } else if (uninstallQueueStatus != null) { return plugin.GetResourceString("LOCNowPlayingTermsQueuedForUninstall") + $" ({uninstallQueueStatus})"; } else if (nowInstalling) { return plugin.GetResourceString(isSpeedLimited ? "LOCNowPlayingTermsInstallSpeedLimit" : "LOCNowPlayingTermsInstalling") + "..."; } else if (nowUninstalling) { return plugin.GetResourceString("LOCNowPlayingTermsUninstalling") + "..."; } else { switch (state) { case GameCacheState.Played: case GameCacheState.Populated: return plugin.GetResourceString("LOCNowPlayingTermsInstalled"); case GameCacheState.InProgress: return plugin.GetResourceString("LOCNowPlayingTermsPaused"); case GameCacheState.Empty: return plugin.GetResourceString("LOCNowPlayingTermsUninstalled"); default: return "** " + plugin.GetResourceString("LOCNowPlayingTermsInvalid") + " **"; } } } } }
source/ViewModels/GameCacheViewModel.cs
gittromney-Playnite-NowPlaying-23eec41
[ { "filename": "source/ViewModels/CacheRootViewModel.cs", "retrieved_chunk": " public readonly NowPlaying plugin;\n public CacheRoot root;\n public string Directory => root.Directory;\n public string Device => System.IO.Directory.GetDirectoryRoot(Directory);\n public double MaxFillLevel => root.MaxFillLevel;\n public ObservableCollection<GameCacheViewModel> GameCaches { get; private set; }\n public long GamesEnabled { get; private set; }\n public int CachesInstalled { get; private set; }\n public long cachesAggregateSizeOnDisk { get; private set; }\n public string CachesInstalledSize => cachesAggregateSizeOnDisk > 0 ? \"(\" + SmartUnits.Bytes(cachesAggregateSizeOnDisk) + \")\" : \"\";", "score": 0.880130410194397 }, { "filename": "source/ViewModels/GameViewModel.cs", "retrieved_chunk": " public string InstallDir => game.InstallDirectory;\n public string InstallSize => SmartUnits.Bytes((long)(game.InstallSize ?? 0));\n public long InstallSizeBytes => (long)(game.InstallSize ?? 0);\n public string Genres => game.Genres != null ? string.Join(\", \", game.Genres.Select(x => x.Name)) : \"\";\n public GameCachePlatform Platform { get; private set; }\n public GameViewModel(Game game)\n {\n this.game = game;\n this.Platform = NowPlaying.GetGameCachePlatform(game);\n }", "score": 0.8759952783584595 }, { "filename": "source/Models/GameCacheEntry.cs", "retrieved_chunk": " string exePath,\n string xtraArgs,\n string cacheRoot,\n string cacheSubDir = null,\n long installFiles = 0,\n long installSize = 0,\n long cacheSize = 0,\n long cacheSizeOnDisk = 0,\n GameCachePlatform platform = GameCachePlatform.WinPC,\n GameCacheState state = GameCacheState.Unknown)", "score": 0.874411940574646 }, { "filename": "source/Models/GameCacheEntry.cs", "retrieved_chunk": " private long installFiles;\n private long installSize;\n private long cacheSizeOnDisk;\n public long InstallFiles => installFiles;\n public long InstallSize => installSize;\n public long CacheSize { get; set; }\n public long CacheSizeOnDisk\n {\n get => cacheSizeOnDisk;\n set { cacheSizeOnDisk = value; }", "score": 0.863153874874115 }, { "filename": "source/ViewModels/InstallProgressViewModel.cs", "retrieved_chunk": " }\n }\n }\n public RelayCommand PauseInstallCommand { get; private set; }\n public RelayCommand CancelInstallCommand { get; private set; }\n public string GameTitle => gameCache.Title;\n public string InstallSize => SmartUnits.Bytes(gameCache.InstallSize);\n //\n // Real-time GameCacheJob Statistics\n //", "score": 0.8577492237091064 } ]
csharp
GameCachePlatform Platform => entry.Platform;
using Microsoft.Extensions.DependencyInjection; namespace TraTech.WebSocketHub { public static class WebSocketHubServiceCollectionExtensions { /// <summary> /// Adds the WebSocketHub to the service collection with the specified key type. /// </summary> /// <typeparam name="TKey">The type of key associated with WebSocket connections.</typeparam> /// <param name="services">The IServiceCollection instance.</param> /// <returns>A WebSocketHubBuilder instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="services"/> is null.</exception> /// <remarks> /// This extension method adds the WebSocketHub to the service collection with the specified key type. It also registers the WebSocketHub as a singleton service and adds options to the service collection. /// </remarks> public static
WebSocketHubBuilder AddWebSocketHub<TKey>(this IServiceCollection services) where TKey : notnull {
if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddOptions(); services.AddSingleton<WebSocketHub<TKey>>(); return new WebSocketHubBuilder(services); } } }
src/WebSocketHub/Core/src/WebSocketHubServiceCollectionExtensions.cs
TRA-Tech-dotnet-websocket-9049854
[ { "filename": "src/WebSocketHub/Core/src/WebSocketHubBuilder.cs", "retrieved_chunk": " /// This property returns the collection of services registered in the application. It is used to add and configure services for the WebSocketHub.\n /// </remarks>\n public virtual IServiceCollection Services { get; }\n /// <summary>\n /// Adds a WebSocket request handler of type THandler for the specified message type to the WebSocketHubOptions.\n /// </summary>\n /// <typeparam name=\"THandler\">The type of WebSocket request handler to add.</typeparam>\n /// <param name=\"messageType\">The message type associated with the WebSocket request handler.</param>\n /// <returns>A WebSocketHubBuilder instance.</returns>\n /// <remarks>", "score": 0.925512433052063 }, { "filename": "src/WebSocketHub/Core/src/WebSocketHubBuilder.cs", "retrieved_chunk": " /// </summary>\n /// <param name=\"services\">The collection of services to use for the WebSocketHub.</param>\n /// <remarks>\n /// This constructor initializes a new instance of the WebSocketHubBuilder class with the specified collection of services. It is used to configure services for the WebSocketHub.\n /// </remarks>\n public WebSocketHubBuilder(IServiceCollection services) => Services = services;\n /// <summary>\n /// Gets the collection of services registered in the application.\n /// </summary>\n /// <remarks>", "score": 0.9122788906097412 }, { "filename": "src/WebSocketHub/Core/src/WebSocketHub.cs", "retrieved_chunk": " private static readonly Func<WebSocket, bool> _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n /// <summary>\n /// Initializes a new instance of the WebSocketHub class with the specified options.\n /// </summary>\n /// <param name=\"options\">The options to configure the WebSocketHub.</param>\n /// <exception cref=\"ArgumentNullException\">Thrown when <paramref name=\"options\"/> is null.</exception>\n /// <remarks>\n /// This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n /// </remarks>", "score": 0.9022588729858398 }, { "filename": "src/WebSocketHub/Core/src/WebSocketHubAppBuilderExtensions.cs", "retrieved_chunk": " /// <typeparam name=\"TKey\">The type of key associated with WebSocket connections.</typeparam>\n /// <param name=\"app\">The IApplicationBuilder instance.</param>\n /// <param name=\"acceptIf\">The function used to determine if a WebSocket request should be accepted.</param>\n /// <param name=\"keyGenerator\">The function used to generate a key for the WebSocket connection.</param>\n /// <returns>The IApplicationBuilder instance.</returns>\n /// <exception cref=\"ArgumentNullException\">Thrown when <paramref name=\"app\"/>, <paramref name=\"acceptIf\"/>, or <paramref name=\"keyGenerator\"/> is null.</exception>\n /// <remarks>\n /// This extension method adds the WebSocketHubMiddleware to the pipeline with the specified acceptIf and keyGenerator functions for handling WebSocket requests associated with keys of type TKey.\n /// </remarks>\n public static IApplicationBuilder UseWebSocketHub<TKey>(this IApplicationBuilder app, Func<HttpContext, bool> acceptIf, Func<HttpContext, TKey> keyGenerator)", "score": 0.8921273946762085 }, { "filename": "src/WebSocketHub/Core/src/WebSocketHubAppBuilderExtensions.cs", "retrieved_chunk": " /// <param name=\"app\">The IApplicationBuilder instance.</param>\n /// <param name=\"options\">The WebSocket options to configure the middleware.</param>\n /// <remarks>\n /// This method verifies that the WebSocketMiddleware is registered in the application services. If it is not registered, this method adds it to the pipeline with the specified WebSocket options, or with default options if no options are specified.\n /// </remarks>\n private static void VerifyServicesRegistered(IApplicationBuilder app, WebSocketOptions? options = null)\n {\n if (app.ApplicationServices.GetService(typeof(WebSocketMiddleware)) == null)\n {\n if (options is not null)", "score": 0.8916729688644409 } ]
csharp
WebSocketHubBuilder AddWebSocketHub<TKey>(this IServiceCollection services) where TKey : notnull {
#nullable enable using System.Collections.Generic; using UnityEngine; namespace Mochineko.FacialExpressions.Blink { /// <summary> /// A simple implementation of <see cref="IEyelidMorpher"/> for <see cref="Animator"/>. /// </summary> public sealed class AnimatorEyelidMorpher : IEyelidMorpher { private readonly Animator animator; private readonly IReadOnlyDictionary<
Eyelid, int> idMap;
/// <summary> /// Creates a new instance of <see cref="AnimatorEyelidMorpher"/>. /// </summary> /// <param name="animator">Target animator.</param> /// <param name="idMap">Map of eyelid to animator float key.</param> public AnimatorEyelidMorpher( Animator animator, IReadOnlyDictionary<Eyelid, int> idMap) { this.animator = animator; this.idMap = idMap; } public void MorphInto(EyelidSample sample) { if (idMap.TryGetValue(sample.eyelid, out var id)) { animator.SetFloat(id, sample.weight); } } public float GetWeightOf(Eyelid eyelid) { if (idMap.TryGetValue(eyelid, out var id)) { return animator.GetFloat(id); } else { return 0f; } } public void Reset() { foreach (var id in idMap.Values) { animator.SetFloat(id, 0f); } } } }
Assets/Mochineko/FacialExpressions/Blink/AnimatorEyelidMorpher.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "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.9172351360321045 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/CompositeEyelidMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// Composition of some <see cref=\"IEyelidMorpher\"/>s.\n /// </summary>\n public sealed class CompositeEyelidMorpher : IEyelidMorpher\n {\n private readonly IReadOnlyList<IEyelidMorpher> morphers;", "score": 0.903499960899353 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/IFramewiseEyelidAnimator.cs", "retrieved_chunk": "#nullable enable\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// Defines an animator to update eyelid animation per game engine frame.\n /// </summary>\n public interface IFramewiseEyelidAnimator\n {\n /// <summary>\n /// Updates animation.", "score": 0.8666008114814758 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/SequentialLipAnimator.cs", "retrieved_chunk": " /// </summary>\n public sealed class SequentialLipAnimator : ISequentialLipAnimator\n {\n private readonly ILipMorpher morpher;\n private CancellationTokenSource? animationCanceller;\n /// <summary>\n /// Creates a new instance of <see cref=\"SequentialLipAnimator\"/>.\n /// </summary>\n /// <param name=\"morpher\">Target morpher.</param>\n public SequentialLipAnimator(ILipMorpher morpher)", "score": 0.8646944761276245 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/IEyelidMorpher.cs", "retrieved_chunk": "#nullable enable\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// Defines a morpher of eyelid.\n /// </summary>\n public interface IEyelidMorpher\n {\n /// <summary>\n /// Morphs specified eyelid into specified weight. ", "score": 0.8645046949386597 } ]
csharp
Eyelid, int> idMap;
using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Net.Http; using System.Threading; namespace HttpMessageHandlerFactory.Implementations { /// <summary> /// 默认的Http消息处理者工厂 /// </summary> sealed class DefaultHttpMessageHandlerFactory : IHttpMessageHandlerFactory { private readonly
NameRegistration nameRegistration;
private readonly IServiceScopeFactory serviceScopeFactory; private readonly ExpiredHandlerEntryCleaner expiredHandlerEntryCleaner; /// <summary> /// 过期回调 /// </summary> private readonly TimerCallback expiryCallback; /// <summary> /// LazyOf(ActiveHandlerEntry)缓存 /// </summary> private readonly ConcurrentDictionary<NameProxy, Lazy<ActiveHandlerEntry>> activeHandlerEntries = new(); /// <summary> /// Http消息处理者工厂 /// </summary> /// <param name="nameRegistration"></param> /// <param name="serviceScopeFactory"></param> /// <param name="expiredHandlerEntryCleaner"></param> public DefaultHttpMessageHandlerFactory( NameRegistration nameRegistration, IServiceScopeFactory serviceScopeFactory, ExpiredHandlerEntryCleaner expiredHandlerEntryCleaner) { this.nameRegistration = nameRegistration; this.serviceScopeFactory = serviceScopeFactory; this.expiredHandlerEntryCleaner = expiredHandlerEntryCleaner; this.expiryCallback = this.ExpiryTimer_Tick; } /// <summary> /// 创建用于请求的HttpMessageHandler /// </summary> /// <param name="name">别名</param> /// <param name="proxyUri">支持携带UserInfo的代理地址</param> /// <returns></returns> public HttpMessageHandler CreateHandler(string name, Uri? proxyUri) { if (this.nameRegistration.Contains(name) == false) { throw new InvalidOperationException($"尚未登记别名为 {name} 的HttpMessageHandler"); } var nameProxy = new NameProxy(name, proxyUri); var ativeEntry = this.activeHandlerEntries.GetOrAdd(nameProxy, this.CreateActiveHandlerEntryLazy).Value; ativeEntry.StartExpiryTimer(this.expiryCallback); return ativeEntry.LifetimeHttpHandler; } /// <summary> /// 创建LazyOf(ActiveHandlerEntry) /// </summary> /// <param name="nameProxy"></param> /// <returns></returns> private Lazy<ActiveHandlerEntry> CreateActiveHandlerEntryLazy(NameProxy nameProxy) { return new Lazy<ActiveHandlerEntry>(() => this.CreateActiveHandlerEntry(nameProxy), LazyThreadSafetyMode.ExecutionAndPublication); } /// <summary> /// 创建ActiveHandlerEntry /// </summary> /// <param name="nameProxy"></param> /// <returns></returns> private ActiveHandlerEntry CreateActiveHandlerEntry(NameProxy nameProxy) { var serviceScope = this.serviceScopeFactory.CreateScope(); var serviceProvider = serviceScope.ServiceProvider; var builder = serviceProvider.GetRequiredService<HttpMessageHandlerBuilder>(); builder.NameProxy = nameProxy; var httpHandler = builder.Build(); var lifetime = builder.GetLifetime(); var lifeTimeHandler = new LifetimeHttpHandler(httpHandler); return new ActiveHandlerEntry(lifetime, nameProxy, serviceScope, lifeTimeHandler); } /// <summary> /// 过期timer回调 /// </summary> /// <param name="state"></param> private void ExpiryTimer_Tick(object? state) { var ativeEntry = (ActiveHandlerEntry)state!; // The timer callback should be the only one removing from the active collection. If we can't find // our entry in the collection, then this is a bug. var removed = this.activeHandlerEntries.TryRemove(ativeEntry.NameProxy, out Lazy<ActiveHandlerEntry>? found); Debug.Assert(removed, "Entry not found. We should always be able to remove the entry"); Debug.Assert(object.ReferenceEquals(ativeEntry, found!.Value), "Different entry found. The entry should not have been replaced"); // At this point the handler is no longer 'active' and will not be handed out to any new clients. // However we haven't dropped our strong reference to the handler, so we can't yet determine if // there are still any other outstanding references (we know there is at least one). // We use a different state object to track expired handlers. This allows any other thread that acquired // the 'active' entry to use it without safety problems. var expiredEntry = new ExpiredHandlerEntry(ativeEntry); this.expiredHandlerEntryCleaner.Add(expiredEntry); } } }
HttpMessageHandlerFactory/Implementations/DefaultHttpMessageHandlerFactory.cs
xljiulang-HttpMessageHandlerFactory-4b1d13b
[ { "filename": "HttpMessageHandlerFactory/Implementations/LifetimeHttpHandler.cs", "retrieved_chunk": "using System.Net.Http;\nnamespace HttpMessageHandlerFactory.Implementations\n{\n /// <summary>\n /// 表示自主管理生命周期的的HttpMessageHandler\n /// </summary>\n sealed class LifetimeHttpHandler : DelegatingHandler\n {\n /// <summary>\n /// 具有生命周期的HttpHandler", "score": 0.9298934936523438 }, { "filename": "HttpMessageHandlerFactory/IHttpMessageHandlerFactory.cs", "retrieved_chunk": "using System;\nusing System.Net.Http;\nnamespace HttpMessageHandlerFactory\n{\n /// <summary>\n /// Http消息处理者工厂\n /// </summary>\n public interface IHttpMessageHandlerFactory\n {\n /// <summary>", "score": 0.9190778732299805 }, { "filename": "HttpMessageHandlerFactory/Implementations/NameRegistration.cs", "retrieved_chunk": "using System.Collections.Generic;\nnamespace HttpMessageHandlerFactory.Implementations\n{\n /// <summary>\n /// 别登记\n /// </summary>\n sealed class NameRegistration : HashSet<string>\n {\n }\n}", "score": 0.9064761996269226 }, { "filename": "HttpMessageHandlerFactory/HttpMessageHandlerOptions.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Net.Http;\nnamespace HttpMessageHandlerFactory\n{\n /// <summary>\n /// HttpMessageHandler选项\n /// </summary>\n public class HttpMessageHandlerOptions\n {", "score": 0.8822676539421082 }, { "filename": "HttpMessageHandlerFactory/DependencyInjection/IHttpMessageHandlerBuilder.cs", "retrieved_chunk": "namespace Microsoft.Extensions.DependencyInjection\n{\n /// <summary>\n /// Http消息处理者创建者\n /// </summary>\n public interface IHttpMessageHandlerBuilder\n {\n /// <summary>\n /// 选项名\n /// </summary>", "score": 0.8819344639778137 } ]
csharp
NameRegistration nameRegistration;
using System; using LogDashboard.LogDashboardBuilder; using LogDashboard.Handle; using LogDashboard.Route; using Microsoft.Extensions.DependencyInjection; using LogDashboard.Views.Dashboard; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; using LogDashboard; namespace LogDashboard { public static class LogDashboardServiceCollectionExtensions { public static ILogDashboardBuilder AddLogDashboard(this IServiceCollection services,
LogdashboardAccountAuthorizeFilter filter, Action<LogDashboardOptions> func = null) {
LogDashboardRoutes.Routes.AddRoute(new LogDashboardRoute(LogDashboardAuthorizationConsts.LoginRoute, typeof(Login))); services.AddSingleton(filter); services.AddSingleton<IStartupFilter, LogDashboardLoginStartupFilter>(); services.AddTransient<AuthorizationHandle>(); services.AddTransient<Login>(); var options = new LogDashboardOptions(); func?.Invoke(options); options.AddAuthorizationFilter(filter); Action<LogDashboardOptions> config = x => { func?.Invoke(x); x.AddAuthorizationFilter(filter); }; return services.AddLogDashboard(config); } } } internal class LogDashboardLoginStartupFilter : IStartupFilter { public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) { return app => { var options = app.ApplicationServices.GetRequiredService<LogDashboardOptions>(); app.Map($"{options.PathMatch}{LogDashboardAuthorizationConsts.LoginRoute}", app => { app.UseMiddleware<LogDashboardAuthorizationMiddleware>(); }); next(app); }; } }
src/LogDashboard.Authorization/LogDashboardServiceCollectionExtensions.cs
Bryan-Cyf-LogDashboard.Authorization-14d4540
[ { "filename": "src/LogDashboard.Authorization/Handle/AuthorizationHandle.cs", "retrieved_chunk": "using LogDashboard.Models;\nusing LogDashboard.Route;\nusing System;\nusing System.Threading.Tasks;\nnamespace LogDashboard.Handle\n{\n public class AuthorizationHandle : LogDashboardHandleBase\n {\n private readonly LogdashboardAccountAuthorizeFilter _filter;\n public AuthorizationHandle(", "score": 0.8590409755706787 }, { "filename": "src/LogDashboard.Authorization/LogDashboardAuthorizationMiddleware.cs", "retrieved_chunk": "using LogDashboard.Authorization;\nusing LogDashboard.EmbeddedFiles;\nusing LogDashboard.Handle;\nusing LogDashboard.Repository;\nusing LogDashboard.Route;\nusing Microsoft.Extensions.DependencyInjection;\nnamespace LogDashboard\n{\n public class LogDashboardAuthorizationMiddleware\n {", "score": 0.8341600894927979 }, { "filename": "src/LogDashboard.Authorization/Authorization/LogdashboardAccountAuthorizeFilter.cs", "retrieved_chunk": " }\n public LogdashboardAccountAuthorizeFilter(string userName, string password, Action<LogDashboardCookieOptions> cookieConfig)\n {\n UserName = userName;\n Password = password;\n CookieOptions = new LogDashboardCookieOptions();\n cookieConfig.Invoke(CookieOptions);\n }\n public bool Authorization(LogDashboardContext context)\n {", "score": 0.8039379715919495 }, { "filename": "src/LogDashboard.Authorization/LogDashboardAuthorizationConsts.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace LogDashboard\n{\n public class LogDashboardAuthorizationConsts\n {\n public const string LoginRoute = \"/Authorization/Login\";\n }\n}", "score": 0.8021930456161499 }, { "filename": "src/LogDashboard.Authorization/LogDashboardAuthorizationMiddleware.cs", "retrieved_chunk": " private readonly RequestDelegate _next;\n public LogDashboardAuthorizationMiddleware(RequestDelegate next)\n {\n _next = next;\n }\n public async Task InvokeAsync(HttpContext httpContext)\n {\n using var scope = httpContext.RequestServices.CreateScope();\n var opts = scope.ServiceProvider.GetService<LogDashboardOptions>();\n var requestUrl = httpContext.Request.Path.Value;", "score": 0.7884601950645447 } ]
csharp
LogdashboardAccountAuthorizeFilter filter, Action<LogDashboardOptions> func = null) {
using JWLSLMerge.Data.Attributes; namespace JWLSLMerge.Data.Models { public class Location { [Ignore] public int LocationId { get; set; } public int? BookNumber { get; set; } public int? ChapterNumber { get; set; } public int? DocumentId { get; set; } public int? Track { get; set; } public int IssueTagNumber { get; set; } public string? KeySymbol { get; set; } public int? MepsLanguage { get; set; } public int Type { get; set; } public string? Title { get; set; } [
Ignore] public int NewLocationId {
get; set; } } }
JWLSLMerge.Data/Models/Location.cs
pliniobrunelli-JWLSLMerge-7fe66dc
[ { "filename": "JWLSLMerge.Data/Models/Note.cs", "retrieved_chunk": " public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}", "score": 0.9560940265655518 }, { "filename": "JWLSLMerge.Data/Models/Bookmark.cs", "retrieved_chunk": " public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}", "score": 0.9245538711547852 }, { "filename": "JWLSLMerge.Data/Models/Manifest.cs", "retrieved_chunk": " public class UserDataBackup\n {\n public string LastModifiedDate { get; set; } = null!;\n public string DeviceName { get; set; } = null!;\n public string DatabaseName { get; set; } = null!;\n public string Hash { get; set; } = null!;\n public int SchemaVersion { get; set; }\n }\n}", "score": 0.9205065965652466 }, { "filename": "JWLSLMerge.Data/Models/Manifest.cs", "retrieved_chunk": "namespace JWLSLMerge.Data.Models\n{\n public class Manifest\n {\n public string Name { get; set; } = null!;\n public string CreationDate { get; set; } = null!;\n public int Version { get; set; } = 1;\n public int Type { get; set; } = 0;\n public UserDataBackup UserDataBackup { get; set; } = null!;\n }", "score": 0.9097421169281006 }, { "filename": "JWLSLMerge.Data/Models/PlayListItem.cs", "retrieved_chunk": " public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}", "score": 0.9031020998954773 } ]
csharp
Ignore] public int NewLocationId {
using Features.Feature; using HelperTool; using Junkctrl.ITreeNode; using Junkctrl.Theming; using Junkctrl.Views; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows.Forms; namespace Junkctrl { public partial class MainForm : Form { private static readonly ErrorHelper logger = ErrorHelper.Instance; public static List<string> recycleList = new List<string>(); public Control INavPage; private
PluginBase pluginBase;
private int progression = 0; private int progressionIncrease = 0; public MainForm() { InitializeComponent(); pluginBase = new PluginBase(lnkStatus, progressBar, checkResults); } private void MainForm_Shown(object sender, EventArgs e) { _Assembly.Text = "Version " + Program.GetCurrentVersionTostring(); this.AddJunkScans(); this.SetStyle(); } private void SetStyle() { btnKebapMenu.Text = "\u22ee"; btnBack.Text = "\uE72B"; pnlForm.BackColor = pnlMain.BackColor = tvwFeatures.BackColor = checkResults.BackColor = pnlCapabilities.BackColor = Color.FromArgb(239, 239, 247); pbBackground.ImageLocation = "https://github.com/builtbybel/BloatyNosy/blob/main/assets/BackgroundImageA.png?raw=true"; INavPage = pnlForm.Controls[0]; // Set default NavPage logger.SetTarget(checkResults); // Add results to checkedListBox } public void SetView(Control View) { var control = View as Control; control.Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom); control.Dock = DockStyle.Fill; INavPage.Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom); INavPage.Dock = DockStyle.Fill; pnlForm.Controls.Clear(); pnlForm.Controls.Add(View); } public void AddJunkScans() { tvwFeatures.Nodes.Clear(); tvwFeatures.BeginUpdate(); // Default auto scans TreeNode root = new TreeNode("Windows 11 " + OsHelper.GetVersion(), new TreeNode[] { new FeatureNode(new Features.Feature.Apps.AutoJunk()), new FeatureNode(new Features.Feature.Apps.PrivateJunk()), }) { Checked = true, }; // Skip if the "PluginsDir" directory does not exist if (!Directory.Exists(HelperTool.Utils.Data.PluginsDir)) { tvwFeatures.Nodes.Add(root); AddCopilotNode(root); ExpandTreeViewNodes(); tvwFeatures.Nodes[0].NodeFont = new Font(tvwFeatures.Font, FontStyle.Bold); tvwFeatures.EndUpdate(); return; } // If the "PluginsDir" directory exists, continue with the plugin functionality if (Directory.GetFiles(HelperTool.Utils.Data.PluginsDir, "*.txt").Length > 0) { TreeNode pluginsNode = CreatePluginsNode(); root.Nodes.Add(pluginsNode); } tvwFeatures.Nodes.Add(root); AddCopilotNode(root); ExpandTreeViewNodes(); tvwFeatures.Nodes[0].NodeFont = new Font(tvwFeatures.Font, FontStyle.Bold); tvwFeatures.EndUpdate(); } // Use Copilot for skipping auto scans private void AddCopilotNode(TreeNode root) { TreeNode copilotNode = new TreeNode("Skip and use Copilot "); root.Nodes.Add(copilotNode); TreeNodeTheming.RemoveCheckmarks(tvwFeatures, copilotNode); } // Add the Plugins node (if available) private TreeNode CreatePluginsNode() { TreeNode pluginsNode = new TreeNode("Plugins"); string pluginDirectory = HelperTool.Utils.Data.PluginsDir; foreach (string textFile in Directory.GetFiles(pluginDirectory, "*.txt")) { pluginsNode.Nodes.Add(new TreeNode(Path.GetFileNameWithoutExtension(textFile))); } return pluginsNode; } private void ExpandTreeViewNodes() { foreach (TreeNode tn in tvwFeatures.Nodes) { tn.ExpandAll(); } } private void tvwFeatures_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { // Check if the clicked TreeNode is a FeatureNode if (e.Node is FeatureNode clickedFeatureNode) { // Get the FeatureNode's FeatureBase object FeatureBase feature = clickedFeatureNode.Feature; // Get the information from the Info() method string info = feature.Info(); lnkHeader.Text = info; } else if (e.Node.Parent != null && e.Node.Parent.Text == "Plugins") { // Get the plugin name string pluginName = e.Node.Text; // Get the plugin info using the GetPluginInfo method string info = pluginBase.GetPluginInfo(pluginName); // Display the info lnkHeader.Text = info; } else { lnkHeader.Text = "Idle."; } switch (e.Node.Text) { case "Skip and use Copilot ": this.SetView(new CopilotPageView()); // Set Copilot view break; default: break; } } private void tvwFeatures_AfterCheck(object sender, TreeViewEventArgs e) { tvwFeatures.BeginUpdate(); foreach (System.Windows.Forms.TreeNode child in e.Node.Nodes) { child.Checked = e.Node.Checked; } // Remove checkmarks from copilot child node TreeNodeTheming.RemoveCheckmarks(tvwFeatures, tvwFeatures.Nodes[0].Nodes[3]); tvwFeatures.EndUpdate(); } private async void btnSearch_Click(object sender, EventArgs e) { Reset(); btnBack.PerformClick(); pnlCapabilities.SendToBack(); checkResults.Items.Clear(); logger.GetLogList().Clear(); btnSearch.Enabled = false; int performFeaturesCount = 0; List<FeatureNode> selectedFeatures = CollectFeatureNodes(); lnkStatus.Text = $"{selectedFeatures.Count} auto scans are running..."; foreach (FeatureNode node in selectedFeatures) { var feature = node.Feature; ConfiguredTaskAwaitable<bool> analyzeTask = Task<bool>.Factory.StartNew(() => feature.CheckFeature()).ConfigureAwait(true); bool shouldPerform = await analyzeTask; lnkStatus.Text = "Check " + feature.ID(); if (shouldPerform) { performFeaturesCount += 1; // node.ForeColor = Color.Crimson; } else { node.Checked = false; // node.ForeColor = Color.Gray; } } // Pass corresponding Plugin instances foreach (TreeNode node in tvwFeatures.Nodes) { await pluginBase.CheckNodeForSearch(node); } tvwFeatures.SelectedNode = tvwFeatures.Nodes[0]; DoProgress(100); btnSearch.Enabled = true; lnkStatus.Text = "Scans completed. Click to switch view."; btnBack.Enabled = true; int itemsInRecycleList = checkResults.Items.Count; lblItemsInRecycleList.Text = itemsInRecycleList.ToString() + " junk apps found."; } private void SelectFeatureNodes(TreeNodeCollection trNodeCollection, bool isCheck) { foreach (TreeNode trNode in trNodeCollection) { trNode.Checked = isCheck; if (trNode.Nodes.Count > 0) SelectFeatureNodes(trNode.Nodes, isCheck); } } private List<FeatureNode> CollectFeatureNodes() { List<FeatureNode> selectedFeatures = new List<FeatureNode>(); foreach (TreeNode treeNode in tvwFeatures.Nodes.All()) { if (treeNode.Checked && treeNode.GetType() == typeof(FeatureNode)) { selectedFeatures.Add((FeatureNode)treeNode); } } progressionIncrease = (int)Math.Floor(100.0f / selectedFeatures.Count); return selectedFeatures; } private void btnBin_Click(object sender, EventArgs e) { Reset(); recycleList.Clear(); for (int i = 0; i < checkResults.Items.Count; i++) { if (checkResults.GetItemChecked(i)) { string item = checkResults.Items[i].ToString(); if (item.Contains("[!]") || (item.Contains("(We recommend uninstalling this app)"))) { // Skip adding the item to the recycleList continue; } recycleList.Add(item); IncrementProgress(); } } DoProgress(100); if (recycleList.Count == 0) { MessageBox.Show("You haven't done a search yet or added anything to the bin.\nAccordingly the recycle list is empty. Please select at least one item."); } else { this.SetView(new CopilotPageView()); } } private void Reset() { lnkStatus.Visible = true; progression = 0; progressionIncrease = 0; progressBar.Value = 0; progressBar.Visible = true; checkResults.Visible = true; checkResults.Text = ""; } private void DoProgress(int value) { progression = value; progressBar.Value = progression; } private void IncrementProgress() { progression += progressionIncrease; progressBar.Value = progression; } public void ToggleControlVisibility() { pnlCapabilities.Visible = !pnlCapabilities.Visible; if (pnlCapabilities.Visible) { pnlCapabilities.BringToFront(); checkResults.Visible = true; } else { checkResults.Visible = true; } } private void btnBack_Click(object sender, EventArgs e) { pnlForm.Controls.Add(INavPage); ToggleControlVisibility(); } public void ClearPanel2Controls() => pnlForm.Controls.Clear(); public void AddINavPageToPanel2() => pnlForm.Controls.Add(INavPage); private void lnkStatus_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => btnBack.PerformClick(); private void lnkHeader_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => MessageBox.Show(lnkHeader.Text, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); private void btnKebapMenu_Click(object sender, EventArgs e) => this.contextKebapMenu.Show(Cursor.Position.X, Cursor.Position.Y); private void lnkAppMediaTwitter_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => Process.Start(HelperTool.Utils.Uri.URL_TWITTER); private void _Assembly_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => HelperTool.Utils.CheckForUpdates(); private void lnkAppMediaDonate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => Process.Start(HelperTool.Utils.Uri.URL_DONATE); private void lnkAppMediaGitHub_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => Process.Start(HelperTool.Utils.Uri.URL_GITREPO); private void lnkHeader_Click(object sender, EventArgs e) => MessageBox.Show(lnkHeader.Text, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); private void menuPluginsDir_Click(object sender, EventArgs e) { // Open the plugins folder string pluginsFolder = Path.GetDirectoryName(HelperTool.Utils.Data.PluginsDir); Process.Start(pluginsFolder); } private void DeleteSelectedPlugin(TreeNode selectedNode) { string selectedPlugin = selectedNode.Text; string appFolderPath = HelperTool.Utils.Data.PluginsDir; string pluginFile = Path.Combine(appFolderPath, $"{selectedPlugin}.txt"); if (File.Exists(pluginFile)) { // Delete the plugin file File.Delete(pluginFile); selectedNode.Remove(); } } private void menuPluginDelete_Click(object sender, EventArgs e) { if (tvwFeatures.SelectedNode != null) { TreeNode selectedNode = tvwFeatures.SelectedNode; DialogResult result = MessageBox.Show("Are you sure you want to delete the selected plugin?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { DeleteSelectedPlugin(selectedNode); } } } private void menuPluginCreate_Click(object sender, EventArgs e) { // Get the path to the plugins folder string appFolderPath = HelperTool.Utils.Data.PluginsDir; // Construct the path to the new plugin file string pluginFile = Path.Combine(appFolderPath, $"New.txt"); // Create an empty plugin file File.Create(pluginFile).Close(); // Open the plugin file using Notepad Process.Start("notepad.exe", pluginFile); // Refresh tvwFeatures.Nodes.Clear(); AddJunkScans(); } private void menuPluginEdit_Click(object sender, EventArgs e) { // Get the selected node from the TreeView TreeNode selectedNode = tvwFeatures.SelectedNode; // Ensure a node is selected if (selectedNode != null) { // Get the path to the plugins folder string appFolderPath = HelperTool.Utils.Data.PluginsDir; // Construct the path to the selected plugin file string selectedPlugin = selectedNode.Text; string pluginFile = Path.Combine(appFolderPath, $"{selectedPlugin}.txt"); if (File.Exists(pluginFile)) { Process.Start("notepad.exe", pluginFile); } else { MessageBox.Show("Selected plugin file does not exist.", "Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("No plugin selected.", "Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void lnkAddTopTenToBin_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { var apps = JunkTopTen.GetList(); foreach (string app in apps) { recycleList.Add(app); } this.SetView(new CopilotPageView()); } } }
Junkctrl/MainForm.cs
builtbybel-JunkCtrl-5be1955
[ { "filename": "Junkctrl/PluginBase.cs", "retrieved_chunk": "using System.Windows.Forms;\nnamespace Junkctrl\n{\n internal class PluginBase\n {\n public static readonly PowerShell powerShell = PowerShell.Create();\n private LinkLabel pluginStatus;\n private ProgressBar pluginProgress;\n private CheckedListBox pluginResults;\n // Initializing the variables within the class", "score": 0.9201943874359131 }, { "filename": "Junkctrl/Helpers/ErrorHelper.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Windows.Forms;\nnamespace Junkctrl\n{\n internal class ErrorHelper\n {\n private static CheckedListBox target = null;\n private static ErrorHelper instance; // Single instance of ErrorHelper\n private List<string> logList = new List<string>(); // Add a List<string> to store log messages", "score": 0.9038969278335571 }, { "filename": "Junkctrl/Features/AutoJunk.cs", "retrieved_chunk": "using Junkctrl;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Text.RegularExpressions;\nnamespace Features.Feature.Apps\n{\n internal class AutoJunk : FeatureBase\n {\n private static readonly ErrorHelper logger = ErrorHelper.Instance;\n private readonly PowerShell powerShell = PowerShell.Create();", "score": 0.8518122434616089 }, { "filename": "Junkctrl/Features/IETopJunk.cs", "retrieved_chunk": "using System.Collections.Generic;\nnamespace Junkctrl\n{\n public static class JunkTopTen\n {\n // Our Windows 11 Hall Of Shame\n public static IEnumerable<string> GetList()\n {\n var apps = new List<string>\n {", "score": 0.8504085540771484 }, { "filename": "Junkctrl/Program.cs", "retrieved_chunk": "using System;\nusing System.Windows.Forms;\nnamespace Junkctrl\n{\n internal static class Program\n {\n /// <summary>\n /// Get app version\n /// </summary>\n internal static string GetCurrentVersionTostring() => new Version(Application.ProductVersion).ToString(3);", "score": 0.8498870134353638 } ]
csharp
PluginBase pluginBase;
// ReSharper disable once RedundantUsingDirective using System.Collections.Generic; // can't alias namespace CsvParsing { public class CsvReader { private readonly
TextReaderWhichIgnoresReturnCarrier _reader;
public CsvReader(System.IO.TextReader reader) { _reader = new TextReaderWhichIgnoresReturnCarrier(reader); } private (string?, string?) ReadQuotedCell() { // Pre-condition if (_reader.Peek() != '"') { throw new System.InvalidOperationException( $"Expected to peek a double-quote, but got: {_reader.Peek()}" ); } _reader.Read(); int? current = _reader.Peek(); _reader.Read(); int? next = _reader.Peek(); var builder = new System.Text.StringBuilder(); while (true) { if (current == -1) { return ( null, "Expected to find the closing double-quote ('\"'), " + "but got an end-of-stream" ); } if (current == '"' && next == '"') { builder.Append('"'); _reader.Read(); current = _reader.Peek(); _reader.Read(); next = _reader.Peek(); } else if (current == '"' && next != '"') { return (builder.ToString(), null); } else { builder.Append((char)current); _reader.Read(); current = next; next = _reader.Peek(); } } } private string ReadUnquotedCell() { // Pre-condition if (_reader.Peek() is -1 or ',' or '\n') { throw new System.InvalidOperationException( $"Expected the cell to start with a valid character, but got: {_reader.Peek()}; " + "the peek has not been handled correctly before." ); } var builder = new System.Text.StringBuilder(); int? lookahead = _reader.Peek(); while (lookahead is not (-1 or ',' or '\n')) { builder.Append((char)lookahead); _reader.Read(); lookahead = _reader.Peek(); } return builder.ToString(); } private (string?, string?) ReadCell() { var lookahead = _reader.Peek(); if (lookahead is -1 or ',' or '\n') { return ("", null); } if (lookahead == '"') { return ReadQuotedCell(); } return (ReadUnquotedCell(), null); } public (List<string>?, string?) ReadRow(int expectedCells) { if (_reader.Peek() == -1) { return (null, null); } if (_reader.Peek() == '\n') { _reader.Read(); return (new List<string>(), null); } var row = new List<string>(expectedCells); while (true) { var (cell, error) = ReadCell(); if (error != null) { return (null, error); } row.Add( cell ?? throw new System.InvalidOperationException( "Unexpected cell null" ) ); var lookahead = _reader.Peek(); if (lookahead == -1) { return (row, null); } if (lookahead == '\n') { _reader.Read(); return (row, null); } if (lookahead == ',') { _reader.Read(); continue; } return ( null, "Expected either a new line, a comma or an end-of-stream, " + $"but got: {(char)lookahead} (character code: {lookahead})" ); } } } }
src/CsvParsing/CsvReader.cs
aas-core-works-aas-core3.0-cli-swiss-knife-eb9a3ef
[ { "filename": "src/CsvParsing/CsvDictionaryReader.cs", "retrieved_chunk": "// ReSharper disable once RedundantUsingDirective\nusing System.Collections.Generic; // can't alias\nnamespace CsvParsing\n{\n public class CsvDictionaryReader\n {\n private readonly CsvReader _reader;\n private List<string>? _header;\n private Dictionary<string, string>? _dictionary;\n public CsvDictionaryReader(CsvReader reader)", "score": 0.8839467763900757 }, { "filename": "src/CsvParsing.Tests/TestCsvDictionaryReader.cs", "retrieved_chunk": "using System.Collections.Generic; // can't alias\nusing NUnit.Framework; // can't alias\nnamespace CsvParsing.Tests\n{\n public class TestCsvDictionaryReader\n {\n private static (List<IReadOnlyDictionary<string, string>>?, string?) ReadTable(\n CsvDictionaryReader csv\n )\n {", "score": 0.846355140209198 }, { "filename": "src/CsvParsing/TextReaderWhichIgnoresReturnCarrier.cs", "retrieved_chunk": "namespace CsvParsing\n{\n internal class TextReaderWhichIgnoresReturnCarrier : System.IO.TextReader\n {\n private readonly System.IO.TextReader _reader;\n private int _lookahead;\n public TextReaderWhichIgnoresReturnCarrier(System.IO.TextReader reader)\n {\n _reader = reader;\n _lookahead = '\\r';", "score": 0.835899829864502 }, { "filename": "src/CsvParsing.Tests/TestCsvReader.cs", "retrieved_chunk": "using System.Collections.Generic; // can't alias\nusing NUnit.Framework; // can't alias\nnamespace CsvParsing.Tests\n{\n public class TestCsvReader\n {\n private static (List<List<string>>?, string?) ReadTable(CsvReader csv)\n {\n var table = new List<List<string>>();\n while (true)", "score": 0.8244677186012268 }, { "filename": "src/EnvironmentFromCsvConceptDescriptions/ParsingConceptDescriptions.cs", "retrieved_chunk": "using Aas = AasCore.Aas3_0; // renamed\nusing System.Collections.Generic; // can't alias\nnamespace EnvironmentFromCsvConceptDescriptions\n{\n internal static class ParsingConceptDescriptions\n {\n internal static class ColumnNames\n {\n internal const string Id = \"ID\";\n internal const string PreferredName = \"Preferred Name\";", "score": 0.8193769454956055 } ]
csharp
TextReaderWhichIgnoresReturnCarrier _reader;
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/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8507252931594849 }, { "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.8486781120300293 }, { "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.8437727689743042 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " void PrepareAltFire()\n {\n }\n void AltFire()\n {\n }\n }\n class V2SecondUpdate\n {\n static bool Prefix(V2 __instance, ref int ___currentWeapon, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb, ref float ___shootCooldown,", "score": 0.8433130979537964 }, { "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.8389918804168701 } ]
csharp
Grenade __instance, ref float __3, out StateInfo __state, bool __1, bool __2) {
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace WAGIapp.AI.AICommands { internal class NoActionCommand : Command { public override string
Name => "no-action";
public override string Description => "does nothing"; public override string Format => "no-action"; public override async Task<string> Execute(Master caller, string[] args) { return "command did nothing"; } } }
WAGIapp/AI/AICommands/NoActionCommand.cs
Woltvint-WAGI-d808927
[ { "filename": "WAGIapp/AI/AICommands/RemoveNoteCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class RemoveNoteCommand : Command\n {\n public override string Name => \"remove-note\";", "score": 0.9161257147789001 }, { "filename": "WAGIapp/AI/AICommands/AddNoteCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class AddNoteCommand : Command\n {\n public override string Name => \"add-note\"; ", "score": 0.9138058423995972 }, { "filename": "WAGIapp/AI/AICommands/SearchWebCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class SearchWebCommand : Command\n {\n public override string Name => \"search-web\";", "score": 0.91229248046875 }, { "filename": "WAGIapp/AI/AICommands/GoalReachedCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class GoalReachedCommand : Command\n {\n public override string Name => \"goal-reached\";", "score": 0.9034982919692993 }, { "filename": "WAGIapp/AI/Utils.cs", "retrieved_chunk": "using System.Text.Json;\nusing System.Text.RegularExpressions;\nusing System.Web;\nusing System;\nusing Microsoft.Extensions.Options;\nusing Microsoft.AspNetCore.Components.WebAssembly.Http;\nnamespace WAGIapp.AI\n{\n internal class Utils\n {", "score": 0.8368839025497437 } ]
csharp
Name => "no-action";
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/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.8343393802642822 }, { "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.8324440717697144 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8204741477966309 }, { "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.8159679174423218 }, { "filename": "Ultrapain/Patches/V2Common.cs", "retrieved_chunk": " // Reverse the direction vector to face away from the target\n direction = -direction;\n return direction;\n }\n }\n class V2CommonExplosion\n {\n static void Postfix(Explosion __instance)\n {\n if (__instance.sourceWeapon == null)", "score": 0.8131230473518372 } ]
csharp
RevolverBeam orbitalBeam = null;
#nullable enable using System.Collections.Generic; using UnityEngine; namespace Mochineko.FacialExpressions.LipSync { /// <summary> /// An implementation of <see cref="ILipMorpher"/> to morph lip by <see cref="SkinnedMeshRenderer"/>. /// </summary> public sealed class SkinnedMeshLipMorpher : ILipMorpher { private readonly SkinnedMeshRenderer skinnedMeshRenderer; private readonly IReadOnlyDictionary<
Viseme, int> indexMap;
/// <summary> /// Creates a new instance of <see cref="SkinnedMeshLipMorpher"/>. /// </summary> /// <param name="skinnedMeshRenderer">Target renderer.</param> /// <param name="indexMap">Map of viseme to blend shape index.</param> public SkinnedMeshLipMorpher( SkinnedMeshRenderer skinnedMeshRenderer, IReadOnlyDictionary<Viseme, int> indexMap) { this.skinnedMeshRenderer = skinnedMeshRenderer; this.indexMap = indexMap; } public void MorphInto(LipSample sample) { if (indexMap.TryGetValue(sample.viseme, out var index)) { skinnedMeshRenderer.SetBlendShapeWeight(index, sample.weight * 100f); } else if (sample.viseme is Viseme.sil) { Reset(); } } public float GetWeightOf(Viseme viseme) { if (indexMap.TryGetValue(viseme, out var index)) { return skinnedMeshRenderer.GetBlendShapeWeight(index) / 100f; } else { return 0f; } } public void Reset() { foreach (var pair in indexMap) { skinnedMeshRenderer.SetBlendShapeWeight(pair.Value, 0f); } } } }
Assets/Mochineko/FacialExpressions/LipSync/SkinnedMeshLipMorpher.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "filename": "Assets/Mochineko/FacialExpressions/Emotion/SkinnedMeshEmotionMorpher.cs", "retrieved_chunk": " public sealed class SkinnedMeshEmotionMorpher<TEmotion>\n : IEmotionMorpher<TEmotion>\n where TEmotion : Enum\n {\n private readonly SkinnedMeshRenderer skinnedMeshRenderer;\n private readonly IReadOnlyDictionary<TEmotion, int> indexMap;\n /// <summary>\n /// Creates a new instance of <see cref=\"SkinnedMeshEmotionMorpher{TEmotion}\"/>.\n /// </summary>\n /// <param name=\"skinnedMeshRenderer\">Target renderer.</param>", "score": 0.8877324461936951 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/VolumeBasedLipAnimator.cs", "retrieved_chunk": "#nullable enable\nusing UnityEngine;\nnamespace Mochineko.FacialExpressions.LipSync\n{\n /// <summary>\n /// An implementation of <see cref=\"IFramewiseLipAnimator\"/> to animate lip by audio volume.\n /// </summary>\n public sealed class VolumeBasedLipAnimator : IFramewiseLipAnimator\n {\n private readonly ILipMorpher morpher;", "score": 0.8774017095565796 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/SkinnedMeshEyelidMorpher.cs", "retrieved_chunk": " private readonly SkinnedMeshRenderer skinnedMeshRenderer;\n private readonly IReadOnlyDictionary<Eyelid, int> indexMap;\n private readonly bool separateBoth;\n /// <summary>\n /// Creates a new instance of <see cref=\"SkinnedMeshEyelidMorpher\"/>.\n /// </summary>\n /// <param name=\"skinnedMeshRenderer\">Target renderer.</param>\n /// <param name=\"indexMap\">Map of eyelid and blend shape index.</param>\n /// <param name=\"separateBoth\">Whether separate both eyelids blend shape.</param>\n public SkinnedMeshEyelidMorpher(", "score": 0.8697208166122437 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/CompositeLipMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nnamespace Mochineko.FacialExpressions.LipSync\n{\n /// <summary>\n /// Composition of some <see cref=\"Mochineko.FacialExpressions.LipSync.ILipMorpher\"/>s.\n /// </summary>\n public sealed class CompositeLipMorpher : ILipMorpher\n {\n private readonly IReadOnlyList<ILipMorpher> morphers;", "score": 0.8653134107589722 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/SequentialLipAnimator.cs", "retrieved_chunk": " /// </summary>\n public sealed class SequentialLipAnimator : ISequentialLipAnimator\n {\n private readonly ILipMorpher morpher;\n private CancellationTokenSource? animationCanceller;\n /// <summary>\n /// Creates a new instance of <see cref=\"SequentialLipAnimator\"/>.\n /// </summary>\n /// <param name=\"morpher\">Target morpher.</param>\n public SequentialLipAnimator(ILipMorpher morpher)", "score": 0.8646477460861206 } ]
csharp
Viseme, int> indexMap;
using Microsoft.Extensions.Options; using System.Collections.Concurrent; namespace CloudDistributedLock { public interface ICloudDistributedLockProviderFactory { ICloudDistributedLockProvider GetLockProvider(); ICloudDistributedLockProvider GetLockProvider(string name); } public class CloudDistributedLockProviderFactory : ICloudDistributedLockProviderFactory { internal const string DefaultName = "__DEFAULT"; private readonly ConcurrentDictionary<string, ICloudDistributedLockProvider> clients = new(); public CloudDistributedLockProviderFactory(IOptionsMonitor<
CloudDistributedLockProviderOptions> optionsMonitor) {
this.OptionsMonitor = optionsMonitor; } protected IOptionsMonitor<CloudDistributedLockProviderOptions> OptionsMonitor { get; } public ICloudDistributedLockProvider GetLockProvider(string name) { return clients.GetOrAdd(name, n => CreateClient(n)); } public ICloudDistributedLockProvider GetLockProvider() { return GetLockProvider(DefaultName); } protected ICloudDistributedLockProvider CreateClient(string name) { var options = OptionsMonitor.Get(name); ArgumentNullException.ThrowIfNull(options.ProviderName); ArgumentNullException.ThrowIfNull(options.CosmosClient); ArgumentNullException.ThrowIfNull(options.DatabaseName); ArgumentNullException.ThrowIfNull(options.ContainerName); return new CloudDistributedLockProvider(options); } } }
CloudDistributedLock/CloudDistributedLockProviderFactory.cs
briandunnington-CloudDistributedLock-04f72e6
[ { "filename": "CloudDistributedLock/CloudDistributedLockProvider.cs", "retrieved_chunk": "namespace CloudDistributedLock\n{\n public interface ICloudDistributedLockProvider\n {\n Task<CloudDistributedLock> TryAquireLockAsync(string name);\n Task<CloudDistributedLock> AcquireLockAsync(string name, TimeSpan? timeout = default);\n }\n public class CloudDistributedLockProvider : ICloudDistributedLockProvider\n {\n private readonly CloudDistributedLockProviderOptions options;", "score": 0.927689790725708 }, { "filename": "ExampleApp/Functions.cs", "retrieved_chunk": " private readonly ICloudDistributedLockProviderFactory lockProviderFactory;\n public Functions(ICloudDistributedLockProviderFactory lockProviderFactory)\n {\n this.lockProviderFactory = lockProviderFactory;\n }\n [Function(\"TryLock\")]\n public async Task<HttpResponseData> TryLock([HttpTrigger(AuthorizationLevel.Anonymous, \"get\")] HttpRequestData req)\n {\n var response = req.CreateResponse();\n var lockProvider = lockProviderFactory.GetLockProvider();", "score": 0.867782473564148 }, { "filename": "CloudDistributedLock/CosmosLockClient.cs", "retrieved_chunk": "using Microsoft.Azure.Cosmos;\nusing System.Net;\nnamespace CloudDistributedLock\n{\n public class CosmosLockClient\n {\n private readonly CloudDistributedLockProviderOptions options;\n private readonly Container container;\n public CosmosLockClient(CloudDistributedLockProviderOptions options)\n {", "score": 0.8543040752410889 }, { "filename": "CloudDistributedLock/ServiceCollectionExtensions.cs", "retrieved_chunk": " public static IServiceCollection AddCloudDistributedLock(this IServiceCollection services, string name, CosmosClient cosmosClient, string databaseName, int ttl, Action<CloudDistributedLockProviderOptions>? configureOptions = null)\n {\n services.AddOptions();\n services.AddSingleton<ICloudDistributedLockProviderFactory, CloudDistributedLockProviderFactory>();\n services.Configure<CloudDistributedLockProviderOptions>(name, o =>\n {\n o.ProviderName = name;\n o.CosmosClient = cosmosClient;\n o.DatabaseName = databaseName;\n o.TTL = ttl;", "score": 0.8455631732940674 }, { "filename": "CloudDistributedLock/CloudDistributedLock.cs", "retrieved_chunk": " private Timer? timer;\n private bool isDisposed;\n public static CloudDistributedLock CreateUnacquiredLock()\n {\n return new CloudDistributedLock();\n }\n public static CloudDistributedLock CreateAcquiredLock(CosmosLockClient cosmosLockClient, ItemResponse<LockRecord> item)\n {\n return new CloudDistributedLock(cosmosLockClient, item);\n }", "score": 0.8442341089248657 } ]
csharp
CloudDistributedLockProviderOptions> optionsMonitor) {
using System.Text.Json.Serialization; namespace Beeching.Models { internal class Resource { [JsonPropertyName("id")] public string Id { get; set; } [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("type")] public string Type { get; set; } [JsonPropertyName("location")] public string Location { get; set; } [JsonPropertyName("tags")] public Dictionary<string, string> Tags { get; set; } public string ResourceGroup { get; set; } public string? ApiVersion { get; set; } public string OutputMessage { get; set; } public bool IsLocked { get; set; } public bool Skip { get; set; } public List<ResourceLock> ResourceLocks { get; set; } public List<
EffectiveRole> Roles {
get; set; } public Resource() { ResourceLocks = new(); Roles = new(); } } }
src/Models/Resource.cs
irarainey-beeching-e846af0
[ { "filename": "src/Models/EffectiveRole.cs", "retrieved_chunk": "namespace Beeching.Models\n{\n internal class EffectiveRole\n {\n public string Name { get; set; }\n public string Type { get; set; }\n public string Scope { get; set; }\n public string ScopeType { get; set; }\n public string RoleDefinitionId { get; set; }\n public bool CanManageLocks { get; set; }", "score": 0.9112102389335632 }, { "filename": "src/Commands/AxeSettings.cs", "retrieved_chunk": " public bool IgnoreUpdate { get; set; }\n public string UserId { get; set; }\n public string SubscriptionRole { get; set; }\n public bool IsSubscriptionRolePrivileged { get; set; }\n }\n}", "score": 0.9110043048858643 }, { "filename": "src/Models/RoleDefinitionProperties.cs", "retrieved_chunk": " public string? CreatedBy { get; set; }\n [JsonPropertyName(\"updatedBy\")]\n public string? UpdatedBy { get; set; }\n public RoleDefinitionProperties()\n {\n AssignableScopes = new();\n Permissions = new();\n }\n }\n}", "score": 0.8705103397369385 }, { "filename": "src/Models/ApiVersion.cs", "retrieved_chunk": " public List<string> ApiVersions { get; set; }\n [JsonPropertyName(\"defaultApiVersion\")]\n public string DefaultApiVersion { get; set; }\n [JsonPropertyName(\"apiProfiles\")]\n public List<ApiProfile> ApiProfiles { get; set; }\n [JsonPropertyName(\"capabilities\")]\n public string Capabilities { get; set; }\n }\n}", "score": 0.8612287044525146 }, { "filename": "src/Models/RoleDefinitionProperties.cs", "retrieved_chunk": " public string Description { get; set; }\n [JsonPropertyName(\"assignableScopes\")]\n public List<string> AssignableScopes { get; set; }\n [JsonPropertyName(\"permissions\")]\n public List<RoleDefinitionPermission> Permissions { get; set; }\n [JsonPropertyName(\"createdOn\")]\n public DateTime CreatedOn { get; set; }\n [JsonPropertyName(\"updatedOn\")]\n public DateTime UpdatedOn { get; set; }\n [JsonPropertyName(\"createdBy\")]", "score": 0.8582661747932434 } ]
csharp
EffectiveRole> Roles {
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.872795820236206 }, { "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.8483901023864746 }, { "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.8473466634750366 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " }\n // ROOT PANEL\n public static BoolField enemyTweakToggle;\n private static ConfigPanel enemyPanel;\n public static BoolField playerTweakToggle;\n private static ConfigPanel playerPanel;\n public static BoolField discordRichPresenceToggle;\n public static BoolField steamRichPresenceToggle;\n public static StringField pluginName;\n public static StringMultilineField pluginInfo;", "score": 0.8444122076034546 }, { "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.8422408103942871 } ]
csharp
GameObject lighningStrikeWindup;
using Microsoft.EntityFrameworkCore; using Ryan.DependencyInjection; using Ryan.Models; namespace Ryan.EntityFrameworkCore { [Shard(typeof(M))] public class SqlServerShardDbContext : ShardDbContext { public SqlServerShardDbContext(
IShardDependency shardDependency) : base(shardDependency) {
} protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=(local);Database=M;User Id=sa;Password=sa;"); } } }
test/Ryan.EntityFrameworkCore.Shard.Tests/EntityFrameworkCore/SqlServerShardDbContext.cs
c-y-r-Ryan.EntityFrameworkCore.Shard-f15124c
[ { "filename": "test/Ryan.EntityFrameworkCore.Shard.Tests/SqlServerShardDbContextTests.cs", "retrieved_chunk": "namespace Ryan\n{\n public class SqlServerShardDbContextTests : IDisposable\n {\n public ServiceProvider ServiceProvider { get; set; }\n public SqlServerShardDbContextTests()\n {\n var collection = new ServiceCollection();\n collection.AddShard();\n collection.AddSingleton<EntityModelBuilder<M>, MEntityModelBuilder>();", "score": 0.8428342938423157 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Proxy/DbContextEntityProxyGenerator.cs", "retrieved_chunk": "using Microsoft.EntityFrameworkCore;\nnamespace Ryan.EntityFrameworkCore.Proxy\n{\n /// <inheritdoc cref=\"IDbContextEntityProxyGenerator\"/>\n public class DbContextEntityProxyGenerator : IDbContextEntityProxyGenerator\n {\n /// <inheritdoc/>\n public DbContextEntityProxy Create(DbContext context)\n {\n return new DbContextEntityProxy(context);", "score": 0.8201274871826172 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/ShardDbContext.cs", "retrieved_chunk": "using System.Threading;\nusing System.Threading.Tasks;\nnamespace Ryan.EntityFrameworkCore\n{\n /// <summary>\n /// 分表上下文\n /// </summary>\n public class ShardDbContext : DbContext\n {\n /// <summary>", "score": 0.8125743269920349 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityShardConfiguration.cs", "retrieved_chunk": "using Ryan.EntityFrameworkCore.Dynamic;\nusing System;\nnamespace Ryan.EntityFrameworkCore.Builder\n{\n /// <inheritdoc cref=\"IEntityShardConfiguration\"/>\n public class EntityShardConfiguration : IEntityShardConfiguration\n {\n /// <inheritdoc cref=\"IEntityImplementationDictionaryGenerator\"/>\n public IEntityImplementationDictionaryGenerator EntityImplementationDictionaryGenerator { get; }\n /// <summary>", "score": 0.802690863609314 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Dynamic/DynamicSourceCodeGenerator.cs", "retrieved_chunk": "using System;\nusing System.Text;\nnamespace Ryan.EntityFrameworkCore.Dynamic\n{\n /// <inheritdoc cref=\"IDynamicSourceCodeGenerator\"/>\n public class DynamicSourceCodeGenerator : IDynamicSourceCodeGenerator\n {\n /// <inheritdoc/>\n public virtual string Create(Type entityType)\n {", "score": 0.786239743232727 } ]
csharp
IShardDependency shardDependency) : base(shardDependency) {
#nullable enable using System; using System.IO; using System.Threading; using Cysharp.Threading.Tasks; using Mochineko.ChatGPT_API; using Mochineko.FacialExpressions.Blink; using Mochineko.FacialExpressions.Emotion; using Mochineko.FacialExpressions.Extensions.VRM; using Mochineko.FacialExpressions.LipSync; using Mochineko.FacialExpressions.Samples; using Mochineko.LLMAgent.Chat; using Mochineko.LLMAgent.Emotion; using Mochineko.LLMAgent.Memory; using Mochineko.LLMAgent.Speech; using Mochineko.LLMAgent.Summarization; using Mochineko.Relent.Extensions.NewtonsoftJson; using Mochineko.Relent.Result; using Mochineko.RelentStateMachine; using Mochineko.VOICEVOX_API.QueryCreation; using UnityEngine; using UniVRM10; using VRMShaders; namespace Mochineko.LLMAgent.Operation { internal sealed class DemoOperator : MonoBehaviour { [SerializeField] private Model model = Model.Turbo; [SerializeField, TextArea] private string prompt = string.Empty; [SerializeField, TextArea] private string defaultConversations = string.Empty; [SerializeField, TextArea] private string message = string.Empty; [SerializeField] private int speakerID; [SerializeField] private string vrmAvatarPath = string.Empty; [SerializeField] private float emotionFollowingTime = 1f; [SerializeField] private float emotionWeight = 1f; [SerializeField] private AudioSource? audioSource = null; [SerializeField] private RuntimeAnimatorController? animatorController = null; private
IChatMemoryStore? store;
private LongTermChatMemory? memory; internal LongTermChatMemory? Memory => memory; private ChatCompletion? chatCompletion; private ChatCompletion? stateCompletion; private VoiceVoxSpeechSynthesis? speechSynthesis; private IFiniteStateMachine<AgentEvent, AgentContext>? agentStateMachine; private async void Start() { await SetupAgentAsync(this.GetCancellationTokenOnDestroy()); } private async void Update() { if (agentStateMachine == null) { return; } var updateResult = await agentStateMachine .UpdateAsync(this.GetCancellationTokenOnDestroy()); if (updateResult is IFailureResult updateFailure) { Debug.LogError($"Failed to update agent state machine because -> {updateFailure.Message}."); } } private void OnDestroy() { agentStateMachine?.Dispose(); } private async UniTask SetupAgentAsync(CancellationToken cancellationToken) { if (audioSource == null) { throw new NullReferenceException(nameof(audioSource)); } if (animatorController == null) { throw new NullReferenceException(nameof(animatorController)); } var apiKeyPath = Path.Combine( Application.dataPath, "Mochineko/LLMAgent/Operation/OpenAI_API_Key.txt"); var apiKey = await File.ReadAllTextAsync(apiKeyPath, cancellationToken); if (string.IsNullOrEmpty(apiKey)) { throw new Exception($"[LLMAgent.Operation] Loaded API Key is empty from path:{apiKeyPath}"); } store = new NullChatMemoryStore(); memory = await LongTermChatMemory.InstantiateAsync( maxShortTermMemoriesTokenLength: 1000, maxBufferMemoriesTokenLength: 1000, apiKey, model, store, cancellationToken); chatCompletion = new ChatCompletion( apiKey, model, prompt + PromptTemplate.MessageResponseWithEmotion, memory); if (!string.IsNullOrEmpty(defaultConversations)) { var conversationsDeserializeResult = RelentJsonSerializer .Deserialize<ConversationCollection>(defaultConversations); if (conversationsDeserializeResult is ISuccessResult<ConversationCollection> successResult) { for (var i = 0; i < successResult.Result.Conversations.Count; i++) { await memory.AddMessageAsync( successResult.Result.Conversations[i], cancellationToken); } } else if (conversationsDeserializeResult is IFailureResult<ConversationCollection> failureResult) { Debug.LogError( $"[LLMAgent.Operation] Failed to deserialize default conversations because -> {failureResult.Message}"); } } speechSynthesis = new VoiceVoxSpeechSynthesis(speakerID); var binary = await File.ReadAllBytesAsync( vrmAvatarPath, cancellationToken); var instance = await LoadVRMAsync( binary, cancellationToken); var lipMorpher = new VRMLipMorpher(instance.Runtime.Expression); var lipAnimator = new FollowingLipAnimator(lipMorpher); var emotionMorpher = new VRMEmotionMorpher(instance.Runtime.Expression); var emotionAnimator = new ExclusiveFollowingEmotionAnimator<FacialExpressions.Emotion.Emotion>( emotionMorpher, followingTime: emotionFollowingTime); var eyelidMorpher = new VRMEyelidMorpher(instance.Runtime.Expression); var eyelidAnimator = new SequentialEyelidAnimator(eyelidMorpher); var eyelidAnimationFrames = ProbabilisticEyelidAnimationGenerator.Generate( Eyelid.Both, blinkCount: 20); var agentContext = new AgentContext( eyelidAnimator, eyelidAnimationFrames, lipMorpher, lipAnimator, audioSource, emotionAnimator); agentStateMachine = await AgentStateMachineFactory.CreateAsync( agentContext, cancellationToken); instance .GetComponent<Animator>() .runtimeAnimatorController = animatorController; } // ReSharper disable once InconsistentNaming private static async UniTask<Vrm10Instance> LoadVRMAsync( byte[] binaryData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await Vrm10.LoadBytesAsync( bytes: binaryData, canLoadVrm0X: true, controlRigGenerationOption: ControlRigGenerationOption.Generate, showMeshes: true, awaitCaller: new RuntimeOnlyAwaitCaller(), ct: cancellationToken ); } [ContextMenu(nameof(StartChatAsync))] public void StartChatAsync() { ChatAsync(message, this.GetCancellationTokenOnDestroy()) .Forget(); } public async UniTask ChatAsync(string message, CancellationToken cancellationToken) { if (chatCompletion == null) { throw new NullReferenceException(nameof(chatCompletion)); } if (speechSynthesis == null) { throw new NullReferenceException(nameof(speechSynthesis)); } if (agentStateMachine == null) { throw new NullReferenceException(nameof(agentStateMachine)); } string chatResponse; var chatResult = await chatCompletion.CompleteChatAsync(message, cancellationToken); switch (chatResult) { case ISuccessResult<string> chatSuccess: { Debug.Log($"[LLMAgent.Operation] Complete chat message:{chatSuccess.Result}."); chatResponse = chatSuccess.Result; break; } case IFailureResult<string> chatFailure: { Debug.LogError($"[LLMAgent.Operation] Failed to complete chat because of {chatFailure.Message}."); return; } default: throw new ResultPatternMatchException(nameof(chatResult)); } EmotionalMessage emotionalMessage; var deserializeResult = RelentJsonSerializer.Deserialize<EmotionalMessage>(chatResponse); switch (deserializeResult) { case ISuccessResult<EmotionalMessage> deserializeSuccess: { emotionalMessage = deserializeSuccess.Result; break; } case IFailureResult<EmotionalMessage> deserializeFailure: { Debug.LogError( $"[LLMAgent.Operation] Failed to deserialize emotional message:{chatResponse} because of {deserializeFailure.Message}."); return; } default: throw new ResultPatternMatchException(nameof(deserializeResult)); } var emotion = EmotionConverter.ExcludeHighestEmotion(emotionalMessage.Emotion); Debug.Log($"[LLMAgent.Operation] Exclude emotion:{emotion}."); var synthesisResult = await speechSynthesis.SynthesisSpeechAsync( HttpClientPool.PooledClient, emotionalMessage.Message, cancellationToken); switch (synthesisResult) { case ISuccessResult<(AudioQuery query, AudioClip clip)> synthesisSuccess: { agentStateMachine.Context.SpeechQueue.Enqueue(new SpeechCommand( synthesisSuccess.Result.query, synthesisSuccess.Result.clip, new EmotionSample<FacialExpressions.Emotion.Emotion>(emotion, emotionWeight))); if (agentStateMachine.IsCurrentState<AgentIdleState>()) { var sendEventResult = await agentStateMachine.SendEventAsync( AgentEvent.BeginSpeaking, cancellationToken); if (sendEventResult is IFailureResult sendEventFailure) { Debug.LogError( $"[LLMAgent.Operation] Failed to send event because of {sendEventFailure.Message}."); } } break; } case IFailureResult<(AudioQuery query, AudioClip clip)> synthesisFailure: { Debug.Log( $"[LLMAgent.Operation] Failed to synthesis speech because of {synthesisFailure.Message}."); return; } default: return; } } } }
Assets/Mochineko/LLMAgent/Operation/DemoOperator.cs
mochi-neko-llm-agent-sandbox-unity-6521c0b
[ { "filename": "Assets/Mochineko/KoeiromapAPI.Samples/KoeiromapAPISample.cs", "retrieved_chunk": "using UnityEngine.Assertions;\nnamespace Mochineko.KoeiromapAPI.Samples\n{\n internal sealed class KoeiromapAPISample : MonoBehaviour\n {\n [SerializeField, Range(-3f, 3f)] private float speakerX;\n [SerializeField, Range(-3f, 3f)] private float speakerY;\n [SerializeField] private bool useSeed;\n [SerializeField] private ulong seed;\n [SerializeField, TextArea] private string text = string.Empty;", "score": 0.8513041734695435 }, { "filename": "Assets/Mochineko/KoeiromapAPI.Samples/KoeiromapAPISample.cs", "retrieved_chunk": " [SerializeField] private Style style;\n [SerializeField] private AudioSource? audioSource;\n private static readonly HttpClient HttpClient = new();\n private IPolicy<Stream>? policy;\n private void Awake()\n {\n Assert.IsNotNull(audioSource);\n policy = PolicyFactory.BuildPolicy();\n }\n [ContextMenu(nameof(Synthesis))]", "score": 0.8235586881637573 }, { "filename": "Assets/Mochineko/LLMAgent/Operation/DemoOperatorUI.cs", "retrieved_chunk": " [SerializeField] private DemoOperator? demoOperator = null;\n [SerializeField] private TMPro.TMP_InputField? messageInput = null;\n [SerializeField] private Button? sendButton = null;\n private void Awake()\n {\n if (demoOperator == null)\n {\n throw new NullReferenceException(nameof(demoOperator));\n }\n if (messageInput == null)", "score": 0.8022549152374268 }, { "filename": "Assets/Mochineko/LLMAgent/Summarization/Summarizer.cs", "retrieved_chunk": " public sealed class Summarizer\n {\n private readonly Model model;\n private readonly TikToken tikToken;\n private readonly RelentChatCompletionAPIConnection connection;\n private readonly IChatMemory simpleChatMemory = new SimpleChatMemory();\n private readonly IPolicy<ChatCompletionResponseBody> policy;\n private readonly string summary = string.Empty;\n private const int MaxSummaryTokenLength = 2000;\n public Summarizer(", "score": 0.7968106269836426 }, { "filename": "Assets/Mochineko/KoeiromapAPI/RequestBody.cs", "retrieved_chunk": " [JsonProperty(\"text\"), JsonRequired]\n public string Text { get; }\n /// <summary>\n /// Optional.\n /// Defaults to 0.0.\n /// [-3.0, 3.0]\n /// </summary>\n [JsonProperty(\"speaker_x\")]\n public float? SpeakerX { get; }\n /// <summary>", "score": 0.7870714664459229 } ]
csharp
IChatMemoryStore? store;
// Kaplan Copyright (c) DragonFruit Network <[email protected]> // Licensed under Apache-2. Refer to the LICENSE file for more info using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Security.Principal; using System.Threading.Tasks; using System.Windows.Input; using Windows.ApplicationModel; using Windows.Management.Deployment; using Avalonia.Threading; using DragonFruit.Kaplan.ViewModels.Enums; using DragonFruit.Kaplan.ViewModels.Messages; using DynamicData; using DynamicData.Binding; using Microsoft.Extensions.Logging; using ReactiveUI; namespace DragonFruit.Kaplan.ViewModels { public class MainWindowViewModel : ReactiveObject, IDisposable { private readonly ILogger _logger; private readonly WindowsIdentity _currentUser; private readonly PackageManager _packageManager; private readonly IDisposable _packageRefreshListener; private readonly ObservableAsPropertyHelper<IEnumerable<PackageViewModel>> _displayedPackages; private string _searchQuery = string.Empty; private PackageInstallationMode _packageMode = PackageInstallationMode.User; private IReadOnlyCollection<
PackageViewModel> _discoveredPackages = Array.Empty<PackageViewModel>();
public MainWindowViewModel() { _packageManager = new PackageManager(); _currentUser = WindowsIdentity.GetCurrent(); _logger = App.GetLogger<MainWindowViewModel>(); AvailablePackageModes = _currentUser.User != null ? Enum.GetValues<PackageInstallationMode>() : new[] {PackageInstallationMode.Machine}; // create observables var packagesSelected = SelectedPackages.ToObservableChangeSet() .ToCollection() .ObserveOn(RxApp.MainThreadScheduler) .Select(x => x.Any()); _packageRefreshListener = MessageBus.Current.Listen<UninstallEventArgs>().ObserveOn(RxApp.TaskpoolScheduler).Subscribe(x => RefreshPackagesImpl()); _displayedPackages = this.WhenAnyValue(x => x.DiscoveredPackages, x => x.SearchQuery, x => x.SelectedPackages) .ObserveOn(RxApp.TaskpoolScheduler) .Select(q => { // because filters remove selected entries, the search will split the listing into two groups, with the matches showing above var matches = q.Item1.ToLookup(x => x.IsSearchMatch(q.Item2)); return matches[true].Concat(matches[false]); }) .ToProperty(this, x => x.DisplayedPackages); // create commands RefreshPackages = ReactiveCommand.CreateFromTask(RefreshPackagesImpl); RemovePackages = ReactiveCommand.Create(RemovePackagesImpl, packagesSelected); ClearSelection = ReactiveCommand.Create(() => SelectedPackages.Clear(), packagesSelected); ShowAbout = ReactiveCommand.Create(() => MessageBus.Current.SendMessage(new ShowAboutWindowEventArgs())); // auto refresh the package list if the user package filter switch is changed this.WhenValueChanged(x => x.PackageMode).ObserveOn(RxApp.TaskpoolScheduler).Subscribe(_ => RefreshPackages.Execute(null)); } public IEnumerable<PackageInstallationMode> AvailablePackageModes { get; } public ObservableCollection<PackageViewModel> SelectedPackages { get; } = new(); public IEnumerable<PackageViewModel> DisplayedPackages => _displayedPackages.Value; private IReadOnlyCollection<PackageViewModel> DiscoveredPackages { get => _discoveredPackages; set => this.RaiseAndSetIfChanged(ref _discoveredPackages, value); } /// <summary> /// Gets or sets whether the <see cref="DiscoveredPackages"/> collection should show packages installed for the selected user /// </summary> public PackageInstallationMode PackageMode { get => _packageMode; set => this.RaiseAndSetIfChanged(ref _packageMode, value); } /// <summary> /// Gets or sets the search query used to filter <see cref="DisplayedPackages"/> /// </summary> public string SearchQuery { get => _searchQuery; set => this.RaiseAndSetIfChanged(ref _searchQuery, value); } public ICommand ShowAbout { get; } public ICommand ClearSelection { get; } public ICommand RemovePackages { get; } public ICommand RefreshPackages { get; } private async Task RefreshPackagesImpl() { IEnumerable<Package> packages; switch (PackageMode) { case PackageInstallationMode.User when _currentUser.User != null: _logger.LogInformation("Loading Packages for user {userId}", _currentUser.User.Value); packages = _packageManager.FindPackagesForUser(_currentUser.User.Value); break; case PackageInstallationMode.Machine: _logger.LogInformation("Loading machine-wide packages"); packages = _packageManager.FindPackages(); break; default: throw new ArgumentOutOfRangeException(); } var filteredPackageModels = packages.Where(x => x.SignatureKind != PackageSignatureKind.System) .Select(x => new PackageViewModel(x)) .ToList(); _logger.LogDebug("Discovered {x} packages", filteredPackageModels.Count); // ensure the ui doesn't have non-existent packages nominated through an intersection // ToList needed due to deferred nature of iterators used. var reselectedPackages = filteredPackageModels.IntersectBy(SelectedPackages.Select(x => x.Package.Id.FullName), x => x.Package.Id.FullName).ToList(); await Dispatcher.UIThread.InvokeAsync(() => { SelectedPackages.Clear(); SearchQuery = string.Empty; DiscoveredPackages = filteredPackageModels; SelectedPackages.AddRange(reselectedPackages); }); } private void RemovePackagesImpl() { var packages = SelectedPackages.Select(x => x.Package).ToList(); var args = new UninstallEventArgs(packages, PackageMode); _logger.LogInformation("Starting removal of {x} packages", packages.Count); MessageBus.Current.SendMessage(args); } public void Dispose() { _displayedPackages?.Dispose(); _packageRefreshListener?.Dispose(); } } }
DragonFruit.Kaplan/ViewModels/MainWindowViewModel.cs
dragonfruitnetwork-kaplan-13bdb39
[ { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": "{\n public class RemovalProgressViewModel : ReactiveObject, IHandlesClosingEvent, IExecutesTaskPostLoad, ICanCloseWindow\n {\n private readonly ILogger _logger = App.GetLogger<RemovalProgressViewModel>();\n private readonly AsyncLock _lock = new();\n private readonly PackageInstallationMode _mode;\n private readonly CancellationTokenSource _cancellation = new();\n private readonly ObservableAsPropertyHelper<ISolidColorBrush> _progressColor;\n private OperationState _status;\n private int _currentPackageNumber;", "score": 0.894885778427124 }, { "filename": "DragonFruit.Kaplan/ViewModels/PackageRemovalTask.cs", "retrieved_chunk": "namespace DragonFruit.Kaplan.ViewModels\n{\n public class PackageRemovalTask : ReactiveObject\n {\n private readonly ObservableAsPropertyHelper<string> _statusString;\n private readonly PackageInstallationMode _mode;\n private readonly PackageManager _manager;\n private DeploymentProgress? _progress;\n public PackageRemovalTask(PackageManager manager, Package package, PackageInstallationMode mode)\n {", "score": 0.8596329689025879 }, { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": " }\n public OperationState Status\n {\n get => _status;\n private set => this.RaiseAndSetIfChanged(ref _status, value);\n }\n public bool CancellationRequested => _cancellation.IsCancellationRequested;\n public ISolidColorBrush ProgressColor => _progressColor.Value;\n public IReadOnlyList<Package> Packages { get; }\n public ICommand RequestCancellation { get; }", "score": 0.7699340581893921 }, { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": " public event Action CloseRequested;\n public PackageRemovalTask Current\n {\n get => _current;\n private set => this.RaiseAndSetIfChanged(ref _current, value);\n }\n public int CurrentPackageNumber\n {\n get => _currentPackageNumber;\n private set => this.RaiseAndSetIfChanged(ref _currentPackageNumber, value);", "score": 0.7538416981697083 }, { "filename": "DragonFruit.Kaplan/ViewModels/PackageViewModel.cs", "retrieved_chunk": " // defer image loading until someone requests it.\n _logoLoadTask ??= LoadIconStream();\n return _logo;\n }\n private set => this.RaiseAndSetIfChanged(ref _logo, value);\n }\n public string Id => Package.Id.Name;\n public string Name => Package.DisplayName;\n public string Publisher => Package.PublisherDisplayName;\n public bool IsSearchMatch(string query)", "score": 0.7445085048675537 } ]
csharp
PackageViewModel> _discoveredPackages = Array.Empty<PackageViewModel>();
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using VeilsClaim.Classes.Managers; using VeilsClaim.Classes.Objects.Entities; using VeilsClaim.Classes.Objects.Particles; namespace VeilsClaim.Classes.Objects.Effects { public class Overdrive : EntityEffect { public Overdrive() { MaxTime = 4f; Strength = 3f; } public float Strength; protected Color oldThrustStartColour; protected Color oldThrustEndColour; protected Color oldThrustSparkStartColour; protected Color oldThrustSparkEndColour; public override void
Remove(Entity target) {
((Vehicle)target).ThrustStrength /= Strength; ((Vehicle)target).ThrustStartColour = oldThrustStartColour; ((Vehicle)target).ThrustEndColour = oldThrustEndColour; ((Vehicle)target).ThrustSparkStartColour = oldThrustSparkStartColour; ((Vehicle)target).ThrustSparkEndColour = oldThrustSparkEndColour; base.Remove(target); } public override void Update(float delta, Entity target) { if (target is not Vehicle) return; if (timeActive == 0f) { ((Vehicle)target).ThrustStrength *= Strength; oldThrustStartColour = ((Vehicle)target).ThrustStartColour; oldThrustEndColour = ((Vehicle)target).ThrustEndColour; oldThrustSparkStartColour = ((Vehicle)target).ThrustSparkStartColour; oldThrustSparkEndColour = ((Vehicle)target).ThrustSparkEndColour; } if (((Vehicle)target).Thrust != 0f) { Vector2 dir = new Vector2(MathF.Cos(target.Rotation), MathF.Sin(target.Rotation)); ParticleManager.particles.Add(new SparkParticle() { Position = target.Position - dir * 5f, Force = -target.Force, Size = 5f, StartSize = 5f, EndSize = 15f, SparkSize = 5f, SparkStartSize = 5f, SparkEndSize = 2.5f, Colour = Color.Crimson, StartColour = Color.Crimson, EndColour = Color.DarkMagenta, SparkColour = Color.LightCoral, SparkStartColour = Color.LightCoral, SparkEndColour = Color.SlateBlue, Friction = 0.1f, Mass = 0.01f, WindStrength = 4f, MaxLifespan = 0.5f + Main.Random.NextSingle() / 5f, }); } base.Update(delta, target); } public override void Draw(SpriteBatch spriteBatch, Entity target) { } } }
VeilsClaim/Classes/Objects/Effects/Overdrive.cs
IsCactus0-Veils-Claim-de09cef
[ { "filename": "VeilsClaim/Classes/Objects/Entities/Vehicle.cs", "retrieved_chunk": " ThrustSparkStartColour = Color.Tomato;\n ThrustSparkEndColour = Color.MediumOrchid;\n }\n public float Thrust;\n public float ThrustStrength;\n public int SelectedWeapon;\n public List<Weapon> Weapons;\n public Color ThrustStartColour;\n public Color ThrustEndColour;\n public Color ThrustSparkStartColour;", "score": 0.8960748910903931 }, { "filename": "VeilsClaim/Classes/Objects/Particles/FadeParticle.cs", "retrieved_chunk": " public FadeParticle(Color startColour, Color endColour, float startSize, float endSize)\n : base(startColour, startSize, endSize)\n {\n StartColour = startColour;\n EndColour = endColour;\n }\n public Color StartColour;\n public Color EndColour;\n public override void Update(float delta)\n {", "score": 0.8738340139389038 }, { "filename": "VeilsClaim/Classes/Objects/Particles/SparkParticle.cs", "retrieved_chunk": " SparkColour = Color.White;\n SparkStartColour = Color.White;\n SparkEndColour = Color.White;\n SparkSize = 10f;\n SparkStartSize = 10f;\n SparkEndSize = 2f;\n }\n public Color SparkStartColour;\n public Color SparkEndColour;\n public Color SparkColour;", "score": 0.8735136985778809 }, { "filename": "VeilsClaim/Classes/Objects/Trail.cs", "retrieved_chunk": " StartThickness = startThickness;\n EndThickness = endThickness;\n AllowShrinking = allowShrinking;\n StartColour = startColour;\n EndColour = endColour;\n }\n public float SegmentLength;\n public float StartThickness;\n public float EndThickness;\n public bool AllowShrinking;", "score": 0.8619022369384766 }, { "filename": "VeilsClaim/Classes/Objects/Entities/Boid.cs", "retrieved_chunk": " CoherenceStrength = 0.8f;\n AvoidanceStrength = 0.0f;\n }\n public float VisionRange;\n public float AvoidRange;\n public float SeperationStrength;\n public float AlignmentStrength;\n public float CoherenceStrength;\n public float AvoidanceStrength;\n public virtual List<Boid> FindNeighbours(float range)", "score": 0.8571949005126953 } ]
csharp
Remove(Entity target) {
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.8180382251739502 }, { "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.8037166595458984 }, { "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.7704343199729919 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Common/Defines.cs", "retrieved_chunk": "namespace DotNetDevBadgeWeb.Common\n{\n public enum ELevel\n {\n Bronze,\n Silver,\n Gold,\n }\n public enum ETheme\n {", "score": 0.7422467470169067 }, { "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.7362886071205139 } ]
csharp
JsonProperty("topics_entered")] public int TopicsEntered {
using System; using System.Collections.Generic; using SQLServerCoverage.Gateway; namespace SQLServerCoverage.Trace { abstract class TraceController { protected readonly string DatabaseId; protected readonly DatabaseGateway Gateway; protected string FileName; protected readonly string Name; public TraceController(
DatabaseGateway gateway, string databaseName) {
Gateway = gateway; DatabaseId = gateway.GetString(string.Format("select db_id('{0}')", databaseName)); Name = string.Format($"SQLServerCoverage-Trace-{Guid.NewGuid().ToString()}"); } public abstract void Start(); public abstract void Stop(); public abstract List<string> ReadTrace(); public abstract void Drop(); protected void RunScript(string query, string error, int timeout = 60) { var script = GetScript(query); try { Gateway.Execute(script, timeout); } catch (Exception ex) { throw new InvalidOperationException(string.Format(error, ex.Message), ex); } } protected string GetScript(string query) { if (query.Contains("{2}")) { return string.Format(query, Name, DatabaseId, FileName + ".xel"); } if (query.Contains("{1}")) { return string.Format(query, Name, DatabaseId); } return string.Format(query, Name); } } }
src/SQLServerCoverageLib/Trace/TraceController.cs
sayantandey-SQLServerCoverage-aea57e3
[ { "filename": "src/SQLServerCoverageLib/CodeCoverage.cs", "retrieved_chunk": "{\n public class CodeCoverage\n {\n private const int MAX_DISPATCH_LATENCY = 1000;\n private readonly DatabaseGateway _database;\n private readonly string _databaseName;\n private readonly bool _debugger;\n private readonly TraceControllerType _traceType;\n private readonly List<string> _excludeFilter;\n private readonly bool _logging;", "score": 0.90248703956604 }, { "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.9004798531532288 }, { "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.8887911438941956 }, { "filename": "src/SQLServerCoverageLib/Gateway/DatabaseSourceGateway.cs", "retrieved_chunk": "{\n public class DatabaseSourceGateway : SourceGateway\n {\n private readonly DatabaseGateway _databaseGateway;\n public DatabaseSourceGateway(DatabaseGateway databaseGateway)\n {\n _databaseGateway = databaseGateway;\n }\n public SqlServerVersion GetVersion()\n {", "score": 0.8835772275924683 }, { "filename": "src/SQLServerCoverageLib/Objects/Statement.cs", "retrieved_chunk": " Text = text;\n Offset = offset;\n Length = length;\n }\n public string Text;\n public int Offset;\n public int Length;\n }\n public class Statement : CoverageInformation\n {", "score": 0.8663102984428406 } ]
csharp
DatabaseGateway gateway, string databaseName) {
namespace WAGIapp.AI.AICommands { internal class WriteLineCommand : Command { public override string
Name => "write-line";
public override string Description => "writes the given text to the line number"; public override string Format => "write-line | line number | text"; public override async Task<string> Execute(Master caller, string[] args) { if (args.Length < 3) return "error! not enough parameters"; int line; try { line = Convert.ToInt32(args[1]); } catch (Exception) { return "error! given line number is not a number"; } return caller.scriptFile.WriteLine(line, args[2]); } } }
WAGIapp/AI/AICommands/WriteLineCommand.cs
Woltvint-WAGI-d808927
[ { "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.8431689739227295 }, { "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.8181793093681335 }, { "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.8090161681175232 }, { "filename": "WAGIapp/AI/AICommands/AddNoteCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class AddNoteCommand : Command\n {\n public override string Name => \"add-note\"; ", "score": 0.8078066110610962 }, { "filename": "WAGIapp/AI/AICommands/RemoveNoteCommand.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace WAGIapp.AI.AICommands\n{\n internal class RemoveNoteCommand : Command\n {\n public override string Name => \"remove-note\";", "score": 0.8049940466880798 } ]
csharp
Name => "write-line";