Dataset Preview
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed because of a cast error
Error code: DatasetGenerationCastError Exception: DatasetGenerationCastError Message: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 1 new columns ({'crossfile_context'}) This happened while the json dataset builder was generating data using hf://datasets/Vincentvmt/CrossCodeEval/crosscodeeval_data/csharp/line_completion_oracle_bm25.jsonl (at revision 41f916e35cc48bcca5dc369664f931afd9ffa22f) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations) Traceback: Traceback (most recent call last): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2011, in _prepare_split_single writer.write_table(table) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 585, in write_table pa_table = table_cast(pa_table, self._schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast return cast_table_to_schema(table, schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2256, in cast_table_to_schema raise CastError( datasets.table.CastError: Couldn't cast prompt: string groundtruth: string right_context: string metadata: struct<task_id: string, repository: string, file: string, context_start_lineno: int64, groundtruth_start_lineno: int64, right_context_start_lineno: int64> child 0, task_id: string child 1, repository: string child 2, file: string child 3, context_start_lineno: int64 child 4, groundtruth_start_lineno: int64 child 5, right_context_start_lineno: int64 crossfile_context: struct<text: string, list: list<item: struct<retrieved_chunk: string, filename: string, score: double>>> child 0, text: string child 1, list: list<item: struct<retrieved_chunk: string, filename: string, score: double>> child 0, item: struct<retrieved_chunk: string, filename: string, score: double> child 0, retrieved_chunk: string child 1, filename: string child 2, score: double to {'prompt': Value(dtype='string', id=None), 'groundtruth': Value(dtype='string', id=None), 'right_context': Value(dtype='string', id=None), 'metadata': {'task_id': Value(dtype='string', id=None), 'repository': Value(dtype='string', id=None), 'file': Value(dtype='string', id=None), 'context_start_lineno': Value(dtype='int64', id=None), 'groundtruth_start_lineno': Value(dtype='int64', id=None), 'right_context_start_lineno': Value(dtype='int64', id=None)}} because column names don't match During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1321, in compute_config_parquet_and_info_response parquet_operations = convert_to_parquet(builder) File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 935, in convert_to_parquet builder.download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare self._download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2013, in _prepare_split_single raise DatasetGenerationCastError.from_cast_error( datasets.exceptions.DatasetGenerationCastError: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 1 new columns ({'crossfile_context'}) This happened while the json dataset builder was generating data using hf://datasets/Vincentvmt/CrossCodeEval/crosscodeeval_data/csharp/line_completion_oracle_bm25.jsonl (at revision 41f916e35cc48bcca5dc369664f931afd9ffa22f) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
prompt
string | groundtruth
string | right_context
string | metadata
dict |
---|---|---|---|
using LassoProcessManager.Models.Rules;
using Newtonsoft.Json;
using ProcessManager.Models.Configs;
using System.Reflection;
namespace ProcessManager.Providers
{
public class ConfigProvider : IConfigProvider
{
private const string ConfigFileName = "Config.json";
private ManagerConfig managerConfig;
private ILogProvider LogProvider { get; set; }
public ConfigProvider(ILogProvider logProvider)
=> this.LogProvider = logProvider;
public ManagerConfig GetManagerConfig()
{
if (managerConfig != null)
return managerConfig;
string configPath = GetConfigFilePath();
try
{
managerConfig = JsonConvert.DeserializeObject<ManagerConfig>(File.ReadAllText(GetConfigFilePath()));
return managerConfig;
}
catch
{
LogProvider.Log($"Failed to load config at '{configPath}'.");
}
return null;
}
public List<BaseRule> GetRules()
{
List<BaseRule> rules = new List<BaseRule>();
rules.AddRange(managerConfig.ProcessRules);
rules.AddRange(managerConfig.FolderRules);
return rules;
}
public Dictionary<string,
|
LassoProfile> GetLassoProfiles()
{
|
Dictionary<string, LassoProfile> lassoProfiles = new Dictionary<string, LassoProfile>();
// Load lasso profiles
foreach (var profile in managerConfig.Profiles)
{
if (!lassoProfiles.ContainsKey(profile.Name))
{
lassoProfiles.Add(profile.Name, profile);
}
}
return lassoProfiles;
}
private string GetConfigFilePath()
=> Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);
}
}
|
{
"task_id": "project_cc_csharp/27",
"repository": "kenshinakh1-LassoProcessManager-bcc481f",
"file": "ProcessManager/Providers/ConfigProvider.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 45,
"right_context_start_lineno": 47
}
|
using System.Text;
using System.Net;
using Microsoft.Extensions.Caching.Memory;
using Serilog;
using Serilog.Events;
using Iced.Intel;
using static Iced.Intel.AssemblerRegisters;
namespace OGXbdmDumper
{
public class Xbox : IDisposable
{
#region Properties
private bool _disposed;
private const int _cacheDuration = 1; // in minutes
private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });
private bool? _hasFastGetmem;
public ScratchBuffer StaticScratch;
public bool HasFastGetmem
{
get
{
if (_hasFastGetmem == null)
{
try
{
long testAddress = 0x10000;
if (IsValidAddress(testAddress))
{
Session.SendCommandStrict("getmem2 addr={0} length=1", testAddress.ToHexString());
Session.ClearReceiveBuffer();
_hasFastGetmem = true;
Log.Information("Fast getmem support detected.");
}
else _hasFastGetmem = false;
}
catch
{
_hasFastGetmem = false;
}
}
return _hasFastGetmem.Value;
}
}
/// <summary>
/// Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.
/// </summary>
public bool SafeMode { get; set; } = true;
public bool IsConnected => Session.IsConnected;
public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }
public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }
public Connection Session { get; private set; } = new Connection();
public ConnectionInfo? ConnectionInfo { get; protected set; }
/// <summary>
/// The Xbox memory stream.
/// </summary>
public XboxMemoryStream Memory { get; private set; }
public Kernel Kernel { get; private set; }
public List<Module> Modules => GetModules();
public List<
|
Thread> Threads => GetThreads();
|
public Version Version => GetVersion();
#endregion
#region Connection
public void Connect(string host, int port = 731)
{
_cache.Clear();
ConnectionInfo = Session.Connect(host, port);
// init subsystems
Memory = new XboxMemoryStream(this);
Kernel = new Kernel(this);
StaticScratch = new ScratchBuffer(this);
Log.Information("Loaded Modules:");
foreach (var module in Modules)
{
Log.Information("\t{0} ({1})", module.Name, module.TimeStamp);
}
Log.Information("Xbdm Version {0}", Version);
Log.Information("Kernel Version {0}", Kernel.Version);
// enable remote code execution and use the remainder reloc section as scratch
PatchXbdm(this);
}
public void Disconnect()
{
Session.Disconnect();
ConnectionInfo = null;
_cache.Clear();
}
public List<ConnectionInfo> Discover(int timeout = 500)
{
return ConnectionInfo.DiscoverXbdm(731, timeout);
}
public void Connect(IPEndPoint endpoint)
{
Connect(endpoint.Address.ToString(), endpoint.Port);
}
public void Connect(int timeout = 500)
{
Connect(Discover(timeout).First().Endpoint);
}
#endregion
#region Memory
public bool IsValidAddress(long address)
{
try
{
Session.SendCommandStrict("getmem addr={0} length=1", address.ToHexString());
return "??" != Session.ReceiveMultilineResponse()[0];
}
catch
{
return false;
}
}
public void ReadMemory(long address, Span<byte> buffer)
{
if (HasFastGetmem && !SafeMode)
{
Session.SendCommandStrict("getmem2 addr={0} length={1}", address.ToHexString(), buffer.Length);
Session.Read(buffer);
if (Log.IsEnabled(LogEventLevel.Verbose))
{
Log.Verbose(buffer.ToHexString());
}
}
else if (!SafeMode)
{
// custom getmem2
Session.SendCommandStrict("funccall type=1 addr={0} length={1}", address, buffer.Length);
Session.ReadExactly(buffer);
if (Log.IsEnabled(LogEventLevel.Verbose))
{
Log.Verbose(buffer.ToHexString());
}
}
else
{
Session.SendCommandStrict("getmem addr={0} length={1}", address.ToHexString(), buffer.Length);
int bytesRead = 0;
string hexString;
while ((hexString = Session.ReceiveLine()) != ".")
{
Span<byte> slice = buffer.Slice(bytesRead, hexString.Length / 2);
slice.FromHexString(hexString);
bytesRead += slice.Length;
}
}
}
public void ReadMemory(long address, byte[] buffer, int offset, int count)
{
ReadMemory(address, buffer.AsSpan(offset, count));
}
public void ReadMemory(long address, int count, Stream destination)
{
// argument checks
if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
if (destination == null) throw new ArgumentNullException(nameof(destination));
Span<byte> buffer = stackalloc byte[1024 * 80];
while (count > 0)
{
int bytesToRead = Math.Min(buffer.Length, count);
Span<byte> slice = buffer.Slice(0, bytesToRead);
ReadMemory(address, slice);
destination.Write(slice);
count -= bytesToRead;
address += (uint)bytesToRead;
}
}
public void WriteMemory(long address, ReadOnlySpan<byte> buffer)
{
const int maxBytesPerLine = 240;
int totalWritten = 0;
while (totalWritten < buffer.Length)
{
ReadOnlySpan<byte> slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));
Session.SendCommandStrict("setmem addr={0} data={1}", (address + totalWritten).ToHexString(), slice.ToHexString());
totalWritten += slice.Length;
}
}
public void WriteMemory(long address, byte[] buffer, int offset, int count)
{
WriteMemory(address, buffer.AsSpan(offset, count));
}
public void WriteMemory(long address, int count, Stream source)
{
// argument checks
if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
if (source == null) throw new ArgumentNullException(nameof(source));
Span<byte> buffer = stackalloc byte[1024 * 80];
while (count > 0)
{
int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));
WriteMemory(address, buffer.Slice(0, bytesRead));
count -= bytesRead;
address += bytesRead;
}
}
#endregion
#region Process
public List<Thread> GetThreads()
{
List<Thread> threads = new List<Thread>();
Session.SendCommandStrict("threads");
foreach (var threadId in Session.ReceiveMultilineResponse())
{
Session.SendCommandStrict("threadinfo thread={0}", threadId);
var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));
threads.Add(new Thread
{
Id = Convert.ToInt32(threadId),
Suspend = (int)(uint)info["suspend"], // initially -1 in earlier xbdm versions, 0 in later ones
Priority = (int)(uint)info["priority"],
TlsBase = (uint)info["tlsbase"],
// optional depending on xbdm version
Start = info.ContainsKey("start") ? (uint)info["start"] : 0,
Base = info.ContainsKey("base") ? (uint)info["base"] : 0,
Limit = info.ContainsKey("limit") ? (uint)info["limit"] : 0,
CreationTime = DateTime.FromFileTime(
(info.ContainsKey("createhi") ? (((long)(uint)info["createhi"]) << 32) : 0) |
(info.ContainsKey("createlo") ? (uint)info["createlo"] : 0))
});
}
return threads;
}
public List<Module> GetModules()
{
List<Module> modules = new List<Module>();
Session.SendCommandStrict("modules");
foreach (var moduleResponse in Session.ReceiveMultilineResponse())
{
var moduleInfo = Connection.ParseKvpResponse(moduleResponse);
Module module = new Module
{
Name = (string)moduleInfo["name"],
BaseAddress = (uint)moduleInfo["base"],
Size = (int)(uint)moduleInfo["size"],
Checksum = (uint)moduleInfo["check"],
TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo["timestamp"]).DateTime,
Sections = new List<ModuleSection>(),
HasTls = moduleInfo.ContainsKey("tls"),
IsXbe = moduleInfo.ContainsKey("xbe")
};
Session.SendCommandStrict("modsections name=\"{0}\"", module.Name);
foreach (var sectionResponse in Session.ReceiveMultilineResponse())
{
var sectionInfo = Connection.ParseKvpResponse(sectionResponse);
module.Sections.Add(new ModuleSection
{
Name = (string)sectionInfo["name"],
Base = (uint)sectionInfo["base"],
Size = (int)(uint)sectionInfo["size"],
Flags = (uint)sectionInfo["flags"]
});
}
modules.Add(module);
}
return modules;
}
public Version GetVersion()
{
var version = _cache.Get<Version>(nameof(GetVersion));
if (version == null)
{
try
{
// peek inside VS_VERSIONINFO struct
var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals("xbdm.dll")).GetSection(".rsrc").Base + 0x98;
// call getmem directly to avoid dependency loops with ReadMemory checking the version
Span<byte> buffer = stackalloc byte[sizeof(ushort) * 4];
Session.SendCommandStrict("getmem addr={0} length={1}", versionAddress.ToHexString(), buffer.Length);
buffer.FromHexString(Session.ReceiveMultilineResponse().First());
version = new Version(
BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),
BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),
BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),
BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))
);
// cache the result
_cache.Set(nameof(GetVersion), version);
}
catch
{
version = new Version("0.0.0.0");
}
}
return version;
}
public void Stop()
{
Log.Information("Suspending xbox execution.");
Session.SendCommand("stop");
}
public void Go()
{
Log.Information("Resuming xbox execution.");
Session.SendCommand("go");
}
/// <summary>
/// Calls an Xbox function.
/// </summary>
/// <param name="address">The function address.</param>
/// <param name="args">The function arguments.</param>
/// <returns>Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.</returns>
public uint Call(long address, params object[] args)
{
// TODO: call context (~4039+ which requires qwordparam)
// injected script pushes arguments in reverse order for simplicity, this corrects that
var reversedArgs = args.Reverse().ToArray();
StringBuilder command = new StringBuilder();
command.AppendFormat("funccall type=0 addr={0} ", address);
for (int i = 0; i < reversedArgs.Length; i++)
{
command.AppendFormat("arg{0}={1} ", i, Convert.ToUInt32(reversedArgs[i]));
}
var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);
return (uint)returnValues["eax"];
}
/// <summary>
/// Original Xbox Debug Monitor runtime patches.
/// Prevents crashdumps from being written to the HDD and enables remote code execution.
/// </summary>
/// <param name="target"></param>
private void PatchXbdm(Xbox target)
{
// the spin routine to be patched in after the signature patterns
// spin:
// jmp spin
// int 3
var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };
// prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)
if (target.Signatures.ContainsKey("ReadWriteOneSector"))
{
Log.Information("Disabling crashdump functionality.");
target.WriteMemory(target.Signatures["ReadWriteOneSector"] + 9, spinBytes);
}
else if (target.Signatures.ContainsKey("WriteSMBusByte"))
{
// this will prevent the LED state from changing upon crash
Log.Information("Disabling crashdump functionality.");
target.WriteMemory(target.Signatures["WriteSMBusByte"] + 9, spinBytes);
}
Log.Information("Patching xbdm memory to enable remote code execution.");
uint argThreadStringAddress = StaticScratch.Alloc("thread\0");
uint argTypeStringAddress = StaticScratch.Alloc("type\0");
uint argAddrStringAddress = StaticScratch.Alloc("addr\0");
uint argLengthStringAddress = StaticScratch.Alloc("length\0");
uint argFormatStringAddress = StaticScratch.Alloc("arg%01d\0");
uint returnFormatAddress = StaticScratch.Alloc("eax=0x%X\0");
var asm = new Assembler(32);
#region HrSendGetMemory2Data
uint getmem2CallbackAddress = 0;
if (!HasFastGetmem)
{
// labels
var label1 = asm.CreateLabel();
var label2 = asm.CreateLabel();
var label3 = asm.CreateLabel();
asm.push(ebx);
asm.mov(ebx, __dword_ptr[esp + 8]); // pdmcc
asm.mov(eax, __dword_ptr[ebx + 0x14]); // size
asm.test(eax, eax);
asm.mov(edx, __dword_ptr[ebx + 0x10]);
asm.ja(label1);
//asm.push(__dword_ptr[ebx + 8]);
//asm.call((uint)target.Signatures["DmFreePool"]);
//asm.and(__dword_ptr[ebx + 8], 0);
asm.mov(eax, 0x82DB0104);
asm.jmp(label3);
asm.Label(ref label1);
asm.mov(ecx, __dword_ptr[ebx + 0xC]); // buffer size
asm.cmp(eax, ecx);
asm.jb(label2);
asm.mov(eax, ecx);
asm.Label(ref label2);
asm.push(ebp);
asm.push(esi);
asm.mov(esi, __dword_ptr[edx + 0x14]); // address
asm.push(edi);
asm.mov(edi, __dword_ptr[ebx + 8]);
asm.mov(ecx, eax);
asm.mov(ebp, ecx);
asm.shr(ecx, 2);
asm.rep.movsd();
asm.mov(ecx, ebp);
asm.and(ecx, 3);
asm.rep.movsb();
asm.sub(__dword_ptr[ebx + 0x14], eax);
asm.pop(edi);
asm.mov(__dword_ptr[ebx + 4], eax);
asm.add(__dword_ptr[edx + 0x14], eax);
asm.pop(esi);
asm.mov(eax, 0x2DB0000);
asm.pop(ebp);
asm.Label(ref label3);
asm.pop(ebx);
asm.ret(0xC);
getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));
}
#endregion
#region HrFunctionCall
// 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different
asm = new Assembler(32);
// labels
var binaryResponseLabel = asm.CreateLabel();
var getmem2Label = asm.CreateLabel();
var errorLabel = asm.CreateLabel();
var successLabel = asm.CreateLabel();
// prolog
asm.push(ebp);
asm.mov(ebp, esp);
asm.sub(esp, 0x10); // carve out arbitrary space for local temp variables
asm.pushad();
// disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space
asm.mov(eax, cr0);
asm.and(eax, 0xFFFEFFFF);
asm.mov(cr0, eax);
// arguments
var commandPtr = ebp + 0x8;
var responseAddress = ebp + 0xC;
var pdmcc = ebp + 0x14;
// local variables
var temp = ebp - 0x4;
var callAddress = ebp - 0x8;
var argName = ebp - 0x10;
// check for thread id
asm.lea(eax, temp);
asm.push(eax);
asm.push(argThreadStringAddress); // 'thread', 0
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetDwParam"]);
asm.test(eax, eax);
var customCommandLabel = asm.CreateLabel();
asm.je(customCommandLabel);
// call original code if thread id exists
asm.push(__dword_ptr[temp]);
asm.call((uint)target.Signatures["DmSetupFunctionCall"]);
var doneLabel = asm.CreateLabel();
asm.jmp(doneLabel);
// thread argument doesn't exist, must be a custom command
asm.Label(ref customCommandLabel);
// determine custom function type
asm.lea(eax, temp);
asm.push(eax);
asm.push(argTypeStringAddress); // 'type', 0
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetDwParam"]);
asm.test(eax, eax);
asm.je(errorLabel);
#region Custom Call (type 0)
asm.cmp(__dword_ptr[temp], 0);
asm.jne(getmem2Label);
// get the call address
asm.lea(eax, __dword_ptr[callAddress]);
asm.push(eax);
asm.push(argAddrStringAddress); // 'addr', 0
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetDwParam"]);
asm.test(eax, eax);
asm.je(errorLabel);
// push arguments (leave it up to caller to reverse argument order and supply the correct amount)
asm.xor(edi, edi);
var nextArgLabel = asm.CreateLabel();
var noMoreArgsLabel = asm.CreateLabel();
asm.Label(ref nextArgLabel);
{
// get argument name
asm.push(edi); // argument index
asm.push(argFormatStringAddress); // format string address
asm.lea(eax, __dword_ptr[argName]); // argument name address
asm.push(eax);
asm.call((uint)target.Signatures["sprintf"]);
asm.add(esp, 0xC);
// check if it's included in the command
asm.lea(eax, __[temp]); // argument value address
asm.push(eax);
asm.lea(eax, __[argName]); // argument name address
asm.push(eax);
asm.push(__dword_ptr[commandPtr]); // command
asm.call((uint)target.Signatures["FGetDwParam"]);
asm.test(eax, eax);
asm.je(noMoreArgsLabel);
// push it on the stack
asm.push(__dword_ptr[temp]);
asm.inc(edi);
// move on to the next argument
asm.jmp(nextArgLabel);
}
asm.Label(ref noMoreArgsLabel);
// perform the call
asm.call(__dword_ptr[callAddress]);
// print response message
asm.push(eax); // integer return value
asm.push(returnFormatAddress); // format string address
asm.push(__dword_ptr[responseAddress]); // response address
asm.call((uint)target.Signatures["sprintf"]);
asm.add(esp, 0xC);
asm.jmp(successLabel);
#endregion
#region Fast Getmem (type 1)
asm.Label(ref getmem2Label);
asm.cmp(__dword_ptr[temp], 1);
asm.jne(errorLabel);
if (!HasFastGetmem)
{
// TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)
StaticScratch.Align16();
uint getmem2BufferSize = 512;
uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);
// get length and size args
asm.mov(esi, __dword_ptr[pdmcc]);
asm.push(__dword_ptr[responseAddress]);
asm.mov(edi, __dword_ptr[esi + 0x10]);
asm.lea(eax, __dword_ptr[pdmcc]);
asm.push(eax);
asm.push(argAddrStringAddress);
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetNamedDwParam"]);
asm.test(eax, eax);
asm.jz(errorLabel);
asm.push(__dword_ptr[responseAddress]);
asm.lea(eax, __dword_ptr[responseAddress]);
asm.push(eax);
asm.push(argLengthStringAddress);
asm.push(__dword_ptr[commandPtr]);
asm.call((uint)target.Signatures["FGetNamedDwParam"]);
asm.test(eax, eax);
asm.jz(errorLabel);
asm.mov(eax, __dword_ptr[pdmcc]); // address
asm.and(__dword_ptr[edi + 0x10], 0);
asm.mov(__dword_ptr[edi + 0x14], eax);
//asm.mov(eax, 0x2000); // TODO: increase pool size?
//asm.push(eax);
//asm.call((uint)target.Signatures["DmAllocatePool"]); // TODO: crashes in here, possible IRQ issues?
asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); // buffer size
asm.mov(__dword_ptr[esi + 8], getmem2buffer); // buffer address
asm.mov(eax, __dword_ptr[responseAddress]);
asm.mov(__dword_ptr[esi + 0x14], eax);
asm.mov(__dword_ptr[esi], getmem2CallbackAddress);
asm.jmp(binaryResponseLabel);
}
#endregion
#region Return Codes
// if we're here, must be an unknown custom type
asm.jmp(errorLabel);
// generic success epilog
asm.Label(ref successLabel);
asm.popad();
asm.leave();
asm.mov(eax, 0x2DB0000);
asm.ret(0x10);
// successful binary response follows epilog
asm.Label(ref binaryResponseLabel);
asm.popad();
asm.leave();
asm.mov(eax, 0x2DB0003);
asm.ret(0x10);
// generic failure epilog
asm.Label(ref errorLabel);
asm.popad();
asm.leave();
asm.mov(eax, 0x82DB0000);
asm.ret(0x10);
// original epilog
asm.Label(ref doneLabel);
asm.popad();
asm.leave();
asm.ret(0x10);
#endregion
// inject RPC handler and hook
uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));
Log.Information("HrFuncCall address {0}", caveAddress.ToHexString());
asm.Hook(target, target.Signatures["HrFunctionCall"], caveAddress);
#endregion
}
public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)
{
// read code from xbox memory
byte[] code = Memory.ReadBytes(address, length);
// disassemble valid instructions
var decoder = Iced.Intel.Decoder.Create(32, code);
decoder.IP = (ulong)address;
var instructions = new List<Instruction>();
while (decoder.IP < decoder.IP + (uint)code.Length)
{
var insn = decoder.Decode();
if (insn.IsInvalid)
break;
instructions.Add(insn);
}
// formatting options
var formatter = new MasmFormatter();
formatter.Options.FirstOperandCharIndex = 8;
formatter.Options.SpaceAfterOperandSeparator = true;
// convert to string
var output = new StringOutput();
var disassembly = new StringBuilder();
bool firstInstruction = true;
foreach (var instr in instructions)
{
// skip newline for the first instruction
if (firstInstruction)
{
firstInstruction = false;
} else disassembly.AppendLine();
// optionally indent
if (tabPrefix)
{
disassembly.Append('\t');
}
// output address
disassembly.Append(instr.IP.ToString("X8"));
disassembly.Append(' ');
// optionally output instruction bytes
if (showBytes)
{
for (int i = 0; i < instr.Length; i++)
disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString("X2"));
int missingBytes = 10 - instr.Length;
for (int i = 0; i < missingBytes; i++)
disassembly.Append(" ");
disassembly.Append(' ');
}
// output the decoded instruction
formatter.Format(instr, output);
disassembly.Append(output.ToStringAndReset());
}
return disassembly.ToString();
}
public Dictionary<string, long> Signatures
{
get
{
var signatures = _cache.Get<Dictionary<string, long>>(nameof(Signatures));
if (signatures == null)
{
var resolver = new SignatureResolver
{
// NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect
// universal pattern
new SodmaSignature("ReadWriteOneSector")
{
// mov ebp, esp
new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),
// mov dx, 1F6h
new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),
// mov al, 0A0h
new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })
},
// universal pattern
new SodmaSignature("WriteSMBusByte")
{
// mov al, 20h
new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),
// mov dx, 0C004h
new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),
},
// universal pattern
new SodmaSignature("FGetDwParam")
{
// jz short 0x2C
new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),
// push 20h
new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),
// mov [ecx], eax
new OdmPattern(0x33, new byte[] { 0x89, 0x01 })
},
// universal pattern
new SodmaSignature("FGetNamedDwParam")
{
// mov ebp, esp
new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),
// jnz short 0x17
new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),
// retn 10h
new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })
},
// universal pattern
new SodmaSignature("DmSetupFunctionCall")
{
// test ax, 280h
new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),
// push 63666D64h
new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })
},
// early revisions
new SodmaSignature("HrFunctionCall")
{
// mov eax, 80004005h
new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),
// mov ebx, 10008h
new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })
},
// later revisions
new SodmaSignature("HrFunctionCall")
{
// mov eax, 80004005h
new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),
// mov ebx, 10008h
new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })
},
// xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha/dvt3/dvt4/dvt6 etc.
new SodmaSignature("sprintf")
{
// mov esi, [ebp+arg_0]
new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),
// mov [ebp+var_1C], 7FFFFFFFh
new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })
},
// early revisions
new SodmaSignature("DmAllocatePool")
{
// push ebp
new OdmPattern(0x0, new byte[] { 0x55 }),
// mov ebp, esp
new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),
// push 'enoN'
new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })
},
// later revisions
new SodmaSignature("DmAllocatePool")
{
// push 'enoN'
new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),
// retn 4
new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })
},
// universal pattern
new SodmaSignature("DmFreePool")
{
// cmp eax, 0B0000000h
new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })
}
};
// read xbdm .text section
var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals("xbdm.dll")).GetSection(".text");
byte[] data = new byte[xbdmTextSegment.Size];
ReadMemory(xbdmTextSegment.Base, data);
// scan for signatures
signatures = resolver.Resolve(data, xbdmTextSegment.Base);
// cache the result indefinitely
_cache.Set(nameof(Signatures), signatures);
}
return signatures;
}
}
#endregion
#region File
public char[] GetDrives()
{
return Session.SendCommandStrict("drivelist").Message.ToCharArray();
}
public List<XboxFileInformation> GetDirectoryList(string path)
{
var list = new List<XboxFileInformation>();
Session.SendCommandStrict("dirlist name=\"{0}\"", path);
foreach (string file in Session.ReceiveMultilineResponse())
{
var fileInfo = file.ParseXboxResponseLine();
var info = new XboxFileInformation();
info.FullName = Path.Combine(path, (string)fileInfo["name"]);
info.Size = ((long)fileInfo["sizehi"] << 32) | (long)fileInfo["sizelo"];
info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo["createhi"] << 32) | (long)fileInfo["createlo"]);
info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo["changehi"] << 32) | (long)fileInfo["changelo"]);
info.Attributes |= file.Contains("directory") ? FileAttributes.Directory : FileAttributes.Normal;
info.Attributes |= file.Contains("readonly") ? FileAttributes.ReadOnly : 0;
info.Attributes |= file.Contains("hidden") ? FileAttributes.Hidden : 0;
list.Add(info);
}
return list;
}
public void GetFile(string localPath, string remotePath)
{
Session.SendCommandStrict("getfile name=\"{0}\"", remotePath);
using var lfs = File.Create(localPath);
Session.CopyToCount(lfs, Session.Reader.ReadInt32());
}
#endregion
#region IDisposable
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
Session?.Dispose();
// TODO: set large fields to null
_disposed = true;
}
}
~Xbox()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
|
{
"task_id": "project_cc_csharp/20",
"repository": "Ernegien-OGXbdmDumper-07a1e82",
"file": "src/OGXbdmDumper/Xbox.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 75,
"right_context_start_lineno": 76
}
|
//#define PRINT_DEBUG
using System;
using System.IO;
using Godot;
using Mono.Unix;
using Directory = System.IO.Directory;
using Environment = System.Environment;
using File = System.IO.File;
using Path = System.IO.Path;
namespace GodotLauncher
{
public class DataPaths
{
static string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
static string BasePath => Path.Combine(AppDataPath, "ReadyToLaunch");
public static string platformOverride;
public static string SanitizeProjectPath(string path)
{
if (File.Exists(path))
{
path = new FileInfo(path).DirectoryName;
}
return path;
}
public static void EnsureProjectExists(string path)
{
var filePath = Path.Combine(path, "project.godot");
if (!File.Exists(filePath)) File.WriteAllText(filePath, "");
}
public static string GetExecutablePath(InstallerEntryData installerEntryData)
{
string platformName = GetPlatformName();
string path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);
path = Path.Combine(path, installerEntryData.ExecutableName);
return path;
}
public static string GetPlatformName()
{
if (!string.IsNullOrEmpty(platformOverride)) return platformOverride;
return OS.GetName();
}
public static void WriteFile(string fileName, byte[] data)
{
var path = Path.Combine(BasePath, fileName);
#if PRINT_DEBUG
GD.Print("Writing: " + path);
#endif
File.WriteAllBytes(path, data);
}
public static void WriteFile(string fileName, string data)
{
var path = Path.Combine(BasePath, fileName);
#if PRINT_DEBUG
GD.Print("Writing: " + path);
#endif
File.WriteAllText(path, data);
}
public static string ReadFile(string fileName, string defaultData = null)
{
var path = Path.Combine(BasePath, fileName);
if (File.Exists(path))
{
#if PRINT_DEBUG
GD.Print("Reading: " + path);
#endif
return File.ReadAllText(path);
}
#if PRINT_DEBUG
GD.Print("File not found: " + path);
#endif
return defaultData;
}
public static bool ExecutableExists(
|
InstallerEntryData installerEntryData)
{
|
string path = GetExecutablePath(installerEntryData);
bool exists = File.Exists(path);
#if PRINT_DEBUG
GD.Print("Checking if path exists: " + path + " exists=" + exists);
#endif
return exists;
}
public static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)
{
string source = Path.Combine(BasePath, fileName);
string dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);
if (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);
File.Delete(source);
}
public static void DeleteVersion(string version, string buildType)
{
Directory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);
}
public static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = "")
{
string path = GetExecutablePath(installerEntryData);
#if PRINT_DEBUG
GD.Print("Launching: " + path);
#endif
if (!OS.GetName().Equals("Windows"))
{
var unixFile = new UnixFileInfo(path);
unixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute
| FileAccessPermissions.GroupExecute
| FileAccessPermissions.OtherExecute;
}
using var process = new System.Diagnostics.Process();
process.StartInfo.FileName = path;
process.StartInfo.WorkingDirectory = BasePath;
process.StartInfo.Arguments = arguments;
process.Start();
}
public static void CreateInstallationDirectory()
{
MoveOldInstallationDirectory("ReadyForLaunch");
MoveOldInstallationDirectory("GodotLauncher");
Directory.CreateDirectory(BasePath);
}
static void MoveOldInstallationDirectory(string oldName)
{
var oldPath = Path.Combine(AppDataPath, oldName);
if (!Directory.Exists(oldPath) || Directory.Exists(BasePath))
return;
Directory.Move(oldPath, BasePath);
}
public static void ShowInFolder(string filePath)
{
filePath = "\"" + filePath + "\"";
switch (OS.GetName())
{
case "Linux":
System.Diagnostics.Process.Start("xdg-open", filePath);
break;
case "Windows":
string argument = "/select, " + filePath;
System.Diagnostics.Process.Start("explorer.exe", argument);
break;
case "macOS":
System.Diagnostics.Process.Start("open", filePath);
break;
default:
throw new Exception("OS not defined! " + OS.GetName());
}
}
}
}
|
{
"task_id": "project_cc_csharp/55",
"repository": "NathanWarden-ready-to-launch-58eba6d",
"file": "godot-project/Scripts/DataManagement/DataPaths.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 94,
"right_context_start_lineno": 96
}
|
using Newtonsoft.Json;
namespace DotNetDevBadgeWeb.Model
{
public class UserSummary
{
[
|
JsonProperty("likes_given")]
public int LikesGiven {
|
get; set; }
[JsonProperty("likes_received")]
public int LikesReceived { get; set; }
[JsonProperty("topics_entered")]
public int TopicsEntered { get; set; }
[JsonProperty("posts_read_count")]
public int PostsReadCount { get; set; }
[JsonProperty("days_visited")]
public int DaysVisited { get; set; }
[JsonProperty("topic_count")]
public int TopicCount { get; set; }
[JsonProperty("post_count")]
public int PostCount { get; set; }
[JsonProperty("time_read")]
public int TimeRead { get; set; }
[JsonProperty("recent_time_read")]
public int RecentTimeRead { get; set; }
[JsonProperty("bookmark_count")]
public int BookmarkCount { get; set; }
[JsonProperty("can_see_summary_stats")]
public bool CanSeeSummaryStats { get; set; }
[JsonProperty("solved_count")]
public int SolvedCount { get; set; }
}
}
|
{
"task_id": "project_cc_csharp/48",
"repository": "chanos-dev-dotnetdev-badge-5740a40",
"file": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 6,
"right_context_start_lineno": 8
}
|
using System.Net.WebSockets;
using System.Text;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace TraTech.WebSocketHub
{
public class WebSocketHubMiddleware<TKey>
where TKey : notnull
{
private readonly IServiceProvider _serviceProvider;
private readonly RequestDelegate _next;
private readonly Func<HttpContext, bool> _acceptIf;
private readonly WebSocketHub<TKey> _webSocketHub;
private readonly Func<HttpContext, TKey> _keyGenerator;
private readonly byte[] _receiveBuffer;
public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next,
|
WebSocketHub<TKey> webSocketHub, Func<HttpContext, bool> acceptIf, Func<HttpContext, TKey> keyGenerator)
{
|
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
_next = next ?? throw new ArgumentNullException(nameof(next));
_acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));
_webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));
_keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));
_receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))
{
try
{
WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();
var key = _keyGenerator(httpContext);
_webSocketHub.Add(key, webSocket);
while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)
{
try
{
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(_receiveBuffer), CancellationToken.None);
string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
Message? serializedRequest = _webSocketHub.DeserializeMessage(request);
if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }
Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);
if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }
if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }
await service.HandleRequestAsync(
JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),
JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)
);
}
catch (Exception exp)
{
Console.WriteLine(exp.ToString());
continue;
}
}
await _webSocketHub.RemoveAsync(key, webSocket);
}
catch (Exception exp)
{
Console.WriteLine(exp.ToString());
}
}
else
{
await _next(httpContext);
}
}
}
}
|
{
"task_id": "project_cc_csharp/68",
"repository": "TRA-Tech-dotnet-websocket-9049854",
"file": "src/WebSocketHub/Core/src/WebSocketHubMiddleware.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 17,
"right_context_start_lineno": 19
}
|
using System.Collections.Generic;
namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData
{
public class JXLDataExtracted
{
public List<
|
JXLWorkbookData> WorkbooksData {
|
get; set; } = new List<JXLWorkbookData>();
}
}
|
{
"task_id": "project_cc_csharp/50",
"repository": "JdeJabali-JXLDataTableExtractor-90a12f4",
"file": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLDataExtracted.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 6,
"right_context_start_lineno": 7
}
|
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using static ServiceSelf.AdvApi32;
namespace ServiceSelf
{
sealed class WindowsService : Service
{
private const string WorkingDirArgName = "WD";
[SupportedOSPlatform("windows")]
public WindowsService(string name)
: base(name)
{
}
/// <summary>
/// 应用工作目录
/// </summary>
/// <param name="args">启动参数</param>
/// <returns></returns>
public static bool UseWorkingDirectory(string[] args)
{
if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))
{
Environment.CurrentDirectory = workingDir;
return true;
}
return false;
}
[SupportedOSPlatform("windows")]
public override void CreateStart(string filePath, ServiceOptions options)
{
using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);
if (managerHandle.IsInvalid == true)
{
throw new Win32Exception();
}
filePath = Path.GetFullPath(filePath);
using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);
if (oldServiceHandle.IsInvalid)
{
using var newServiceHandle = this.CreateService(managerHandle, filePath, options);
StartService(newServiceHandle);
}
else
{
var oldFilePath = QueryServiceFilePath(oldServiceHandle);
if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)
{
throw new InvalidOperationException("系统已存在同名但不同路径的服务");
}
StartService(oldServiceHandle);
}
}
private unsafe
|
SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)
{
|
var arguments = options.Arguments ?? Enumerable.Empty<Argument>();
arguments = string.IsNullOrEmpty(options.WorkingDirectory)
? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))
: arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));
var serviceHandle = AdvApi32.CreateService(
managerHandle,
this.Name,
options.Windows.DisplayName,
ServiceAccess.SERVICE_ALL_ACCESS,
ServiceType.SERVICE_WIN32_OWN_PROCESS,
ServiceStartType.SERVICE_AUTO_START,
ServiceErrorControl.SERVICE_ERROR_NORMAL,
$@"""{filePath}"" {string.Join(' ', arguments)}",
lpLoadOrderGroup: null,
lpdwTagId: 0,
lpDependencies: options.Windows.Dependencies,
lpServiceStartName: options.Windows.ServiceStartName,
lpPassword: options.Windows.Password);
if (serviceHandle.IsInvalid == true)
{
throw new Win32Exception();
}
if (string.IsNullOrEmpty(options.Description) == false)
{
var desc = new ServiceDescription { lpDescription = options.Description };
var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));
Marshal.StructureToPtr(desc, pDesc, false);
ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());
Marshal.FreeHGlobal(pDesc);
}
var action = new SC_ACTION
{
Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,
};
var failureAction = new SERVICE_FAILURE_ACTIONS
{
cActions = 1,
lpsaActions = &action,
dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds
};
if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)
{
throw new Win32Exception();
}
return serviceHandle;
}
private static ReadOnlySpan<char> QueryServiceFilePath(SafeServiceHandle serviceHandle)
{
const int ERROR_INSUFFICIENT_BUFFER = 122;
if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)
{
if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)
{
throw new Win32Exception();
}
}
var buffer = Marshal.AllocHGlobal(bytesNeeded);
try
{
if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)
{
throw new Win32Exception();
}
var serviceConfig = Marshal.PtrToStructure<QUERY_SERVICE_CONFIG>(buffer);
var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();
if (binaryPathName.IsEmpty)
{
return ReadOnlySpan<char>.Empty;
}
if (binaryPathName[0] == '"')
{
binaryPathName = binaryPathName[1..];
var index = binaryPathName.IndexOf('"');
return index < 0 ? binaryPathName : binaryPathName[..index];
}
else
{
var index = binaryPathName.IndexOf(' ');
return index < 0 ? binaryPathName : binaryPathName[..index];
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
private static void StartService(SafeServiceHandle serviceHandle)
{
var status = new SERVICE_STATUS();
if (QueryServiceStatus(serviceHandle, ref status) == false)
{
throw new Win32Exception();
}
if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||
status.dwCurrentState == ServiceState.SERVICE_START_PENDING)
{
return;
}
if (AdvApi32.StartService(serviceHandle, 0, null) == false)
{
throw new Win32Exception();
}
}
/// <summary>
/// 停止并删除服务
/// </summary>
[SupportedOSPlatform("windows")]
public override void StopDelete()
{
using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);
if (managerHandle.IsInvalid == true)
{
throw new Win32Exception();
}
using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);
if (serviceHandle.IsInvalid == true)
{
return;
}
StopService(serviceHandle, TimeSpan.FromSeconds(30d));
if (DeleteService(serviceHandle) == false)
{
throw new Win32Exception();
}
}
private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)
{
var status = new SERVICE_STATUS();
if (QueryServiceStatus(serviceHandle, ref status) == false)
{
throw new Win32Exception();
}
if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)
{
return;
}
if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)
{
var failureAction = new SERVICE_FAILURE_ACTIONS();
if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)
{
throw new Win32Exception();
}
if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)
{
throw new Win32Exception();
}
// 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务
}
var stopwatch = Stopwatch.StartNew();
var statusQueryDelay = TimeSpan.FromMilliseconds(100d);
while (stopwatch.Elapsed < maxWaitTime)
{
if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)
{
return;
}
Thread.Sleep(statusQueryDelay);
if (QueryServiceStatus(serviceHandle, ref status) == false)
{
throw new Win32Exception();
}
}
throw new TimeoutException($"等待服务停止超过了{maxWaitTime.TotalSeconds}秒");
}
/// <summary>
/// 尝试获取服务的进程id
/// </summary>
/// <param name="processId"></param>
/// <returns></returns>
protected unsafe override bool TryGetProcessId(out int processId)
{
processId = 0;
using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);
if (managerHandle.IsInvalid == true)
{
throw new Win32Exception();
}
using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);
if (serviceHandle.IsInvalid == true)
{
return false;
}
var status = new SERVICE_STATUS_PROCESS();
if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)
{
return false;
}
processId = (int)status.dwProcessId;
return processId > 0;
}
}
}
|
{
"task_id": "project_cc_csharp/14",
"repository": "xljiulang-ServiceSelf-7f8604b",
"file": "ServiceSelf/WindowsService.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 66,
"right_context_start_lineno": 68
}
|
using JWLSLMerge.Data.Attributes;
namespace JWLSLMerge.Data.Models
{
public class Note
{
[
|
Ignore]
public int NoteId {
|
get; set; }
public string Guid { get; set; } = null!;
public int? UserMarkId { get; set; }
public int? LocationId { get; set; }
public string? Title { get; set; }
public string? Content { get; set; }
public string LastModified { get; set; } = null!;
public string Created { get; set; } = null!;
public int BlockType { get; set; }
public int? BlockIdentifier { get; set; }
[Ignore]
public int NewNoteId { get; set; }
}
}
|
{
"task_id": "project_cc_csharp/51",
"repository": "pliniobrunelli-JWLSLMerge-7fe66dc",
"file": "JWLSLMerge.Data/Models/Note.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 6,
"right_context_start_lineno": 8
}
|
using JWLSLMerge.Data.Attributes;
namespace JWLSLMerge.Data.Models
{
public class PlayListItem
{
[Ignore]
public int PlaylistItemId { get; set; }
public string Label { get; set; } = null!;
public int StartTrimOffsetTicks { get; set; }
public int EndTrimOffsetTicks { get; set; }
public int Accuracy { get; set; }
public int EndAction { get; set; }
public string ThumbnailFilePath { get; set; } = null!;
[
|
Ignore]
public int NewPlaylistItemId {
|
get; set; }
}
}
|
{
"task_id": "project_cc_csharp/37",
"repository": "pliniobrunelli-JWLSLMerge-7fe66dc",
"file": "JWLSLMerge.Data/Models/PlayListItem.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 15,
"right_context_start_lineno": 17
}
|
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; }
}
}
|
{
"task_id": "project_cc_csharp/29",
"repository": "pliniobrunelli-JWLSLMerge-7fe66dc",
"file": "JWLSLMerge.Data/Models/PlaylistItemMarker.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 14,
"right_context_start_lineno": 16
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using UnityEditor.Experimental.GraphView;
using UnityEditor;
using UnityEngine.Windows;
using System;
namespace QuestSystem.QuestEditor
{
public class QuestGraphSaveUtility
{
private QuestGraphView _targetGraphView;
private List<Edge> Edges => _targetGraphView.edges.ToList();
private List<NodeQuestGraph> node => _targetGraphView.nodes.ToList().Cast<NodeQuestGraph>().ToList();
private List<NodeQuest> _cacheNodes = new List<NodeQuest>();
public static QuestGraphSaveUtility GetInstance(QuestGraphView targetGraphView)
{
return new QuestGraphSaveUtility
{
_targetGraphView = targetGraphView,
};
}
private void creteNodeQuestAssets(Quest Q, ref List<
|
NodeQuest> NodesInGraph)
{
|
int j = 0;
CheckFolders(Q);
string path = QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}/Nodes";
string tempPath = QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}/Temp";
//Move all nodes OUT to temp
if (AssetDatabase.IsValidFolder(path)) {
AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER + $"{Q.misionName}", "Temp");
var debug = AssetDatabase.MoveAsset(path, tempPath);
}
Debug.Log("GUID: " + AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}", "Nodes"));
//Order by position
List<NodeQuestGraph> nodeList = node.Where(node => !node.entryPoint).ToList();
foreach (var nodequest in nodeList)
{
//Visual part
string nodeSaveName = Q.misionName + "_Node" + j;
NodeQuest saveNode;
//Si existe en temps
bool alredyExists = false;
if (alredyExists = !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(tempPath + "/" + nodeSaveName + ".asset")))
{
saveNode = AssetDatabase.LoadAssetAtPath<NodeQuest>(tempPath + "/" + nodeSaveName + ".asset");
}
else
{
saveNode = ScriptableObject.CreateInstance<NodeQuest>();
}
saveNode.GUID = nodequest.GUID;
saveNode.position = nodequest.GetPosition().position;
//Quest Part
saveNode.isFinal = nodequest.isFinal;
saveNode.extraText = nodequest.extraText;
saveNode.nodeObjectives = createObjectivesFromGraph(nodequest.questObjectives);
if(!alredyExists)
AssetDatabase.CreateAsset(saveNode, $"{QuestConstants.MISIONS_FOLDER}/{Q.misionName}/Nodes/{nodeSaveName}.asset");
else
{
AssetDatabase.MoveAsset(tempPath + "/" + nodeSaveName + ".asset", path + "/" + nodeSaveName + ".asset");
}
EditorUtility.SetDirty(saveNode);
AssetDatabase.SaveAssets();
NodesInGraph.Add(saveNode);
j++;
}
AssetDatabase.DeleteAsset(tempPath);
}
public void CheckFolders(Quest Q)
{
if (!AssetDatabase.IsValidFolder(QuestConstants.RESOURCES_PATH))
{
AssetDatabase.CreateFolder(QuestConstants.PARENT_PATH, QuestConstants.RESOURCES_NAME);
}
if (!AssetDatabase.IsValidFolder(QuestConstants.MISIONS_FOLDER))
{
AssetDatabase.CreateFolder(QuestConstants.RESOURCES_PATH, QuestConstants.MISIONS_NAME);
}
if (!AssetDatabase.IsValidFolder(QuestConstants.MISIONS_FOLDER + $"/{Q.misionName}"))
{
AssetDatabase.CreateFolder(QuestConstants.MISIONS_FOLDER, $"{Q.misionName}");
}
}
private void saveConections(Quest Q, List<NodeQuest> nodesInGraph)
{
var connectedPorts = Edges.Where(x => x.input.node != null).ToArray();
Q.ResetNodeLinksGraph();
foreach (NodeQuest currentNode in nodesInGraph)
{
currentNode.nextNode.Clear();
}
for (int i = 0; i < connectedPorts.Length; i++)
{
var outputNode = connectedPorts[i].output.node as NodeQuestGraph;
var inputNode = connectedPorts[i].input.node as NodeQuestGraph;
Q.nodeLinkData.Add(new Quest.NodeLinksGraph
{
baseNodeGUID = outputNode.GUID,
portName = connectedPorts[i].output.portName,
targetNodeGUID = inputNode.GUID
});
//Add to next node list
NodeQuest baseNode = nodesInGraph.Find(n => n.GUID == outputNode.GUID);
NodeQuest targetNode = nodesInGraph.Find(n => n.GUID == inputNode.GUID);
if (targetNode != null && baseNode != null)
baseNode.nextNode.Add(targetNode);
}
}
public void SaveGraph(Quest Q)
{
if (!Edges.Any()) return;
List<NodeQuest> NodesInGraph = new List<NodeQuest>();
// Nodes
creteNodeQuestAssets(Q, ref NodesInGraph);
// Conections
saveConections(Q, NodesInGraph);
//Last Quest parameters
var startNode = node.Find(node => node.entryPoint); //Find the first node Graph
Q.startDay = startNode.startDay;
Q.limitDay = startNode.limitDay;
Q.isMain = startNode.isMain;
//Questionable
var firstMisionNode = Edges.Find(x => x.output.portName == "Next");
var firstMisionNode2 = firstMisionNode.input.node as NodeQuestGraph;
string GUIDfirst = firstMisionNode2.GUID;
Q.firtsNode = NodesInGraph.Find(n => n.GUID == GUIDfirst);
EditorUtility.SetDirty(Q);
}
public void LoadGraph(Quest Q)
{
if (Q == null)
{
EditorUtility.DisplayDialog("Error!!", "Quest aprece como null, revisa el scriptable object", "OK");
return;
}
NodeQuest[] getNodes = Resources.LoadAll<NodeQuest>($"{QuestConstants.MISIONS_NAME}/{ Q.misionName}/Nodes");
_cacheNodes = new List<NodeQuest>(getNodes);
clearGraph(Q);
LoadNodes(Q);
ConectNodes(Q);
}
private void clearGraph(Quest Q)
{
node.Find(x => x.entryPoint).GUID = Q.nodeLinkData[0].baseNodeGUID;
foreach (var node in node)
{
if (node.entryPoint)
{
var aux = node.mainContainer.Children().ToList();
var aux2 = aux[2].Children().ToList();
// C
TextField misionName = aux2[0] as TextField;
Toggle isMain = aux2[1] as Toggle;
IntegerField startDay = aux2[2] as IntegerField;
IntegerField limitDay = aux2[3] as IntegerField;
misionName.value = Q.misionName;
isMain.value = Q.isMain;
startDay.value = Q.startDay;
limitDay.value = Q.limitDay;
//
node.limitDay = Q.limitDay;
node.startDay = Q.startDay;
node.isMain = Q.isMain;
node.misionName = Q.misionName;
continue;
}
//Remove edges
Edges.Where(x => x.input.node == node).ToList().ForEach(edge => _targetGraphView.RemoveElement(edge));
//Remove Node
_targetGraphView.RemoveElement(node);
}
}
private void LoadNodes(Quest Q)
{
foreach (var node in _cacheNodes)
{
var tempNode = _targetGraphView.CreateNodeQuest(node.name, Vector2.zero, node.extraText, node.isFinal);
//Load node variables
tempNode.GUID = node.GUID;
tempNode.extraText = node.extraText;
tempNode.isFinal = node.isFinal;
tempNode.RefreshPorts();
if (node.nodeObjectives != null) {
foreach (QuestObjective qObjective in node.nodeObjectives)
{
//CreateObjectives
QuestObjectiveGraph objtemp = new QuestObjectiveGraph(qObjective.keyName, qObjective.maxItems, qObjective.actualItems,
qObjective.description, qObjective.hiddenObjective, qObjective.autoExitOnCompleted);
var deleteButton = new Button(clickEvent: () => _targetGraphView.removeQuestObjective(tempNode, objtemp))
{
text = "x"
};
objtemp.Add(deleteButton);
var newBox = new Box();
objtemp.Add(newBox);
objtemp.actualItems = qObjective.actualItems;
objtemp.description = qObjective.description;
objtemp.maxItems = qObjective.maxItems;
objtemp.keyName = qObjective.keyName;
objtemp.hiddenObjective = qObjective.hiddenObjective;
objtemp.autoExitOnCompleted = qObjective.autoExitOnCompleted;
tempNode.objectivesRef.Add(objtemp);
tempNode.questObjectives.Add(objtemp);
}
}
_targetGraphView.AddElement(tempNode);
var nodePorts = Q.nodeLinkData.Where(x => x.baseNodeGUID == node.GUID).ToList();
nodePorts.ForEach(x => _targetGraphView.AddNextNodePort(tempNode));
}
}
private void ConectNodes(Quest Q)
{
List<NodeQuestGraph> nodeListCopy = new List<NodeQuestGraph>(node);
for (int i = 0; i < nodeListCopy.Count; i++)
{
var conections = Q.nodeLinkData.Where(x => x.baseNodeGUID == nodeListCopy[i].GUID).ToList();
for (int j = 0; j < conections.Count(); j++)
{
string targetNodeGUID = conections[j].targetNodeGUID;
var targetNode = nodeListCopy.Find(x => x.GUID == targetNodeGUID);
LinkNodes(nodeListCopy[i].outputContainer[j].Q<Port>(), (Port)targetNode.inputContainer[0]);
targetNode.SetPosition(new Rect(_cacheNodes.First(x => x.GUID == targetNodeGUID).position, new Vector2(150, 200)));
}
}
}
private void LinkNodes(Port outpor, Port inport)
{
var tempEdge = new Edge
{
output = outpor,
input = inport
};
tempEdge.input.Connect(tempEdge);
tempEdge.output.Connect(tempEdge);
_targetGraphView.Add(tempEdge);
}
public QuestObjective[] createObjectivesFromGraph(List<QuestObjectiveGraph> qog)
{
List<QuestObjective> Listaux = new List<QuestObjective>();
foreach (QuestObjectiveGraph obj in qog)
{
QuestObjective aux = new QuestObjective
{
keyName = obj.keyName,
maxItems = obj.maxItems,
actualItems = obj.actualItems,
description = obj.description,
hiddenObjective = obj.hiddenObjective,
autoExitOnCompleted = obj.autoExitOnCompleted
};
Listaux.Add(aux);
}
return Listaux.ToArray();
}
}
}
|
{
"task_id": "project_cc_csharp/49",
"repository": "lluispalerm-QuestSystem-cd836cc",
"file": "Editor/GraphEditor/QuestGraphSaveUtility.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 30,
"right_context_start_lineno": 32
}
|
// <copyright file="ToolOptionsPanel.cs" company="algernon (K. Algernon A. Sheppard)">
// Copyright (c) algernon (K. Algernon A. Sheppard). All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
// </copyright>
namespace LineToolMod
{
using AlgernonCommons.Translation;
using AlgernonCommons.UI;
using ColossalFramework.UI;
using UnityEngine;
/// <summary>
/// Control panel for the line tool.
/// TODO: quick-and-dirty hack only for development, not production design.
/// </summary>
internal class ToolOptionsPanel : StandalonePanel
{
// Panel components.
private
|
BOBSlider _spacingSlider;
|
private UIButton _stepButton;
private UIButton _skipButton;
private UIMultiStateButton _relativeAngleButton;
private UIMultiStateButton _absoluteAngleButton;
/// <summary>
/// Gets the panel width.
/// </summary>
public override float PanelWidth => 36f * 7f;
/// <summary>
/// Gets the panel height.
/// </summary>
public override float PanelHeight => 250f;
/// <summary>
/// Gets the panel's default position.
/// </summary>
public override Vector3 DefaultPosition
{
get
{
UIComponent optionsBar = GameObject.Find("OptionsBar").GetComponent<UIComponent>();
return optionsBar.absolutePosition - new Vector3(0f, PanelHeight + Margin);
}
}
/// <summary>
/// Gets the panel's title.
/// </summary>
protected override string PanelTitle => Translations.Translate("MOD_NAME");
/// <summary>
/// Called by Unity before the first frame.
/// Used to perform setup.
/// </summary>
public override void Start()
{
base.Start();
const float DoubleMargin = Margin * 2f;
const float ToggleSize = 45f;
float currentY = 50f;
// Spacing slider.
_spacingSlider = AddBOBSlider(this, DoubleMargin, currentY, PanelWidth - DoubleMargin - DoubleMargin, "SPACING", 1f, 100f, 0.1f, "Spacing");
_spacingSlider.value = LineTool.Instance.Spacing;
_spacingSlider.eventValueChanged += (c, value) => LineTool.Instance.Spacing = value;
currentY += 40f;
// Rotation slider.
BOBSlider rotationSlider = AddBOBSlider(this, DoubleMargin, currentY, PanelWidth - DoubleMargin - DoubleMargin, "ROTATION", 0f, 360f, 0.1f, "Rotation");
rotationSlider.value = LineTool.Instance.Rotation * Mathf.Rad2Deg;
rotationSlider.eventValueChanged += (c, value) => LineTool.Instance.Rotation = value * Mathf.Deg2Rad;
currentY += 40f;
// Angle mode buttons.
UITextureAtlas toggleAtlas = UITextures.CreateSpriteAtlas("LineToolToggles", 1024, "LineOptions");
_relativeAngleButton = AddToggleButton(this, "AngleRelative", toggleAtlas, ToggleSize);
_relativeAngleButton.relativePosition = new Vector2(Margin, currentY);
_relativeAngleButton.tooltip = Translations.Translate("ROTATION_RELATIVE");
_absoluteAngleButton = AddToggleButton(this, "AngleAbsolute", toggleAtlas, ToggleSize);
_absoluteAngleButton.relativePosition = new Vector2(ToggleSize + DoubleMargin, currentY);
_absoluteAngleButton.tooltip = Translations.Translate("ROTATION_ABSOLUTE");
// Set to length button.
UIButton lengthButton = AddIconButton(this, "Length", toggleAtlas, ToggleSize);
lengthButton.relativePosition = new Vector2((ToggleSize + DoubleMargin) * 2f, currentY);
lengthButton.eventClicked += (c, p) => LineTool.Instance?.SetToLength();
lengthButton.tooltip = Translations.Translate("SET_LENGTH");
// Set to width button.
UIButton widthButton = AddIconButton(this, "Width", toggleAtlas, ToggleSize);
widthButton.relativePosition = new Vector2((ToggleSize + DoubleMargin) * 3f, currentY);
widthButton.eventClicked += (c, p) => LineTool.Instance?.SetToWidth();
widthButton.tooltip = Translations.Translate("SET_WIDTH");
currentY += ToggleSize + Margin + Margin;
// Spacer panel.
UISpacers.AddOptionsSpacer(this, Margin, currentY, PanelWidth - DoubleMargin);
currentY += 10f;
// Step check.
UICheckBox stepCheck = UICheckBoxes.AddLabelledCheckBox(this, Margin, currentY, Translations.Translate("STEP_ENABLED"));
stepCheck.isChecked = LineTool.Instance.StepMode;
stepCheck.eventCheckChanged += (c, isChecked) => LineTool.Instance.StepMode = isChecked;
currentY += 25f;
// Step button.
float buttonWidth = (PanelWidth / 2f) - (Margin * 2f);
_stepButton = UIButtons.AddEvenSmallerButton(this, Margin, currentY, Translations.Translate("STEP"), buttonWidth);
_stepButton.eventClicked += (c, p) =>
{
LineTool.Instance.Step();
};
// Skip button.
_skipButton = UIButtons.AddEvenSmallerButton(this, (Margin * 3f) + buttonWidth, currentY, Translations.Translate("SKIP"), buttonWidth);
_skipButton.eventClicked += (c, p) =>
{
LineTool.Instance.Skip();
};
// Set initial angle toggle mode.
if (LineTool.Instance.RelativeRotation)
{
_relativeAngleButton.activeStateIndex = 1;
}
else
{
_absoluteAngleButton.activeStateIndex = 1;
}
// Absolute angle toggle event handler.
_absoluteAngleButton.eventActiveStateIndexChanged += (c, state) =>
{
if (state == 1)
{
// Deselect relative angle toggle if this is selected.
_relativeAngleButton.activeStateIndex = 0;
LineTool.Instance.RelativeRotation = false;
}
else if (_relativeAngleButton.activeStateIndex == 0)
{
// If relative angle button is not selected, force this one active.
_absoluteAngleButton.activeStateIndex = 1;
}
};
// Relative angle toggle event handler.
_relativeAngleButton.eventActiveStateIndexChanged += (c, state) =>
{
if (state == 1)
{
// Deselect absolute angle toggle if this is selected.
_absoluteAngleButton.activeStateIndex = 0;
LineTool.Instance.RelativeRotation = true;
}
else if (_absoluteAngleButton.activeStateIndex == 0)
{
// If absolute angle button is not selected, force this one active.
_relativeAngleButton.activeStateIndex = 1;
}
};
// Set initial state.
UpdateButtonStates();
}
/// <summary>
/// Applies the panel's default position.
/// </summary>
public override void ApplyDefaultPosition()
{
absolutePosition = DefaultPosition;
}
/// <summary>
/// Refreshes the spacing slider's value.
/// </summary>
internal void RefreshSpacing() => _spacingSlider.TrueValue = LineTool.Instance.Spacing;
/// <summary>
/// Updates button states to reflect the current tool state.
/// </summary>
internal void UpdateButtonStates()
{
// Set according to current stepping state.
if (LineTool.Instance != null && LineTool.Instance.Stepping)
{
_spacingSlider.Hide();
_skipButton.Enable();
_stepButton.Enable();
}
else
{
_spacingSlider.Show();
_skipButton.Disable();
_stepButton.Disable();
}
}
/// <summary>
/// Performs any actions required before closing the panel and checks that it's safe to do so.
/// </summary>
/// <returns>Always true (panel can always close).</returns>
protected override bool PreClose()
{
// Save panel position if it's not at the default.
if (absolutePosition != DefaultPosition)
{
ModSettings.Save();
}
return true;
}
/// <summary>
/// Adds a BOB slider to the specified component.
/// </summary>
/// <param name="parent">Parent component.</param>
/// <param name="xPos">Relative X position.</param>
/// <param name="yPos">Relative Y position.</param>
/// <param name="width">Slider width.</param>
/// <param name="labelKey">Text label translation key.</param>
/// <param name="minValue">Minimum displayed value.</param>
/// <param name="maxValue">Maximum displayed value.</param>
/// <param name="stepSize">Minimum slider step size.</param>
/// <param name="name">Slider name.</param>
/// <returns>New BOBSlider.</returns>
private BOBSlider AddBOBSlider(UIComponent parent, float xPos, float yPos, float width, string labelKey, float minValue, float maxValue, float stepSize, string name)
{
const float SliderY = 18f;
const float ValueY = 3f;
const float LabelY = -13f;
const float SliderHeight = 18f;
const float FloatTextFieldWidth = 45f;
const float IntTextFieldWidth = 38f;
// Slider control.
BOBSlider newSlider = parent.AddUIComponent<BOBSlider>();
newSlider.size = new Vector2(width, SliderHeight);
newSlider.relativePosition = new Vector2(xPos, yPos + SliderY);
newSlider.name = name;
// Value field - added to parent, not to slider, otherwise slider catches all input attempts. Integer textfields (stepsize == 1) have shorter widths.
float textFieldWidth = stepSize == 1 ? IntTextFieldWidth : FloatTextFieldWidth;
UITextField valueField = UITextFields.AddTinyTextField(parent, xPos + Margin + newSlider.width - textFieldWidth, yPos + ValueY, textFieldWidth);
// Title label.
UILabel titleLabel = UILabels.AddLabel(newSlider, 0f, LabelY, Translations.Translate(labelKey), textScale: 0.7f);
// Autoscale tile label text, with minimum size 0.35.
while (titleLabel.width > newSlider.width - textFieldWidth && titleLabel.textScale > 0.35f)
{
titleLabel.textScale -= 0.05f;
}
// Slider track.
UISlicedSprite sliderSprite = newSlider.AddUIComponent<UISlicedSprite>();
sliderSprite.atlas = UITextures.InGameAtlas;
sliderSprite.spriteName = "BudgetSlider";
sliderSprite.size = new Vector2(newSlider.width, 9f);
sliderSprite.relativePosition = new Vector2(0f, 4f);
// Slider thumb.
UISlicedSprite sliderThumb = newSlider.AddUIComponent<UISlicedSprite>();
sliderThumb.atlas = UITextures.InGameAtlas;
sliderThumb.spriteName = "SliderBudget";
newSlider.thumbObject = sliderThumb;
// Set references.
newSlider.ValueField = valueField;
// Set initial values.
newSlider.StepSize = stepSize;
newSlider.maxValue = maxValue;
newSlider.minValue = minValue;
newSlider.TrueValue = 0f;
// Ensure value textfield is in front.
valueField.BringToFront();
return newSlider;
}
/// <summary>
/// Adds a multi-state toggle button to the specified UIComponent.
/// </summary>
/// <param name="parent">Parent UIComponent.</param>
/// <param name="spriteName">Sprite name.</param>
/// <param name="atlas">Button atlas.</param>
/// <param name="size">Button size.</param>
/// <returns>New UIMultiStateButton.</returns>
private UIMultiStateButton AddToggleButton(UIComponent parent, string spriteName, UITextureAtlas atlas, float size)
{
// Create button.
UIMultiStateButton newButton = parent.AddUIComponent<UIMultiStateButton>();
newButton.name = spriteName;
newButton.atlas = atlas;
// Get sprite sets.
UIMultiStateButton.SpriteSetState fgSpriteSetState = newButton.foregroundSprites;
UIMultiStateButton.SpriteSetState bgSpriteSetState = newButton.backgroundSprites;
// State 0 background.
UIMultiStateButton.SpriteSet bgSpriteSetZero = bgSpriteSetState[0];
bgSpriteSetZero.normal = spriteName;
bgSpriteSetZero.focused = spriteName + "Pressed";
bgSpriteSetZero.hovered = spriteName + "Hovered";
bgSpriteSetZero.pressed = spriteName + "Pressed";
bgSpriteSetZero.disabled = spriteName;
// Add state 1.
fgSpriteSetState.AddState();
bgSpriteSetState.AddState();
// State 1 background.
UIMultiStateButton.SpriteSet bgSpriteSetOne = bgSpriteSetState[1];
bgSpriteSetOne.normal = spriteName + "Pressed";
bgSpriteSetOne.focused = spriteName + "Pressed";
bgSpriteSetOne.hovered = spriteName + "Pressed";
bgSpriteSetOne.pressed = spriteName + "Pressed";
bgSpriteSetOne.disabled = spriteName + "Pressed";
// Set initial state.
newButton.state = UIMultiStateButton.ButtonState.Normal;
newButton.activeStateIndex = 0;
// Size and appearance.
newButton.autoSize = false;
newButton.width = size;
newButton.height = size;
newButton.foregroundSpriteMode = UIForegroundSpriteMode.Fill;
newButton.spritePadding = new RectOffset(0, 0, 0, 0);
newButton.playAudioEvents = true;
// Enforce defaults.
newButton.canFocus = false;
newButton.enabled = true;
newButton.isInteractive = true;
newButton.isVisible = true;
return newButton;
}
/// <summary>
/// Adds an icon button to the specified component.
/// </summary>
/// <param name="parent">Parent UIComponent.</param>
/// <param name="spriteName">Sprite name.</param>
/// <param name="atlas">Button atlas.</param>
/// <param name="size">Button size.</param>
/// <returns>New UIButton.</returns>
private UIButton AddIconButton(UIComponent parent, string spriteName, UITextureAtlas atlas, float size)
{
UIButton newButton = parent.AddUIComponent<UIButton>();
// Size and position.
newButton.height = size;
newButton.width = size;
// Appearance.
newButton.atlas = atlas;
newButton.normalFgSprite = spriteName;
newButton.focusedFgSprite = spriteName;
newButton.hoveredFgSprite = spriteName + "Hovered";
newButton.disabledFgSprite = spriteName;
newButton.pressedFgSprite = spriteName + "Pressed";
newButton.playAudioEvents = true;
return newButton;
}
}
}
|
{
"task_id": "project_cc_csharp/64",
"repository": "algernon-A-LineTool-f63b447",
"file": "Code/UI/ToolOptionsPanel.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 19,
"right_context_start_lineno": 20
}
|
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Linq;
using UnityEngine;
using Utilities.WebRequestRest.Interfaces;
namespace BlockadeLabs
{
public sealed class BlockadeLabsSettings : ISettings
{
public BlockadeLabsSettings()
{
if (cachedDefault != null) { return; }
var config = Resources.LoadAll<BlockadeLabsConfiguration>(string.Empty)
.FirstOrDefault(asset => asset != null);
if (config != null)
{
Info = new BlockadeLabsSettingsInfo(config.ProxyDomain);
Default = new BlockadeLabsSettings(Info);
}
else
{
Info = new BlockadeLabsSettingsInfo();
Default = new BlockadeLabsSettings(Info);
}
}
public BlockadeLabsSettings(
|
BlockadeLabsSettingsInfo settingsInfo)
=> Info = settingsInfo;
|
public BlockadeLabsSettings(string domain)
=> Info = new BlockadeLabsSettingsInfo(domain);
private static BlockadeLabsSettings cachedDefault;
public static BlockadeLabsSettings Default
{
get => cachedDefault ??= new BlockadeLabsSettings();
internal set => cachedDefault = value;
}
public BlockadeLabsSettingsInfo Info { get; }
public string BaseRequestUrlFormat => Info.BaseRequestUrlFormat;
}
}
|
{
"task_id": "project_cc_csharp/69",
"repository": "RageAgainstThePixel-com.rest.blockadelabs-aa2142f",
"file": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/BlockadeLabsSettings.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 29,
"right_context_start_lineno": 31
}
|
using HarmonyLib;
using UnityEngine;
namespace Ultrapain.Patches
{
class Solider_Start_Patch
{
static void Postfix(ZombieProjectiles __instance, ref GameObject ___decProjectile, ref GameObject ___projectile, ref EnemyIdentifier ___eid, ref Animator ___anim)
{
if (___eid.enemyType != EnemyType.Soldier)
return;
/*___projectile = Plugin.soliderBullet;
if (Plugin.decorativeProjectile2.gameObject != null)
___decProjectile = Plugin.decorativeProjectile2.gameObject;*/
__instance.gameObject.AddComponent<SoliderShootCounter>();
}
}
class Solider_SpawnProjectile_Patch
{
static void Postfix(ZombieProjectiles __instance, ref
|
EnemyIdentifier ___eid, ref GameObject ___origWP)
{
|
if (___eid.enemyType != EnemyType.Soldier)
return;
___eid.weakPoint = null;
}
}
class SoliderGrenadeFlag : MonoBehaviour
{
public GameObject tempExplosion;
}
class Solider_ThrowProjectile_Patch
{
static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, ref EnemyIdentifier ___eid, ref GameObject ___player, ref Animator ___anim, ref float ___coolDown)
{
if (___eid.enemyType != EnemyType.Soldier)
return;
___currentProjectile.GetComponent<ProjectileSpread>().spreadAmount = 10;
___currentProjectile.SetActive(true);
SoliderShootCounter counter = __instance.gameObject.GetComponent<SoliderShootCounter>();
if (counter.remainingShots > 0)
{
counter.remainingShots -= 1;
if (counter.remainingShots != 0)
{
___anim.Play("Shoot", 0, Plugin.SoliderShootAnimationStart / 2f);
___anim.fireEvents = true;
__instance.DamageStart();
___coolDown = 0;
}
else
{
counter.remainingShots = ConfigManager.soliderShootCount.value;
if (ConfigManager.soliderShootGrenadeToggle.value)
{
GameObject grenade = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject, ___currentProjectile.transform.position, ___currentProjectile.transform.rotation);
grenade.transform.Translate(Vector3.forward * 0.5f);
Vector3 targetPos = Plugin.PredictPlayerPosition(__instance.GetComponent<Collider>(), ___eid.totalSpeedModifier);
grenade.transform.LookAt(targetPos);
Rigidbody rb = grenade.GetComponent<Rigidbody>();
//rb.maxAngularVelocity = 10000;
//foreach (Rigidbody r in grenade.GetComponentsInChildren<Rigidbody>())
// r.maxAngularVelocity = 10000;
rb.AddForce(grenade.transform.forward * Plugin.SoliderGrenadeForce);
//rb.velocity = ___currentProjectile.transform.forward * Plugin.instance.SoliderGrenadeForce;
rb.useGravity = false;
grenade.GetComponent<Grenade>().enemy = true;
grenade.GetComponent<Grenade>().CanCollideWithPlayer(true);
grenade.AddComponent<SoliderGrenadeFlag>();
}
}
}
//counter.remainingShots = ConfigManager.soliderShootCount.value;
}
}
class Grenade_Explode_Patch
{
static bool Prefix(Grenade __instance, out bool __state)
{
__state = false;
SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>();
if (flag == null)
return true;
flag.tempExplosion = GameObject.Instantiate(__instance.explosion);
__state = true;
foreach(Explosion e in flag.tempExplosion.GetComponentsInChildren<Explosion>())
{
e.damage = ConfigManager.soliderGrenadeDamage.value;
e.maxSize *= ConfigManager.soliderGrenadeSize.value;
e.speed *= ConfigManager.soliderGrenadeSize.value;
}
__instance.explosion = flag.tempExplosion;
return true;
}
static void Postfix(Grenade __instance, bool __state)
{
if (!__state)
return;
SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>();
GameObject.Destroy(flag.tempExplosion);
}
}
class SoliderShootCounter : MonoBehaviour
{
public int remainingShots = ConfigManager.soliderShootCount.value;
}
}
|
{
"task_id": "project_cc_csharp/11",
"repository": "eternalUnion-UltraPain-ad924af",
"file": "Ultrapain/Patches/Solider.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 23,
"right_context_start_lineno": 25
}
|
using HarmonyLib;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.AI;
namespace Ultrapain.Patches
{
class FerrymanFlag : MonoBehaviour
{
private int currentCombo = 0;
public List<int> randomComboPattern = new List<int>();
public int remainingCombo = ConfigManager.ferrymanComboCount.value;
void Start()
{
int attackCount = 3;
int allocationPerAttack = 1;
for (int attack = 0; attack < attackCount; attack++)
for (int i = 0; i < allocationPerAttack; i++)
randomComboPattern.Add(attack);
System.Random rng = new System.Random(System.DateTime.Today.Millisecond);
randomComboPattern.OrderBy(a => rng.Next()).ToList();
}
public int GetNextCombo()
{
currentCombo++;
if (currentCombo >= randomComboPattern.Count)
currentCombo = 0;
return randomComboPattern[currentCombo];
}
}
class FerrymanStart
{
static void Postfix(Ferryman __instance)
{
__instance.gameObject.AddComponent<FerrymanFlag>();
}
}
class FerrymanStopMoving
{
public static MethodInfo SnapToGround = typeof(Ferryman).GetMethod("SnapToGround", BindingFlags.Instance | BindingFlags.NonPublic);
static void Postfix(Ferryman __instance, ref Animator ___anim, ref bool ___inAction, ref bool ___tracking, ref
|
NavMeshAgent ___nma,
ref bool ___useMain, ref bool ___useOar, ref bool ___useKick, ref bool ___backTrailActive,
bool ___bossVersion, bool ___inPhaseChange)
{
|
FerrymanFlag flag = __instance.gameObject.GetComponent<FerrymanFlag>();
if (flag == null)
return;
if (___bossVersion && ___inPhaseChange)
{
flag.remainingCombo = ConfigManager.ferrymanComboCount.value;
return;
}
string clipName = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name;
if (clipName != "OarCombo" && clipName != "KickCombo" && clipName != "Stinger" && clipName != "BackstepAttack")
return;
AnimationClip clip = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip;
float time = clip.events.Where(obj => obj.functionName == "StopMoving").Last().time;
if (___anim.GetCurrentAnimatorStateInfo(0).normalizedTime < time / clip.length)
return;
//if (flag.remainingCombo == ConfigManager.ferrymanComboCount.value && clipName == "KickCombo")
// flag.remainingCombo -= 1;
flag.remainingCombo -= 1;
if(flag.remainingCombo <= 0)
{
flag.remainingCombo = ConfigManager.ferrymanComboCount.value;
return;
}
int attackType = flag.GetNextCombo();
if (attackType == 0)
{
// time = 0.8347
// total = 2.4667
___anim.Play("OarCombo", 0, (0.8347f * (1f - ConfigManager.ferrymanAttackDelay.value)) / 2.4667f);
SnapToGround.Invoke(__instance, new object[0]);
___inAction = true;
___tracking = true;
if (___nma.isOnNavMesh)
{
___nma.SetDestination(__instance.transform.position);
}
//__instance.anim.SetTrigger("OarCombo");
___backTrailActive = true;
___useMain = true;
___useOar = true;
___useKick = false;
}
else if(attackType == 1)
{
// time = 0.8347
// total = 2.4667
___anim.Play("KickCombo", 0, (0.8347f * (1f - ConfigManager.ferrymanAttackDelay.value)) / 2.4667f);
SnapToGround.Invoke(__instance, new object[0]);
___inAction = true;
___tracking = true;
if (___nma.isOnNavMesh)
{
___nma.SetDestination(__instance.transform.position);
}
//__instance.anim.SetTrigger("KickCombo");
___backTrailActive = true;
___useMain = true;
___useOar = false;
___useKick = true;
}
else
{
// time = 0.4129
// total = 1.3
___anim.Play("Stinger", 0, 0);
SnapToGround.Invoke(__instance, new object[0]);
___inAction = true;
___tracking = true;
if (___nma.isOnNavMesh)
{
___nma.SetDestination(__instance.transform.position);
}
//__instance.anim.SetTrigger("KickCombo");
___backTrailActive = true;
___useMain = true;
___useOar = true;
___useKick = false;
}
}
}
}
|
{
"task_id": "project_cc_csharp/12",
"repository": "eternalUnion-UltraPain-ad924af",
"file": "Ultrapain/Patches/Ferryman.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 49,
"right_context_start_lineno": 53
}
|
using HarmonyLib;
using UnityEngine.UI;
namespace Ultrapain
{
class DifficultySelectPatch
{
static void Postfix(
|
DifficultySelectButton __instance)
{
|
string difficultyName = __instance.transform.Find("Name").GetComponent<Text>().text;
Plugin.ultrapainDifficulty = difficultyName == ConfigManager.pluginName.value || ConfigManager.globalDifficultySwitch.value;
Plugin.realUltrapainDifficulty = difficultyName == ConfigManager.pluginName.value;
}
}
}
|
{
"task_id": "project_cc_csharp/52",
"repository": "eternalUnion-UltraPain-ad924af",
"file": "Ultrapain/DifficultySelectPatch.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 7,
"right_context_start_lineno": 9
}
|
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");
}
}
}*/
}
|
{
"task_id": "project_cc_csharp/41",
"repository": "eternalUnion-UltraPain-ad924af",
"file": "Ultrapain/Plugin.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 108,
"right_context_start_lineno": 109
}
|
using TreeifyTask;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using TaskStatus = TreeifyTask.TaskStatus;
namespace TreeifyTask.Sample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
ITaskNode rootTask;
public MainWindow()
{
InitializeComponent();
Dispatcher.UnhandledException += Dispatcher_UnhandledException;
CreateTasks();
}
private void CreateTasks()
{
CodeBehavior defaultCodeBehavior = new();
rootTask = new TaskNode("TaskNode-1");
rootTask.AddChild(new TaskNode("TaskNode-1.1", async (reporter, token) => await SimpleTimer(reporter, token, defaultCodeBehavior with { IntervalDelay = 20 }, "1.1")));
var subTask = new TaskNode("TaskNode-1.2");
subTask.AddChild(new TaskNode("TaskNode-1.2.1", async (reporter, token) => await SimpleTimer(reporter, token,
defaultCodeBehavior with { ShouldPerformAnInDeterminateAction = true, InDeterminateActionDelay = 2000 }, "1.2.1")));
var subTask2 = new TaskNode("TaskNode-1.2.2");
subTask2.AddChild(new TaskNode("TaskNode-1.2.2.1", async (reporter, token) => await SimpleTimer(reporter, token,
defaultCodeBehavior with { ShouldThrowExceptionDuringProgress = false, IntervalDelay = 65 }, "1.2.2.1")));
subTask.AddChild(subTask2);
subTask.AddChild(new TaskNode("TaskNode-1.2.3", async (reporter, token) => await SimpleTimer(reporter, token, defaultCodeBehavior with { IntervalDelay = 60 }, "1.2.3")));
subTask.AddChild(new TaskNode("TaskNode-1.2.4", async (reporter, token) => await SimpleTimer(reporter, token, defaultCodeBehavior with { IntervalDelay = 30 }, "1.2.4")));
rootTask.AddChild(subTask);
rootTask.AddChild(new TaskNode("TaskNode-1.3", async (reporter, token) => await SimpleTimer(reporter, token, defaultCodeBehavior with { IntervalDelay = 160 }, "1.3")));
rootTask.AddChild(new TaskNode("TaskNode-1.4", async (reporter, token) => await SimpleTimer(reporter, token, defaultCodeBehavior with { IntervalDelay = 50 }, "1.4")));
rootTask.AddChild(new TaskNode("TaskNode-1.5", async (reporter, token) => await SimpleTimer(reporter, token, defaultCodeBehavior with { IntervalDelay = 20 }, "1.5")));
rootTask.AddChild(new TaskNode("TaskNode-1.6", async (reporter, token) => await SimpleTimer(reporter, token, defaultCodeBehavior with { IntervalDelay = 250 }, "1.6")));
rootTask.Reporting += (sender, eArgs) =>
{
if (eArgs.TaskStatus == TaskStatus.InDeterminate)
{
pb.IsIndeterminate = true;
}
else
{
pb.IsIndeterminate = false;
pb.Value = eArgs.ProgressValue;
}
};
tv.ItemsSource = new ObservableCollection<TaskNodeViewModel> { new TaskNodeViewModel(rootTask) };
}
private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
txtError.Text = e.Exception.Message;
errorBox.Visibility = Visibility.Visible;
CreateTasks();
e.Handled = true;
}
private async Task SimpleTimer(
|
IProgressReporter progressReporter, CancellationToken token, CodeBehavior behaviors = null, string progressMessage = null)
{
|
behaviors ??= new CodeBehavior();
progressMessage ??= "In progress ";
progressReporter.Report(TaskStatus.InProgress, 0, $"{progressMessage}: 0%");
bool error = false;
if (behaviors.ShouldThrowException)
{
throw new Exception();
}
try
{
if (behaviors.ShouldPerformAnInDeterminateAction)
{
progressReporter.Report(TaskStatus.InDeterminate, 0, $"{progressMessage}: 0%");
if (behaviors.ShouldHangInAnInDeterminateState)
{
await Task.Delay(-1);
}
await Task.Delay(behaviors.InDeterminateActionDelay);
}
else
{
foreach (int i in Enumerable.Range(1, 100))
{
if (behaviors.ShouldThrowExceptionDuringProgress)
{
throw new Exception();
}
if (token.IsCancellationRequested)
{
progressReporter.Report(TaskStatus.Cancelled, i);
break;
}
await Task.Delay(behaviors.IntervalDelay);
progressReporter.Report(TaskStatus.InProgress, i, $"{progressMessage}: {i}%");
if (i > 20 && behaviors.ShouldHangDuringProgress)
{
await Task.Delay(-1);
}
}
}
}
catch (Exception ex)
{
error = true;
progressReporter.Report(TaskStatus.Failed, 0, ex);
throw;
}
if (!error && !token.IsCancellationRequested)
{
progressReporter.Report(TaskStatus.Completed, 100, $"{progressMessage}: 100%");
}
}
CancellationTokenSource tokenSource;
private async void StartClick(object sender, RoutedEventArgs e)
{
grpExecutionMethod.IsEnabled = false;
btnStart.IsEnabled = false;
btnCancel.IsEnabled = true;
try
{
tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
await (rdConcurrent.IsChecked.HasValue && rdConcurrent.IsChecked.Value ?
rootTask.ExecuteConcurrently(token, true) :
rootTask.ExecuteInSeries(token, true));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
btnStart.IsEnabled = true;
btnCancel.IsEnabled = false;
grpExecutionMethod.IsEnabled = true;
}
private void CancelClick(object sender, RoutedEventArgs e)
{
tokenSource?.Cancel();
}
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Escape)
{
errorBox.Visibility = Visibility.Collapsed;
// RESET UI Controls
btnCancel.IsEnabled = false;
btnStart.IsEnabled = true;
pb.Value = 0;
rdConcurrent.IsChecked = false;
}
}
private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (e.OldValue is TaskNodeViewModel oldTask)
{
oldTask.BaseTaskNode.Reporting -= ChildReport;
}
if (e.NewValue is TaskNodeViewModel taskVM)
{
var task = taskVM.BaseTaskNode;
txtId.Text = task.Id;
txtStatus.Text = task.TaskStatus.ToString("G");
pbChild.Value = task.ProgressValue;
txtChildState.Text = task.ProgressState + "";
task.Reporting += ChildReport;
}
}
private void ChildReport(object sender, ProgressReportingEventArgs eventArgs)
{
if (sender is ITaskNode task)
{
txtId.Text = task.Id;
txtStatus.Text = task.TaskStatus.ToString("G");
pbChild.Value = task.ProgressValue;
txtChildState.Text = task.ProgressState + "";
}
}
private void btnResetClick(object sender, RoutedEventArgs e)
{
CreateTasks();
btnCancel.IsEnabled = false;
btnStart.IsEnabled = true;
pb.Value = 0;
rdConcurrent.IsChecked = false;
rdSeries.IsChecked = true;
}
}
}
|
{
"task_id": "project_cc_csharp/63",
"repository": "intuit-TreeifyTask-4b124d4",
"file": "Source/TreeifyTask.WpfSample/MainWindow.xaml.cs",
"context_start_lineno": 0,
"groundtruth_start_lineno": 75,
"right_context_start_lineno": 77
}
|
End of preview.
README.md exists but content is empty.
- Downloads last month
- 5