prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
using System.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/Base/SceneToolsWindowBase.cs", "retrieved_chunk": "using Sandland.SceneTool.Editor.Common.Utils;\nusing Sandland.SceneTool.Editor.Services;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nnamespace Sandland.SceneTool.Editor.Views.Base\n{\n internal abstract class SceneToolsWindowBase : EditorWindow\n {\n private const string GlobalStyleSheetName = \"SceneToolsMain\";", "score": 0.9075555801391602 }, { "filename": "Assets/SceneTools/Editor/Views/SceneToolsSetupWindow/Handlers/ThemesSelectionUiHandler.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing Sandland.SceneTool.Editor.Common.Data;\nusing Sandland.SceneTool.Editor.Common.Utils;\nusing Sandland.SceneTool.Editor.Services;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nnamespace Sandland.SceneTool.Editor.Views.Handlers\n{", "score": 0.881031334400177 }, { "filename": "Assets/SceneTools/Editor/Views/SceneToolsSetupWindow/Handlers/SceneClassGenerationUiHandler.cs", "retrieved_chunk": "using System.IO;\nusing Sandland.SceneTool.Editor.Common.Utils;\nusing Sandland.SceneTool.Editor.Services;\nusing UnityEditor;\nusing UnityEngine.UIElements;\nnamespace Sandland.SceneTool.Editor.Views.Handlers\n{\n internal class SceneClassGenerationUiHandler : ISceneToolsSetupUiHandler\n {\n private const string HiddenContentClass = \"hidden\";", "score": 0.8785586953163147 }, { "filename": "Assets/SceneTools/Editor/Views/SceneSelectorWindow/SceneSelectorWindow.cs", "retrieved_chunk": "using System.Linq;\nusing Sandland.SceneTool.Editor.Common.Data;\nusing Sandland.SceneTool.Editor.Common.Utils;\nusing Sandland.SceneTool.Editor.Services;\nusing Sandland.SceneTool.Editor.Views.Base;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nnamespace Sandland.SceneTool.Editor.Views\n{", "score": 0.8781535625457764 }, { "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.8723978996276855 } ]
csharp
MenuItems.Tools.Root + "Setup Scene Tools";
using JWLSLMerge.Data.Attributes; namespace JWLSLMerge.Data.Models { public class PlaylistItemMarker { [
Ignore] public int PlaylistItemMarkerId {
get; set; } public int PlaylistItemId { get; set; } public string Label { get; set; } = null!; public long StartTimeTicks { get; set; } public long DurationTicks { get; set; } public long EndTransitionDurationTicks { get; set; } [Ignore] public int NewPlaylistItemMarkerId { get; set; } } }
JWLSLMerge.Data/Models/PlaylistItemMarker.cs
pliniobrunelli-JWLSLMerge-7fe66dc
[ { "filename": "JWLSLMerge.Data/Models/PlayListItem.cs", "retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }", "score": 0.8930943608283997 }, { "filename": "JWLSLMerge.Data/Models/TagMap.cs", "retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class TagMap\n {\n [Ignore]\n public int TagMapId { get; set; }\n public int? PlaylistItemId { get; set; }\n public int? LocationId { get; set; }\n public int? NoteId { get; set; }", "score": 0.8895865678787231 }, { "filename": "JWLSLMerge.Data/Models/PlaylistItemMarkerBibleVerseMap.cs", "retrieved_chunk": "namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerBibleVerseMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int VerseId { get; set; }\n }\n}", "score": 0.8888929486274719 }, { "filename": "JWLSLMerge.Data/Models/Bookmark.cs", "retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class Bookmark\n {\n [Ignore]\n public int BookmarkId { get; set; }\n public int LocationId { get; set; }\n public int PublicationLocationId { get; set; }\n public int Slot { get; set; }", "score": 0.884943425655365 }, { "filename": "JWLSLMerge.Data/Models/PlaylistItemMarkerParagraphMap.cs", "retrieved_chunk": "namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}", "score": 0.8835888504981995 } ]
csharp
Ignore] public int PlaylistItemMarkerId {
using Microsoft.EntityFrameworkCore; using Ryan.EntityFrameworkCore.Builder; using Ryan.Models; using System.Collections.Generic; namespace Ryan.EntityFrameworkCore.ModelBuilders { public class MEntityModelBuilder : EntityModelBuilder<M> { public override void Build<TImplementation>(ModelBuilder modelBuilder, string tableName) { modelBuilder.Entity<TImplementation>(b => { b.ToTable(tableName).HasKey(x => x.Id).IsClustered(false); b.Property(x => x.Id).ValueGeneratedOnAdd(); b.Property(x => x.Year).IsRequired(); b.Property(x => x.Name).IsRequired().HasMaxLength(50); }); } public override string
GetTableName(Dictionary<string, string> value) {
return $"M_{value["Year"]}"; } protected override void EntityConfiguration() { Apply(x => x.Year); } } }
test/Ryan.EntityFrameworkCore.Shard.Tests/EntityFrameworkCore/ModelBuilders/MEntityModelBuilder.cs
c-y-r-Ryan.EntityFrameworkCore.Shard-f15124c
[ { "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.8248379230499268 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityModelBuilder.cs", "retrieved_chunk": " /// <inheritdoc/>\n public virtual IEnumerable<EntityExpressionVisitor> GetExpressionVisitors()\n {\n return Visitors.Select(x => x());\n }\n /// <inheritdoc/>\n public abstract string GetTableName(Dictionary<string, string> value);\n /// <summary>\n /// 构建 <typeparamref name=\"TImplementation\"/> 类型 Model\n /// </summary>", "score": 0.8092991709709167 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityImplementation.cs", "retrieved_chunk": " /// </summary>\n public Type EntityType { get; }\n /// <summary>\n /// 实现类型\n /// </summary>\n public Type ImplementationType { get; }\n /// <summary>\n /// 表名\n /// </summary>\n public string TableName { get; }", "score": 0.7963445782661438 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Proxy/EntityProxyGenerator.cs", "retrieved_chunk": " var visitors = builder.GetExpressionVisitors().ToList();\n foreach (var visitor in visitors)\n {\n visitor.Visit(entity);\n }\n var pairs = visitors.Select(x => new KeyValuePair<string, string?>(x.MemberExpression.Member.Name, x.Values.FirstOrDefault()));\n var dictionary = new Dictionary<string, string>(pairs!);\n var tableName = builder.GetTableName(dictionary);\n var ei = EntityImplementationDictionaryGenerator.Create(entity.GetType())[tableName];\n var entityImplementation = Activator.CreateInstance(ei.ImplementationType)!;", "score": 0.783784806728363 }, { "filename": "src/Ryan.EntityFrameworkCore.Shard/EntityFrameworkCore/Builder/EntityShardConfiguration.cs", "retrieved_chunk": " EntityImplementationDictionaryGenerator = entityImplementationDictionaryGenerator;\n DynamicTypeGenerator = dynamicTypeGenerator;\n }\n /// <inheritdoc/>\n public Type AddShard<TEntity>(string tableName) where TEntity : class\n {\n var implementationType = DynamicTypeGenerator.Create(typeof(TEntity));\n EntityImplementationDictionaryGenerator\n .Create(typeof(TEntity))\n .Add(tableName, new EntityImplementation(typeof(TEntity), implementationType, tableName));", "score": 0.7826282382011414 } ]
csharp
GetTableName(Dictionary<string, string> value) {
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/QuestGraphSaveUtility.cs", "retrieved_chunk": " _targetGraphView.AddElement(tempNode);\n var nodePorts = Q.nodeLinkData.Where(x => x.baseNodeGUID == node.GUID).ToList();\n nodePorts.ForEach(x => _targetGraphView.AddNextNodePort(tempNode));\n }\n }\n private void ConectNodes(Quest Q)\n {\n List<NodeQuestGraph> nodeListCopy = new List<NodeQuestGraph>(node);\n for (int i = 0; i < nodeListCopy.Count; i++)\n {", "score": 0.8304598331451416 }, { "filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs", "retrieved_chunk": " private void LinkNodes(Port outpor, Port inport)\n {\n var tempEdge = new Edge\n {\n output = outpor,\n input = inport\n };\n tempEdge.input.Connect(tempEdge);\n tempEdge.output.Connect(tempEdge);\n _targetGraphView.Add(tempEdge);", "score": 0.8275336623191833 }, { "filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs", "retrieved_chunk": " //CreateObjectives\n QuestObjectiveGraph objtemp = new QuestObjectiveGraph(qObjective.keyName, qObjective.maxItems, qObjective.actualItems,\n qObjective.description, qObjective.hiddenObjective, qObjective.autoExitOnCompleted);\n var deleteButton = new Button(clickEvent: () => _targetGraphView.removeQuestObjective(tempNode, objtemp))\n {\n text = \"x\"\n };\n objtemp.Add(deleteButton);\n var newBox = new Box();\n objtemp.Add(newBox);", "score": 0.8255743980407715 }, { "filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs", "retrieved_chunk": " {\n var tempNode = _targetGraphView.CreateNodeQuest(node.name, Vector2.zero, node.extraText, node.isFinal);\n //Load node variables\n tempNode.GUID = node.GUID;\n tempNode.extraText = node.extraText;\n tempNode.isFinal = node.isFinal;\n tempNode.RefreshPorts();\n if (node.nodeObjectives != null) {\n foreach (QuestObjective qObjective in node.nodeObjectives)\n {", "score": 0.8211377263069153 }, { "filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs", "retrieved_chunk": " var connectedPorts = Edges.Where(x => x.input.node != null).ToArray();\n Q.ResetNodeLinksGraph();\n foreach (NodeQuest currentNode in nodesInGraph)\n {\n currentNode.nextNode.Clear();\n }\n for (int i = 0; i < connectedPorts.Length; i++)\n {\n var outputNode = connectedPorts[i].output.node as NodeQuestGraph;\n var inputNode = connectedPorts[i].input.node as NodeQuestGraph;", "score": 0.8202288150787354 } ]
csharp
NodeQuestGraph node, Port p) {
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": " Ray ray = new Ray(player.position, unitSphere);\n LayerMask mask = new LayerMask();\n mask.value |= 256 | 16777216;\n if (Physics.Raycast(ray, out RaycastHit hit, max, mask, QueryTriggerInteraction.Ignore))\n {\n if (hit.distance < min)\n return;\n Vector3 point = ray.GetPoint(hit.distance - 5);\n __instance.Teleport(point, __instance.transform.position);\n }", "score": 0.8630920052528381 }, { "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.8609943389892578 }, { "filename": "Ultrapain/Patches/V2Common.cs", "retrieved_chunk": " reflectComp.alreadyHitPlayer = false;\n reflectedBullet.transform.forward = Vector3.Reflect(comp.transform.forward, comp.targetHit.normal).normalized;\n Vector3 playerPos = NewMovement.Instance.transform.position;\n Vector3 playerVectorFromBullet = playerPos - reflectedBullet.transform.position;\n float angle = Vector3.Angle(playerVectorFromBullet, reflectedBullet.transform.forward);\n if (angle <= ConfigManager.v2FirstSharpshooterAutoaimAngle.value)\n {\n Quaternion lastRotation = reflectedBullet.transform.rotation;\n reflectedBullet.transform.LookAt(NewMovement.Instance.playerCollider.bounds.center);\n RaycastHit[] hits = Physics.RaycastAll(reflectedBullet.transform.position, reflectedBullet.transform.forward, Vector3.Distance(reflectedBullet.transform.position, playerPos));", "score": 0.8539407849311829 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " {\n Instantiate<GameObject>(Plugin.v2flashUnparryable, this.shootPoint.position, this.shootPoint.rotation).transform.localScale *= 4f;\n }\n void Fire()\n {\n cooldown = ConfigManager.v2SecondMalCannonSnipeCooldown.value;\n Transform target = V2Utils.GetClosestGrenade();\n Vector3 targetPosition = Vector3.zero;\n if (target != null)\n {", "score": 0.8515405654907227 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " Vector3 playerPos = Tools.PredictPlayerPosition(0.5f);\n rocket.LookAt(playerPos);\n Rigidbody rb = rocket.GetComponent<Rigidbody>();\n rb.velocity = Vector3.zero;\n rb.AddForce(rocket.transform.forward * 10000f);\n }\n void Fire()\n {\n GameObject rocket = Instantiate<GameObject>(Plugin.rocket, shootPoint.transform.position, shootPoint.transform.rotation);\n rocket.transform.position = new Vector3(rocket.transform.position.x, v2collider.bounds.center.y, rocket.transform.position.z);", "score": 0.8514681458473206 } ]
csharp
Vector3 RandomVector(float min, float max) {
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/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.8575717210769653 }, { "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.8454151153564453 }, { "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.8355517983436584 }, { "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.8285291194915771 }, { "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.8173823356628418 } ]
csharp
Description => "writes the given text to the line number";
using SandBox.Conversation.MissionLogics; using SandBox.View.Missions; using System; using TaleWorlds.CampaignSystem.Conversation; using TaleWorlds.CampaignSystem; using TaleWorlds.Core; using TaleWorlds.Engine.GauntletUI; using TaleWorlds.Engine.Screens; using TaleWorlds.InputSystem; using TaleWorlds.Library; using TaleWorlds.MountAndBlade.GauntletUI.Mission; using TaleWorlds.MountAndBlade.View.MissionViews.Singleplayer; using TaleWorlds.MountAndBlade.View.MissionViews; using TaleWorlds.MountAndBlade.View; using TaleWorlds.ScreenSystem; using TaleWorlds.TwoDimension; namespace Inworld.InworldView { [OverrideView(typeof(MissionConversationView))] public class InworldMissionConversationView : MissionView, IConversationStateHandler { private
InworldMissionChatVM _dataSource;
private GauntletLayer _gauntletLayer; private ConversationManager _conversationManager; private MissionConversationCameraView _conversationCameraView; private MissionGauntletEscapeMenuBase _escapeView; private SpriteCategory _conversationCategory; public MissionConversationLogic ConversationHandler { get; private set; } public InworldMissionConversationView() => this.ViewOrderPriority = 49; public override void OnMissionScreenTick(float dt) { base.OnMissionScreenTick(dt); MissionGauntletEscapeMenuBase escapeView = this._escapeView; if (_conversationManager != null && _gauntletLayer != null && _gauntletLayer.Input != null) { if (Input.IsKeyDown(InputKey.Tab) || this.IsGameKeyReleasedInAnyLayer("Leave", true) || this._gauntletLayer.Input.IsKeyDown(InputKey.Tab)) { this._dataSource.BackToChat(); return; } else if (Input.IsKeyDown(InputKey.Enter) || this.IsGameKeyReleasedInAnyLayer("Confirm", true) || this._gauntletLayer.Input.IsKeyDown(InputKey.Enter)) { if (this._dataSource.GetType() == typeof(InworldMissionChatVM)) { this._dataSource.SendPlayerInput(); } } } if ((escapeView != null ? (!escapeView.IsActive ? 1 : 0) : 1) == 0 || this._gauntletLayer == null) return; InworldMissionChatVM dataSource1 = this._dataSource; if (dataSource1 != null) { dataSource1.OnTick(dt); } if ((dataSource1 != null ? (dataSource1.AnswerList.Count <= 0 ? 1 : 0) : 0) != 0 && this.Mission.Mode != MissionMode.Barter) { if (!this.IsReleasedInSceneLayer("ContinueClick", false)) { if (this.IsReleasedInGauntletLayer("ContinueKey", true)) { InworldMissionChatVM dataSource2 = this._dataSource; if ((dataSource2 != null ? (!dataSource2.SelectedAnOptionOrLinkThisFrame ? 1 : 0) : 0) == 0) goto label_7; } else goto label_7; } if(!State.ChatViewSharedState.IsChatRequiresType) this._dataSource?.ExecuteContinue(); } label_7: if (this._gauntletLayer != null && this.IsGameKeyReleasedInAnyLayer("ToggleEscapeMenu", true)) this.MissionScreen.OnEscape(); if (this._dataSource != null) this._dataSource.SelectedAnOptionOrLinkThisFrame = false; if (this.MissionScreen.SceneLayer.Input.IsKeyDown(InputKey.RightMouseButton)) this._gauntletLayer?.InputRestrictions.SetMouseVisibility(false); else this._gauntletLayer?.InputRestrictions.SetInputRestrictions(); } public override void OnMissionScreenFinalize() { Campaign.Current.ConversationManager.Handler = (IConversationStateHandler)null; if (this._dataSource != null) { this._dataSource?.OnFinalize(); this._dataSource = (InworldMissionChatVM)null; } this._gauntletLayer = (GauntletLayer)null; this.ConversationHandler = (MissionConversationLogic)null; base.OnMissionScreenFinalize(); } public override void EarlyStart() { base.EarlyStart(); this.ConversationHandler = this.Mission.GetMissionBehavior<MissionConversationLogic>(); this._conversationCameraView = this.Mission.GetMissionBehavior<MissionConversationCameraView>(); Campaign.Current.ConversationManager.Handler = (IConversationStateHandler)this; } public override void OnMissionScreenActivate() { base.OnMissionScreenActivate(); if (this._dataSource == null) return; this.MissionScreen.SetLayerCategoriesStateAndDeactivateOthers(new string[2] { "Conversation", "SceneLayer" }, true); ScreenManager.TrySetFocus((ScreenLayer)this._gauntletLayer); } void IConversationStateHandler.OnConversationInstall() { this.MissionScreen.SetConversationActive(true); SpriteData spriteData = UIResourceManager.SpriteData; TwoDimensionEngineResourceContext resourceContext = UIResourceManager.ResourceContext; ResourceDepot uiResourceDepot = UIResourceManager.UIResourceDepot; this._conversationCategory = spriteData.SpriteCategories["ui_conversation"]; this._conversationCategory.Load((ITwoDimensionResourceContext)resourceContext, uiResourceDepot); this._dataSource = new InworldMissionChatVM(new Func<string>(this.GetContinueKeyText)); this._gauntletLayer = new GauntletLayer(this.ViewOrderPriority, "Conversation"); this._gauntletLayer.LoadMovie("InworldConversation", (ViewModel)this._dataSource); GameKeyContext category = HotKeyManager.GetCategory("ConversationHotKeyCategory"); this._gauntletLayer.Input.RegisterHotKeyCategory(category); if (!this.MissionScreen.SceneLayer.Input.IsCategoryRegistered(category)) this.MissionScreen.SceneLayer.Input.RegisterHotKeyCategory(category); this._gauntletLayer.IsFocusLayer = true; this._gauntletLayer.InputRestrictions.SetInputRestrictions(); this._escapeView = this.Mission.GetMissionBehavior<MissionGauntletEscapeMenuBase>(); this.MissionScreen.AddLayer((ScreenLayer)this._gauntletLayer); this.MissionScreen.SetLayerCategoriesStateAndDeactivateOthers(new string[2] { "Conversation", "SceneLayer" }, true); ScreenManager.TrySetFocus((ScreenLayer)this._gauntletLayer); this._conversationManager = Campaign.Current.ConversationManager; InformationManager.ClearAllMessages(); } public override void OnMissionModeChange(MissionMode oldMissionMode, bool atStart) { base.OnMissionModeChange(oldMissionMode, atStart); if (oldMissionMode != MissionMode.Barter || this.Mission.Mode != MissionMode.Conversation) return; ScreenManager.TrySetFocus((ScreenLayer)this._gauntletLayer); } void IConversationStateHandler.OnConversationUninstall() { this.MissionScreen.SetConversationActive(false); if (this._dataSource != null) { this._dataSource?.OnFinalize(); this._dataSource = (InworldMissionChatVM)null; } this._conversationCategory.Unload(); this._gauntletLayer.IsFocusLayer = false; ScreenManager.TryLoseFocus((ScreenLayer)this._gauntletLayer); this._gauntletLayer.InputRestrictions.ResetInputRestrictions(); this.MissionScreen.SetLayerCategoriesStateAndToggleOthers(new string[1] { "Conversation" }, false); this.MissionScreen.SetLayerCategoriesState(new string[1] { "SceneLayer" }, true); this.MissionScreen.RemoveLayer((ScreenLayer)this._gauntletLayer); this._gauntletLayer = (GauntletLayer)null; this._escapeView = (MissionGauntletEscapeMenuBase)null; } private string GetContinueKeyText() { GameTexts.SetVariable("CONSOLE_KEY_NAME", HyperlinkTexts.GetKeyHyperlinkText(HotKeyManager.GetHotKeyId("ConversationHotKeyCategory", "ContinueKey"))); return GameTexts.FindText("str_click_to_continue_console").ToString(); } void IConversationStateHandler.OnConversationActivate() => this.MissionScreen.SetLayerCategoriesStateAndDeactivateOthers(new string[2] { "Conversation", "SceneLayer" }, true); void IConversationStateHandler.OnConversationDeactivate() => MBInformationManager.HideInformations(); void IConversationStateHandler.OnConversationContinue() => this._dataSource.OnConversationContinue(); void IConversationStateHandler.ExecuteConversationContinue() { if (State.ChatViewSharedState.IsChatRequiresType) return; this._dataSource.ExecuteContinue(); } private bool IsGameKeyReleasedInAnyLayer(string hotKeyID, bool isDownAndReleased) => this.IsReleasedInSceneLayer(hotKeyID, isDownAndReleased) | this.IsReleasedInGauntletLayer(hotKeyID, isDownAndReleased); private bool IsReleasedInSceneLayer(string hotKeyID, bool isDownAndReleased) { if (isDownAndReleased) { SceneLayer sceneLayer = this.MissionScreen.SceneLayer; return sceneLayer != null && sceneLayer.Input.IsHotKeyDownAndReleased(hotKeyID); } SceneLayer sceneLayer1 = this.MissionScreen.SceneLayer; return sceneLayer1 != null && sceneLayer1.Input.IsHotKeyReleased(hotKeyID); } private bool IsReleasedInGauntletLayer(string hotKeyID, bool isDownAndReleased) { if (isDownAndReleased) { GauntletLayer gauntletLayer = this._gauntletLayer; return gauntletLayer != null && gauntletLayer.Input.IsHotKeyDownAndReleased(hotKeyID); } GauntletLayer gauntletLayer1 = this._gauntletLayer; return gauntletLayer1 != null && gauntletLayer1.Input.IsHotKeyReleased(hotKeyID); } } }
Bannerlord/Code/Inworld/Inworld/InworldView/InworldMissionConversationView.cs
BlocTheWorker-Inworld-Bannerlord-Mod-75242ae
[ { "filename": "Bannerlord/Code/Inworld/Inworld/InworldView/InworldMissionChatVM.cs", "retrieved_chunk": "using Inworld.InMission;\nusing Inworld.Engine;\nusing TaleWorlds.Engine.Options;\nusing TaleWorlds.InputSystem;\nnamespace Inworld.InworldView\n{\n public class InworldMissionChatVM : ViewModel\n {\n private readonly ConversationManager _conversationManager;\n private readonly bool _isLinksDisabled;", "score": 0.894230842590332 }, { "filename": "Bannerlord/Code/Inworld/Inworld/Mission/SceneChatCharacterController.cs", "retrieved_chunk": "using TaleWorlds.CampaignSystem.Encounters;\nusing TaleWorlds.CampaignSystem.LogEntries;\nusing TaleWorlds.CampaignSystem.Settlements;\nusing TaleWorlds.CampaignSystem.Settlements.Locations;\nusing TaleWorlds.Core;\nusing TaleWorlds.Library;\nusing TaleWorlds.MountAndBlade;\nnamespace Inworld.InMission\n{\n internal class SceneChatCharacterController : MissionLogic", "score": 0.8421162962913513 }, { "filename": "Bannerlord/Code/Inworld/Inworld/InworldView/InworldMissionChatVM.cs", "retrieved_chunk": " private WaveOutEvent _player;\n private List<RawSourceWaveStream> _streamQueue;\n CharacterEngine.EmotionBehavior lastEmotion = CharacterEngine.EmotionBehavior.NEUTRAL;\n private bool updatedVillager;\n private bool IsWaitingToSend;\n private string jsonToSend;\n private bool isFirstEmotionArrived;\n public InworldMissionChatVM(Func<string> getContinueInputText, bool isLinksDisabled = false)\n {\n this.AnswerList = new MBBindingList<ConversationItemVM>();", "score": 0.8353933095932007 }, { "filename": "Bannerlord/Code/Inworld/Inworld/SubModule.cs", "retrieved_chunk": "using HarmonyLib;\nusing TaleWorlds.CampaignSystem.GameComponents;\nusing TaleWorlds.CampaignSystem;\nusing TaleWorlds.Library;\nusing TaleWorlds.Localization;\nusing TaleWorlds.MountAndBlade;\nusing TaleWorlds.Core;\nusing Inworld.Behavior;\nusing TaleWorlds.MountAndBlade.GauntletUI.Widgets.Conversation;\nusing Inworld.InMission;", "score": 0.8223637342453003 }, { "filename": "Bannerlord/Code/Inworld/Inworld/Behavior/InworldStateCampaignBehavior.cs", "retrieved_chunk": " {\n dataStore.SyncData(\"inworldInitialized\", ref _inworldInitialized);\n dataStore.SyncData(\"inworldMemorableEvents\", ref _memorableEvents);\n dataStore.SyncData(\"inworldHeroLog\", ref _heroLog);\n dataStore.SyncData(\"inworldModVersion\", ref _modver);\n dataStore.SyncData(\"inworldModSaveIdentifier\", ref _modIdentifier);\n }\n public void AddConversations(CampaignGameStarter starter)\n {\n starter.AddPlayerLine(\"direct_question\", \"hero_main_options\", \"talking_with_text\", \"{=}I need to talk with you.\", new ConversationSentence.OnConditionDelegate(this.conversation_player_wants_chat_on_condition), (ConversationSentence.OnConsequenceDelegate)(this.conversation_player_wants_chat_on_consequence));", "score": 0.8216310143470764 } ]
csharp
InworldMissionChatVM _dataSource;
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/Panopticon.cs", "retrieved_chunk": " }\n }\n return code.AsEnumerable();\n }\n }\n}", "score": 0.7984216213226318 }, { "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.7950296401977539 }, { "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.7949761152267456 }, { "filename": "Ultrapain/Patches/V2Common.cs", "retrieved_chunk": " class V2CommonRevolverComp : MonoBehaviour\n {\n public bool secondPhase = false;\n public bool shootingForSharpshooter = false;\n }\n class V2CommonRevolverPrepareAltFire\n {\n static bool Prefix(EnemyRevolver __instance, GameObject ___altCharge)\n {\n if(__instance.TryGetComponent<V2CommonRevolverComp>(out V2CommonRevolverComp comp))", "score": 0.7923541069030762 }, { "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.7918230295181274 } ]
csharp
GameObject core) {
using HarmonyLib; using Sandbox; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.AI; namespace Ultrapain.Patches { class MinosPrimeCharge { static GameObject decoy; public static void CreateDecoy() { if (decoy != null || Plugin.minosPrime == null) return; decoy = GameObject.Instantiate(Plugin.minosPrime, Vector3.zero, Quaternion.identity); decoy.SetActive(false); GameObject.Destroy(decoy.GetComponent<MinosPrime>()); GameObject.Destroy(decoy.GetComponent<Machine>()); GameObject.Destroy(decoy.GetComponent<BossHealthBar>()); GameObject.Destroy(decoy.GetComponent<EventOnDestroy>()); GameObject.Destroy(decoy.GetComponent<BossIdentifier>()); GameObject.Destroy(decoy.GetComponent<EnemyIdentifier>()); GameObject.Destroy(decoy.GetComponent<BasicEnemyDataRelay>()); GameObject.Destroy(decoy.GetComponent<Rigidbody>()); GameObject.Destroy(decoy.GetComponent<CapsuleCollider>()); GameObject.Destroy(decoy.GetComponent<AudioSource>()); GameObject.Destroy(decoy.GetComponent<NavMeshAgent>()); foreach (SkinnedMeshRenderer renderer in UnityUtils.GetComponentsInChildrenRecursively<SkinnedMeshRenderer>(decoy.transform)) { renderer.material = new Material(Plugin.gabrielFakeMat); } SandboxEnemy sbe = decoy.GetComponent<SandboxEnemy>(); if (sbe != null) GameObject.Destroy(sbe); MindflayerDecoy comp = decoy.AddComponent<MindflayerDecoy>(); comp.fadeSpeed = 1f; //decoy.GetComponent<Animator>().StopPlayback(); //decoy.GetComponent<Animator>().Update(100f); GameObject.Destroy(decoy.transform.Find("SwingCheck").gameObject); GameObject.Destroy(decoy.transform.Find("Capsule").gameObject); GameObject.Destroy(decoy.transform.Find("Point Light").gameObject); foreach (EnemyIdentifierIdentifier eii in UnityUtils.GetComponentsInChildrenRecursively<EnemyIdentifierIdentifier>(decoy.transform)) GameObject.Destroy(eii); } static void DrawTrail(MinosPrime instance, Animator anim, Vector3 startPosition,
Vector3 targetPosition) {
if(decoy == null) { CreateDecoy(); return; } targetPosition = Vector3.MoveTowards(targetPosition, startPosition, 5f); Vector3 currentPosition = startPosition; float distance = Vector3.Distance(startPosition, targetPosition); if (distance < 2.5f) return; float deltaDistance = 2.5f; float fadeSpeed = 1f / ConfigManager.minosPrimeTeleportTrailDuration.value; AnimatorStateInfo currentAnimatorStateInfo = anim.GetCurrentAnimatorStateInfo(0); int maxIterations = Mathf.CeilToInt(distance / deltaDistance); float currentTransparency = 0.1f; float deltaTransparencyPerIteration = 1f / maxIterations; while (currentPosition != targetPosition) { GameObject gameObject = GameObject.Instantiate(decoy, currentPosition, instance.transform.rotation); gameObject.SetActive(true); Animator componentInChildren = gameObject.GetComponentInChildren<Animator>(); componentInChildren.Play(currentAnimatorStateInfo.shortNameHash, 0, currentAnimatorStateInfo.normalizedTime); componentInChildren.speed = 0f; MindflayerDecoy comp = gameObject.GetComponent<MindflayerDecoy>(); comp.fadeSpeed = fadeSpeed; currentTransparency += deltaTransparencyPerIteration; comp.fadeOverride = Mathf.Min(1f, currentTransparency); currentPosition = Vector3.MoveTowards(currentPosition, targetPosition, deltaDistance); } } static void Postfix(MinosPrime __instance, Animator ___anim) { string stateName = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (stateName == "Combo" || (flag != null && flag.throwingProjectile)) return; Transform player = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); float min = ConfigManager.minosPrimeRandomTeleportMinDistance.value; float max = ConfigManager.minosPrimeRandomTeleportMaxDistance.value; Vector3 unitSphere = UnityEngine.Random.onUnitSphere; unitSphere.y = Mathf.Abs(unitSphere.y); float distance = UnityEngine.Random.Range(min, max); Ray ray = new Ray(player.position, unitSphere); LayerMask mask = new LayerMask(); mask.value |= 256 | 16777216; if (Physics.Raycast(ray, out RaycastHit hit, max, mask, QueryTriggerInteraction.Ignore)) { if (hit.distance < min) return; Vector3 point = ray.GetPoint(hit.distance - 5); __instance.Teleport(point, __instance.transform.position); } else { Vector3 point = ray.GetPoint(distance); __instance.Teleport(point, __instance.transform.position); } } static void TeleportPostfix(MinosPrime __instance, Animator ___anim, Vector3 __0, Vector3 __1) { DrawTrail(__instance, ___anim, __1, __0); } } class MinosPrimeFlag : MonoBehaviour { void Start() { } public void ComboExplosion() { GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity); foreach(Explosion e in explosion.GetComponentsInChildren<Explosion>()) { e.toIgnore.Add(EnemyType.MinosPrime); e.maxSize *= ConfigManager.minosPrimeComboExplosionSize.value; e.speed *= ConfigManager.minosPrimeComboExplosionSize.value; e.damage = (int)(e.damage * ConfigManager.minosPrimeComboExplosionDamage.value); } } public void BigExplosion() { GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity); foreach (Explosion e in explosion.GetComponentsInChildren<Explosion>()) { e.toIgnore.Add(EnemyType.MinosPrime); e.maxSize *= ConfigManager.minosPrimeExplosionSize.value; e.speed *= ConfigManager.minosPrimeExplosionSize.value; e.damage = (int)(e.damage * ConfigManager.minosPrimeExplosionDamage.value); } } public bool throwingProjectile = false; public string plannedAttack = ""; public bool explosionAttack = false; } class MinosPrime_Start { static void Postfix(MinosPrime __instance, Animator ___anim, ref bool ___enraged) { if (ConfigManager.minosPrimeEarlyPhaseToggle.value) ___enraged = true; __instance.gameObject.AddComponent<MinosPrimeFlag>(); if (ConfigManager.minosPrimeComboExplosionToggle.value) { AnimationClip boxing = ___anim.runtimeAnimatorController.animationClips.Where(item => item.name == "Boxing").First(); List<UnityEngine.AnimationEvent> boxingEvents = boxing.events.ToList(); boxingEvents.Insert(15, new UnityEngine.AnimationEvent() { time = 2.4f, functionName = "ComboExplosion", messageOptions = SendMessageOptions.RequireReceiver }); boxing.events = boxingEvents.ToArray(); } } } class MinosPrime_StopAction { static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return; if (flag.plannedAttack != "") { __instance.SendMessage(flag.plannedAttack); flag.plannedAttack = ""; } } } // aka JUDGEMENT class MinosPrime_Dropkick { static bool Prefix(MinosPrime __instance, EnemyIdentifier ___eid, ref bool ___inAction, Animator ___anim) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.throwingProjectile) { if (ConfigManager.minosPrimeExplosionToggle.value && UnityEngine.Random.Range(0, 99.9f) < ConfigManager.minosPrimeExplosionChance.value) { __instance.TeleportAnywhere(); ___inAction = true; flag.explosionAttack = true; ___anim.speed = ___eid.totalSpeedModifier * ConfigManager.minosPrimeExplosionWindupSpeed.value; ___anim.Play("Outro", 0, 0.5f); __instance.PlayVoice(new AudioClip[] { __instance.phaseChangeVoice }); return false; } if (ConfigManager.minosPrimeComboToggle.value) { flag.throwingProjectile = true; flag.plannedAttack = "Dropkick"; __instance.SendMessage("ProjectilePunch"); } return false; } else { if (ConfigManager.minosPrimeComboToggle.value) { flag.plannedAttack = "ProjectilePunch"; flag.throwingProjectile = false; } } return true; } } // aka PREPARE THYSELF class MinosPrime_Combo { static float timing = 3f; static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid) { if (!ConfigManager.minosPrimeComboToggle.value) return; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return; flag.plannedAttack = "Uppercut"; } } // aka DIE class MinosPrime_RiderKick { static bool Prefix(MinosPrime __instance, ref bool ___previouslyRiderKicked) { if (UnityEngine.Random.Range(0, 99.9f) > ConfigManager.minosPrimeCrushAttackChance.value) return true; ___previouslyRiderKicked = true; Vector3 vector = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.5f); Transform target = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); if (vector.y < target.position.y) { vector.y = target.position.y; } __instance.Teleport(vector + Vector3.up * 25f, __instance.transform.position); __instance.SendMessage("DropAttack"); return false; } } // End of PREPARE THYSELF class MinosPrime_ProjectileCharge { static bool Prefix(MinosPrime __instance, Animator ___anim) { string clipname = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name; if (clipname != "Combo" || UnityEngine.Random.Range(0, 99.9f) > ConfigManager.minosPrimeComboExplosiveEndChance.value) return true; ___anim.Play("Dropkick", 0, (1.0815f - 0.4279f) / 2.65f); return false; } } class MinosPrime_Ascend { static bool Prefix(MinosPrime __instance, EnemyIdentifier ___eid, Animator ___anim, ref bool ___vibrating) { if (___eid.health <= 0) return true; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.explosionAttack) return true; ___anim.speed = ___eid.totalSpeedModifier; ___vibrating = false; flag.explosionAttack = false; flag.BigExplosion(); __instance.Invoke("Uppercut", 0.5f); return false; } } class MinosPrime_Death { static bool Prefix(MinosPrime __instance, Animator ___anim, ref bool ___vibrating) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.explosionAttack) return true; flag.explosionAttack = false; ___vibrating = false; ___anim.speed = 1f; ___anim.Play("Walk", 0, 0f); return true; } } }
Ultrapain/Patches/MinosPrime.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " MonoSingleton<HookArm>.Instance.StopThrow(1f, true);\n __instance.transform.position = targetPosition;\n ___goingLeft = !___goingLeft;\n GameObject.Instantiate<GameObject>(__instance.teleportSound, __instance.transform.position, Quaternion.identity);\n GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.decoy, __instance.transform.GetChild(0).position, __instance.transform.GetChild(0).rotation);\n Animator componentInChildren = gameObject.GetComponentInChildren<Animator>();\n AnimatorStateInfo currentAnimatorStateInfo = ___anim.GetCurrentAnimatorStateInfo(0);\n componentInChildren.Play(currentAnimatorStateInfo.shortNameHash, 0, currentAnimatorStateInfo.normalizedTime);\n componentInChildren.speed = 0f;\n if (___enraged)", "score": 0.8478209972381592 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " flash.transform.LookAt(CameraController.Instance.transform);\n flash.transform.position += flash.transform.forward;\n flash.transform.Rotate(Vector3.up, 90, Space.Self);\n }\n }\n class StatueBoss_StopTracking_Patch\n {\n static void Postfix(StatueBoss __instance, Animator ___anim)\n {\n CerberusFlag flag = __instance.GetComponent<CerberusFlag>();", "score": 0.8366595506668091 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " /*for(int i = 0; i < 20; i++)\n {\n Quaternion randomRotation = Quaternion.LookRotation(MonoSingleton<PlayerTracker>.Instance.GetTarget().position - __instance.transform.position);\n randomRotation.eulerAngles += new Vector3(UnityEngine.Random.Range(-15.0f, 15.0f), UnityEngine.Random.Range(-15.0f, 15.0f), UnityEngine.Random.Range(-15.0f, 15.0f));\n Projectile componentInChildren = GameObject.Instantiate(Plugin.homingProjectile.gameObject, __instance.transform.position + __instance.transform.forward, randomRotation).GetComponentInChildren<Projectile>();\n Vector3 randomPos = __instance.tentacles[UnityEngine.Random.RandomRangeInt(0, __instance.tentacles.Length)].position;\n if (!Physics.Raycast(__instance.transform.position, randomPos - __instance.transform.position, Vector3.Distance(randomPos, __instance.transform.position), ___environmentMask))\n componentInChildren.transform.position = randomPos;\n componentInChildren.speed = 10f * ___eid.totalSpeedModifier * UnityEngine.Random.Range(0.5f, 1.5f);\n componentInChildren.turnSpeed *= UnityEngine.Random.Range(0.5f, 1.5f);", "score": 0.829796314239502 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": " return;\n GameObject createInsignia(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target)\n {\n GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.projectile, ___target.transform.position, Quaternion.identity);\n VirtueInsignia component = gameObject.GetComponent<VirtueInsignia>();\n component.target = MonoSingleton<PlayerTracker>.Instance.GetPlayer();\n component.parentDrone = __instance;\n component.hadParent = true;\n __instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear);\n if (__instance.enraged)", "score": 0.8296349048614502 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " Vector3 randomPos = __instance.tentacles[UnityEngine.Random.RandomRangeInt(0, __instance.tentacles.Length)].position;\n if (!Physics.Raycast(__instance.transform.position, randomPos - __instance.transform.position, Vector3.Distance(randomPos, __instance.transform.position), ___environmentMask))\n componentInChildren.transform.position = randomPos;\n int shotCount = ConfigManager.mindflayerShootAmount.value - counter.shotsLeft;\n componentInChildren.transform.position += componentInChildren.transform.forward * Mathf.Clamp(initialProjectileDistance + shotCount * distancePerProjShot, 0, maxProjDistance);\n componentInChildren.speed = ConfigManager.mindflayerShootInitialSpeed.value * ___eid.totalSpeedModifier;\n componentInChildren.turningSpeedMultiplier = ConfigManager.mindflayerShootTurnSpeed.value;\n componentInChildren.target = MonoSingleton<PlayerTracker>.Instance.GetTarget();\n componentInChildren.safeEnemyType = EnemyType.Mindflayer;\n componentInChildren.damage *= ___eid.totalDamageModifier;", "score": 0.828992486000061 } ]
csharp
Vector3 targetPosition) {
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/QuestGraphSaveUtility.cs", "retrieved_chunk": " var connectedPorts = Edges.Where(x => x.input.node != null).ToArray();\n Q.ResetNodeLinksGraph();\n foreach (NodeQuest currentNode in nodesInGraph)\n {\n currentNode.nextNode.Clear();\n }\n for (int i = 0; i < connectedPorts.Length; i++)\n {\n var outputNode = connectedPorts[i].output.node as NodeQuestGraph;\n var inputNode = connectedPorts[i].input.node as NodeQuestGraph;", "score": 0.8600341081619263 }, { "filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs", "retrieved_chunk": " {\n var tempNode = _targetGraphView.CreateNodeQuest(node.name, Vector2.zero, node.extraText, node.isFinal);\n //Load node variables\n tempNode.GUID = node.GUID;\n tempNode.extraText = node.extraText;\n tempNode.isFinal = node.isFinal;\n tempNode.RefreshPorts();\n if (node.nodeObjectives != null) {\n foreach (QuestObjective qObjective in node.nodeObjectives)\n {", "score": 0.842522382736206 }, { "filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs", "retrieved_chunk": " Q.nodeLinkData.Add(new Quest.NodeLinksGraph\n {\n baseNodeGUID = outputNode.GUID,\n portName = connectedPorts[i].output.portName,\n targetNodeGUID = inputNode.GUID\n });\n //Add to next node list\n NodeQuest baseNode = nodesInGraph.Find(n => n.GUID == outputNode.GUID);\n NodeQuest targetNode = nodesInGraph.Find(n => n.GUID == inputNode.GUID);\n if (targetNode != null && baseNode != null)", "score": 0.8371427655220032 }, { "filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs", "retrieved_chunk": " }\n //Remove edges\n Edges.Where(x => x.input.node == node).ToList().ForEach(edge => _targetGraphView.RemoveElement(edge));\n //Remove Node\n _targetGraphView.RemoveElement(node);\n }\n }\n private void LoadNodes(Quest Q)\n {\n foreach (var node in _cacheNodes)", "score": 0.8370901346206665 }, { "filename": "Editor/GraphEditor/QuestGraphSaveUtility.cs", "retrieved_chunk": " //CreateObjectives\n QuestObjectiveGraph objtemp = new QuestObjectiveGraph(qObjective.keyName, qObjective.maxItems, qObjective.actualItems,\n qObjective.description, qObjective.hiddenObjective, qObjective.autoExitOnCompleted);\n var deleteButton = new Button(clickEvent: () => _targetGraphView.removeQuestObjective(tempNode, objtemp))\n {\n text = \"x\"\n };\n objtemp.Add(deleteButton);\n var newBox = new Box();\n objtemp.Add(newBox);", "score": 0.8334746956825256 } ]
csharp
NodeQuestGraph nodes, QuestObjectiveGraph objective) {
using Magic.IndexedDb.Helpers; using Magic.IndexedDb.SchemaAnnotations; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Magic.IndexedDb.Models { public class MagicQuery<T> where T : class { public string SchemaName { get; } public List<string> JsonQueries { get; } public IndexedDbManager Manager { get; } public MagicQuery(string schemaName, IndexedDbManager manager) { Manager = manager; SchemaName = schemaName; JsonQueries = new List<string>(); } public List<
StoredMagicQuery> storedMagicQueries {
get; set; } = new List<StoredMagicQuery>(); public bool ResultsUnique { get; set; } = true; /// <summary> /// Return a list of items in which the items do not have to be unique. Therefore, you can get /// duplicate instances of an object depending on how you write your query. /// </summary> /// <param name="amount"></param> /// <returns></returns> public MagicQuery<T> ResultsNotUnique() { ResultsUnique = false; return this; } public MagicQuery<T> Take(int amount) { StoredMagicQuery smq = new StoredMagicQuery(); smq.Name = MagicQueryFunctions.Take; smq.IntValue = amount; storedMagicQueries.Add(smq); return this; } public MagicQuery<T> TakeLast(int amount) { StoredMagicQuery smq = new StoredMagicQuery(); smq.Name = MagicQueryFunctions.Take_Last; smq.IntValue = amount; storedMagicQueries.Add(smq); return this; } public MagicQuery<T> Skip(int amount) { StoredMagicQuery smq = new StoredMagicQuery(); smq.Name = MagicQueryFunctions.Skip; smq.IntValue = amount; storedMagicQueries.Add(smq); return this; } //public MagicQuery<T> Reverse() //{ // StoredMagicQuery smq = new StoredMagicQuery(); // smq.Name = MagicQueryFunctions.Reverse; // storedMagicQueries.Add(smq); // return this; //} // Not yet working private MagicQuery<T> First() { StoredMagicQuery smq = new StoredMagicQuery(); smq.Name = MagicQueryFunctions.First; storedMagicQueries.Add(smq); return this; } // Not yet working private MagicQuery<T> Last() { StoredMagicQuery smq = new StoredMagicQuery(); smq.Name = MagicQueryFunctions.Last; storedMagicQueries.Add(smq); return this; } public async Task<IEnumerable<T>> Execute() { return await Manager.WhereV2<T>(SchemaName, JsonQueries, this) ?? Enumerable.Empty<T>(); } public async Task<int> Count() { var result = await Manager.WhereV2<T>(SchemaName, JsonQueries, this); int num = result?.Count() ?? 0; return num; } // Not currently available in Dexie version 1,2, or 3 public MagicQuery<T> OrderBy(Expression<Func<T, object>> predicate) { var memberExpression = GetMemberExpressionFromLambda(predicate); var propertyInfo = memberExpression.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException("The expression must represent a single property access."); } var indexDbAttr = propertyInfo.GetCustomAttribute<MagicIndexAttribute>(); var uniqueIndexDbAttr = propertyInfo.GetCustomAttribute<MagicUniqueIndexAttribute>(); var primaryKeyDbAttr = propertyInfo.GetCustomAttribute<MagicPrimaryKeyAttribute>(); if (indexDbAttr == null && uniqueIndexDbAttr == null && primaryKeyDbAttr == null) { throw new ArgumentException("The selected property must have either MagicIndexAttribute, MagicUniqueIndexAttribute, or MagicPrimaryKeyAttribute."); } string? columnName = null; if (indexDbAttr != null) columnName = propertyInfo.GetPropertyColumnName<MagicIndexAttribute>(); else if (primaryKeyDbAttr != null) columnName = propertyInfo.GetPropertyColumnName<MagicPrimaryKeyAttribute>(); else if (uniqueIndexDbAttr != null) columnName = propertyInfo.GetPropertyColumnName<MagicUniqueIndexAttribute>(); StoredMagicQuery smq = new StoredMagicQuery(); smq.Name = MagicQueryFunctions.Order_By; smq.StringValue = columnName; storedMagicQueries.Add(smq); return this; } // Not currently available in Dexie version 1,2, or 3 public MagicQuery<T> OrderByDescending(Expression<Func<T, object>> predicate) { var memberExpression = GetMemberExpressionFromLambda(predicate); var propertyInfo = memberExpression.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException("The expression must represent a single property access."); } var indexDbAttr = propertyInfo.GetCustomAttribute<MagicIndexAttribute>(); var uniqueIndexDbAttr = propertyInfo.GetCustomAttribute<MagicUniqueIndexAttribute>(); var primaryKeyDbAttr = propertyInfo.GetCustomAttribute<MagicPrimaryKeyAttribute>(); if (indexDbAttr == null && uniqueIndexDbAttr == null && primaryKeyDbAttr == null) { throw new ArgumentException("The selected property must have either MagicIndexAttribute, MagicUniqueIndexAttribute, or MagicPrimaryKeyAttribute."); } string? columnName = null; if (indexDbAttr != null) columnName = propertyInfo.GetPropertyColumnName<MagicIndexAttribute>(); else if (primaryKeyDbAttr != null) columnName = propertyInfo.GetPropertyColumnName<MagicPrimaryKeyAttribute>(); else if (uniqueIndexDbAttr != null) columnName = propertyInfo.GetPropertyColumnName<MagicUniqueIndexAttribute>(); StoredMagicQuery smq = new StoredMagicQuery(); smq.Name = MagicQueryFunctions.Order_By_Descending; smq.StringValue = columnName; storedMagicQueries.Add(smq); return this; } #pragma warning disable CS0693 // Mark members as static private MemberExpression GetMemberExpressionFromLambda<T>(Expression<Func<T, object>> expression) #pragma warning restore CS0693 // Mark members as static { if (expression.Body is MemberExpression) { return (MemberExpression)expression.Body; } else if (expression.Body is UnaryExpression && ((UnaryExpression)expression.Body).Operand is MemberExpression) { return (MemberExpression)((UnaryExpression)expression.Body).Operand; } else { throw new ArgumentException("The expression must represent a single property access."); } } } }
Magic.IndexedDb/Models/MagicQuery.cs
magiccodingman-Magic.IndexedDb-a279d6d
[ { "filename": "Magic.IndexedDb/Factories/MagicDbFactory.cs", "retrieved_chunk": " readonly IJSRuntime _jsRuntime;\n readonly IServiceProvider _serviceProvider;\n readonly IDictionary<string, IndexedDbManager> _dbs = new Dictionary<string, IndexedDbManager>();\n //private IJSObjectReference _module;\n public MagicDbFactory(IServiceProvider serviceProvider, IJSRuntime jSRuntime)\n {\n _serviceProvider = serviceProvider;\n _jsRuntime = jSRuntime;\n }\n //public async Task<IndexedDbManager> CreateAsync(DbStore dbStore)", "score": 0.84514319896698 }, { "filename": "Magic.IndexedDb/IndexDbManager.cs", "retrieved_chunk": " {\n if (_module == null)\n {\n _module = await jsRuntime.InvokeAsync<IJSObjectReference>(\"import\", \"./_content/Magic.IndexedDb/magicDB.js\");\n }\n return _module;\n }\n public List<StoreSchema> Stores => _dbStore.StoreSchemas;\n public string CurrentVersion => _dbStore.Version;\n public string DbName => _dbStore.Name;", "score": 0.8342365026473999 }, { "filename": "Magic.IndexedDb/Models/StoreSchema.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class StoreSchema\n {\n public string Name { get; set; }", "score": 0.8325183391571045 }, { "filename": "Magic.IndexedDb/IndexDbManager.cs", "retrieved_chunk": " jsonQueryAdditions = Newtonsoft.Json.JsonConvert.SerializeObject(query.storedMagicQueries.ToArray());\n }\n var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>();\n IList<Dictionary<string, object>>? ListToConvert =\n await CallJavascript<IList<Dictionary<string, object>>>\n (IndexedDbFunctions.WHEREV2, trans, DbName, storeName, jsonQuery.ToArray(), jsonQueryAdditions!, query?.ResultsUnique!);\n var resultList = ConvertListToRecords<T>(ListToConvert, propertyMappings);\n return resultList;\n }\n catch (Exception jse)", "score": 0.8280378580093384 }, { "filename": "Magic.IndexedDb/Factories/MagicDbFactory.cs", "retrieved_chunk": "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Collections.Generic;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.JSInterop;\nnamespace Magic.IndexedDb\n{\n public class MagicDbFactory : IMagicDbFactory\n {", "score": 0.82802414894104 } ]
csharp
StoredMagicQuery> storedMagicQueries {
using HarmonyLib; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.ConstrainedExecution; using UnityEngine; namespace Ultrapain.Patches { class Drone_Start_Patch { static void Postfix(Drone __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Drone) return; __instance.gameObject.AddComponent<DroneFlag>(); } } class Drone_PlaySound_Patch { static FieldInfo antennaFlashField = typeof(Turret).GetField("antennaFlash", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); static ParticleSystem antennaFlash; public static Color defaultLineColor = new Color(1f, 0.44f, 0.74f); static bool Prefix(Drone __instance, EnemyIdentifier ___eid, AudioClip __0) { if (___eid.enemyType != EnemyType.Drone) return true; if(__0 == __instance.windUpSound) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; List<Tuple<DroneFlag.Firemode, float>> chances = new List<Tuple<DroneFlag.Firemode, float>>(); if (ConfigManager.droneProjectileToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.Projectile, ConfigManager.droneProjectileChance.value)); if (ConfigManager.droneExplosionBeamToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.Explosive, ConfigManager.droneExplosionBeamChance.value)); if (ConfigManager.droneSentryBeamToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.TurretBeam, ConfigManager.droneSentryBeamChance.value)); if (chances.Count == 0 || chances.Sum(item => item.Item2) <= 0) flag.currentMode = DroneFlag.Firemode.Projectile; else flag.currentMode = UnityUtils.GetRandomFloatWeightedItem(chances, item => item.Item2).Item1; if (flag.currentMode == DroneFlag.Firemode.Projectile) { flag.attackDelay = ConfigManager.droneProjectileDelay.value; return true; } else if (flag.currentMode == DroneFlag.Firemode.Explosive) { flag.attackDelay = ConfigManager.droneExplosionBeamDelay.value; GameObject chargeEffect = GameObject.Instantiate(Plugin.chargeEffect, __instance.transform); chargeEffect.transform.localPosition = new Vector3(0, 0, 0.8f); chargeEffect.transform.localScale = Vector3.zero; float duration = ConfigManager.droneExplosionBeamDelay.value / ___eid.totalSpeedModifier; RemoveOnTime remover = chargeEffect.AddComponent<RemoveOnTime>(); remover.time = duration; CommonLinearScaler scaler = chargeEffect.AddComponent<CommonLinearScaler>(); scaler.targetTransform = scaler.transform; scaler.scaleSpeed = 1f / duration; CommonAudioPitchScaler pitchScaler = chargeEffect.AddComponent<CommonAudioPitchScaler>(); pitchScaler.targetAud = chargeEffect.GetComponent<AudioSource>(); pitchScaler.scaleSpeed = 1f / duration; return false; } else if (flag.currentMode == DroneFlag.Firemode.TurretBeam) { flag.attackDelay = ConfigManager.droneSentryBeamDelay.value; if(ConfigManager.droneDrawSentryBeamLine.value) { flag.lr.enabled = true; flag.SetLineColor(ConfigManager.droneSentryBeamLineNormalColor.value); flag.Invoke("LineRendererColorToWarning", Mathf.Max(0.01f, (flag.attackDelay / ___eid.totalSpeedModifier) - ConfigManager.droneSentryBeamLineIndicatorDelay.value)); } if (flag.particleSystem == null) { if (antennaFlash == null) antennaFlash = (ParticleSystem)antennaFlashField.GetValue(Plugin.turret); flag.particleSystem = GameObject.Instantiate(antennaFlash, __instance.transform); flag.particleSystem.transform.localPosition = new Vector3(0, 0, 2); } flag.particleSystem.Play(); GameObject flash = GameObject.Instantiate(Plugin.turretFinalFlash, __instance.transform); GameObject.Destroy(flash.transform.Find("MuzzleFlash/muzzleflash").gameObject); return false; } } return true; } } class Drone_Shoot_Patch { static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if(flag == null || __instance.crashing) return true; DroneFlag.Firemode mode = flag.currentMode; if (mode == DroneFlag.Firemode.Projectile) return true; if (mode == DroneFlag.Firemode.Explosive) { GameObject beam = GameObject.Instantiate(Plugin.beam.gameObject, __instance.transform.position + __instance.transform.forward, __instance.transform.rotation); RevolverBeam revBeam = beam.GetComponent<RevolverBeam>(); revBeam.hitParticle = Plugin.shotgunGrenade.gameObject.GetComponent<Grenade>().explosion; revBeam.damage /= 2; revBeam.damage *= ___eid.totalDamageModifier; return false; } if(mode == DroneFlag.Firemode.TurretBeam) { GameObject turretBeam = GameObject.Instantiate(Plugin.turretBeam.gameObject, __instance.transform.position + __instance.transform.forward * 2f, __instance.transform.rotation); if (turretBeam.TryGetComponent<RevolverBeam>(out RevolverBeam revBeam)) { revBeam.damage = ConfigManager.droneSentryBeamDamage.value; revBeam.damage *= ___eid.totalDamageModifier; revBeam.alternateStartPoint = __instance.transform.position + __instance.transform.forward; revBeam.ignoreEnemyType = EnemyType.Drone; } flag.lr.enabled = false; return false; } Debug.LogError($"Drone fire mode in impossible state. Current value: {mode} : {(int)mode}"); return true; } } class Drone_Update { static void Postfix(Drone __instance,
EnemyIdentifier ___eid, ref float ___attackCooldown, int ___difficulty) {
if (___eid.enemyType != EnemyType.Drone) return; DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null || flag.attackDelay < 0) return; float attackSpeedDecay = (float)(___difficulty / 2); if (___difficulty == 1) { attackSpeedDecay = 0.75f; } else if (___difficulty == 0) { attackSpeedDecay = 0.5f; } attackSpeedDecay *= ___eid.totalSpeedModifier; float delay = flag.attackDelay / ___eid.totalSpeedModifier; __instance.CancelInvoke("Shoot"); __instance.Invoke("Shoot", delay); ___attackCooldown = UnityEngine.Random.Range(2f, 4f) + (flag.attackDelay - 0.75f) * attackSpeedDecay; flag.attackDelay = -1; } } class DroneFlag : MonoBehaviour { public enum Firemode : int { Projectile = 0, Explosive, TurretBeam } public ParticleSystem particleSystem; public LineRenderer lr; public Firemode currentMode = Firemode.Projectile; private static Firemode[] allModes = Enum.GetValues(typeof(Firemode)) as Firemode[]; static FieldInfo turretAimLine = typeof(Turret).GetField("aimLine", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); static Material whiteMat; public void Awake() { lr = gameObject.AddComponent<LineRenderer>(); lr.enabled = false; lr.receiveShadows = false; lr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; lr.startWidth = lr.endWidth = lr.widthMultiplier = 0.025f; if (whiteMat == null) whiteMat = ((LineRenderer)turretAimLine.GetValue(Plugin.turret)).material; lr.material = whiteMat; } public void SetLineColor(Color c) { Gradient gradient = new Gradient(); GradientColorKey[] array = new GradientColorKey[1]; array[0].color = c; GradientAlphaKey[] array2 = new GradientAlphaKey[1]; array2[0].alpha = 1f; gradient.SetKeys(array, array2); lr.colorGradient = gradient; } public void LineRendererColorToWarning() { SetLineColor(ConfigManager.droneSentryBeamLineWarningColor.value); } public float attackDelay = -1; public bool homingTowardsPlayer = false; Transform target; Rigidbody rb; private void Update() { if(homingTowardsPlayer) { if(target == null) target = PlayerTracker.Instance.GetTarget(); if (rb == null) rb = GetComponent<Rigidbody>(); Quaternion to = Quaternion.LookRotation(target.position/* + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity()*/ - transform.position); transform.rotation = Quaternion.RotateTowards(transform.rotation, to, Time.deltaTime * ConfigManager.droneHomeTurnSpeed.value); rb.velocity = transform.forward * rb.velocity.magnitude; } if(lr.enabled) { lr.SetPosition(0, transform.position); lr.SetPosition(1, transform.position + transform.forward * 1000); } } } class Drone_Death_Patch { static bool Prefix(Drone __instance, EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Drone || __instance.crashing) return true; DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; if (___eid.hitter == "heavypunch" || ___eid.hitter == "punch") return true; flag.homingTowardsPlayer = true; return true; } } class Drone_GetHurt_Patch { static bool Prefix(Drone __instance, EnemyIdentifier ___eid, bool ___parried) { if((___eid.hitter == "shotgunzone" || ___eid.hitter == "punch") && !___parried) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; flag.homingTowardsPlayer = false; } return true; } } }
Ultrapain/Patches/Drone.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": " ___usedAttacks += 1;\n if(___usedAttacks == 3)\n {\n __instance.Invoke(\"Enrage\", 3f / ___eid.totalSpeedModifier);\n }\n return false;\n }\n /*static void Postfix(Drone __instance, ref EnemyIdentifier ___eid, ref int ___difficulty, ref Transform ___target, bool __state)\n {\n if (!__state)", "score": 0.9026684761047363 }, { "filename": "Ultrapain/Patches/Panopticon.cs", "retrieved_chunk": " if (___fleshDroneCooldown < 1f)\n {\n ___fleshDroneCooldown = 1f;\n }\n return false;\n }\n }\n class Panopticon_HomingProjectileAttack\n {\n static void Postfix(FleshPrison __instance, EnemyIdentifier ___eid)", "score": 0.8860381841659546 }, { "filename": "Ultrapain/Patches/DruidKnight.cs", "retrieved_chunk": " return true;\n }\n public static float offset = 0.2f;\n static void Postfix(Drone __instance, bool ___exploded, bool __state)\n {\n if (__state)\n return;\n if (!___exploded || __instance.gameObject.GetComponent<Mandalore>() == null)\n return;\n GameObject obj = new GameObject();", "score": 0.882670521736145 }, { "filename": "Ultrapain/Patches/StreetCleaner.cs", "retrieved_chunk": " }\n static void Postfix(Streetcleaner __instance, ref float ___dodgeCooldown)\n {\n if(didDodge)\n ___dodgeCooldown = UnityEngine.Random.Range(0f, 1f);\n }\n }*/\n class BulletCheck_OnTriggerEnter_Patch\n {\n static void Postfix(BulletCheck __instance, Collider __0/*, EnemyIdentifier ___eid*/)", "score": 0.8743878602981567 }, { "filename": "Ultrapain/Patches/StreetCleaner.cs", "retrieved_chunk": " return true;\n }\n static void Postfix(Streetcleaner __instance, ref EnemyIdentifier ___eid)\n {\n if(__instance.IsInvoking(\"StartFire\") && cancelStartFireInvoke)\n {\n __instance.CancelInvoke(\"StartFire\");\n __instance.Invoke(\"StartFire\", 0.1f);\n }\n }", "score": 0.8720300197601318 } ]
csharp
EnemyIdentifier ___eid, ref float ___attackCooldown, int ___difficulty) {
using BepInEx; using BepInEx.Configuration; using Comfort.Common; using EFT; using LootingBots.Patch.Components; using LootingBots.Patch.Util; using LootingBots.Patch; using LootingBots.Brain; using DrakiaXYZ.BigBrain.Brains; using System.Collections.Generic; using HandbookClass = GClass2775; namespace LootingBots { [BepInPlugin(MOD_GUID, MOD_NAME, MOD_VERSION)] [BepInDependency("xyz.drakia.bigbrain", "0.1.4")] [BepInProcess("EscapeFromTarkov.exe")] public class LootingBots : BaseUnityPlugin { private const string MOD_GUID = "me.skwizzy.lootingbots"; private const string MOD_NAME = "LootingBots"; private const string MOD_VERSION = "1.1.2"; public const BotType SettingsDefaults = BotType.Scav | BotType.Pmc | BotType.Raider; // Loot Finder Settings public static ConfigEntry<BotType> CorpseLootingEnabled; public static ConfigEntry<BotType> ContainerLootingEnabled; public static ConfigEntry<BotType> LooseItemLootingEnabled; public static ConfigEntry<float> TimeToWaitBetweenLoot; public static ConfigEntry<float> DetectItemDistance; public static ConfigEntry<float> DetectContainerDistance; public static ConfigEntry<float> DetectCorpseDistance; public static ConfigEntry<bool> DebugLootNavigation; public static ConfigEntry<LogLevel> LootingLogLevels; public static
Log LootLog;
// Loot Settings public static ConfigEntry<bool> UseMarketPrices; public static ConfigEntry<bool> ValueFromMods; public static ConfigEntry<bool> CanStripAttachments; public static ConfigEntry<float> PMCLootThreshold; public static ConfigEntry<float> ScavLootThreshold; public static ConfigEntry<EquipmentType> PMCGearToEquip; public static ConfigEntry<EquipmentType> PMCGearToPickup; public static ConfigEntry<EquipmentType> ScavGearToEquip; public static ConfigEntry<EquipmentType> ScavGearToPickup; public static ConfigEntry<LogLevel> ItemAppraiserLogLevels; public static Log ItemAppraiserLog; public static ItemAppraiser ItemAppraiser = new ItemAppraiser(); public void LootFinderSettings() { CorpseLootingEnabled = Config.Bind( "Loot Finder", "Enable corpse looting", SettingsDefaults, new ConfigDescription( "Enables corpse looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 10 } ) ); DetectCorpseDistance = Config.Bind( "Loot Finder", "Detect corpse distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect a corpse", null, new ConfigurationManagerAttributes { Order = 9 } ) ); ContainerLootingEnabled = Config.Bind( "Loot Finder", "Enable container looting", SettingsDefaults, new ConfigDescription( "Enables container looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 8 } ) ); DetectContainerDistance = Config.Bind( "Loot Finder", "Detect container distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect a container", null, new ConfigurationManagerAttributes { Order = 7 } ) ); LooseItemLootingEnabled = Config.Bind( "Loot Finder", "Enable loose item looting", SettingsDefaults, new ConfigDescription( "Enables loose item looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 6 } ) ); DetectItemDistance = Config.Bind( "Loot Finder", "Detect item distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect an item", null, new ConfigurationManagerAttributes { Order = 5 } ) ); TimeToWaitBetweenLoot = Config.Bind( "Loot Finder", "Delay between looting", 15f, new ConfigDescription( "The amount of time the bot will wait after looting an container/item/corpse before trying to find the next nearest item/container/corpse", null, new ConfigurationManagerAttributes { Order = 2 } ) ); LootingLogLevels = Config.Bind( "Loot Finder", "Log Levels", LogLevel.Error | LogLevel.Info, new ConfigDescription( "Enable different levels of log messages to show in the logs", null, new ConfigurationManagerAttributes { Order = 1 } ) ); DebugLootNavigation = Config.Bind( "Loot Finder", "Debug: Show navigation points", false, new ConfigDescription( "Renders shperes where bots are trying to navigate when container looting. (Red): Container position. (Black): 'Optimized' container position. (Green): Calculated bot destination. (Blue): NavMesh corrected destination (where the bot will move).", null, new ConfigurationManagerAttributes { Order = 0 } ) ); } public void LootSettings() { UseMarketPrices = Config.Bind( "Loot Settings", "Use flea market prices", false, new ConfigDescription( "Bots will query more accurate ragfair prices to do item value checks. Will make a query to get ragfair prices when the client is first started", null, new ConfigurationManagerAttributes { Order = 10 } ) ); ValueFromMods = Config.Bind( "Loot Settings", "Calculate weapon value from attachments", true, new ConfigDescription( "Calculate weapon value by looking up each attachement. More accurate than just looking at the base weapon template but a slightly more expensive check", null, new ConfigurationManagerAttributes { Order = 9 } ) ); CanStripAttachments = Config.Bind( "Loot Settings", "Allow weapon attachment stripping", true, new ConfigDescription( "Allows bots to take the attachments off of a weapon if they are not able to pick the weapon up into their inventory", null, new ConfigurationManagerAttributes { Order = 8 } ) ); PMCLootThreshold = Config.Bind( "Loot Settings", "PMC: Loot value threshold", 12000f, new ConfigDescription( "PMC bots will only loot items that exceed the specified value in roubles", null, new ConfigurationManagerAttributes { Order = 6 } ) ); PMCGearToEquip = Config.Bind( "Loot Settings", "PMC: Allowed gear to equip", EquipmentType.All, new ConfigDescription( "The equipment a PMC bot is able to equip during raid", null, new ConfigurationManagerAttributes { Order = 5 } ) ); PMCGearToPickup = Config.Bind( "Loot Settings", "PMC: Allowed gear in bags", EquipmentType.All, new ConfigDescription( "The equipment a PMC bot is able to place in their backpack/rig", null, new ConfigurationManagerAttributes { Order = 4 } ) ); ScavLootThreshold = Config.Bind( "Loot Settings", "Scav: Loot value threshold", 5000f, new ConfigDescription( "All non-PMC bots will only loot items that exceed the specified value in roubles.", null, new ConfigurationManagerAttributes { Order = 3 } ) ); ScavGearToEquip = Config.Bind( "Loot Settings", "Scav: Allowed gear to equip", EquipmentType.All, new ConfigDescription( "The equipment a non-PMC bot is able to equip during raid", null, new ConfigurationManagerAttributes { Order = 2 } ) ); ScavGearToPickup = Config.Bind( "Loot Settings", "Scav: Allowed gear in bags", EquipmentType.All, new ConfigDescription( "The equipment a non-PMC bot is able to place in their backpack/rig", null, new ConfigurationManagerAttributes { Order = 1 } ) ); ItemAppraiserLogLevels = Config.Bind( "Loot Settings", "Log Levels", LogLevel.Error, new ConfigDescription( "Enables logs for the item apprasier that calcualtes the weapon values", null, new ConfigurationManagerAttributes { Order = 0 } ) ); } public void Awake() { LootFinderSettings(); LootSettings(); LootLog = new Log(Logger, LootingLogLevels); ItemAppraiserLog = new Log(Logger, ItemAppraiserLogLevels); new SettingsAndCachePatch().Enable(); new RemoveComponent().Enable(); BrainManager.RemoveLayer( "Utility peace", new List<string>() { "Assault", "ExUsec", "BossSanitar", "CursAssault", "PMC", "SectantWarrior" } ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "Assault", "BossSanitar", "CursAssault", "BossKojaniy", "SectantPriest", "FollowerGluharScout", "FollowerGluharProtect", "FollowerGluharAssault", "BossGluhar", "Fl_Zraychiy", "TagillaFollower", "FollowerSanitar", "FollowerBully", "BirdEye", "BigPipe", "Knight", "BossZryachiy", "Tagilla", "Killa", "BossSanitar", "BossBully" }, 2 ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "PMC", "ExUsec" }, 3 ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "SectantWarrior" }, 13 ); } public void Update() { bool shoultInitAppraiser = (!UseMarketPrices.Value && ItemAppraiser.HandbookData == null) || (UseMarketPrices.Value && !ItemAppraiser.MarketInitialized); // Initialize the itemAppraiser when the BE instance comes online if ( Singleton<ClientApplication<ISession>>.Instance != null && Singleton<HandbookClass>.Instance != null && shoultInitAppraiser ) { LootLog.LogInfo($"Initializing item appraiser"); ItemAppraiser.Init(); } } } }
LootingBots/LootingBots.cs
Skwizzy-SPT-LootingBots-76279a3
[ { "filename": "LootingBots/logics/FindLootLogic.cs", "retrieved_chunk": " {\n private readonly LootingBrain _lootingBrain;\n private readonly BotLog _log;\n private float DetectCorpseDistance\n {\n get { return Mathf.Pow(LootingBots.DetectCorpseDistance.Value, 2); }\n }\n private float DetectContainerDistance\n {\n get { return Mathf.Pow(LootingBots.DetectContainerDistance.Value, 2); }", "score": 0.8640635013580322 }, { "filename": "LootingBots/components/LootingBrain.cs", "retrieved_chunk": " public InventoryController InventoryController;\n // Current container that the bot will try to loot\n public LootableContainer ActiveContainer;\n // Current loose item that the bot will try to loot\n public LootItem ActiveItem;\n // Current corpse that the bot will try to loot\n public BotOwner ActiveCorpse;\n // Center of the loot object's collider used to help in navigation\n public Vector3 LootObjectCenter;\n // Collider.transform.position for the active lootable. Used in LOS checks to make sure bots dont loot through walls", "score": 0.8595101833343506 }, { "filename": "LootingBots/patches/SettingsAndCache.cs", "retrieved_chunk": " bool itemLootEnabled = LootingBots.LooseItemLootingEnabled.Value.IsBotEnabled(\n ___wildSpawnType_0\n );\n if (corpseLootEnabled || containerLootEnabled || itemLootEnabled)\n {\n __instance.FileSettings.Shoot.CHANCE_TO_CHANGE_WEAPON = 80;\n __instance.FileSettings.Shoot.CHANCE_TO_CHANGE_WEAPON_WITH_HELMET = 40;\n }\n }\n }", "score": 0.8498471975326538 }, { "filename": "LootingBots/patches/SettingsAndCache.cs", "retrieved_chunk": " ref BotDifficultySettingsClass __instance,\n ref WildSpawnType ___wildSpawnType_0\n )\n {\n bool corpseLootEnabled = LootingBots.CorpseLootingEnabled.Value.IsBotEnabled(\n ___wildSpawnType_0\n );\n bool containerLootEnabled = LootingBots.ContainerLootingEnabled.Value.IsBotEnabled(\n ___wildSpawnType_0\n );", "score": 0.8430108428001404 }, { "filename": "LootingBots/components/LootingBrain.cs", "retrieved_chunk": " public Vector3 LootObjectPosition;\n // Object ids that the bot has looted\n public List<string> IgnoredLootIds;\n // Object ids that were not able to be reached even though a valid path exists. Is cleared every 2 mins by default\n public List<string> NonNavigableLootIds;\n public BotStats Stats\n {\n get { return InventoryController.Stats; }\n }\n public bool IsBotLooting {", "score": 0.8428992629051208 } ]
csharp
Log LootLog;
using System; using System.ComponentModel; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace dev.kemomimi.TimelineExtension.CustomActivationTrack { [DisplayName("Custom Activation Clip")] [Serializable] public class CustomActivationClip : PlayableAsset, ITimelineClipAsset { [NonSerialized] public int TrackIndexPassingThrough; [NonSerialized] public int ClipIndexPassingThrough; [NonSerialized] public double StartTimingPassthrough; [NonSerialized] public double EndTimingPassthrough; [NonSerialized] public double DurationPassthrough; private
CustomActivationPlayableBehavior data = new ();
public ClipCaps clipCaps { get { return ClipCaps.None; } } public override Playable CreatePlayable(PlayableGraph graph, GameObject go) { data.TrackIndex = TrackIndexPassingThrough; data.ClipIndex = ClipIndexPassingThrough; data.StartTiming = StartTimingPassthrough; data.EndTiming = EndTimingPassthrough; data.Duration = DurationPassthrough; return ScriptPlayable<CustomActivationPlayableBehavior>.Create(graph, data); } } }
Assets/TimelineExtension/Scripts/CustomActivationTrack/CustomActivationClip.cs
nmxi-Unity_AbstractTimelineExtention-b518049
[ { "filename": "Assets/TimelineExtension/Scripts/CustomActivationTrack/CustomActivationTrack.cs", "retrieved_chunk": "using System;\nusing System.ComponentModel;\nusing System.Linq;\nusing UnityEngine;\nusing UnityEngine.Playables;\nusing UnityEngine.Timeline;\nnamespace dev.kemomimi.TimelineExtension.CustomActivationTrack\n{\n [TrackClipType(typeof(CustomActivationClip))]\n [TrackBindingType(typeof(GameObject))]", "score": 0.9026030898094177 }, { "filename": "Assets/TimelineExtension/Scripts/CustomActivationTrack/CustomActivationPlayableBehavior.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.Playables;\nusing UnityEngine.Timeline;\nnamespace dev.kemomimi.TimelineExtension.CustomActivationTrack\n{\n [Serializable]\n public class CustomActivationPlayableBehavior : PlayableBehaviour\n {", "score": 0.8983957767486572 }, { "filename": "Assets/TimelineExtension/Scripts/CustomActivationTrack/CustomActivationTrack.cs", "retrieved_chunk": " customActivationClip.TrackIndexPassingThrough = TrackIndex;\n customActivationClip.ClipIndexPassingThrough = i;\n customActivationClip.StartTimingPassthrough = clips[i].start;\n customActivationClip.EndTimingPassthrough = clips[i].end;\n customActivationClip.DurationPassthrough = clips[i].duration;\n }\n var playable = ScriptPlayable<CustomActivationMixerBehavior>.Create(graph, inputCount);\n var behaviour = playable.GetBehaviour();\n behaviour.Director = go.GetComponent<PlayableDirector>();\n behaviour.TrackBindingObject = (GameObject)go.GetComponent<PlayableDirector>().GetGenericBinding(this);", "score": 0.8920761942863464 }, { "filename": "Assets/TimelineExtension/Scripts/CustomActivationTrack/CustomActivationTrack.cs", "retrieved_chunk": " [DisplayName(\"Additional/Custom Activation Track\")]\n public class CustomActivationTrack : TrackAsset\n {\n [HideInInspector] public int TrackIndex;\n public override Playable CreateTrackMixer(PlayableGraph graph, GameObject go, int inputCount)\n {\n var clips = GetClips().ToArray();\n for (var i = 0; i < clips.Length; i++)\n {\n var customActivationClip = clips[i].asset as CustomActivationClip;", "score": 0.8840237855911255 }, { "filename": "Assets/TimelineExtension/Editor/CustomActivationTrackEditor/ActivationTrackConverter.cs", "retrieved_chunk": " var activationClips = track.GetClips().ToList();\n foreach (var activationClip in activationClips)\n {\n var customActivationClip = newCustomActivationTrack.CreateDefaultClip();\n customActivationClip.displayName = activationClip.displayName;\n customActivationClip.start = activationClip.start;\n customActivationClip.duration = activationClip.duration;\n }\n //get binding\n var binding = director.playableAsset.outputs.ToArray()[index].sourceObject;", "score": 0.8656726479530334 } ]
csharp
CustomActivationPlayableBehavior data = new ();
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/SisyphusInstructionist.cs", "retrieved_chunk": " }\n GameObject explosion = Object.Instantiate<GameObject>(Plugin.sisyphiusPrimeExplosion, vector, Quaternion.identity);\n foreach(Explosion exp in explosion.GetComponentsInChildren<Explosion>())\n {\n exp.enemy = true;\n exp.toIgnore.Add(EnemyType.Sisyphus);\n exp.maxSize *= ConfigManager.sisyInstStrongerExplosionSizeMulti.value;\n exp.speed *= ConfigManager.sisyInstStrongerExplosionSizeMulti.value * ___eid.totalSpeedModifier;\n exp.damage = (int)(exp.damage * ConfigManager.sisyInstStrongerExplosionDamageMulti.value * ___eid.totalDamageModifier);\n }", "score": 0.8727428317070007 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static BoolField sisyInstBoulderShockwave;\n public static FloatField sisyInstBoulderShockwaveSize;\n public static FloatField sisyInstBoulderShockwaveSpeed;\n public static IntField sisyInstBoulderShockwaveDamage;\n public static BoolField sisyInstJumpShockwave;\n public static FloatField sisyInstJumpShockwaveSize;\n public static FloatField sisyInstJumpShockwaveSpeed;\n public static IntField sisyInstJumpShockwaveDamage;\n public static BoolField sisyInstStrongerExplosion;\n public static FloatField sisyInstStrongerExplosionSizeMulti;", "score": 0.8664988875389099 }, { "filename": "Ultrapain/Patches/SisyphusInstructionist.cs", "retrieved_chunk": " esi.enraged = true;\n }\n GameObject effect = GameObject.Instantiate(Plugin.enrageEffect, __instance.transform);\n effect.transform.localScale = Vector3.one * 0.2f;\n }\n }*/\n public class SisyphusInstructionist_Start\n {\n public static GameObject _shockwave;\n public static GameObject shockwave", "score": 0.865073025226593 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static FloatField sisyInstStrongerExplosionDamageMulti;\n // ADD ME\n // LEVIATHAN\n public static BoolField leviathanSecondPhaseBegin;\n public static BoolField leviathanProjectileMixToggle;\n public static FloatSliderField leviathanProjectileBlueChance;\n public static FloatSliderField leviathanProjectileYellowChance;\n public static IntField leviathanProjectileCount;\n public static FloatField leviathanProjectileDensity;\n public static FloatSliderField leviathanProjectileFriendlyFireDamageMultiplier;", "score": 0.858353853225708 }, { "filename": "Ultrapain/Patches/SisyphusInstructionist.cs", "retrieved_chunk": " }\n public class SisyphusInstructionist_SetupExplosion\n {\n static void Postfix(Sisyphus __instance, ref GameObject __0, EnemyIdentifier ___eid)\n {\n GameObject shockwave = GameObject.Instantiate(Plugin.shockwave, __0.transform.position, __0.transform.rotation);\n PhysicalShockwave comp = shockwave.GetComponent<PhysicalShockwave>();\n comp.enemy = true;\n comp.enemyType = EnemyType.Sisyphus;\n comp.maxSize = 100f;", "score": 0.8532407283782959 } ]
csharp
GameObject sisyphusDestroyExplosion;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using CommunityToolkit.WinUI; using Microsoft.UI.Dispatching; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using Windows.Media.Devices; using wingman.Interfaces; namespace wingman.ViewModels { public class AudioInputControlViewModel : ObservableObject, IDisposable { private readonly
IMicrophoneDeviceService _microphoneDeviceService;
private readonly ISettingsService _settingsService; private List<MicrophoneDevice> _micDevices; private readonly DispatcherQueue _dispatcherQueue; private readonly TimeSpan _updateInterval = TimeSpan.FromMilliseconds(100); private readonly Stopwatch _stopwatch; private double _lastVolume; private List<string> _microphoneDeviceOptions = new List<string>(); private readonly EventHandler<double> _microphoneServiceVolumeChanged; private double _progressBarValue; public ICommand RefreshDevices { get; } private string _selectedMicrophoneDevice; private bool _disposed = false; private bool _disposing = false; public AudioInputControlViewModel(IMicrophoneDeviceService microphoneDeviceService, ISettingsService settingsService) { _microphoneDeviceService = microphoneDeviceService ?? throw new ArgumentNullException(nameof(microphoneDeviceService)); _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); _microphoneServiceVolumeChanged = async (sender, volume) => { if (!_disposing && !_disposed) await VolumeHandler(volume); }; _microphoneDeviceService.VolumeChanged += _microphoneServiceVolumeChanged; _dispatcherQueue = DispatcherQueue.GetForCurrentThread(); _stopwatch = Stopwatch.StartNew(); RefreshDevices = new RelayCommand(PopulateMicrophoneDeviceOptions); PopulateMicrophoneDeviceOptions(); var chooseForMe = MediaDevice.GetDefaultAudioCaptureId(AudioDeviceRole.Communications); if (!string.IsNullOrEmpty(chooseForMe)) { var chooser = _micDevices.FirstOrDefault(x => x.Info.Id.Equals(chooseForMe)); if (chooser != null) SelectedMicrophoneDevice = chooser.Name; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { _disposing = disposing; if (_disposed) return; if (disposing) { // Unsubscribe from event handlers if (_microphoneDeviceService != null) { _microphoneDeviceService.VolumeChanged -= _microphoneServiceVolumeChanged; } // Dispose of any disposable objects } _disposed = true; } private async Task VolumeHandler(double volume) { if (_disposing || _disposed) return; _lastVolume = volume; if (_stopwatch.Elapsed >= _updateInterval) { _stopwatch.Restart(); await _dispatcherQueue.EnqueueAsync(() => { ProgressBarValue = _lastVolume; }); } } private async void PopulateMicrophoneDeviceOptions() { _micDevices = new List<MicrophoneDevice>(); var devices = await _microphoneDeviceService.GetMicrophoneDevicesAsync(); if (devices == null || devices.Count == 0) return; foreach (MicrophoneDevice dev in devices) _micDevices.Add(dev); MicrophoneDeviceOptions = devices.Select(d => d.Name).ToList(); } public double ProgressBarValue { get => _progressBarValue; set => SetProperty(ref _progressBarValue, value); } public List<string> MicrophoneDeviceOptions { get => _microphoneDeviceOptions; set => SetProperty(ref _microphoneDeviceOptions, value); } public string SelectedMicrophoneDevice { get => _selectedMicrophoneDevice; set { if (value != _selectedMicrophoneDevice) { var newMic = _micDevices.Find(x => x.Name.Equals(value)); _microphoneDeviceService.SetMicrophoneDeviceAsync(newMic); SetProperty(ref _selectedMicrophoneDevice, value); } } } } }
ViewModels/AudioInputControlViewModel.cs
dannyr-git-wingman-41103f3
[ { "filename": "Services/MicrophoneDeviceService.cs", "retrieved_chunk": "using Windows.Media.Capture;\nusing Windows.Media.MediaProperties;\nusing Windows.Media.Render;\nusing Windows.Storage;\nusing wingman.Interfaces;\nusing WinRT;\nnamespace wingman.Services\n{\n public class MicrophoneDeviceService : IMicrophoneDeviceService, IDisposable\n {", "score": 0.9169120192527771 }, { "filename": "Views/Controls/AudioInputControl.xaml.cs", "retrieved_chunk": "using CommunityToolkit.Mvvm.DependencyInjection;\nusing Microsoft.UI.Xaml.Controls;\nusing wingman.ViewModels;\nnamespace wingman.Views\n{\n public sealed partial class AudioInputControl : UserControl\n {\n public AudioInputControl()\n {\n InitializeComponent();", "score": 0.9003229737281799 }, { "filename": "Interfaces/IMicrophoneDeviceService.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Windows.Devices.Enumeration;\nusing Windows.Storage;\nnamespace wingman.Interfaces\n{\n public interface IMicrophoneDeviceService\n {\n event EventHandler<double> VolumeChanged;", "score": 0.8851871490478516 }, { "filename": "Views/Controls/AudioInputControl.xaml.cs", "retrieved_chunk": " ViewModel = Ioc.Default.GetRequiredService<AudioInputControlViewModel>();\n DataContext=ViewModel;\n }\n public AudioInputControlViewModel ViewModel { get; }\n }\n}", "score": 0.883362889289856 }, { "filename": "ViewModels/OpenAIControlViewModel.cs", "retrieved_chunk": "using CommunityToolkit.Mvvm.ComponentModel;\nusing Microsoft.UI.Xaml;\nusing Microsoft.UI.Xaml.Controls.Primitives;\nusing System;\nusing wingman.Interfaces;\nusing wingman.Services;\nnamespace wingman.ViewModels\n{\n public class OpenAIControlViewModel : ObservableObject\n {", "score": 0.8768404722213745 } ]
csharp
IMicrophoneDeviceService _microphoneDeviceService;
using FayElf.Plugins.WeChat.OfficialAccount.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; 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-18 08:56:16 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.OfficialAccount { /// <summary> /// 模板消息操作类 /// </summary> public class Template { #region 构造器 /// <summary> /// 无参构造器 /// </summary> public Template() { this.Config = Config.Current; } /// <summary> /// 设置配置 /// </summary> /// <param name="config">配置</param> public Template(Config config) { this.Config = config; } #endregion #region 属性 /// <summary> /// 配置 /// </summary> public Config Config { get; set; } #endregion #region 方法 #region 设置所属行业 /// <summary> /// 设置所属行业 /// </summary> /// <param name="industry1">公众号模板消息所属行业编号</param> /// <param name="industry2">公众号模板消息所属行业编号</param> /// <returns></returns> public BaseResult SetIndustry(Industry industry1,Industry industry2) { 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/cgi-bin/template/api_set_industry?access_token={token.AccessToken}", BodyData = $@"{{""industry_id1"":""{(int)industry1}"",""industry_id2"":""{(int)industry2}""}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<BaseResult>(); } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取设置的行业信息 /* * { "primary_industry":{"first_class":"运输与仓储","second_class":"快递"}, "secondary_industry":{"first_class":"IT科技","second_class":"互联网|电子商务"} } */ /// <summary> /// 获取设置的行业信息 /// </summary> /// <returns></returns> public IndustryModelResult GetIndustry() { 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/cgi-bin/template/get_industry?access_token={token.AccessToken}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<IndustryModelResult>(); } else { return new IndustryModelResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获得模板ID /// <summary> /// 获得模板ID /// </summary> /// <param name="templateId">模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式</param> /// <returns></returns> public IndustryTemplateResult AddTemplate(string templateId) { 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/cgi-bin/template/api_add_template?access_token={token.AccessToken}", BodyData = $@"{{""template_id_short"":""{templateId}""}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<IndustryTemplateResult>(); } else { return new IndustryTemplateResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 获取模板列表 /// <summary> /// 获取模板列表 /// </summary> /// <returns></returns> public
IndustryTemplateListResult GetAllPrivateTemplate() {
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/cgi-bin/template/api_add_template?access_token={token.AccessToken}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<IndustryTemplateListResult>(); } else { return new IndustryTemplateListResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); } #endregion #region 删除模板 /// <summary> /// 删除模板 /// </summary> /// <param name="templateId">公众帐号下模板消息ID</param> /// <returns></returns> public Boolean DeletePrivateTemplate(string templateId) { var config = this.Config.GetConfig(WeChatType.Applets); var result = Common.Execute(config.AppID, config.AppSecret, token => { var response = HttpHelper.GetHtml(new HttpRequest { Method = HttpMethod.Post, Address = $"https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token={token.AccessToken}", BodyData = $@"{{""template_id"":""{templateId}""}}" }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<BaseResult>(); } else { return new BaseResult { ErrCode = 500, ErrMsg = "请求失败." }; } }); return result.ErrCode == 0; } #endregion #region 发送模板消息 /// <summary> /// 发送模板消息 /// </summary> /// <param name="data">发送数据</param> /// <returns></returns> public IndustryTemplateSendDataResult Send(IndustryTemplateSendData 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 = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token.AccessToken}", BodyData = data.ToJson() }); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return response.Html.JsonToObject<IndustryTemplateSendDataResult>(); } else { return new IndustryTemplateSendDataResult { ErrCode = 500, ErrMsg = "请求出错." }; } }); } #endregion #endregion } }
OfficialAccount/Template.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " ErrCode = 500,\n ErrMsg = \"请求失败.\"\n };\n }\n });\n }\n #endregion\n #region 获取私有模板列表\n /// <summary>\n /// 获取私有模板列表", "score": 0.8961714506149292 }, { "filename": "OfficialAccount/Model/IndustryTemplateListResult.cs", "retrieved_chunk": " public List<IndustryTemplateListModel> TemplateList { get; set; }\n #endregion\n #region 方法\n #endregion\n }\n /// <summary>\n /// 行业模板模型\n /// </summary>\n public class IndustryTemplateListModel\n {", "score": 0.8843298554420471 }, { "filename": "OfficialAccount/Model/IndustryTemplateListResult.cs", "retrieved_chunk": " /// 行业模板列表\n /// </summary>\n public class IndustryTemplateListResult:BaseResult\n {\n #region 构造器\n /// <summary>\n /// 无参构造器\n /// </summary>\n public IndustryTemplateListResult()\n {", "score": 0.8765944838523865 }, { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " /// </summary>\n /// <returns></returns>\n public TemplateResult GetTemplateList()\n {\n var config = this.Config.GetConfig(WeChatType.Applets);\n return Common.Execute(config.AppID, config.AppSecret, token =>\n {\n var response = HttpHelper.GetHtml(new HttpRequest\n {\n Method = HttpMethod.Get,", "score": 0.8706210255622864 }, { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " }\n });\n }\n #endregion\n #region 获取公众号类目\n /// <summary>\n /// 获取公众号类目\n /// </summary>\n /// <returns></returns>\n public TemplateCategoryResult GetCategory()", "score": 0.8674988746643066 } ]
csharp
IndustryTemplateListResult GetAllPrivateTemplate() {
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Messaging; using Microsoft.Toolkit.Uwp.Notifications; using SupernoteDesktopClient.Core; using SupernoteDesktopClient.Extensions; using SupernoteDesktopClient.Messages; using SupernoteDesktopClient.Services.Contracts; using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using Wpf.Ui.Common.Interfaces; namespace SupernoteDesktopClient.ViewModels { public partial class SyncViewModel : ObservableObject, INavigationAware { // services private readonly IMediaDeviceService _mediaDeviceService; private readonly ISyncService _syncService; [ObservableProperty] private bool _isDeviceConnected; [ObservableProperty] private bool _isSyncRunning; [ObservableProperty] private string _sourceFolder; [ObservableProperty] private string _backupFolder; [ObservableProperty] private string _lastBackupDateTime; [ObservableProperty] private ObservableCollection<Models.ArchiveFileAttributes> _archiveFiles; [ObservableProperty] private bool _archivesVisible; public void OnNavigatedTo() { DiagnosticLogger.Log($"{this}"); UpdateSync(); } public void OnNavigatedFrom() { } public SyncViewModel(
IMediaDeviceService mediaDeviceService, ISyncService syncService) {
// services _mediaDeviceService = mediaDeviceService; _syncService = syncService; // Register a message subscriber WeakReferenceMessenger.Default.Register<MediaDeviceChangedMessage>(this, (r, m) => { UpdateSync(m.Value); }); } [RelayCommand] private async Task ExecuteSync() { IsSyncRunning = true; await Task.Run(() => _syncService.Sync()); IsSyncRunning = false; UpdateSync(); } private void UpdateSync(DeviceInfo deviceInfo = null) { _mediaDeviceService.RefreshMediaDeviceInfo(); SourceFolder = _mediaDeviceService.SupernoteInfo.RootFolder; // Backup BackupFolder = _syncService.BackupFolder ?? "N/A"; // Last backup DateTime DateTime? lastBackupDateTime = FileSystemManager.GetFolderCreateDateTime(BackupFolder); LastBackupDateTime = (lastBackupDateTime != null) ? lastBackupDateTime.GetValueOrDefault().ToString("F") : "N/A"; // Archive ArchiveFiles = ArchiveManager.GetArchivesList(_syncService.ArchiveFolder); ArchivesVisible = ArchiveFiles.Count > 0; IsSyncRunning = _syncService.IsBusy; IsDeviceConnected = _mediaDeviceService.IsDeviceConnected; // auto sync on connect if (SettingsManager.Instance.Settings.Sync.AutomaticSyncOnConnect == true && deviceInfo?.IsConnected == true) { ExecuteSync().Await(); new ToastContentBuilder() .AddText("Automatic sync completed") .Show(); } } } }
ViewModels/SyncViewModel.cs
nelinory-SupernoteDesktopClient-e527602
[ { "filename": "ViewModels/DashboardViewModel.cs", "retrieved_chunk": " UpdateDashboard();\n RefreshUpdateStatus(false).Await();\n }\n public void OnNavigatedFrom()\n {\n }\n public DashboardViewModel(IMediaDeviceService mediaDeviceService)\n {\n // services\n _mediaDeviceService = mediaDeviceService;", "score": 0.9285742044448853 }, { "filename": "ViewModels/ExplorerViewModel.cs", "retrieved_chunk": " private bool _convertionInProgress = false;\n public void OnNavigatedTo()\n {\n DiagnosticLogger.Log($\"{this}\");\n LoadExplorer();\n }\n public void OnNavigatedFrom()\n {\n }\n public ExplorerViewModel(IMediaDeviceService mediaDeviceService)", "score": 0.9170498847961426 }, { "filename": "ViewModels/DashboardViewModel.cs", "retrieved_chunk": " private decimal _deviceUsedSpacePercentage;\n [ObservableProperty]\n private bool _isUpdateAvailable = false;\n [ObservableProperty]\n private string _updateMessage = String.Empty;\n [ObservableProperty]\n private string _updateDetails = String.Empty;\n public void OnNavigatedTo()\n {\n DiagnosticLogger.Log($\"{this}\");", "score": 0.890911877155304 }, { "filename": "ViewModels/AboutViewModel.cs", "retrieved_chunk": " private string _updateDetails = String.Empty;\n public void OnNavigatedTo()\n {\n DiagnosticLogger.Log($\"{this}\");\n RefreshUpdateStatus(false).Await();\n }\n public void OnNavigatedFrom()\n {\n }\n public AboutViewModel()", "score": 0.8884460926055908 }, { "filename": "Services/SyncService.cs", "retrieved_chunk": " // services\n private readonly IMediaDeviceService _mediaDeviceService;\n private const string BACKUP_FOLDER = \"Backup\";\n private const string ARCHIVE_FOLDER = \"Archive\";\n public bool IsBusy { get; private set; }\n public string SourceFolder { get { return _mediaDeviceService.SupernoteInfo.RootFolder; } }\n public string BackupFolder { get { return GetFolderByType(BACKUP_FOLDER); } }\n public string ArchiveFolder { get { return GetFolderByType(ARCHIVE_FOLDER); } }\n public SyncService(IMediaDeviceService mediaDeviceService)\n {", "score": 0.8666226267814636 } ]
csharp
IMediaDeviceService mediaDeviceService, ISyncService syncService) {
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Jamesnet.Wpf.Controls; using Jamesnet.Wpf.Mvvm; using Microsoft.Win32; using Newtonsoft.Json; using objective.Core; using objective.Core.Events; using objective.Forms.Local.Models; using objective.Models; using objective.SampleData; using Prism.Events; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Imaging; using System.Windows.Media; using objective.Forms.UI.Views; using System.Windows.Controls; namespace objective.Forms.Local.ViewModels { public partial class MainContentViewModel : ObservableBase, IViewLoadable { private FrameworkElement aaa; [ObservableProperty] private bool isLoad = false; [ObservableProperty] private ReportObject _selectedObject; [ObservableProperty] private List<ToolItem> _tools; [ObservableProperty] private ObservableCollection<
PageModel> pages;
[ObservableProperty] ObservableCollection<ReportObject> multiObject = new (); [ObservableProperty] private List<ToolItem> _subTools; private readonly IEventAggregator _eh; public MainContentViewModel(IEventAggregator eh) { _eh = eh; Tools = GetTools (); SubTools = GetSubTools (); this.Pages = new (); this._eh.GetEvent<ClosedEvent> ().Subscribe (() => { this.Save (); }); } public void OnLoaded(IViewable smartWindow) { aaa = smartWindow.View; Task.Run (() => { OpenFileDialog ofd = new (); ofd.InitialDirectory = Environment.CurrentDirectory; ofd.Filter = "objective files(*.objective) | *.objective"; ofd.Multiselect = false; if (ofd.ShowDialog () == false) { FilePath = Environment.CurrentDirectory; FileLoadName = "Default.objective"; string PullPath = $@"{FilePath}\{FileLoadName}"; File.Create ("Default.objective"); Application.Current.Dispatcher.Invoke (() => { GetReportSource (EncryptData.Base64); }, null); return; } this.FileLoad (ofd); }); } private string FilePath; private string FileLoadName; private void GetReportSource(string base64) { byte[] bytes = Convert.FromBase64String (base64); string json = Encoding.UTF8.GetString (bytes); var objs = JsonConvert.DeserializeObject<List<ReportModel>> (json); if(objs == null) { bytes = Convert.FromBase64String (EncryptData.Base64); json = Encoding.UTF8.GetString (bytes); objs = JsonConvert.DeserializeObject<List<ReportModel>> (json); } if (objs.Count > 0) { this.Pages.Clear (); IsLoad = true; } foreach (var obj in objs) { this.Pages.Add (new PageModel ()); } Task.Run (() => { Thread.Sleep (1000); Application.Current.Dispatcher.Invoke (() => { for (int i = 0; i < this.Pages.Count; i++) { this.Pages[i].SetReportSource (objs[i]); } IsLoad = false; }, null); }); } [RelayCommand] private void Load() { OpenFileDialog ofd = new (); ofd.InitialDirectory = Environment.CurrentDirectory; ofd.Filter = "objective files(*.objective) | *.objective"; ofd.Multiselect = false; if (ofd.ShowDialog () == false) return; this.FileLoad (ofd); } private void FileLoad(OpenFileDialog ofd) { FilePath = Path.GetDirectoryName (ofd.FileName); FileLoadName = Path.GetFileName (ofd.FileName); string line = null; using (var reader = new StreamReader (ofd.FileName)) { // 파일 내용 한 줄씩 읽기 line = reader.ReadToEnd (); } IsLoad = false; if (!String.IsNullOrWhiteSpace (FilePath)) Application.Current.Dispatcher.Invoke (() => { GetReportSource (line); }, null); } [RelayCommand] private void NewPage() { this.Pages.Add (new PageModel ()); } [RelayCommand] private void RemovePage() { if(this.Pages.Count == 1) { this.Pages[0].Clear (); return; } var lastPages = this.Pages.Last (); this.Pages.Remove (lastPages); } [RelayCommand] private void Save() { List<ReportModel> reportModels = new List<ReportModel> (); foreach (var page in Pages) { reportModels.Add (page.Save ()); } string json = JsonConvert.SerializeObject (reportModels); byte[] bytes = Encoding.UTF8.GetBytes (json); string base64 = Convert.ToBase64String (bytes); string PullPath = $@"{FilePath}\{FileLoadName}"; Clipboard.SetText (base64); using (StreamWriter sw =File.CreateText(PullPath)) { sw.Write (base64); } } private List<ToolItem> GetTools() { List<ToolItem> source = new (); source.Add (new ToolItem ("Page")); source.Add (new ToolItem ("RemovePage")); source.Add (new ToolItem ("Title")); source.Add (new ToolItem ("Table")); source.Add (new ToolItem ("Horizontal Line")); source.Add (new ToolItem ("Image")); return source; } private List<ToolItem> GetSubTools() { List<ToolItem> source = new (); source.Add (new ToolItem ("좌정렬")); source.Add (new ToolItem ("위정렬")); source.Add (new ToolItem ("가로길이동기화")); source.Add (new ToolItem ("초기화")); source.Add (new ToolItem ("세이브!")); return source; } [RelayCommand] private void SelectItem(ReportObject item) { SelectedObject = item; if(isPress == true) { if (item.GetType ().Name == "CellField" || item.GetType ().Name == "PageCanvas") return; this.MultiObject.Add (item); } } private bool isPress = false; [RelayCommand] private void MultiSelectItem(bool isPress) { this.isPress = isPress; } [RelayCommand] private void SubTool(ToolItem item) { if(item.Name == "초기화") this.MultiObject.Clear (); else if(item.Name=="좌정렬") { foreach(var obj in this.MultiObject.Skip(1).ToList()) { obj.SetLeft (this.MultiObject[0].GetProperties ().Left); } } else if (item.Name == "위정렬") { foreach (var obj in this.MultiObject.Skip (1).ToList ()) { obj.SetTop (this.MultiObject[0].GetProperties ().Top); } } else if(item.Name == "가로길이동기화") { var FirstTable = this.MultiObject.FirstOrDefault (x => x.GetType().Name == "Table"); if (FirstTable == null) return; var TableList = this.MultiObject.Where (x => x.GetType ().Name == "Table").ToList (); if (TableList.Count == 1) return; foreach (var obj in TableList.Skip (1).ToList ()) { obj.WidthSync (this.MultiObject[0].GetProperties ().Width); } } else if (item.Name == "세이브!") { //for(int i=0; i <100; i++) //{ // var aabbba = obj.GetValue (Control.NameProperty) as string; // if (String.IsNullOrEmpty (aabbba)) // continue; // Console.WriteLine (""); //} ////SaveImage (test, "aaa.jpeg"); } } private void SaveImage(FrameworkElement frameworkElement, string filePath) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap ( (int)frameworkElement.ActualWidth, (int)frameworkElement.ActualHeight, 96d, 96d, PixelFormats.Default ); renderTargetBitmap.Render (frameworkElement); using (Stream stream = new FileStream (filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { JpegBitmapEncoder encoder = new JpegBitmapEncoder (); encoder.Frames.Add (BitmapFrame.Create (renderTargetBitmap)); encoder.Save (stream); } } } }
objective/objective/objective.Forms/Local/ViewModels/MainContentViewModel.cs
jamesnet214-objective-0e60b6f
[ { "filename": "objective/objective/objective.Forms/Local/Models/PageModel.cs", "retrieved_chunk": "namespace objective.Forms.Local.Models\n{\n\t\tpublic partial class PageModel : ObservableBase\n\t\t{\n\t\t\t\t[ObservableProperty]\n\t\t\t\tprivate ObservableCollection<ReportObject> _reportSource;\n\t\t\t\tpublic PageModel()\n\t\t\t\t{\n\t\t\t\t\t\tthis.ReportSource = new ();\n\t\t\t\t}", "score": 0.8653706312179565 }, { "filename": "objective/objective/objective.Forms/UI/Units/PageCanvas.cs", "retrieved_chunk": " {\n public static readonly DependencyProperty SelectItemCommandProperty = DependencyProperty.Register(\"SelectItemCommand\", typeof(ICommand), typeof(PageCanvas), new PropertyMetadata(null));\n public static readonly DependencyProperty ReportDataProperty = DependencyProperty.Register(\"ReportData\", typeof(ObservableCollection<ReportObject>), typeof(PageCanvas), new PropertyMetadata(null, ReportDataPropertyChanged));\n private Canvas _canvas;\n public ICommand SelectItemCommand\n {\n get { return (ICommand)GetValue(SelectItemCommandProperty); }\n set { SetValue(SelectItemCommandProperty, value); }\n }\n public ObservableCollection<ReportObject> ReportData", "score": 0.8642199039459229 }, { "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.8507257699966431 }, { "filename": "objective/objective/objective.Core/ReportObject.cs", "retrieved_chunk": "using objective.Models;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\nnamespace objective.Core\n{\n public abstract class ReportObject : ContentControl\n {\n public abstract ReportObjectModel GetProperties();\n protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)", "score": 0.8166061639785767 }, { "filename": "objective/objective/objective.Core/Models/ReportModel.cs", "retrieved_chunk": "\t\t\t\tpublic List<ReportObjectModel> Objects { get; set; }\n\t\t}\n}", "score": 0.8157614469528198 } ]
csharp
PageModel> pages;
#nullable enable using System.Collections.Generic; using UnityEngine; namespace Mochineko.FacialExpressions.Blink { /// <summary> /// A simple implementation of <see cref="IEyelidMorpher"/> for <see cref="skinnedMeshRenderer"/>. /// </summary> public sealed class SkinnedMeshEyelidMorpher : IEyelidMorpher { private readonly SkinnedMeshRenderer skinnedMeshRenderer; private readonly IReadOnlyDictionary<
Eyelid, int> indexMap;
private readonly bool separateBoth; /// <summary> /// Creates a new instance of <see cref="SkinnedMeshEyelidMorpher"/>. /// </summary> /// <param name="skinnedMeshRenderer">Target renderer.</param> /// <param name="indexMap">Map of eyelid and blend shape index.</param> /// <param name="separateBoth">Whether separate both eyelids blend shape.</param> public SkinnedMeshEyelidMorpher( SkinnedMeshRenderer skinnedMeshRenderer, IReadOnlyDictionary<Eyelid, int> indexMap, bool separateBoth = false) { this.skinnedMeshRenderer = skinnedMeshRenderer; this.indexMap = indexMap; this.separateBoth = separateBoth; } public void MorphInto(EyelidSample sample) { if (separateBoth && sample.eyelid == Eyelid.Both) { if (indexMap.TryGetValue(Eyelid.Left, out var rightIndex)) { skinnedMeshRenderer.SetBlendShapeWeight(rightIndex, sample.weight * 100f); } if (indexMap.TryGetValue(Eyelid.Right, out var leftIndex)) { skinnedMeshRenderer.SetBlendShapeWeight(leftIndex, sample.weight * 100f); } } else if (indexMap.TryGetValue(sample.eyelid, out var index)) { skinnedMeshRenderer.SetBlendShapeWeight(index, sample.weight * 100f); } } public float GetWeightOf(Eyelid eyelid) { if (indexMap.TryGetValue(eyelid, 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/Blink/SkinnedMeshEyelidMorpher.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "filename": "Assets/Mochineko/FacialExpressions/LipSync/SkinnedMeshLipMorpher.cs", "retrieved_chunk": " private readonly SkinnedMeshRenderer skinnedMeshRenderer;\n private readonly IReadOnlyDictionary<Viseme, int> indexMap;\n /// <summary>\n /// Creates a new instance of <see cref=\"SkinnedMeshLipMorpher\"/>.\n /// </summary>\n /// <param name=\"skinnedMeshRenderer\">Target renderer.</param>\n /// <param name=\"indexMap\">Map of viseme to blend shape index.</param>\n public SkinnedMeshLipMorpher(\n SkinnedMeshRenderer skinnedMeshRenderer,\n IReadOnlyDictionary<Viseme, int> indexMap)", "score": 0.8951433300971985 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/AnimatorEyelidMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace Mochineko.FacialExpressions.Blink\n{\n /// <summary>\n /// A simple implementation of <see cref=\"IEyelidMorpher\"/> for <see cref=\"Animator\"/>.\n /// </summary>\n public sealed class AnimatorEyelidMorpher : IEyelidMorpher\n {", "score": 0.8936647772789001 }, { "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.8805459141731262 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/SkinnedMeshLipMorpher.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace Mochineko.FacialExpressions.LipSync\n{\n /// <summary>\n /// An implementation of <see cref=\"ILipMorpher\"/> to morph lip by <see cref=\"SkinnedMeshRenderer\"/>.\n /// </summary>\n public sealed class SkinnedMeshLipMorpher : ILipMorpher\n {", "score": 0.8796050548553467 }, { "filename": "Assets/Mochineko/FacialExpressions.Extensions/VRM/VRMEyelidMorpher.cs", "retrieved_chunk": " public sealed class VRMEyelidMorpher : IEyelidMorpher\n {\n private readonly Vrm10RuntimeExpression expression;\n private static readonly IReadOnlyDictionary<Eyelid, ExpressionKey> KeyMap\n = new Dictionary<Eyelid, ExpressionKey>\n {\n [Eyelid.Both] = ExpressionKey.Blink,\n [Eyelid.Left] = ExpressionKey.BlinkLeft,\n [Eyelid.Right] = ExpressionKey.BlinkRight,\n };", "score": 0.8677938580513 } ]
csharp
Eyelid, int> indexMap;
using HarmonyLib; using System.Security.Cryptography; using UnityEngine; namespace Ultrapain.Patches { class SwordsMachineFlag : MonoBehaviour { public SwordsMachine sm; public Animator anim; public EnemyIdentifier eid; public bool speedingUp = false; private void ResetAnimSpeed() { if(anim.GetCurrentAnimatorStateInfo(0).IsName("Knockdown")) { Invoke("ResetAnimSpeed", 0.01f); return; } Debug.Log("Resetting speed"); speedingUp = false; sm.SendMessage("SetSpeed"); } private void Awake() { anim = GetComponent<Animator>(); eid = GetComponent<EnemyIdentifier>(); } public float speed = 1f; private void Update() { if (speedingUp) { if (anim == null) { anim = sm.GetComponent<Animator>(); if (anim == null) { Destroy(this); return; } } anim.speed = speed; } } } class SwordsMachine_Start { static void Postfix(SwordsMachine __instance) { SwordsMachineFlag flag = __instance.gameObject.AddComponent<SwordsMachineFlag>(); flag.sm = __instance; } } class SwordsMachine_Knockdown_Patch { static bool Prefix(
SwordsMachine __instance, bool __0) {
__instance.Enrage(); if (!__0) __instance.SwordCatch(); return false; } } class SwordsMachine_Down_Patch { static bool Prefix(SwordsMachine __instance) { if (ConfigManager.swordsMachineSecondPhaseMode.value == ConfigManager.SwordsMachineSecondPhase.Skip && __instance.secondPhasePosTarget == null) return false; return true; } static void Postfix(SwordsMachine __instance, Animator ___anim, EnemyIdentifier ___eid) { if (ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.SpeedUp || __instance.secondPhasePosTarget != null) return; SwordsMachineFlag flag = __instance.GetComponent<SwordsMachineFlag>(); if (flag == null) { flag = __instance.gameObject.AddComponent<SwordsMachineFlag>(); flag.sm = __instance; } flag.speedingUp = true; flag.speed = (1f * ___eid.totalSpeedModifier) * ConfigManager.swordsMachineSecondPhaseSpeed.value; ___anim.speed = flag.speed; AnimatorClipInfo clipInfo = ___anim.GetCurrentAnimatorClipInfo(0)[0]; flag.Invoke("ResetAnimSpeed", clipInfo.clip.length / flag.speed); } } class SwordsMachine_EndFirstPhase_Patch { static bool Prefix(SwordsMachine __instance) { if (ConfigManager.swordsMachineSecondPhaseMode.value == ConfigManager.SwordsMachineSecondPhase.Skip && __instance.secondPhasePosTarget == null) return false; return true; } static void Postfix(SwordsMachine __instance, Animator ___anim, EnemyIdentifier ___eid) { if (ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.SpeedUp || __instance.secondPhasePosTarget != null) return; SwordsMachineFlag flag = __instance.GetComponent<SwordsMachineFlag>(); if (flag == null) { flag = __instance.gameObject.AddComponent<SwordsMachineFlag>(); flag.sm = __instance; } flag.speedingUp = true; flag.speed = (1f * ___eid.totalSpeedModifier) * ConfigManager.swordsMachineSecondPhaseSpeed.value; ___anim.speed = flag.speed; AnimatorClipInfo clipInfo = ___anim.GetCurrentAnimatorClipInfo(0)[0]; flag.Invoke("ResetAnimSpeed", clipInfo.clip.length / flag.speed); } } /*class SwordsMachine_SetSpeed_Patch { static bool Prefix(SwordsMachine __instance, ref Animator ___anim) { if (___anim == null) ___anim = __instance.GetComponent<Animator>(); SwordsMachineFlag flag = __instance.GetComponent<SwordsMachineFlag>(); if (flag == null || !flag.speedingUp) return true; return false; } }*/ /*[HarmonyPatch(typeof(SwordsMachine))] [HarmonyPatch("Down")] class SwordsMachine_Down_Patch { static void Postfix(SwordsMachine __instance, ref Animator ___anim, ref Machine ___mach) { ___anim.Play("Knockdown", 0, Plugin.SwordsMachineKnockdownTimeNormalized); __instance.CancelInvoke("CheckLoop"); ___mach.health = ___mach.symbiote.health; __instance.downed = false; } } [HarmonyPatch(typeof(SwordsMachine))] [HarmonyPatch("CheckLoop")] class SwordsMachine_CheckLoop_Patch { static bool Prefix(SwordsMachine __instance) { return false; } }*/ /*[HarmonyPatch(typeof(SwordsMachine))] [HarmonyPatch("ShootGun")] class SwordsMachine_ShootGun_Patch { static bool Prefix(SwordsMachine __instance) { if(UnityEngine.Random.RandomRangeInt(0, 2) == 1) { GameObject grn = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject, __instance.transform.position, __instance.transform.rotation); grn.transform.position += grn.transform.forward * 0.5f + grn.transform.up * 0.5f; Grenade grnComp = grn.GetComponent<Grenade>(); grnComp.enemy = true; grnComp.CanCollideWithPlayer(true); Vector3 playerPosition = MonoSingleton<PlayerTracker>.Instance.gameObject.transform.position; float distanceFromPlayer = Vector3.Distance(playerPosition, grn.transform.position); Vector3 predictedPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(distanceFromPlayer / 40); grn.transform.LookAt(predictedPosition); grn.GetComponent<Rigidbody>().maxAngularVelocity = 40; grn.GetComponent<Rigidbody>().velocity = grn.transform.forward * 40; return false; } return true; } }*/ class ThrownSword_Start_Patch { static void Postfix(ThrownSword __instance) { __instance.gameObject.AddComponent<ThrownSwordCollisionDetector>(); } } class ThrownSword_OnTriggerEnter_Patch { static void Postfix(ThrownSword __instance, Collider __0) { if (__0.gameObject.tag == "Player") { GameObject explosionObj = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject.GetComponent<Grenade>().explosion, __0.gameObject.transform.position, __0.gameObject.transform.rotation); foreach (Explosion explosion in explosionObj.GetComponentsInChildren<Explosion>()) { explosion.enemy = true; } } } } class ThrownSwordCollisionDetector : MonoBehaviour { public bool exploded = false; public void OnCollisionEnter(Collision other) { if (exploded) return; if (other.gameObject.layer != 24) { Debug.Log($"Hit layer {other.gameObject.layer}"); return; } exploded = true; GameObject explosionObj = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject.GetComponent<Grenade>().explosion, transform.position, transform.rotation); foreach (Explosion explosion in explosionObj.GetComponentsInChildren<Explosion>()) { explosion.enemy = true; explosion.damage = ConfigManager.swordsMachineExplosiveSwordDamage.value; explosion.maxSize *= ConfigManager.swordsMachineExplosiveSwordSize.value; explosion.speed *= ConfigManager.swordsMachineExplosiveSwordSize.value; } gameObject.GetComponent<ThrownSword>().Invoke("Return", 0.1f); } } }
Ultrapain/Patches/SwordsMachine.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/SisyphusInstructionist.cs", "retrieved_chunk": " public class SisyphusInstructionist_Knockdown_Patch\n {\n static void Postfix(Sisyphus __instance, ref EnemyIdentifier ___eid)\n {\n SisyphusInstructionistFlag flag = __instance.GetComponent<SisyphusInstructionistFlag>();\n if (flag != null)\n return;\n __instance.gameObject.AddComponent<SisyphusInstructionistFlag>();\n foreach(EnemySimplifier esi in UnityUtils.GetComponentsInChildrenRecursively<EnemySimplifier>(__instance.transform))\n {", "score": 0.8889347314834595 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " if (flag == null)\n return;\n if (___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name != \"Tackle\")\n return;\n flag.MakeParryable();\n }\n }\n class StatueBoss_Stomp_Patch\n {\n static void Postfix(StatueBoss __instance)", "score": 0.8852127194404602 }, { "filename": "Ultrapain/Patches/Screwdriver.cs", "retrieved_chunk": " if (!__instance.drill)\n return;\n DrillFlag flag = __instance.gameObject.AddComponent<DrillFlag>();\n flag.drill = __instance;\n }\n }\n class Harpoon_Punched\n {\n static void Postfix(Harpoon __instance, EnemyIdentifierIdentifier ___target)\n {", "score": 0.8851359486579895 }, { "filename": "Ultrapain/Patches/Solider.cs", "retrieved_chunk": " //counter.remainingShots = ConfigManager.soliderShootCount.value;\n }\n }\n class Grenade_Explode_Patch\n {\n static bool Prefix(Grenade __instance, out bool __state)\n {\n __state = false;\n SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>();\n if (flag == null)", "score": 0.8769786953926086 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " {\n CerberusFlag flag = __instance.GetComponent<CerberusFlag>();\n if (flag == null)\n return;\n flag.MakeParryable();\n }\n }\n class Statue_GetHurt_Patch\n {\n static bool Prefix(Statue __instance, EnemyIdentifier ___eid)", "score": 0.8763914704322815 } ]
csharp
SwordsMachine __instance, bool __0) {
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using WindowsHook; using wingman.Interfaces; using static wingman.Helpers.KeyConverter; namespace wingman.Services { public class KeyCombination { public Keys KeyCode { get; } public ModifierKeys Modifiers { get; } public KeyCombination OriginalRecord { get; } public KeyCombination(Keys keyCode, ModifierKeys modifiers) { KeyCode = keyCode; Modifiers = modifiers; OriginalRecord = null; } public KeyCombination(Keys keyCode, ModifierKeys modifiers, KeyCombination originalRecord) { KeyCode = keyCode; Modifiers = modifiers; OriginalRecord = originalRecord; } public override bool Equals(object obj) { return obj is KeyCombination other && KeyCode == other.KeyCode && Modifiers == other.Modifiers; } public static bool operator ==(KeyCombination left, KeyCombination right) { if (left is null) return right is null; return left.Equals(right); } public static bool operator !=(KeyCombination left, KeyCombination right) { return !(left == right); } public override int GetHashCode() { return HashCode.Combine(KeyCode, Modifiers); } } public enum HotkeyType { KeyDown, KeyUp } public class GlobalHotkeyService : IGlobalHotkeyService { private readonly IKeyboardMouseEvents _hook; private readonly Dictionary<
WingmanSettings, EventHandler> _hotkeyUpHandlers;
private readonly Dictionary<WingmanSettings, EventHandler> _hotkeyDownHandlers; private readonly ISettingsService _settingsService; private readonly Dictionary<HotkeyType, KeyCombination> _cachedValidHotkeys; private readonly HashSet<KeyCombination> _currentlyPressedCombinations; public GlobalHotkeyService(ISettingsService settingsService) { _hook = Hook.GlobalEvents(); _hotkeyUpHandlers = new Dictionary<WingmanSettings, EventHandler>(); _hotkeyDownHandlers = new Dictionary<WingmanSettings, EventHandler>(); _settingsService = settingsService; _currentlyPressedKeys = new HashSet<Keys>(); _cachedValidHotkeys = new Dictionary<HotkeyType, KeyCombination>(); _currentlyPressedCombinations = new HashSet<KeyCombination>(); _hook.KeyDown += Hook_KeyDown; _hook.KeyUp += Hook_KeyUp; } public void UpdateHotkeyCache() // could potentially speed up keyup/down events; not sure if it's worth it { foreach (var handlerEntry in _hotkeyUpHandlers) { WingmanSettings settingsKey = handlerEntry.Key; var hotkeyStr = _settingsService.Load<string>(settingsKey); var hotkeyCombination = ParseHotkeyCombination(hotkeyStr); _cachedValidHotkeys[HotkeyType.KeyUp] = hotkeyCombination; } foreach (var handlerEntry in _hotkeyDownHandlers) { WingmanSettings settingsKey = handlerEntry.Key; var hotkeyStr = _settingsService.Load<string>(settingsKey); var hotkeyCombination = ParseHotkeyCombination(hotkeyStr); _cachedValidHotkeys[HotkeyType.KeyDown] = hotkeyCombination; } } public void RegisterHotkeyUp(WingmanSettings settingsKey, EventHandler handler) { if (!_hotkeyUpHandlers.ContainsKey(settingsKey)) { _hotkeyUpHandlers[settingsKey] = null; } _hotkeyUpHandlers[settingsKey] += handler; } public void RegisterHotkeyDown(WingmanSettings settingsKey, EventHandler handler) { if (!_hotkeyDownHandlers.ContainsKey(settingsKey)) { _hotkeyDownHandlers[settingsKey] = null; } _hotkeyDownHandlers[settingsKey] += handler; } public void UnregisterHotkeyUp(WingmanSettings settingsKey, EventHandler handler) { if (_hotkeyUpHandlers.ContainsKey(settingsKey)) { _hotkeyUpHandlers[settingsKey] -= handler; } } public void UnregisterHotkeyDown(WingmanSettings settingsKey, EventHandler handler) { if (_hotkeyDownHandlers.ContainsKey(settingsKey)) { _hotkeyDownHandlers[settingsKey] -= handler; } } private void Hook_KeyDown(object sender, KeyEventArgs e) { if (!IsModifierKey(e.KeyCode)) { var currentModifiers = GetCurrentModifiers(e); var keyCombination = new KeyCombination(e.KeyCode, currentModifiers, new KeyCombination(e.KeyCode, currentModifiers)); _currentlyPressedCombinations.Add(keyCombination); if (HandleKeyEvent(keyCombination, _hotkeyDownHandlers)) { Console.WriteLine(String.Format("D: {0} has been handled with mods: {1}", e.KeyCode.ToString(), e.Modifiers.ToString())); e.Handled = true; } else { _currentlyPressedCombinations.Remove(keyCombination); } } else { // Ignore modifier keys by themselves } } private void Hook_KeyUp(object sender, KeyEventArgs e) { if (!IsModifierKey(e.KeyCode)) { var findPressed = _currentlyPressedCombinations.FirstOrDefault(x => x.KeyCode == e.KeyCode); if (findPressed == null) return; _currentlyPressedCombinations.Remove(findPressed); if (HandleKeyEvent(findPressed.OriginalRecord, _hotkeyUpHandlers)) { e.Handled = true; Debug.WriteLine(String.Format("UpX. {0} is handled.", e.KeyCode.ToString())); } } } // takes KeyCombination private bool HandleKeyEvent(KeyCombination pressed, Dictionary<WingmanSettings, EventHandler> handlers) { bool isHandled = false; foreach (var handlerEntry in handlers) { var settingsKey = handlerEntry.Key; var handler = handlerEntry.Value; var hotkeySettingString = _settingsService.Load<string>(settingsKey); var hotkeyCombo = ParseHotkeyCombination(hotkeySettingString); if (hotkeyCombo == pressed) { handler?.Invoke(this, EventArgs.Empty); isHandled = true; } } return isHandled; } private readonly Dictionary<string, Keys> specialKeysMap = new Dictionary<string, Keys> { { "`", Keys.Oem3 }, { ";", Keys.Oem1 }, { "=", Keys.Oemplus }, { ",", Keys.Oemcomma }, { "-", Keys.OemMinus }, { ".", Keys.OemPeriod }, { "/", Keys.Oem2 }, { "[", Keys.Oem4 }, { "\\", Keys.Oem5 }, { "]", Keys.Oem6 }, { "'", Keys.Oem7 } }; private KeyCombination ParseHotkeyCombination(string hotkeyCombination) { Keys newkey = Keys.None; ModifierKeys modifiers = ModifierKeys.None; if (hotkeyCombination.Length > 1 && hotkeyCombination.Contains('+')) { var keysAndModifiers = hotkeyCombination.Split("+"); var keystr = keysAndModifiers.TakeLast(1).Single().Trim(); Array.Resize(ref keysAndModifiers, keysAndModifiers.Length - 1); newkey = specialKeysMap.ContainsKey(keystr) ? specialKeysMap[keystr] : (Keys)Enum.Parse(typeof(Keys), keystr, ignoreCase: true); foreach (var modifier in keysAndModifiers) { // Check if the key is a modifier key if (modifier == "Alt") { modifiers |= ModifierKeys.Alt; } else if (modifier == "Ctrl") { modifiers |= ModifierKeys.Control; } else if (modifier == "Shift") { modifiers |= ModifierKeys.Shift; } else if (modifier == "Win") { modifiers |= ModifierKeys.Windows; } } } else { modifiers = ModifierKeys.None; newkey = specialKeysMap.ContainsKey(hotkeyCombination) ? specialKeysMap[hotkeyCombination] : (Keys)Enum.Parse(typeof(Keys), hotkeyCombination, ignoreCase: true); } // Create the key combination return new KeyCombination(newkey, modifiers); } private ModifierKeys GetCurrentModifiers(KeyEventArgs e) { ModifierKeys currentModifiers = ModifierKeys.None; if (e.Control) currentModifiers |= ModifierKeys.Control; if (e.Shift) currentModifiers |= ModifierKeys.Shift; if (e.Alt) currentModifiers |= ModifierKeys.Alt; return currentModifiers; } // Start of Hotkey Configuration Routines private Func<string, bool> _keyConfigurationCallback; private readonly HashSet<Keys> _currentlyPressedKeys; public async Task ConfigureHotkeyAsync(Func<string, bool> keyConfigurationCallback) { _currentlyPressedKeys.Clear(); _keyConfigurationCallback = keyConfigurationCallback; // Unregister the original KeyDown and KeyUp listeners. _hook.KeyDown -= Hook_KeyDown; _hook.KeyUp -= Hook_KeyUp; // Register the configuration KeyDown and KeyUp listeners. _hook.KeyDown += Hook_KeyDown_Configuration; _hook.KeyUp += Hook_KeyUp_Configuration; while (_keyConfigurationCallback != null) { await Task.Delay(500); } // Unregister the configuration KeyDown and KeyUp listeners. _hook.KeyDown -= Hook_KeyDown_Configuration; _hook.KeyUp -= Hook_KeyUp_Configuration; // Re-register the original KeyDown and KeyUp listeners. _hook.KeyDown += Hook_KeyDown; _hook.KeyUp += Hook_KeyUp; } private void Hook_KeyDown_Configuration(object sender, KeyEventArgs e) { if (!IsModifierKey(e.KeyCode)) { _currentlyPressedKeys.Add(e.KeyCode); } ModifierKeys currentModifiers = ModifierKeys.None; if (e.Control) currentModifiers |= ModifierKeys.Control; if (e.Shift) currentModifiers |= ModifierKeys.Shift; if (e.Alt) currentModifiers |= ModifierKeys.Alt; var otherModifiers = GetCurrentModifiers(e); if ((otherModifiers & ModifierKeys.Windows) != 0) currentModifiers |= ModifierKeys.Windows; if (!IsModifierKey(e.KeyCode)) { var hkstr = BuildHotkeyString(e); _keyConfigurationCallback?.Invoke(hkstr); _keyConfigurationCallback = null; e.Handled = true; } } private void Hook_KeyUp_Configuration(object sender, KeyEventArgs e) { _currentlyPressedKeys.Remove(e.KeyCode); } private bool IsModifierKey(Keys keyCode) { return keyCode == Keys.ControlKey || keyCode == Keys.ShiftKey || keyCode == Keys.Menu || keyCode == Keys.LMenu || keyCode == Keys.RMenu || keyCode == Keys.LShiftKey || keyCode == Keys.RShiftKey || keyCode == Keys.LControlKey || keyCode == Keys.RControlKey || keyCode == Keys.LWin || keyCode == Keys.RWin; } private string BuildHotkeyString(KeyEventArgs e) { List<string> keyParts = new List<string>(); if (e.Control) keyParts.Add("Ctrl"); if (e.Shift) keyParts.Add("Shift"); if (e.Alt) keyParts.Add("Alt"); var otherModifiers = GetCurrentModifiers(e); if ((otherModifiers & ModifierKeys.Windows) != 0) keyParts.Add("Win"); string mainKey = specialKeysMap.FirstOrDefault(x => x.Value == e.KeyCode).Key; if (string.IsNullOrEmpty(mainKey)) { mainKey = e.KeyCode.ToString(); } keyParts.Add(mainKey); return string.Join("+", keyParts); } } }
Services/GlobalHotkeyService.cs
dannyr-git-wingman-41103f3
[ { "filename": "Interfaces/IGlobalHotkeyService.cs", "retrieved_chunk": "using System;\nusing System.Threading.Tasks;\nusing wingman.Services;\nnamespace wingman.Interfaces\n{\n public interface IGlobalHotkeyService\n {\n Task ConfigureHotkeyAsync(Func<string, bool> keyConfigurationCallback);\n void RegisterHotkeyUp(WingmanSettings settingsKey, EventHandler handler);\n void RegisterHotkeyDown(WingmanSettings settingsKey, EventHandler handler);", "score": 0.9125128984451294 }, { "filename": "Services/EventHandlerService.cs", "retrieved_chunk": "namespace wingman.Services\n{\n public class EventHandlerService : IEventHandlerService, IDisposable\n {\n private readonly IGlobalHotkeyService globalHotkeyService;\n private readonly IMicrophoneDeviceService micService;\n private readonly IStdInService stdInService;\n private readonly ISettingsService settingsService;\n private readonly ILoggingService Logger;\n private readonly IWindowingService windowingService;", "score": 0.8688793182373047 }, { "filename": "ViewModels/OpenAIControlViewModel.cs", "retrieved_chunk": " private readonly ISettingsService _settingsService;\n private readonly IGlobalHotkeyService _globalHotkeyService;\n private readonly ILoggingService _logger;\n private string _apikey;\n private bool _keypressed;\n private string _mainhotkey;\n private string _modalhotkey;\n private string _purgatoryhotkey;\n private bool _trimwhitespaces;\n private bool _trimnewlines;", "score": 0.8629189133644104 }, { "filename": "Interfaces/IGlobalHotkeyService.cs", "retrieved_chunk": " void UnregisterHotkeyUp(WingmanSettings settingsKey, EventHandler handler);\n void UnregisterHotkeyDown(WingmanSettings settingsKey, EventHandler handler);\n }\n}", "score": 0.8625743389129639 }, { "filename": "Services/EventHandlerService.cs", "retrieved_chunk": " IStdInService stdInService,\n ISettingsService settingsService,\n ILoggingService loggingService,\n IWindowingService windowingService\n )\n {\n this.globalHotkeyService = globalHotkeyService;\n this.micService = micService;\n this.stdInService = stdInService;\n this.settingsService = settingsService;", "score": 0.8524729013442993 } ]
csharp
WingmanSettings, EventHandler> _hotkeyUpHandlers;
using System; using System.Collections.Generic; using TMPro; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEngine; using UnityEngine.Profiling; using UnityEngine.Rendering; using UnityEngine.TextCore; using static ZimGui.Core.MathHelper; namespace ZimGui.Core { public sealed unsafe class UiMesh : IDisposable { public readonly Mesh Mesh; readonly Material _material; Material _textureMaterial; MaterialPropertyBlock _materialPropertyBlock; List<Texture> _textures; int _textureLength => _textures?.Count ?? 0; UnsafeList<Quad> _textureQuads; static int _textureShaderPropertyId = Shader.PropertyToID("_MainTex"); public void SetUpForTexture(Material material, int capacity) { _textureMaterial = material; _materialPropertyBlock = new MaterialPropertyBlock(); _textures = new List<Texture>(capacity); _textureQuads = new UnsafeList<Quad>(capacity, Allocator.Persistent); } public void AddTexture(Rect rect, Texture texture) { _textures.Add(texture); EnsureNextTextureQuadCapacity(); var last = _textureQuads.Length; _textureQuads.Length = last + 1; Quad.WriteWithOutUV(ref _textureQuads.Ptr[last], new Vector2(rect.width, rect.height), new Vector2(rect.xMin, rect.yMin), new UiColor(255, 255, 255, 255)); } public void AddTexture(Rect rect, Texture texture, UiColor color) { _textures.Add(texture); EnsureNextTextureQuadCapacity(); var last = _textureQuads.Length; _textureQuads.Length = last + 1; Quad.WriteWithOutUV(ref _textureQuads.Ptr[last], new Vector2(rect.width, -rect.height), new Vector2(rect.xMin, rect.yMax), color); } void EnsureTextureCapacity(int capacity) { if (_textureQuads.Capacity >= capacity) return; capacity = MathHelper.CeilPow2(capacity); _textureQuads.SetCapacity(capacity); } void EnsureNextTextureQuadCapacity() { var capacity = _textureQuads.Length + 1; if (_textureQuads.Capacity >= capacity) return; capacity = CeilPow2(capacity); _textureQuads.SetCapacity(capacity); } UnsafeList<Quad> _quads; UnsafeList<uint> _indices; public readonly float PointSize; public readonly float LineHeight; // public readonly float BoldSpacing; // public readonly float BoldStyle; // public readonly float NormalStyle; // public readonly float NormalSpacingOffset; public int Length { get => _quads.Length; set { EnsureCapacity(value); _quads.Length = value; } } public readonly Texture2D Texture; public readonly Vector2 InvUvScale; public FixedCharMap<CharInfo> Map; public NativeArray<Quad> ReadQuads() => _quads.AsArray(); public Span<Quad> ReadQuadsSpan() => _quads.AsSpan(); public Span<Quad> ReadAdditionalQuadSpan(int length) { var start = _quads.Length; EnsureCapacity(_quads.Length + length); _quads.Length += length; return _quads.AsSpan()[start..]; } public ref Quad ReadAdditionalQuad() { var start = _quads.Length; EnsureCapacity(_quads.Length + 1); _quads.Length += 1; return ref _quads.Ptr[start]; } public void Swap(int start, int middle, int end) { NativeCollectionsExtensions.Swap(_quads.Ptr + start, (middle - start) * sizeof(Quad), (end - middle) * sizeof(Quad)); } public NativeArray<Quad> ReadAdditionalQuadNativeArray(int length) { var start = _quads.Length; EnsureCapacity(_quads.Length + length); _quads.Length += length; return _quads.AsArray().GetSubArray(start, Length); } public void EnsureCapacity(int capacity) { if (_quads.Capacity >= capacity) return; capacity = MathHelper.CeilPow2(capacity); _quads.SetCapacity(capacity); } public readonly Vector2 CircleCenter; public readonly Vector4 CircleUV; public readonly float SpaceXAdvance; const char circle = '\u25CF'; //● public static byte[] CreateAsset(TMP_FontAsset fontAsset) { var texture = (Texture2D) fontAsset.material.mainTexture; var textureWidth = texture.width; var textureHeight = (float) texture.height; var charList = fontAsset.characterTable; var length = charList.Count; var map = new FixedCharMap<CharInfo>(length + 3); var faceInfo = fontAsset.faceInfo; var scale = faceInfo.scale; var pointSize = faceInfo.pointSize / scale; var lineHeight = fontAsset.faceInfo.lineHeight / pointSize; var padding = fontAsset.atlasPadding; if (charList == null) { throw new NullReferenceException("characterTable is null"); } foreach (var tmp_character in charList) { var unicode = tmp_character.unicode; var glyph = tmp_character.glyph; var info = new CharInfo(glyph, textureWidth, textureHeight, pointSize, padding); map[(ushort) unicode] = info; } var bytes = new byte[8 + map.ByteLength]; var span = bytes.AsSpan(); var offset = 0; span.Write(ref offset,pointSize); span.Write(ref offset, lineHeight); map.Serialize(span, ref offset); return bytes; } public UiMesh(ReadOnlySpan<byte> data, Texture2D texture, Material material, int capacity = 512) { Texture = texture; material.mainTexture = texture; _material = material; var offset = 0; PointSize =data.ReadSingle(ref offset); LineHeight = data.ReadSingle(ref offset); InvUvScale = new Vector2(texture.width, texture.height) / PointSize; Map = new FixedCharMap<CharInfo>(data[offset..]); if (Map.TryGetValue(circle, out var info)) { var uv = CircleUV = info.UV; CircleCenter = new Vector2(uv.z + uv.x / 2, uv.w + uv.y / 2); } else { throw new NotSupportedException("● \\u25CF is needed."); } SpaceXAdvance = Map[' '].XAdvance; Mesh = new Mesh() { indexFormat = IndexFormat.UInt32 }; Mesh.MarkDynamic(); _quads = new UnsafeList<Quad>(capacity, Allocator.Persistent); var indices = new UnsafeList<uint>(capacity * 4, Allocator.Persistent); for (int i = 0; i < capacity * 4; i++) { indices.AddNoResize((uint) i); } _indices = indices; } public UiMesh(TMP_FontAsset fontAsset, Material material, int capacity = 512) { if (fontAsset == null) { throw new NullReferenceException("fontAsset is null."); } if (material == null) { throw new NullReferenceException("material is null."); } if (fontAsset.sourceFontFile != null) { throw new NotSupportedException("Dynamic font is not supported."); } try { Texture = (Texture2D) fontAsset.material.mainTexture; } catch (Exception) { throw new NotSupportedException("mainTexture is needed."); } _material = material; _material.mainTexture = Texture; // BoldSpacing = fontAsset.boldSpacing; // BoldStyle = fontAsset.boldStyle; // NormalStyle = fontAsset.normalStyle; // NormalSpacingOffset = fontAsset.normalSpacingOffset; var textureWidth = Texture.width; var textureHeight = (float) Texture.height; var charList = fontAsset.characterTable; var length = charList.Count; Map = new FixedCharMap<CharInfo>(length + 3); var faceInfo = fontAsset.faceInfo; var scale = faceInfo.scale; var tabWidth = faceInfo.tabWidth; PointSize = faceInfo.pointSize / scale; LineHeight = fontAsset.faceInfo.lineHeight / PointSize; var padding = fontAsset.atlasPadding; CharInfo info; if (charList == null) { throw new NullReferenceException("characterTable is null"); } foreach (var tmp_character in charList) { var unicode = tmp_character.unicode; var glyph = tmp_character.glyph; info = new CharInfo(glyph, textureWidth, textureHeight, PointSize, padding); Map[(ushort) unicode] = info; } if (Map.TryGetValue(' ', out info)) { SpaceXAdvance = info.XAdvance; Map[9] = new CharInfo(4 * SpaceXAdvance, 0, 0); } else { SpaceXAdvance = tabWidth / PointSize; Map[9] = new CharInfo(4 * SpaceXAdvance, 0, 0); } if (Map.TryGetValue(circle, out info)) { var uv = CircleUV = info.UV; CircleCenter = new Vector2(uv.z + uv.x / 2, uv.w + uv.y / 2); } else { throw new NotSupportedException("● \\u25CF is needed."); } Map.DefaultIndex = Map.GetEntryIndex(circle); Mesh = new Mesh() { indexFormat = IndexFormat.UInt32 }; Mesh.MarkDynamic(); _quads = new UnsafeList<Quad>(capacity, Allocator.Persistent); var indices = new UnsafeList<uint>(capacity * 4, Allocator.Persistent); for (int i = 0; i < capacity * 4; i++) { indices.AddNoResize((uint) i); } _indices = indices; InvUvScale = new Vector2(textureWidth, textureHeight) / PointSize; } void CheckAddLength(int length) { var nextQuadLength = (_quads.Length + length); if (_quads.Capacity >= nextQuadLength) return; nextQuadLength = MathHelper.CeilPow2(nextQuadLength); _quads.SetCapacity(nextQuadLength); } public void AddDefault() { CheckAddLength(1); ; var last = _quads.Length; _quads.Resize(last + 1, NativeArrayOptions.ClearMemory); } public void Advance() { CheckAddLength(1); ; _quads.Length += 1; } public void AdvanceUnsafe() { _quads.Length += 1; } public void Add(ref Quad quad) { CheckAddLength(1); ; var last = _quads.Length; _quads.Resize(last + 1); _quads[last] = quad; } public void AddRange(ReadOnlySpan<Quad> quads) { CheckAddLength(quads.Length); var last = _quads.Length; _quads.Length += quads.Length; quads.CopyTo(_quads.AsSpan()[last..]); } public void AddRange(
Quad* ptr, int count) {
CheckAddLength(count); _quads.AddRange(ptr, count); } public ref Quad Next() { var last = _quads.Length; if (_quads.Capacity <= last + 1) EnsureCapacity(last + 1); _quads.Length = last + 1; return ref _quads.Ptr[last]; } public const float Sqrt3 =1.732050807f; public void AddInvertedTriangle(Vector2 center,float height, UiColor color) { ref var quad = ref Next(); quad.V3.Position.x = center.x; quad.V0.Position.x = center.x-height/Sqrt3; quad.V2.Position.y= quad.V0.Position.y = center.y+height/3; quad.V2.Position.x = center.x+height/Sqrt3; quad.V3.Position.y = center.y-height*2/3; quad.V3.Color = quad.V2.Color = quad.V0.Color = color; quad.V3.Options.Size = quad.V2.Options.Size = quad.V0.Options.Size = 255; quad.V3.UV = quad.V2.UV = quad.V0.UV = CircleCenter; quad.V1 = quad.V0; } public void AddRightPointingTriangle(Vector2 center,float height, UiColor color) { ref var quad = ref Next(); quad.V3.Position.y = center.y; quad.V0.Position.y = center.y-height/Sqrt3; quad.V2.Position.x= quad.V0.Position.x = center.x-height/3; quad.V2.Position.y = center.y+height/Sqrt3; quad.V3.Position.x = center.x+height*2/3; quad.V3.Color = quad.V2.Color = quad.V0.Color = color; quad.V3.Options.Size = quad.V2.Options.Size = quad.V0.Options.Size = 255; quad.V3.UV = quad.V2.UV = quad.V0.UV = CircleCenter; quad.V1 = quad.V0; } public void AddTriangle(Vector2 a, Vector2 b, Vector2 c, UiColor color) { ref var quad = ref Next(); quad.V0.Position =a; quad.V2.Position= b; quad.V3.Position = c; quad.V3.Color = quad.V2.Color = quad.V0.Color = color; quad.V3.Options.Size = quad.V2.Options.Size = quad.V0.Options.Size = 255; quad.V3.UV = quad.V2.UV = quad.V0.UV = CircleCenter; quad.V1 = quad.V0; } public void AddBottomRightTriangle(Rect rect, UiColor color) { CheckAddLength(1); var last = _quads.Length; _quads.Length = last + 1; ref var quad = ref _quads.Ptr[last]; ref var v0 = ref quad.V0; v0.Position = rect.min; v0.Color = color; v0.UV = CircleCenter; v0.Options.Size = 255; quad.V1 = quad.V2 = quad.V3 = v0; quad.V1.Position.y = rect.yMax; quad.V2.Position.x = quad.V1.Position.x = rect.xMax; quad.V2.Position.y = rect.yMin; } public void AddRect(Rect rect, UiColor color) { var last = _quads.Length; if (_quads.Capacity <= last + 1) EnsureCapacity(last + 1); _quads.Length = last + 1; ref var quad = ref _quads.Ptr[last]; quad.V3.Position.x = quad.V0.Position.x = rect.xMin; quad.V1.Position.y = quad.V0.Position.y = rect.yMax; quad.V2.Position.x = quad.V1.Position.x = rect.xMax; quad.V3.Position.y = quad.V2.Position.y = rect.yMin; quad.V3.Color = quad.V2.Color = quad.V1.Color = quad.V0.Color = color; quad.V3.Options.Size = quad.V2.Options.Size = quad.V1.Options.Size = quad.V0.Options.Size = 255; quad.V3.UV = quad.V2.UV = quad.V1.UV = quad.V0.UV = CircleCenter; } public void AddRect(Rect rect, float width, UiColor backColor, UiColor frontColor) { var last = _quads.Length; if (_quads.Capacity <= last + 2) EnsureCapacity(last + 2); _quads.Length = last + 2; ref var quad1 = ref _quads.Ptr[last]; ref var quad2 = ref _quads.Ptr[last + 1]; quad1.V3.Position.x = quad1.V0.Position.x = rect.xMin; quad2.V3.Position.x = quad2.V0.Position.x = rect.xMin + width; quad1.V1.Position.y = quad1.V0.Position.y = rect.yMax; quad2.V1.Position.y = quad2.V0.Position.y = rect.yMax - width; quad1.V2.Position.x = quad1.V1.Position.x = rect.xMax; quad2.V2.Position.x = quad2.V1.Position.x = rect.xMax - width; quad1.V3.Position.y = quad1.V2.Position.y = rect.yMin; quad2.V3.Position.y = quad2.V2.Position.y = rect.yMin + width; quad1.V3.Color = quad1.V2.Color = quad1.V1.Color = quad1.V0.Color = backColor; quad2.V3.Color = quad2.V2.Color = quad2.V1.Color = quad2.V0.Color = frontColor; quad2.V3.Options.Size = quad2.V2.Options.Size = quad2.V1.Options.Size = quad2.V0.Options.Size = quad1.V3.Options.Size = quad1.V2.Options.Size = quad1.V1.Options.Size = quad1.V0.Options.Size = 255; quad2.V3.UV = quad2.V2.UV = quad2.V1.UV = quad2.V0.UV = quad1.V3.UV = quad1.V2.UV = quad1.V1.UV = quad1.V0.UV = CircleCenter; } public void AddRect(BoundingBox box, UiColor color) { var last = _quads.Length; if (_quads.Capacity <= last + 1) EnsureCapacity(last + 1); _quads.Length = last + 1; ref var quad = ref _quads.Ptr[last]; quad.V3.Position.x = quad.V0.Position.x = box.XMin; quad.V1.Position.y = quad.V0.Position.y = box.YMax; quad.V2.Position.x = quad.V1.Position.x = box.XMax; quad.V3.Position.y = quad.V2.Position.y = box.YMin; quad.V3.Color = quad.V2.Color = quad.V1.Color = quad.V0.Color = color; quad.V3.Options.Size = quad.V2.Options.Size = quad.V1.Options.Size = quad.V0.Options.Size = 255; quad.V3.UV = quad.V2.UV = quad.V1.UV = quad.V0.UV = CircleCenter; } public void AddRect(float xMin,float xMax,float yMin,float yMax, UiColor color) { var last = _quads.Length; if (_quads.Capacity <= last + 1) EnsureCapacity(last + 1); _quads.Length = last + 1; ref var quad = ref _quads.Ptr[last]; quad.V3.Position.x = quad.V0.Position.x = xMin; quad.V1.Position.y = quad.V0.Position.y = yMax; quad.V2.Position.x = quad.V1.Position.x = xMax; quad.V3.Position.y = quad.V2.Position.y = yMin; quad.V3.Color = quad.V2.Color = quad.V1.Color = quad.V0.Color = color; quad.V3.Options.Size = quad.V2.Options.Size = quad.V1.Options.Size = quad.V0.Options.Size = 255; quad.V3.UV = quad.V2.UV = quad.V1.UV = quad.V0.UV = CircleCenter; } public void InsertQuad(int index, Rect rect, UiColor color) { CheckAddLength(1); ; var scale = new Vector2(rect.width, -rect.height); var position = new Vector2(rect.xMin, rect.yMax); var uv = CircleCenter; ref var quad = ref _quads.InsertRef(index); quad.V0.Write(position + new Vector2(0, scale.y), 255, color, uv); quad.V1.Write(position + scale, 255, color, uv); quad.V2.Write(position + new Vector2(scale.x, 0), 255, color, uv); quad.V3.Write(position, 255, color, uv); } public void AddHorizontalGradient(Rect rect, UiColor leftColor, UiColor rightColor) { CheckAddLength(1); var last = _quads.Length; _quads.Length = last + 1; var scale = new Vector2(rect.width, rect.height); var position = rect.min; var uv = CircleCenter; ref var quad = ref _quads.Ptr[last]; quad.V0.Write(position + new Vector2(0, scale.y), 255, leftColor, uv); quad.V1.Write(position + scale, 255, rightColor, uv); quad.V2.Write(position + new Vector2(scale.x, 0), 255, rightColor, uv); quad.V3.Write(position, 255, leftColor, uv); } public void AddGradient(Rect rect, UiColor topLeftColor, UiColor topRightColor, UiColor bottomLeftColor, UiColor bottomRightColor) { CheckAddLength(1); var last = _quads.Length; _quads.Length = last + 1; ref var quad = ref _quads.Ptr[last]; var scale = new Vector2(rect.width, rect.height); var position = new Vector2(rect.xMin, rect.yMax); var uv = CircleCenter; quad.V0.Write(position + new Vector2(0, scale.y), 255, topLeftColor, uv); quad.V1.Write(position + scale, 255, topRightColor, uv); quad.V2.Write(position + new Vector2(scale.x, 0), 255, bottomRightColor, uv); quad.V3.Write(position, 255, bottomLeftColor, uv); } public void AddLine(Vector2 start, Vector2 end, float width, UiColor color) { var last = _quads.Length; if (last == _quads.Capacity) CheckAddLength(1); _quads.Length = last + 1; _quads.Ptr[last].WriteLine(start, end, width, color, CircleCenter); } public void AddLine(Vector2 start, Vector2 end, float width, UiColor startColor, UiColor endColor) { var last = _quads.Length; if (last == _quads.Capacity) CheckAddLength(1); _quads.Length = last + 1; _quads.Ptr[last].WriteLine(start, end, width, startColor, endColor, CircleCenter); } public void AddLines(ReadOnlySpan<Vector2> points, float width, UiColor color) { if (points.Length <=1) return; var p0 = points[0]; var p1 = points[1]; if (points.Length == 2) { AddLine(p0, p1, width, color); return; } var half = width / 2; var span = ReadAdditionalQuadSpan(points.Length - 1); Quad.SetUpQuadColorUV(span, color, CircleCenter); var p2 = points[2]; var n0 = (p1 -p0).Perpendicular(); var n1 = (p2 -p1).Perpendicular(); { ref var quad = ref span[0]; var verticalX = n0.x * half; var verticalY = n0.y * half; quad.V0.Position.x = p0.x +verticalX; quad.V0.Position.y = p0.y +verticalY; quad.V3.Position.x = p0.x -verticalX; quad.V3.Position.y = p0.y -verticalY; var interSection = NormIntersection(n0, n1); var interSectionX = interSection.x * half; var interSectionY = interSection.y * half; quad.V1.Position.x = p1.x+ interSectionX; quad.V1.Position.y = p1.y +interSectionY; quad.V2.Position.x = p1.x -interSectionX; quad.V2.Position.y = p1.y -interSectionY; } var end = p2; var lastN = n1; var lastV1 = span[0].V1.Position; var lastV2 = span[0].V2.Position; for (var index = 1; index < span.Length-1; index++) { var nextP = points[index + 2]; var n=(nextP -end).Perpendicular(); var interSection = NormIntersection(lastN, n); lastN = n; var interSectionX = interSection.x * half; var interSectionY = interSection.y * half; ref var quad = ref span[index]; quad.V0.Position = lastV1; quad.V3.Position= lastV2; quad.V1.Position.x = end.x+ interSectionX; quad.V1.Position.y = end.y +interSectionY; lastV1 = quad.V1.Position; quad.V2.Position.x = end.x -interSectionX; quad.V2.Position.y = end.y -interSectionY; lastV2 = quad.V2.Position; end = nextP; } { ref var quad = ref span[^1]; quad.V0.Position = lastV1; quad.V3.Position= lastV2; var interSectionX = lastN.x * half; var interSectionY = lastN.y * half; quad.V1.Position.x = end.x + interSectionX; quad.V1.Position.y = end.y +interSectionY; quad.V2.Position.x = end.x -interSectionX; quad.V2.Position.y = end.y -interSectionY; } } public void AddLinesLoop(ReadOnlySpan<Vector2> points, float width, UiColor color) { if (points.Length <=1) return; var p0 = points[0]; var p1 = points[1]; if (points.Length == 2) { AddLine(p0, p1, width, color); return; ; } var half = width / 2; var span = ReadAdditionalQuadSpan(points.Length ); Quad.SetUpQuadColorUV(span, color, CircleCenter); var p2 = points[2]; var n0 = (p1 -p0).Perpendicular(); var n1 = (p2 -p1).Perpendicular(); { ref var quad = ref span[0]; var interSection = NormIntersection(n0, n1)* half; quad.V1.Position = p1+ interSection; quad.V2.Position= p1 - interSection; } var end = p2; var lastN = n1; var lastV1 = span[0].V1.Position; var lastV2 = span[0].V2.Position; for (var index = 1; index < span.Length-1; index++) { var nextP = points[index==span.Length-2?0:(index + 2)]; var n=(nextP -end).Perpendicular(); var interSection = NormIntersection(lastN, n)* half; lastN = n; ref var quad = ref span[index]; quad.V0.Position = lastV1; quad.V3.Position= lastV2; quad.V1.Position = lastV1=end+ interSection; quad.V2.Position =lastV2= end -interSection; end = nextP; } { var interSection = MathHelper.NormIntersection(lastN, n0)* half; ref var last = ref span[^1]; ref var first = ref span[0]; last.V0.Position = lastV1; last.V3.Position= lastV2; first.V0.Position = last.V1.Position= end + interSection; first.V3.Position = last.V2.Position = end -interSection; } } public void AddUnScaledUV(Vector4 uv,Vector2 center, float size, UiColor color) { var last = _quads.Length; if (last == _quads.Capacity) CheckAddLength(1); _quads.Length = last + 1; _quads.Ptr[last].WriteCircle(center, size/2, color,uv); } public void AddCircle(Rect rect, UiColor color) { CheckAddLength(1); var last = _quads.Length; _quads.Length = last + 1; Quad.WriteWithOutUVScale(ref _quads.Ptr[last], new Vector2(rect.width, -rect.height), new Vector2(rect.xMin, rect.yMax), color, CircleUV); } public void AddCircle(Vector2 center, float radius, UiColor color) { var last = _quads.Length; if (last == _quads.Capacity) CheckAddLength(1); _quads.Length = last + 1; _quads.Ptr[last].WriteCircle(center, radius, color, CircleUV); } public void AddCircle(Vector2 center, float backRadius, UiColor backColor, float frontRadius, UiColor frontColor) { var length = _quads.Length; if (_quads.Capacity <= length + 2) EnsureCapacity(length + 2); _quads.Length = length + 2; ref var quad1 = ref _quads.Ptr[length]; ref var quad2 = ref _quads.Ptr[length + 1]; quad1.SetColorAndSize(backColor,backRadius < 85 ? (byte) (frontRadius * 3) : (byte) 255); quad2.SetColorAndSize(frontColor,frontRadius < 85 ? (byte) (backRadius * 3) : (byte) 255); quad1.V3.Position.x = quad1.V0.Position.x = center.x - backRadius; quad1.V1.Position.y = quad1.V0.Position.y = center.y + backRadius; quad1.V2.Position.x = quad1.V1.Position.x = center.x + backRadius; quad1.V3.Position.y = quad1.V2.Position.y = center.y - backRadius; quad2.V3.Position.x = quad2.V0.Position.x = center.x - frontRadius; quad2.V1.Position.y = quad2.V0.Position.y = center.y + frontRadius; quad2.V2.Position.x = quad2.V1.Position.x = center.x + frontRadius; quad2.V3.Position.y = quad2.V2.Position.y = center.y - frontRadius; quad2.V3.UV.x = quad2.V0.UV.x = quad1.V3.UV.x = quad1.V0.UV.x = CircleUV.z; quad2.V1.UV.y = quad2.V0.UV.y = quad1.V1.UV.y = quad1.V0.UV.y = CircleUV.w + CircleUV.y; quad2.V2.UV.x = quad2.V1.UV.x = quad1.V2.UV.x = quad1.V1.UV.x = CircleUV.x + CircleUV.z; quad2.V3.UV.y = quad2.V2.UV.y = quad1.V3.UV.y = quad1.V2.UV.y = CircleUV.w; } public void AddRadialFilledCircle(Vector2 center, float radius, UiColor color,float fillAmount) { AddRadialFilledUnScaledUV(CircleUV, center, radius*2, color, fillAmount); } public void AddRadialFilledSquare(Vector2 center, float size, UiColor color,float fillAmount) { AddRadialFilledUnScaledUV(new Vector4(0,0,CircleCenter.x,CircleCenter.y), center, size, color, fillAmount); } public void AddRadialFilledUnScaledUV(Vector4 uv,Vector2 center, float size, UiColor color,float fillAmount) { if (fillAmount <= 0) return; fillAmount = Mathf.Clamp01(fillAmount); if (fillAmount == 1) { AddUnScaledUV(uv,center, size, color); return; } var radius = size / 2; var centerUV= new Vector2(uv.z + uv.x / 2, uv.w + uv.y / 2); var last = _quads.Length; if ( _quads.Capacity<last+3) EnsureCapacity(last+3); _quads.Length = last + 1; ref var quad = ref _quads.Ptr[last]; quad.SetColorAndSize(color,radius < 85 ? (byte) (radius * 3) : (byte) 255); quad.V0.Position =center; quad.V0.UV = centerUV; quad.V1.Position =center+new Vector2(0,radius); quad.V1.UV.x = centerUV.x; quad.V1.UV.y = uv.w + uv.y; if (fillAmount <= 0.125f) { var t = FastTan2PI(fillAmount); quad.V3.Position = quad.V2.Position=center+new Vector2(t*radius,radius); quad.V3.UV = quad.V2.UV = new Vector2(centerUV.x + t * uv.x / 2, quad.V1.UV.y); return; } quad.V2.Position =center+new Vector2(radius,radius); quad.V2.UV.y = quad.V1.UV.y; quad.V2.UV.x = uv.x + uv.z; if (fillAmount <= 0.375f) { var t= FastTan2PI(0.25f-fillAmount); quad.V3.Position =center+new Vector2(radius,t*radius); quad.V3.UV.y = centerUV.y + uv.y * t / 2; quad.V3.UV.x = uv.x + uv.z; return; } { quad.V3.Position =center+new Vector2(radius,-radius); quad.V3.UV.y = uv.w; quad.V3.UV.x = uv.x + uv.z; } _quads.Length = last + 2; ref var quad2 = ref _quads.Ptr[last+1]; quad2.SetColorAndSize(color,quad.V0.Options.Size); quad2.V0 = quad.V0; quad2.V1= quad.V3; if (fillAmount <= 0.625f) { var t = FastTan2PI(0.5f-fillAmount); quad2.V3.Position = quad2.V2.Position=center+new Vector2(t*radius,-radius); quad2.V3.UV = quad2.V2.UV = new Vector2(centerUV.x + t * uv.x / 2, uv.w); return; } quad2.V2.Position =center-new Vector2(radius,radius); quad2.V2.UV.y = uv.w; quad2.V2.UV.x = uv.z; if (fillAmount <= 0.875f) { var t = FastTan2PI(fillAmount-0.75f); quad2.V3.Position =center+new Vector2(-radius,radius*t); quad2.V3.UV.y = centerUV.y + uv.y *t / 2; quad2.V3.UV.x = uv.z; return; } { quad2.V3.Position =center+new Vector2(-radius,radius); quad2.V3.UV.y =uv.y+uv.w; quad2.V3.UV.x = uv.z; } _quads.Length = last + 3; ref var quad3 = ref _quads.Ptr[last+2]; { quad3.V0 = quad2.V0; quad3.V2 = quad3.V1 = quad2.V3; quad3.V3.Options.Size = quad3.V0.Options.Size; quad3.V3.Color = quad3.V0.Color; quad3.V3.Position.y = center.y + radius; quad3.V3.UV.y = quad3.V2.UV.y; var t = FastTan2PI((1-fillAmount)); quad3.V3.Position.x =center.x-radius*t; quad3.V3.UV.x = centerUV.x-uv.x *t / 2; } } public float CalculateLength(ReadOnlySpan<char> text, float fontSize) { var map = Map; var deltaOffsetX = fontSize / 4; var spaceXAdvance = SpaceXAdvance; foreach (var c in text) { deltaOffsetX += c == ' ' ? spaceXAdvance : map.GetRef(c).XAdvance; } return deltaOffsetX * fontSize; } public float CalculateLength(ReadOnlySpan<char> text, float fontSize, Span<int> infoIndices) { var map = Map; var deltaOffsetX = 0f; var spaceXAdvance = SpaceXAdvance; for (var i = 0; i < text.Length; i++) { var c = text[i]; if (c == ' ') { deltaOffsetX += spaceXAdvance; infoIndices[i] = -1; } else { var index = map.GetEntryIndex(c); infoIndices[i] = index; deltaOffsetX += map.GetFromEntryIndex(index).XAdvance; } } return deltaOffsetX * fontSize; } public void AddCenterText(Rect rect, float fontSize, ReadOnlySpan<char> span, UiColor textColor) { if (span.Length == 0||rect.width<=0) return ; var scale = new Vector2(fontSize, fontSize); var position = new Vector2(rect.xMin, rect.yMin + rect.height / 2 - fontSize / 4); scale *= InvUvScale; var ptr = _quads.Ptr + _quads.Length; var xMax = rect.xMax; var normXMax = (rect.width) / fontSize; var writeCount = 0; var deltaOffsetX = 0f; foreach (var c in span) { if (c == ' ') { deltaOffsetX += SpaceXAdvance; if (normXMax < deltaOffsetX) { deltaOffsetX = normXMax; break; } } else { ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(position.x+fontSize * deltaOffsetX,position.y,scale,fontSize,info); deltaOffsetX += info.XAdvance; ++writeCount; if (normXMax > deltaOffsetX) continue; quad.MaskTextMaxX(xMax); break; } } var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); if (normXMax < deltaOffsetX) { for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(textColor, scaleX); } } else { var scaledDelta = (rect.width - fontSize * deltaOffsetX)/2 ; for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(textColor, scaleX); ptr->MoveX(scaledDelta); } } _quads.Length += writeCount; } public void AddCenterText(Vector2 center,float width, float fontSize, ReadOnlySpan<char> span, UiColor textColor) { if (span.Length == 0||width<=0) return ; var scale = new Vector2(fontSize, fontSize); var position = new Vector2(center.x-width/2,center.y - fontSize / 4); scale *= InvUvScale; var ptr = _quads.Ptr + _quads.Length; var xMax = center.x+width/2; var normXMax = width / fontSize; var writeCount = 0; var deltaOffsetX = 0f; foreach (var c in span) { if (c == ' ') { deltaOffsetX += SpaceXAdvance; if (normXMax < deltaOffsetX) { deltaOffsetX = normXMax; break; } } else { ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(position.x+fontSize * deltaOffsetX,position.y,scale,fontSize,info); deltaOffsetX += info.XAdvance; ++writeCount; if (normXMax > deltaOffsetX) continue; quad.MaskTextMaxX(xMax); break; } } var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); if (normXMax < deltaOffsetX) { for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(textColor, scaleX); } } else { var scaledDelta = (width - fontSize * deltaOffsetX)/2 ; for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(textColor, scaleX); ptr->MoveX(scaledDelta); } } _quads.Length += writeCount; } public float AddText(Rect rect, ReadOnlySpan<char> span, UiColor color) { if (span.Length == 0||rect.width<=0) return 0; CheckAddLength(span.Length); var fontSize = rect.height; var position = new Vector2(rect.xMin, rect.yMin + rect.height / 2 - fontSize / 3); var xMax = rect.xMax; var scale = new Vector2(fontSize, fontSize); scale *= InvUvScale; var normXMax = (xMax - position.x) / fontSize; var ptr = _quads.Ptr + _quads.Length; var writeCount = 0; var deltaOffsetX = fontSize / 4; foreach (var c in span) { if (c == ' ') { deltaOffsetX += SpaceXAdvance; if (normXMax < deltaOffsetX) { deltaOffsetX = normXMax; break; } } else { ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(position.x+fontSize * deltaOffsetX,position.y,scale,fontSize,info); deltaOffsetX += info.XAdvance; ++writeCount; if (normXMax > deltaOffsetX) continue; quad.MaskTextMaxX(xMax); break; } } var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(color, scaleX); } _quads.Length += writeCount; return fontSize * deltaOffsetX; } public float AddTextNoMask(Rect rect, float fontSize, ReadOnlySpan<char> span, UiColor color) { if (span.Length == 0) return 0; CheckAddLength(span.Length); var position = new Vector2(rect.xMin, rect.yMin + rect.height / 2 - fontSize / 3); var xMax = rect.xMax; var scale = fontSize*InvUvScale; var ptr = _quads.Ptr + _quads.Length; var writeCount = 0; var nextX = position.x+fontSize / 4; foreach (var c in span) { if (c == ' ') { nextX += SpaceXAdvance*fontSize; } ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(nextX,position.y,scale,fontSize,info); nextX += info.XAdvance*fontSize; ++writeCount; } var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(color, scaleX); } _quads.Length += writeCount; return nextX-position.x; } public float AddText(Rect rect, float fontSize, ReadOnlySpan<char> span, ReadOnlySpan<(int length,UiColor color)> colors) { if (span.Length == 0||rect.width<=0) return 0; CheckAddLength(span.Length); var position = new Vector2(rect.xMin, rect.yMin + rect.height / 2 - fontSize / 3); var xMax = rect.xMax; var scale = fontSize*InvUvScale; var ptr = _quads.Ptr + _quads.Length; var writeCount = 0; var nextX = position.x+fontSize / 4; var colorRemainLength = colors[0].length; var colorIndex =0; var color = colors[0].color; foreach (var c in span) { while (--colorRemainLength < 0) { (colorRemainLength, color)= colors[++colorIndex]; } if (c == ' ') { nextX += SpaceXAdvance*fontSize; if (nextX < xMax) continue; break; } ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(nextX,position.y,scale,fontSize,info); quad.SetColor(color); nextX += info.XAdvance*fontSize; ++writeCount; if (nextX <xMax) continue; quad.MaskTextMaxX(xMax); break; } var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); for (int i = 0; i < writeCount; i++) { (--ptr)->SetSize(scaleX); } _quads.Length += writeCount; return nextX-position.x; } public float AddText(Rect rect, float fontSize, ReadOnlySpan<char> span, UiColor color) { if (span.Length == 0) return 0; CheckAddLength(span.Length); var position = new Vector2(rect.xMin, rect.yMin + rect.height / 2 - fontSize / 3); var xMax = rect.xMax; var scale = fontSize*InvUvScale; var ptr = _quads.Ptr + _quads.Length; var writeCount = 0; var nextX = position.x+fontSize / 4; foreach (var c in span) { if (c == ' ') { nextX += SpaceXAdvance*fontSize; if (nextX < xMax) continue; break; } ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(nextX,position.y,scale,fontSize,info); nextX += info.XAdvance*fontSize; ++writeCount; if (nextX <xMax) continue; quad.MaskTextMaxX(xMax); break; } var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(color, scaleX); } _quads.Length += writeCount; return nextX-position.x; } public float AddText(Rect rect, float fontSize, ReadOnlySpan<char> span1,ReadOnlySpan<char> span2, UiColor color) { var length = span1.Length + span2.Length; if (length==0) return 0; CheckAddLength(length); var position = new Vector2(rect.xMin+fontSize / 4, rect.yMin + rect.height / 2 - fontSize / 3); var xMax = rect.xMax; var scale = fontSize*InvUvScale; var ptr = _quads.Ptr + _quads.Length; var writeCount = 0; var nextX = position.x; foreach (var c in span1) { if (c == ' ') { nextX += SpaceXAdvance*fontSize; if (nextX < xMax) continue; goto EndWrite; } ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(nextX,position.y,scale,fontSize,info); nextX += info.XAdvance*fontSize; ++writeCount; if (nextX <xMax) continue; quad.MaskTextMaxX(xMax); goto EndWrite; } foreach (var c in span2) { if (c == ' ') { nextX += SpaceXAdvance*fontSize; if (nextX < xMax) continue; break; } if(c is '\r'or '\n' ) { break; } ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(nextX,position.y,scale,fontSize,info); nextX += info.XAdvance*fontSize; ++writeCount; if (nextX <xMax) continue; quad.MaskTextMaxX(xMax); break; } EndWrite: var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(color, scaleX); } _quads.Length += writeCount; return nextX-position.x; } public void AddTextMultiLine(Rect rect, float fontSize,float yMin,ReadOnlySpan<string> enumerable, UiColor color) { var fullLength = 0; foreach (var text in enumerable) { fullLength += text.Length; } CheckAddLength(fullLength); if (fullLength == 0) return; var position = new Vector2(rect.xMin+fontSize / 4,LineHeight+ rect.yMin + rect.height / 2 - fontSize / 3); var xMax = rect.xMax; var scale = fontSize*InvUvScale; var ptr = _quads.Ptr + _quads.Length; var writeCount = 0; foreach (var text in enumerable) { position.y -= LineHeight*fontSize; if (position.y < yMin) break; var span =text.AsSpan(); var nextX = position.x; foreach (var c in span) { if (c == ' ') { nextX += SpaceXAdvance*fontSize; if (nextX < xMax) continue; break; } ref var quad = ref ptr++[0]; ref readonly var info = ref Map.GetRef(c); quad.Write(nextX,position.y,scale,fontSize,info); nextX += info.XAdvance*fontSize; ++writeCount; if (nextX <xMax) continue; quad.MaskTextMaxX(xMax); break; } } var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); for (int i = 0; i < writeCount; i++) { (--ptr)->SetColorAndSize(color, scaleX); } _quads.Length += writeCount; } public float AddCharMasked(Rect rect, float fontSize, char c, UiColor color) { if (c == ' ') { return SpaceXAdvance; } var position = new Vector2(rect.xMin+fontSize / 3, rect.yMin + rect.height / 2 - fontSize / 2); var scale = new Vector2(fontSize, fontSize); scale *= InvUvScale; CheckAddLength(1); var deltaOffsetX = 0f; var data = Map[c]; var uv = data.UV; var cPosX = position.x + fontSize * (deltaOffsetX + data.XOffset); var cPosX2 = cPosX + uv.x * scale.x; var cPosY = position.y + fontSize * data.YOffset; var cPosY2 = cPosY + uv.y * scale.y; ref var quad = ref (_quads.Ptr + _quads.Length)[0]; quad.V0.Write( cPosX, cPosY2, uv.z, uv.w + uv.y); quad.V1.Write( cPosX2, cPosY2, uv.x + uv.z, uv.y + uv.w); quad.V2.Write( cPosX2, cPosY, uv.x + uv.z, uv.w); quad.V3.Write( cPosX, cPosY, uv.z, uv.w); var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); quad.SetColorAndSize(color, scaleX); _quads.Length += 1; return fontSize * deltaOffsetX; } public float AddChar(Vector2 center,float fontSize, char c, UiColor color) { if (c == ' ') { return SpaceXAdvance; } var scale = new Vector2(fontSize, fontSize); scale *= InvUvScale; CheckAddLength(1); var deltaOffsetX = 0f; var data = Map[c]; var position = new Vector2(center.x-data.XAdvance*fontSize/2,center.y - fontSize / 3); var uv = data.UV; var cPosX = position.x + fontSize * (deltaOffsetX + data.XOffset); var cPosX2 = cPosX + uv.x * scale.x; var cPosY = position.y + fontSize * data.YOffset; var cPosY2 = cPosY + uv.y * scale.y; ref var quad = ref (_quads.Ptr + _quads.Length)[0]; quad.V0.Write( cPosX, cPosY2, uv.z, uv.w + uv.y); quad.V1.Write( cPosX2, cPosY2, uv.x + uv.z, uv.y + uv.w); quad.V2.Write( cPosX2, cPosY, uv.x + uv.z, uv.w); quad.V3.Write( cPosX, cPosY, uv.z, uv.w); var scaleX = (byte) Mathf.Clamp((int) fontSize, 0, 255); quad.SetColorAndSize(color, scaleX); _quads.Length += 1; return fontSize * deltaOffsetX; } static readonly VertexAttributeDescriptor[] _attributes = { new(VertexAttribute.Position, VertexAttributeFormat.Float32, 2), new(VertexAttribute.Color, VertexAttributeFormat.UNorm8, 4), new(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2), new(VertexAttribute.TexCoord1, VertexAttributeFormat.UNorm8, 4), }; int lastVertexCount = -1; int lastTexturesCount = -1; const MeshUpdateFlags MESH_UPDATE_FLAGS = MeshUpdateFlags.DontRecalculateBounds | MeshUpdateFlags.DontValidateIndices | MeshUpdateFlags.DontNotifyMeshUsers; public void SetDeferred(Range range) { var start = range.Start.Value; var end = range.End.Value; var ptr = _quads.Ptr + start; var length1 = end - start; var length2 = _quads.Length - end; NativeCollectionsExtensions.Swap(ptr, length1, length2); } public bool Build() { var textOnlyVertLength = _quads.Length * 4; if (_textureQuads.IsCreated && _textureQuads.Length != 0) { CheckAddLength(_textureQuads.Length); _quads.AddRange(_textureQuads); } if (_quads.Length == 0) { Mesh.Clear(); return false; } var quadCount = _quads.Length; var vertexCount = quadCount * 4; if (_indices.Length < vertexCount) { _indices.SetCapacity(vertexCount); var currentLength = _indices.Length; _indices.Length = vertexCount; var span = _indices.AsSpan(); for (var i = currentLength; i < span.Length; i++) { span[i] = (uint) i; } } var textureLength = _textureLength; if (lastVertexCount != vertexCount || lastTexturesCount != textureLength) { Mesh.Clear(); Mesh.subMeshCount = 1 + textureLength; Mesh.SetVertexBufferParams(vertexCount, _attributes); Mesh.SetIndexBufferParams(vertexCount, IndexFormat.UInt32); var meshDesc = new SubMeshDescriptor(0, textOnlyVertLength, MeshTopology.Quads) { firstVertex = 0, vertexCount = textOnlyVertLength }; ; Mesh.SetSubMesh(0, meshDesc, MESH_UPDATE_FLAGS); try { for (int i = 0; i < textureLength; i++) { var firstVertex = textOnlyVertLength + i * 4; meshDesc = new SubMeshDescriptor(firstVertex, 4, MeshTopology.Quads) { firstVertex = firstVertex, vertexCount = 4 }; Mesh.SetSubMesh(i + 1, meshDesc, MESH_UPDATE_FLAGS); } } catch (Exception e) { Debug.LogException(e); return false; } } Mesh.SetVertexBufferData(_quads.AsArray(), 0, 0, quadCount); Mesh.SetIndexBufferData(_indices.AsArray().GetSubArray(0, vertexCount), 0, 0, vertexCount); lastVertexCount = vertexCount; lastTexturesCount = textureLength; return true; } public void Clear() { _quads.Clear(); if (_textureLength != 0) { _textureQuads.Clear(); _textures.Clear(); } } public int Layer=0; public Camera Camera=null; public void Draw() { Mesh.bounds = new Bounds(default, new Vector3(float.MaxValue, float.MaxValue, float.MaxValue)); Graphics.DrawMesh(Mesh, default, _material, Layer, Camera, 0, null, ShadowCastingMode.Off, false); for (int i = 0; i < _textureLength; i++) { DrawTextureMesh(i); } } void DrawTextureMesh(int index) { _materialPropertyBlock.SetTexture(_textureShaderPropertyId, _textures[index]); Graphics.DrawMesh(Mesh, default, _textureMaterial, Layer, Camera, index + 1, _materialPropertyBlock, ShadowCastingMode.Off, false); } bool _isDisposed; ~UiMesh() => Dispose(false); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool b) { if (!_isDisposed) { if (_quads.IsCreated) _quads.Dispose(); if (_indices.IsCreated) _indices.Dispose(); if (Map.IsCreated) Map.Dispose(); if (_textureQuads.IsCreated) _textureQuads.Dispose(); _isDisposed = true; } } public readonly struct CharInfo { public readonly float XAdvance; public readonly float XOffset; public readonly float YOffset; public readonly Vector4 UV; public CharInfo(Glyph glyph, float textureWidth, float textureHeight, float pointSize, float padding) { var metrics = glyph.metrics; var rect = glyph.glyphRect; var width = (rect.width + 2 * padding); var height = (rect.height + 2 * padding); UV = new Vector4(width / textureWidth, height / textureHeight, (rect.x - padding) / textureWidth, (rect.y - padding) / textureHeight); XAdvance = metrics.horizontalAdvance / pointSize; XOffset = (metrics.horizontalBearingX + (metrics.width - width) / 2) / pointSize; YOffset = (metrics.horizontalBearingY - (metrics.height + height) / 2) / pointSize; } public CharInfo(float xAdvance, float xOffset, float yOffset) { UV = default; XAdvance = xAdvance; XOffset = xOffset; YOffset = yOffset; } } } }
Assets/ZimGui/Core/UiMesh.cs
Akeit0-ZimGui-Unity-cc82fb9
[ { "filename": "Assets/ZimGui/RayCaster.cs", "retrieved_chunk": " Count = 0;\n }\n public void Add(int id, Rect rect) {\n if (Count == Rects.Length) {\n Array.Resize(ref Rects ,Count*2);\n Array.Resize(ref TargetID ,Count*2);\n }\n Rects[Count] = rect;\n TargetID[Count] = id;\n Count++;", "score": 0.8157305717468262 }, { "filename": "Assets/ZimGui/Core/Quad.cs", "retrieved_chunk": " p->SetSize(255);\n p->SetUV(quadUV);\n UnsafeUtility.MemCpyReplicate(p + 1, p, sizeof(Quad), span.Length - 1);\n }\n }\n /// <summary>\n /// /UseThisBefore WriteLinePositionOnly\n /// </summary>\n /// <param name=\"span\"></param>\n /// <param name=\"quadUV\"></param>", "score": 0.8117486834526062 }, { "filename": "Assets/ZimGui/Core/Quad.cs", "retrieved_chunk": " public static unsafe void SetUpQuadUV(Span<Quad> span, Vector2 quadUV) {\n fixed (Quad* p = span) {\n *p = default;\n p->SetSize(255);\n p->SetUV(quadUV);\n UnsafeUtility.MemCpyReplicate(p + 1, p, sizeof(Quad), span.Length - 1);\n }\n }\n /// <summary>\n /// /UseThisBefore WriteLinePositionOnly", "score": 0.803458034992218 }, { "filename": "Assets/ZimGui/RayCaster.cs", "retrieved_chunk": " } \n public void Add(RayCaster child) {\n for (int i = 0; i < child.Count; i++) {\n Add(child.TargetID[i],child.Rects[i]);\n }\n }\n public void Clear() {\n Rects.AsSpan(0,Count).Clear();\n TargetID.AsSpan(0,Count).Clear();\n Count = 0;", "score": 0.7958441972732544 }, { "filename": "Assets/ZimGui/Core/Quad.cs", "retrieved_chunk": " /// </summary>\n /// <param name=\"span\"></param>\n /// <param name=\"v\"></param>\n public static unsafe void SetUpForQuad(Span<Quad> span, Vector2 v) {\n fixed (Quad* p = span) {\n *p = default;\n p->SetSize(255);\n p->SetUV(v);\n UnsafeUtility.MemCpyReplicate(p + 1, p, sizeof(Quad), span.Length - 1);\n }", "score": 0.7955210208892822 } ]
csharp
Quad* ptr, int count) {
using System; using System.Collections.Generic; using System.Text; using XiaoFeng.Xml; using System.Xml; using System.Xml.Serialization; using XiaoFeng; using XiaoFeng.IO; using XiaoFeng.Cryptography; using System.Linq; using FayElf.Plugins.WeChat.Model; using FayElf.Plugins.WeChat.Cryptotraphy; /**************************************************************** * Copyright © (2022) www.fayelf.com All Rights Reserved. * * Author : jacky * * QQ : 7092734 * * Email : [email protected] * * Site : www.fayelf.com * * Create Time : 2022-03-14 17:53:45 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.OfficialAccount { /// <summary> /// 微信接收操作类 /// </summary> public class Receive { #region 构造器 /// <summary> /// 无参构造器 /// </summary> public Receive() { this.Config = Config.Current; } #endregion #region 属性 public Config Config { get; set; } #endregion #region 方法 #region 对请求进行signature校验 /// <summary> /// 对请求进行signature校验 /// </summary> /// <returns></returns> public Boolean CheckSignature(string signature, string nonce, string timestamp,string token) { if (signature.IsNullOrEmpty() || nonce.IsNullOrEmpty() || timestamp.IsNullOrEmpty() || timestamp.IsNotMatch(@"^\d+$")) return false; //LogHelper.WriteLog($"sign:{new string[] { token, nonce, timestamp }.OrderBy(a => a).Join("").SHA1Encrypt().ToLower()}"); return new string[] { token, nonce, timestamp }.OrderBy(a => a).Join("").SHA1Encrypt().ToLower() == signature.ToLower(); } #endregion #region 接收数据 /// <summary> /// 接收数据 /// </summary> /// <returns></returns> public string RequestMessage(Microsoft.AspNetCore.Http.HttpRequest request, Func<BaseMessage?, XmlValue, string> func) { var encrypt_type = request.Query["encrypt_type"].ToString().ToUpper() == "AES"; var signature = request.Query["signature"].ToString(); var timestamp = request.Query["timestamp"].ToString(); var nonce = request.Query["nonce"].ToString(); var echostr = request.Query["echostr"].ToString(); LogHelper.WriteLog($"encrypt_type:{encrypt_type},signature:{signature},timestamp:{timestamp},nonce:{nonce},echostr:{echostr},token:{this.Config.Token}"); if (request.Method == "GET") { return this.CheckSignature(signature, nonce, timestamp, this.Config.Token) ? echostr : "error"; } var msg_signature = request.Query["msg_signature"].ToString(); LogHelper.WriteLog($"msg_signature:{msg_signature}"); var msg = request.Body.ReadToEnd(); LogHelper.Warn(msg); if (encrypt_type) { var wxBizMsgCrypt = new WXBizMsgCrypt(this.Config.Token, this.Config.EncodingAESKey, this.Config.AppID); var _msg = ""; var ret = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref _msg); if (ret != 0)//解密失败 { //TODO:开发者解密失败的业务处理逻辑 LogHelper.Warn($"微信公众号数据解密失败.[decrypt message return {ret}, request body {msg}]"); } msg = _msg; } var data = msg.XmlToEntity() as XmlValue; if (data == null || data.ChildNodes == null || data.ChildNodes.Count < 1) return ""; var xml = data.ChildNodes.First(); var BaseMsg = xml.ToObject(typeof(BaseMessage)) as BaseMessage; var message = func.Invoke(BaseMsg, xml); if (encrypt_type) { var _msg = ""; var wxBizMsgCrypt = new WXBizMsgCrypt(this.Config.Token, this.Config.EncodingAESKey, this.Config.AppID); var ret = wxBizMsgCrypt.EncryptMsg(message, timestamp, nonce, ref _msg); if (ret != 0)//加密失败 { //TODO:开发者加密失败的业务处理逻辑 LogHelper.Warn($"微信公众号数据加密失败.[encrypt message return {ret}, response body {message}]"); } message= _msg; } return message; } #endregion #region 输出内容 /// <summary> /// 输出内容 /// </summary> /// <param name="messageType">内容类型</param> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="func">委托</param> /// <returns></returns> private string ReplayContent(MessageType messageType, string fromUserName, string toUserName, Func<string> func) => $"<xml><ToUserName><![CDATA[{toUserName}]]></ToUserName><FromUserName><![CDATA[{fromUserName}]]></FromUserName><CreateTime>{DateTime.Now.ToTimeStamp()}</CreateTime><MsgType><![CDATA[{messageType.GetEnumName()}]]></MsgType>{func.Invoke()}</xml>"; #endregion #region 输出文本消息 /// <summary> /// 输出文本消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="content">回复内容</param> /// <returns></returns> public string ReplayText(string fromUserName, string toUserName, string content) => this.ReplayContent(MessageType.text, fromUserName, toUserName, () => $"<Content><![CDATA[{content}]]></Content>"); #endregion #region 回复图片 /// <summary> /// 回复图片 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="mediaId">通过素材管理中的接口上传多媒体文件,得到的id</param> /// <returns></returns> public string ReplayImage(string fromUserName, string toUserName, string mediaId) => this.ReplayContent(MessageType.image, fromUserName, toUserName, () => $"<Image><MediaId><![CDATA[{mediaId}]]></MediaId></Image>"); #endregion #region 回复语音消息 /// <summary> /// 回复语音消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="mediaId">通过素材管理中的接口上传多媒体文件,得到的id</param> /// <returns></returns> public string ReplayVoice(string fromUserName, string toUserName, string mediaId) => this.ReplayContent(MessageType.voice, fromUserName, toUserName, () => $"<Voice><MediaId><![CDATA[{mediaId}]]></MediaId></Voice>"); #endregion #region 回复视频消息 /// <summary> /// 回复视频消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="mediaId">通过素材管理中的接口上传多媒体文件,得到的id</param> /// <param name="title">视频消息的标题</param> /// <param name="description">视频消息的描述</param> /// <returns></returns> public string ReplayVideo(string fromUserName, string toUserName, string mediaId, string title, string description) => this.ReplayContent(MessageType.video, fromUserName, toUserName, () => $"<Video><MediaId><![CDATA[{mediaId}]]></MediaId><Title><![CDATA[{title}]]></Title><Description><![CDATA[{description}]]></Description></Video>"); #endregion #region 回复音乐消息 /// <summary> /// 回复视频消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="title">视频消息的标题</param> /// <param name="description">视频消息的描述</param> /// <param name="musicUrl">音乐链接</param> /// <param name="HQmusicUrl">高质量音乐链接,WIFI环境优先使用该链接播放音乐</param> /// <param name="mediaId">通过素材管理中的接口上传多媒体文件,得到的id</param> /// <returns></returns> public string ReplayMusic(string fromUserName, string toUserName, string title, string description, string mediaId,string musicUrl,string HQmusicUrl) => this.ReplayContent(MessageType.music, fromUserName, toUserName, () => $"<Music><Title><![CDATA[{title}]]></Title><Description><![CDATA[{description}]]></Description><MusicUrl><![CDATA[{musicUrl}]]></MusicUrl><HQMusicUrl><![CDATA[{HQmusicUrl}]]></HQMusicUrl><ThumbMediaId><![CDATA[{mediaId}]]></ThumbMediaId></Music>"); #endregion #region 回复图文消息 /// <summary> /// 回复图文消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="list">图文列表</param> /// <returns></returns> public string ReplayNews(string fromUserName, string toUserName,
NewsModel news) => this.ReplayContent(MessageType.news, fromUserName, toUserName, () => {
if (news == null || news.Item == null || news.Item.Count == 0) return ""; return $"<ArticleCount>{news.Item.Count}</ArticleCount>{news.EntityToXml(OmitXmlDeclaration: true, OmitComment: true, Indented: false)}"; }); #endregion #endregion } }
OfficialAccount/Receive.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "Model/BaseMessage.cs", "retrieved_chunk": " public string FromUserName { get; set; }\n /// <summary>\n /// 创建时间\n /// </summary>\n public int CreateTime { get; set; }\n /// <summary>\n /// 消息类型\n /// </summary>\n [XmlCData, XmlConverter(typeof(StringEnumConverter))]\n public MessageType MsgType { get; set; }", "score": 0.8018134832382202 }, { "filename": "Model/ArticleModel.cs", "retrieved_chunk": "{\n /// <summary>\n /// 图文模板类型\n /// </summary>\n [XmlRoot(\"Articles\")]\n public class NewsModel\n {\n /// <summary>\n /// 列表\n /// </summary>", "score": 0.7958909273147583 }, { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " /// <param name=\"touser\">接收者(用户)的 openid</param>\n /// <param name=\"template_id\">所需下发的订阅模板id</param>\n /// <param name=\"page\">跳转网页时填写</param>\n /// <param name=\"miniprogram\">跳转小程序时填写,格式如{ \"appid\": \"\", \"pagepath\": { \"value\": any } }</param>\n /// <param name=\"data\">模板内容,格式形如 { \"key1\": { \"value\": any }, \"key2\": { \"value\": any } }</param>\n /// <returns></returns>\n public BaseResult Send(string touser, string template_id, string page, MiniProgram miniprogram, Dictionary<string, ValueColor> data)\n {\n var config = this.Config.GetConfig(WeChatType.Applets);\n return Common.Execute(config.AppID, config.AppSecret, token =>", "score": 0.7881706357002258 }, { "filename": "OfficialAccount/Subscribe.cs", "retrieved_chunk": " _data.Add(\"data\", data);\n var response = HttpHelper.GetHtml(new HttpRequest\n {\n Method = HttpMethod.Post,\n Address = $\"https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token={token.AccessToken}\",\n BodyData = _data.ToJson()\n });\n if (response.StatusCode == System.Net.HttpStatusCode.OK)\n {\n var result = response.Html.JsonToObject<BaseResult>();", "score": 0.7874757647514343 }, { "filename": "Model/ArticleModel.cs", "retrieved_chunk": " [Description(\"图文消息标题\")]\n [XmlCData]\n public string Title { get; set; }\n /// <summary>\n /// 图文消息描述\n /// </summary>\n [Description(\"图文消息描述\")]\n [XmlCData] \n public string Description { get; set; }\n /// <summary>", "score": 0.7868069410324097 } ]
csharp
NewsModel news) => this.ReplayContent(MessageType.news, fromUserName, toUserName, () => {
#nullable enable using System; using System.Collections.Generic; using Random = UnityEngine.Random; namespace Mochineko.FacialExpressions.Blink { /// <summary> /// A generator of <see cref="EyelidAnimationFrame"/> for linear eyelid animation. /// </summary> public static class LinearEyelidAnimationGenerator { /// <summary> /// Generates a collection of <see cref="EyelidAnimationFrame"/> for some blinking. /// </summary> /// <param name="eyelid"></param> /// <param name="blinkCount"></param> /// <param name="framesPerSecond"></param> /// <param name="closingRate"></param> /// <param name="minDurationSeconds"></param> /// <param name="maxDurationSeconds"></param> /// <param name="minIntervalSeconds"></param> /// <param name="maxIntervalSeconds"></param> /// <returns></returns> public static IEnumerable<EyelidAnimationFrame> Generate( Eyelid eyelid, int blinkCount, int framesPerSecond = 60, float closingRate = 0.2f, float minDurationSeconds = 0.05f, float maxDurationSeconds = 0.2f, float minIntervalSeconds = 0.1f, float maxIntervalSeconds = 6f) { var frames = new List<EyelidAnimationFrame>(); for (var i = 0; i < blinkCount; i++) { var duration = Random.Range(minDurationSeconds, maxDurationSeconds); frames.AddRange(GenerateBlinkAnimationFrames( eyelid, framesPerSecond, duration, closingRate)); var interval = Random.Range(minIntervalSeconds, maxIntervalSeconds); frames.Add(new EyelidAnimationFrame( new EyelidSample(eyelid, weight: 0f), interval)); } return frames; } /// <summary> /// Generates a collection of <see cref="EyelidAnimationFrame"/> for one blinking. /// </summary> /// <param name="eyelid"></param> /// <param name="framesPerSecond"></param> /// <param name="duration"></param> /// <param name="closingRate"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static IEnumerable<EyelidAnimationFrame> GenerateBlinkAnimationFrames(
Eyelid eyelid, int framesPerSecond, float duration, float closingRate) {
if (framesPerSecond <= 0) { throw new ArgumentOutOfRangeException(nameof(framesPerSecond)); } if (duration <= 0f) { throw new ArgumentOutOfRangeException(nameof(duration)); } if (closingRate is <= 0f or >= 1f) { throw new ArgumentOutOfRangeException(nameof(closingRate)); } int frameCount = (int)(duration * framesPerSecond) + 1; var frames = new EyelidAnimationFrame[frameCount]; var t = 0f; var dt = duration / frameCount; for (var i = 0; i < frameCount - 1; i++) { var weight = BlinkFunction .LinearWeight(t / duration, closingRate); frames[i] = new EyelidAnimationFrame( new EyelidSample(eyelid, weight), dt); t += dt; } frames[frameCount - 1] = new EyelidAnimationFrame( new EyelidSample(eyelid, weight: 0f), duration - (t - dt)); return frames; } } }
Assets/Mochineko/FacialExpressions/Blink/LinearEyelidAnimationGenerator.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "filename": "Assets/Mochineko/FacialExpressions/Blink/ProbabilisticEyelidAnimationGenerator.cs", "retrieved_chunk": " /// <returns></returns>\n /// <exception cref=\"ArgumentOutOfRangeException\"></exception>\n public static IEnumerable<EyelidAnimationFrame> GenerateBlinkAnimationFrames(\n Eyelid eyelid,\n int framesPerSecond, float duration, float closingRate,\n float beta, float a)\n {\n if (framesPerSecond <= 0)\n {\n throw new ArgumentOutOfRangeException(nameof(framesPerSecond));", "score": 0.9432034492492676 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/ProbabilisticEyelidAnimationGenerator.cs", "retrieved_chunk": " var duration = RandomFunction.GaussianRandomInRange(\n minDurationSeconds,\n maxDurationSeconds);\n frames.AddRange(GenerateBlinkAnimationFrames(\n eyelid,\n framesPerSecond,\n duration,\n closingRate,\n beta,\n a));", "score": 0.9070090055465698 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/ProbabilisticEyelidAnimationGenerator.cs", "retrieved_chunk": " int blinkCount,\n int framesPerSecond = 60, float closingRate = 0.2f,\n float beta = 10f, float a = 1f,\n float minDurationSeconds = 0.05f, float maxDurationSeconds = 0.2f,\n float minIntervalSeconds = 0.1f, float maxIntervalSeconds = 6f,\n float harmonicScale = 0.03f, float period = 3f)\n {\n var frames = new List<EyelidAnimationFrame>();\n for (var i = 0; i < blinkCount; i++)\n {", "score": 0.9049642086029053 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/ProbabilisticEyelidAnimationGenerator.cs", "retrieved_chunk": " {\n /// <summary>\n /// Generates a collection of <see cref=\"EyelidAnimationFrame\"/>\n /// for approximated eyelid animation and harmonic interval.\n /// </summary>\n /// <param name=\"eyelid\"></param>\n /// <param name=\"blinkCount\"></param>\n /// <param name=\"framesPerSecond\"></param>\n /// <param name=\"closingRate\"></param>\n /// <param name=\"beta\"></param>", "score": 0.9019801020622253 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/ProbabilisticEyelidAnimationGenerator.cs", "retrieved_chunk": " /// <summary>\n /// Generates a collection of <see cref=\"EyelidAnimationFrame\"/>\n /// for one blinking by approximated function.\n /// </summary>\n /// <param name=\"eyelid\"></param>\n /// <param name=\"framesPerSecond\"></param>\n /// <param name=\"duration\"></param>\n /// <param name=\"closingRate\"></param>\n /// <param name=\"beta\"></param>\n /// <param name=\"a\"></param>", "score": 0.9000122547149658 } ]
csharp
Eyelid eyelid, int framesPerSecond, float duration, float closingRate) {
using BepInEx; using BepInEx.Configuration; using Comfort.Common; using EFT; using LootingBots.Patch.Components; using LootingBots.Patch.Util; using LootingBots.Patch; using LootingBots.Brain; using DrakiaXYZ.BigBrain.Brains; using System.Collections.Generic; using HandbookClass = GClass2775; namespace LootingBots { [BepInPlugin(MOD_GUID, MOD_NAME, MOD_VERSION)] [BepInDependency("xyz.drakia.bigbrain", "0.1.4")] [BepInProcess("EscapeFromTarkov.exe")] public class LootingBots : BaseUnityPlugin { private const string MOD_GUID = "me.skwizzy.lootingbots"; private const string MOD_NAME = "LootingBots"; private const string MOD_VERSION = "1.1.2"; public const BotType SettingsDefaults = BotType.Scav | BotType.Pmc | BotType.Raider; // Loot Finder Settings public static ConfigEntry<BotType> CorpseLootingEnabled; public static ConfigEntry<BotType> ContainerLootingEnabled; public static ConfigEntry<
BotType> LooseItemLootingEnabled;
public static ConfigEntry<float> TimeToWaitBetweenLoot; public static ConfigEntry<float> DetectItemDistance; public static ConfigEntry<float> DetectContainerDistance; public static ConfigEntry<float> DetectCorpseDistance; public static ConfigEntry<bool> DebugLootNavigation; public static ConfigEntry<LogLevel> LootingLogLevels; public static Log LootLog; // Loot Settings public static ConfigEntry<bool> UseMarketPrices; public static ConfigEntry<bool> ValueFromMods; public static ConfigEntry<bool> CanStripAttachments; public static ConfigEntry<float> PMCLootThreshold; public static ConfigEntry<float> ScavLootThreshold; public static ConfigEntry<EquipmentType> PMCGearToEquip; public static ConfigEntry<EquipmentType> PMCGearToPickup; public static ConfigEntry<EquipmentType> ScavGearToEquip; public static ConfigEntry<EquipmentType> ScavGearToPickup; public static ConfigEntry<LogLevel> ItemAppraiserLogLevels; public static Log ItemAppraiserLog; public static ItemAppraiser ItemAppraiser = new ItemAppraiser(); public void LootFinderSettings() { CorpseLootingEnabled = Config.Bind( "Loot Finder", "Enable corpse looting", SettingsDefaults, new ConfigDescription( "Enables corpse looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 10 } ) ); DetectCorpseDistance = Config.Bind( "Loot Finder", "Detect corpse distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect a corpse", null, new ConfigurationManagerAttributes { Order = 9 } ) ); ContainerLootingEnabled = Config.Bind( "Loot Finder", "Enable container looting", SettingsDefaults, new ConfigDescription( "Enables container looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 8 } ) ); DetectContainerDistance = Config.Bind( "Loot Finder", "Detect container distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect a container", null, new ConfigurationManagerAttributes { Order = 7 } ) ); LooseItemLootingEnabled = Config.Bind( "Loot Finder", "Enable loose item looting", SettingsDefaults, new ConfigDescription( "Enables loose item looting for the selected bot types", null, new ConfigurationManagerAttributes { Order = 6 } ) ); DetectItemDistance = Config.Bind( "Loot Finder", "Detect item distance", 75f, new ConfigDescription( "Distance (in meters) a bot is able to detect an item", null, new ConfigurationManagerAttributes { Order = 5 } ) ); TimeToWaitBetweenLoot = Config.Bind( "Loot Finder", "Delay between looting", 15f, new ConfigDescription( "The amount of time the bot will wait after looting an container/item/corpse before trying to find the next nearest item/container/corpse", null, new ConfigurationManagerAttributes { Order = 2 } ) ); LootingLogLevels = Config.Bind( "Loot Finder", "Log Levels", LogLevel.Error | LogLevel.Info, new ConfigDescription( "Enable different levels of log messages to show in the logs", null, new ConfigurationManagerAttributes { Order = 1 } ) ); DebugLootNavigation = Config.Bind( "Loot Finder", "Debug: Show navigation points", false, new ConfigDescription( "Renders shperes where bots are trying to navigate when container looting. (Red): Container position. (Black): 'Optimized' container position. (Green): Calculated bot destination. (Blue): NavMesh corrected destination (where the bot will move).", null, new ConfigurationManagerAttributes { Order = 0 } ) ); } public void LootSettings() { UseMarketPrices = Config.Bind( "Loot Settings", "Use flea market prices", false, new ConfigDescription( "Bots will query more accurate ragfair prices to do item value checks. Will make a query to get ragfair prices when the client is first started", null, new ConfigurationManagerAttributes { Order = 10 } ) ); ValueFromMods = Config.Bind( "Loot Settings", "Calculate weapon value from attachments", true, new ConfigDescription( "Calculate weapon value by looking up each attachement. More accurate than just looking at the base weapon template but a slightly more expensive check", null, new ConfigurationManagerAttributes { Order = 9 } ) ); CanStripAttachments = Config.Bind( "Loot Settings", "Allow weapon attachment stripping", true, new ConfigDescription( "Allows bots to take the attachments off of a weapon if they are not able to pick the weapon up into their inventory", null, new ConfigurationManagerAttributes { Order = 8 } ) ); PMCLootThreshold = Config.Bind( "Loot Settings", "PMC: Loot value threshold", 12000f, new ConfigDescription( "PMC bots will only loot items that exceed the specified value in roubles", null, new ConfigurationManagerAttributes { Order = 6 } ) ); PMCGearToEquip = Config.Bind( "Loot Settings", "PMC: Allowed gear to equip", EquipmentType.All, new ConfigDescription( "The equipment a PMC bot is able to equip during raid", null, new ConfigurationManagerAttributes { Order = 5 } ) ); PMCGearToPickup = Config.Bind( "Loot Settings", "PMC: Allowed gear in bags", EquipmentType.All, new ConfigDescription( "The equipment a PMC bot is able to place in their backpack/rig", null, new ConfigurationManagerAttributes { Order = 4 } ) ); ScavLootThreshold = Config.Bind( "Loot Settings", "Scav: Loot value threshold", 5000f, new ConfigDescription( "All non-PMC bots will only loot items that exceed the specified value in roubles.", null, new ConfigurationManagerAttributes { Order = 3 } ) ); ScavGearToEquip = Config.Bind( "Loot Settings", "Scav: Allowed gear to equip", EquipmentType.All, new ConfigDescription( "The equipment a non-PMC bot is able to equip during raid", null, new ConfigurationManagerAttributes { Order = 2 } ) ); ScavGearToPickup = Config.Bind( "Loot Settings", "Scav: Allowed gear in bags", EquipmentType.All, new ConfigDescription( "The equipment a non-PMC bot is able to place in their backpack/rig", null, new ConfigurationManagerAttributes { Order = 1 } ) ); ItemAppraiserLogLevels = Config.Bind( "Loot Settings", "Log Levels", LogLevel.Error, new ConfigDescription( "Enables logs for the item apprasier that calcualtes the weapon values", null, new ConfigurationManagerAttributes { Order = 0 } ) ); } public void Awake() { LootFinderSettings(); LootSettings(); LootLog = new Log(Logger, LootingLogLevels); ItemAppraiserLog = new Log(Logger, ItemAppraiserLogLevels); new SettingsAndCachePatch().Enable(); new RemoveComponent().Enable(); BrainManager.RemoveLayer( "Utility peace", new List<string>() { "Assault", "ExUsec", "BossSanitar", "CursAssault", "PMC", "SectantWarrior" } ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "Assault", "BossSanitar", "CursAssault", "BossKojaniy", "SectantPriest", "FollowerGluharScout", "FollowerGluharProtect", "FollowerGluharAssault", "BossGluhar", "Fl_Zraychiy", "TagillaFollower", "FollowerSanitar", "FollowerBully", "BirdEye", "BigPipe", "Knight", "BossZryachiy", "Tagilla", "Killa", "BossSanitar", "BossBully" }, 2 ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "PMC", "ExUsec" }, 3 ); BrainManager.AddCustomLayer( typeof(LootingLayer), new List<string>() { "SectantWarrior" }, 13 ); } public void Update() { bool shoultInitAppraiser = (!UseMarketPrices.Value && ItemAppraiser.HandbookData == null) || (UseMarketPrices.Value && !ItemAppraiser.MarketInitialized); // Initialize the itemAppraiser when the BE instance comes online if ( Singleton<ClientApplication<ISession>>.Instance != null && Singleton<HandbookClass>.Instance != null && shoultInitAppraiser ) { LootLog.LogInfo($"Initializing item appraiser"); ItemAppraiser.Init(); } } } }
LootingBots/LootingBots.cs
Skwizzy-SPT-LootingBots-76279a3
[ { "filename": "LootingBots/patches/SettingsAndCache.cs", "retrieved_chunk": " ref BotDifficultySettingsClass __instance,\n ref WildSpawnType ___wildSpawnType_0\n )\n {\n bool corpseLootEnabled = LootingBots.CorpseLootingEnabled.Value.IsBotEnabled(\n ___wildSpawnType_0\n );\n bool containerLootEnabled = LootingBots.ContainerLootingEnabled.Value.IsBotEnabled(\n ___wildSpawnType_0\n );", "score": 0.8554531931877136 }, { "filename": "LootingBots/patches/SettingsAndCache.cs", "retrieved_chunk": " bool itemLootEnabled = LootingBots.LooseItemLootingEnabled.Value.IsBotEnabled(\n ___wildSpawnType_0\n );\n if (corpseLootEnabled || containerLootEnabled || itemLootEnabled)\n {\n __instance.FileSettings.Shoot.CHANCE_TO_CHANGE_WEAPON = 80;\n __instance.FileSettings.Shoot.CHANCE_TO_CHANGE_WEAPON_WITH_HELMET = 40;\n }\n }\n }", "score": 0.8497639894485474 }, { "filename": "LootingBots/logics/FindLootLogic.cs", "retrieved_chunk": " {\n private readonly LootingBrain _lootingBrain;\n private readonly BotLog _log;\n private float DetectCorpseDistance\n {\n get { return Mathf.Pow(LootingBots.DetectCorpseDistance.Value, 2); }\n }\n private float DetectContainerDistance\n {\n get { return Mathf.Pow(LootingBots.DetectContainerDistance.Value, 2); }", "score": 0.8432365655899048 }, { "filename": "LootingBots/components/LootingBrain.cs", "retrieved_chunk": " public InventoryController InventoryController;\n // Current container that the bot will try to loot\n public LootableContainer ActiveContainer;\n // Current loose item that the bot will try to loot\n public LootItem ActiveItem;\n // Current corpse that the bot will try to loot\n public BotOwner ActiveCorpse;\n // Center of the loot object's collider used to help in navigation\n public Vector3 LootObjectCenter;\n // Collider.transform.position for the active lootable. Used in LOS checks to make sure bots dont loot through walls", "score": 0.8322705626487732 }, { "filename": "LootingBots/components/LootingBrain.cs", "retrieved_chunk": " public Vector3 LootObjectPosition;\n // Object ids that the bot has looted\n public List<string> IgnoredLootIds;\n // Object ids that were not able to be reached even though a valid path exists. Is cleared every 2 mins by default\n public List<string> NonNavigableLootIds;\n public BotStats Stats\n {\n get { return InventoryController.Stats; }\n }\n public bool IsBotLooting {", "score": 0.8315934538841248 } ]
csharp
BotType> LooseItemLootingEnabled;
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": " return searchPattern.EndsWith(\"?\", StringComparison.Ordinal);\n }\n return true;\n }\n private static IReadOnlyList<string> GetAccessibleFiles(IFileSystem fileSystem, string path, string filespec, string projectDirectory, bool stripProjectDirectory)\n {\n try\n {\n string path2 = ((path.Length == 0) ? s_thisDirectory : path);\n IEnumerable<string> enumerable;", "score": 0.8276574015617371 }, { "filename": "Microsoft.Build.Shared/FileMatcher.cs", "retrieved_chunk": " private static int SkipSlashes(string aString, int startingIndex)\n {\n int i;\n for (i = startingIndex; i < aString.Length && FileUtilities.IsAnySlash(aString[i]); i++)\n {\n }\n return i;\n }\n internal static bool IsRecursiveDirectoryMatch(string path)\n {", "score": 0.8217281699180603 }, { "filename": "Microsoft.Build.Framework/NativeMethods.cs", "retrieved_chunk": " {\n return DateTime.MinValue;\n }\n return File.GetLastWriteTimeUtc(path);\n }\n internal static DateTime GetLastWriteFileUtcTime(string fullPath)\n {\n#if __\n if (Traits.Instance.EscapeHatches.AlwaysDoImmutableFilesUpToDateCheck)\n {", "score": 0.8190310597419739 }, { "filename": "Microsoft.Build.Shared/FileMatcher.cs", "retrieved_chunk": " {\n return true;\n }\n return directorySeparatorCharacters.Contains(possibleChild[possibleParent.Length]);\n }\n private static bool DirectoryEndsWithPattern(string directoryPath, string pattern)\n {\n int num = directoryPath.LastIndexOfAny(FileUtilities.Slashes);\n if (num != -1)\n {", "score": 0.8162716031074524 }, { "filename": "Microsoft.Build.Shared/FileTracker.cs", "retrieved_chunk": " public static bool FileIsExcludedFromDependencies(string fileName)\n {\n#if __\n if (!FileIsUnderPath(fileName, s_applicationDataPath) && !FileIsUnderPath(fileName, s_localApplicationDataPath) && !FileIsUnderPath(fileName, s_localLowApplicationDataPath) && !FileIsUnderPath(fileName, s_tempShortPath) && !FileIsUnderPath(fileName, s_tempLongPath))\n {\n return s_commonApplicationDataPaths.Any((string p) => FileIsUnderPath(fileName, p));\n }\n return true;\n#else\n // Linux下公共文件跟这些目录都没什么关系。", "score": 0.8159962296485901 } ]
csharp
IFileSystem fileSystem = null) {