Here are the examples of the csharp api System.Type.GetField(string, System.Reflection.BindingFlags) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1797 Examples
19
View Source File : FieldInfoHelper.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public static FieldInfo GetField(Type self, string name, BindingFlags bindingAttr) {
Dictionary<string, XnaToFnaFieldInfo> fields;
XnaToFnaFieldInfo field;
if (Map.TryGetValue(self, out fields) && fields.TryGetValue(name, out field)) {
return field;
}
return self.GetField(name, bindingAttr);
}
19
View Source File : DataContext.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void RescanDataTypes(Type[] types) {
foreach (Type type in types) {
if (type.IsAbstract)
continue;
if (typeof(DataType).IsreplacedignableFrom(type)) {
RuntimeHelpers.RunClreplacedConstructor(type.TypeHandle);
string? id = null;
string? source = null;
for (Type parent = type; parent != typeof(object) && id.IsNullOrEmpty() && source.IsNullOrEmpty(); parent = parent.BaseType ?? typeof(object)) {
id = parent.GetField("DataID", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
source = parent.GetField("DataSource", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
}
if (id.IsNullOrEmpty()) {
Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but no DataID");
continue;
}
if (source.IsNullOrEmpty()) {
Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but no DataSource");
continue;
}
if (IDToDataType.ContainsKey(id)) {
Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but conflicting ID {id}");
continue;
}
Logger.Log(LogLevel.INF, "data", $"Found data type {type.FullName} with ID {id}");
IDToDataType[id] = type;
DataTypeToID[type] = id;
DataTypeToSource[type] = source;
} else if (typeof(MetaType).IsreplacedignableFrom(type)) {
RuntimeHelpers.RunClreplacedConstructor(type.TypeHandle);
string? id = null;
for (Type parent = type; parent != typeof(object) && id.IsNullOrEmpty(); parent = parent.BaseType ?? typeof(object)) {
id = parent.GetField("MetaID", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
}
if (id.IsNullOrEmpty()) {
Logger.Log(LogLevel.WRN, "data", $"Found meta type {type.FullName} but no MetaID");
continue;
}
if (IDToMetaType.ContainsKey(id)) {
Logger.Log(LogLevel.WRN, "data", $"Found meta type {type.FullName} but conflicting ID {id}");
continue;
}
Logger.Log(LogLevel.INF, "data", $"Found meta type {type.FullName} with ID {id}");
IDToMetaType[id] = type;
MetaTypeToID[type] = id;
}
}
}
19
View Source File : NativeDecimalGetterHelper.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
private static Func<Decimal, DecimalBinaryBits> Build()
{
ParameterExpression de = Expression.Parameter(typeof(Decimal));
Expression low, mid, high, flags;
try
{
//FRAMEWORK
low = Expression.Field(de, typeof(Decimal).GetField("lo", BindingFlags.Instance | BindingFlags.NonPublic));
mid = Expression.Field(de, typeof(Decimal).GetField("mid", BindingFlags.Instance | BindingFlags.NonPublic));
high = Expression.Field(de, typeof(Decimal).GetField("hi", BindingFlags.Instance | BindingFlags.NonPublic));
flags = Expression.Field(de, typeof(Decimal).GetField("flags", BindingFlags.Instance | BindingFlags.NonPublic));
}
catch
{
try
{
low = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("Low", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
mid = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("Mid", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
high = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("High", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
flags = Expression.Field(de, typeof(Decimal).GetField("_flags", BindingFlags.Instance | BindingFlags.NonPublic));
}
catch (Exception ex)
{
throw BssomSerializationTypeFormatterException.TypeFormatterError(typeof(decimal), ex.Message);
}
}
NewExpression body = Expression.New(typeof(DecimalBinaryBits).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }), low, mid, high, flags);
return Expression.Lambda<Func<Decimal, DecimalBinaryBits>>(body, de).Compile();
}
19
View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static TypeInfo BuildICollectionImplementationType(DynamicFormatterreplacedembly replacedembly, Type type, ConstructorInfo constructor,
Type itemType,
bool isImplGenerIList, bool IsImplIList, bool isImplGenerICollec, bool isImplIReadOnlyList)
{
TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
if (itemType == typeof(object))
{
//itemType is Object, Array2
if (IsImplIList)
{
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
}
else
{
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
}
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
}
else
{
if (Array1FormatterHelper.IsArray1Type(itemType))
{
//Array1
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(itemType) }));
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(itemType) }));
}
else
{
if (isImplGenerIList || isImplIReadOnlyList)
{
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
}
else
{
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
}
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
}
}
MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
ParameterInfo[] args = constructor.GetParameters();
if (args.Length == 1 && args[0].ParameterType != typeof(int))
{
//new T(IEnumerable t)
Type dynamicCacheType = typeof(CollectionDynamicDelegateCache<>).MakeGenericType(type);
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateInjectCtor));
methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(CollectionDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
}
else
{
if (itemType == typeof(DateTime))//DateTime需要特殊处理,因为要处理Standrand和Native
{
Type dtCollBuilder = typeof(DateTimeCollectionDeserializeBuilder<>).MakeGenericType(type);
MethodInfo methodinfo = dtCollBuilder.GetMethod(nameof(DateTimeCollectionDeserializeBuilder<ICollection<DateTime>>.ConstructorInit));
methodinfo.Invoke(null, new object[] { constructor });
TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, dtCollBuilder.GetMethod(nameof(DateTimeCollectionDeserializeBuilder<ICollection<DateTime>>.Deserialize)));
}
else
{
Type dynamicCacheType = typeof(CollectionDynamicDelegateCache<>).MakeGenericType(type);
if (args.Length == 0)
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateDeserializeWithEmptyCtor));
methodinfo.Invoke(null, new object[] { constructor, isImplGenerICollec, itemType });
}
else
{
DEBUG.replacedert(args.Length == 1 && args[0].ParameterType == typeof(int));
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateDeserializeWithCapacityCtor));
methodinfo.Invoke(null, new object[] { constructor, isImplGenerICollec, itemType });
}
TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(CollectionDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
}
}
return typeBuilder.CreateTypeInfo();
}
19
View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static TypeInfo BuildICollectionInterfaceType(DynamicFormatterreplacedembly replacedembly, Type type, Type elementType)
{
TypeBuilder typeBuilder = replacedembly.DefineCollectionFormatterType(type, elementType);
MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
if (type.IsGenericType == false)
{
DEBUG.replacedert(type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection));
//itemType is Object, Array2
if (type == typeof(IList))
{
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
}
else
{
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
}
TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(typeof(object)));
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
}
else
{
Type genericTypeDefine = type.GetGenericTypeDefinition();
DEBUG.replacedert(genericTypeDefine == typeof(IEnumerable<>) || genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(ICollection<>) || genericTypeDefine == typeof(ISet<>) || genericTypeDefine == typeof(IReadOnlyList<>) || genericTypeDefine == typeof(IReadOnlyCollection<>));
if (Array1FormatterHelper.IsArray1Type(elementType))
{
//Array1
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));
if (genericTypeDefine == typeof(ISet<>))
{
TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.DeserializeSetPrefix + elementType.Name, BindingFlags.Public | BindingFlags.Static));
}
else
{
Type listFormatterType = Array1ResolverGetFormatterHelper.GetListFormatterType(elementType);
FieldInfo field = listFormatterType.GetField(nameof(DateTimeListFormatter.Instance), BindingFlags.Static | BindingFlags.Public);
MethodInfo method = listFormatterType.GetMethod(nameof(DateTimeListFormatter.Deserialize));
TypeBuildHelper.CallOneStaticFieldMethodInDeserialize(deserializeMethod, field, method);
}
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));
}
else
{
if (genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(IReadOnlyList<>))
{
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
}
else
{
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
}
if (genericTypeDefine == typeof(ISet<>))
{
TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeSet), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
}
else
{
TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
}
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
}
}
return typeBuilder.CreateTypeInfo();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static TypeInfo BuildGenericIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type, Type genericKeyType, Type genericValueType)
{
TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));
MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
ParameterInfo[] args = constructor.GetParameters();
Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);
if (args.Length == 0)
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictEmptyCtor));
methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
}
else
{
DEBUG.replacedert(args.Length == 1);
if (args[0].ParameterType == typeof(int))
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictCapacityCtor));
methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
}
else
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
}
}
TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericKeyType, genericValueType));
return typeBuilder.CreateTypeInfo();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static TypeInfo BuildIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type)
{
TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeIDictionary), BindingFlags.Public | BindingFlags.Static));
MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
ParameterInfo[] args = constructor.GetParameters();
Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);
if (args.Length == 1)
{
DEBUG.replacedert(args[0].ParameterType == typeof(IDictionary));
//return new T(IDictionaryFormatter.Deserialize)
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
}
else
{
MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithIDictionaryEmptyCtor));
methodinfo.Invoke(null, new object[] { });
}
TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeIDictionary), BindingFlags.Public | BindingFlags.Static));
return typeBuilder.CreateTypeInfo();
}
19
View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
static object BuildLoaderDelegateMscorlib(byte[] replacedembly)
{
Delegate res = Delegate.CreateDelegate(typeof(Converter<byte[], replacedembly>),
replacedembly,
typeof(replacedembly).GetMethod("Load", new Type[] { typeof(byte[]), typeof(byte[]) }));
HeaderHandler d = new HeaderHandler(Convert.ToString);
d = (HeaderHandler)Delegate.Combine(d, (Delegate)d.Clone());
d = (HeaderHandler)Delegate.Combine(d, (Delegate)d.Clone());
FieldInfo fi = typeof(MulticastDelegate).GetField("_invocationList", BindingFlags.NonPublic | BindingFlags.Instance);
object[] invoke_list = d.GetInvocationList();
invoke_list[1] = res;
fi.SetValue(d, invoke_list);
d = (HeaderHandler)Delegate.Remove(d, (Delegate)invoke_list[0]);
d = (HeaderHandler)Delegate.Remove(d, (Delegate)invoke_list[2]);
return d;
}
19
View Source File : RepositoryDbContext.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic));
19
View Source File : LogConfigUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static string GetStackTrace()
{
Type consoleWindowType = typeof(EditorWindow).replacedembly.GetType("UnityEditor.ConsoleWindow");
FieldInfo fieldInfo = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
object obj = fieldInfo.GetValue(null);
if (obj != null)
{
if (obj == (object)EditorWindow.focusedWindow)
{
fieldInfo = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
return fieldInfo.GetValue(obj).ToString();
}
}
return string.Empty;
}
19
View Source File : ViewModelBinding.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public void Add<TProperty>(string name, Action<TProperty, TProperty> valueChange)
{
FieldInfo fieldInfo = typeof(T).GetField(name, BindingFlags.Instance | BindingFlags.Public);
if (fieldInfo == null) return;
viewModelBindingList.Add((viewModel) =>
{
GetPropertyValue<TProperty>(viewModel, fieldInfo).ValueChange += valueChange;
});
unViewModelBindingList.Add((viewModel) =>
{
GetPropertyValue<TProperty>(viewModel, fieldInfo).ValueChange -= valueChange;
});
}
19
View Source File : CometaryExtensions.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public static FieldInfo GetCorrespondingField(this IFieldSymbol symbol)
{
return symbol.ContainingType.GetCorrespondingType().GetField(symbol.Name, symbol.GetCorrespondingBindingFlags());
}
19
View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static Func<DynamicMethod, RuntimeMethodHandle> MakeFindMethodHandleOfDynamicMethod()
{
// Generate the "FindMethodHandleOfDynamicMethod" delegate.
DynamicMethod findMethodHandle = new DynamicMethod(
nameof(FindMethodHandleOfDynamicMethod),
typeof(RuntimeMethodHandle),
new[] { typeof(DynamicMethod) },
typeof(DynamicMethod), true);
ILGenerator il = findMethodHandle.GetILGenerator(16);
il.Emit(OpCodes.Ldarg_0);
MethodInfo getMethodDescriptor = typeof(DynamicMethod)
.GetMethod("GetMethodDescriptor", NON_PUBLIC_INSTANCE);
if (getMethodDescriptor != null)
{
il.Emit(OpCodes.Callvirt, getMethodDescriptor);
}
else
{
FieldInfo handleField = typeof(DynamicMethod).GetField("m_method", NON_PUBLIC_INSTANCE)
?? typeof(DynamicMethod).GetField("mhandle", NON_PUBLIC_INSTANCE)
?? typeof(DynamicMethod).GetField("m_methodHandle", NON_PUBLIC_INSTANCE);
il.Emit(OpCodes.Ldfld, handleField);
}
il.Emit(OpCodes.Ret);
return findMethodHandle.CreateDelegate(typeof(Func<DynamicMethod, RuntimeMethodHandle>))
as Func<DynamicMethod, RuntimeMethodHandle>;
}
19
View Source File : Helpers.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static Func<DynamicMethod, RuntimeMethodHandle> MakeFindMethodHandleOfDynamicMethod()
{
// Generate the "FindMethodHandleOfDynamicMethod" delegate.
DynamicMethod findMethodHandle = new DynamicMethod(
nameof(FindMethodHandleOfDynamicMethod),
typeof(RuntimeMethodHandle),
new[] { typeof(DynamicMethod) },
typeof(DynamicMethod), true);
ILGenerator il = findMethodHandle.GetILGenerator(16);
il.Emit(OpCodes.Ldarg_0);
MethodInfo getMethodDescriptor = typeof(DynamicMethod)
.GetMethod("GetMethodDescriptor", NON_PUBLIC_INSTANCE);
if (getMethodDescriptor != null)
{
il.Emit(OpCodes.Callvirt, getMethodDescriptor);
}
else
{
FieldInfo handleField = typeof(DynamicMethod).GetField("m_method", NON_PUBLIC_INSTANCE)
?? typeof(DynamicMethod).GetField("mhandle", NON_PUBLIC_INSTANCE)
?? typeof(DynamicMethod).GetField("m_methodHandle", NON_PUBLIC_INSTANCE);
il.Emit(OpCodes.Ldfld, handleField);
}
il.Emit(OpCodes.Ret);
return findMethodHandle.CreateDelegate(typeof(Func<DynamicMethod, RuntimeMethodHandle>))
as Func<DynamicMethod, RuntimeMethodHandle>;
}
19
View Source File : ExtendableEnums.cs
License : MIT License
Project Creator : 7ark
License : MIT License
Project Creator : 7ark
static string GetEnumName(SerializedProperty prop)
{
string[] separatedPaths = prop.propertyPath.Split('.');
System.Object reflectionTarget = prop.serializedObject.targetObject as object;
foreach (var path in separatedPaths)
{
FieldInfo fieldInfo = reflectionTarget.GetType().GetField(path, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
string name = fieldInfo.FieldType.Name;
return name;
}
return "Null";
}
19
View Source File : ExtendableEnums.cs
License : MIT License
Project Creator : 7ark
License : MIT License
Project Creator : 7ark
static T GetBaseProperty<T>(SerializedProperty prop)
{
string[] separatedPaths = prop.propertyPath.Split('.');
System.Object reflectionTarget = prop.serializedObject.targetObject as object;
foreach (var path in separatedPaths)
{
FieldInfo fieldInfo = reflectionTarget.GetType().GetField(path, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
reflectionTarget = fieldInfo.GetValue(reflectionTarget);
}
return (T)reflectionTarget;
}
19
View Source File : UMAUtils.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static TElement[] GetBackingArray<TElement>(this List<TElement> list)
{
// Check if the FieldInfo is already in the cache
var listType = typeof(List<TElement>);
FieldInfo fieldInfo;
if (itemsFields.TryGetValue(listType, out fieldInfo) == false)
{
// Generate the FieldInfo and add it to the cache
fieldInfo = listType.GetField(FieldName, GetFieldFlags);
itemsFields.Add(listType, fieldInfo);
}
// Get the backing array of the given List
var items = (TElement[])fieldInfo.GetValue(list);
return items;
}
19
View Source File : UMAUtils.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static void SetActiveSize<TElement>(this List<TElement> list, int size)
{
// Check if the FieldInfo is already in the cache
var listType = typeof(List<TElement>);
FieldInfo fieldInfo;
if (itemsFields.TryGetValue(listType, out fieldInfo) == false)
{
// Generate the FieldInfo and add it to the cache
fieldInfo = listType.GetField(FieldName, GetFieldFlags);
itemsFields.Add(listType, fieldInfo);
}
// Set the active size of the given List
int newSize = size;
if (newSize < 0) newSize = 0;
if (newSize > list.Capacity) newSize = list.Capacity;
fieldInfo.SetValue(list, newSize);
}
19
View Source File : ThingTrade.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public override Thing CreateThing(bool useOriginalID = false, int stackCount = 0, bool needPirate = false)
{
//useOriginalID не используется.
var def = (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), DefName);
var stuffDef = !string.IsNullOrEmpty(StuffName) ? (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), StuffName) : null;
Thing thing = !string.IsNullOrEmpty(StuffName)
? ThingMaker.MakeThing(def, stuffDef)
: ThingMaker.MakeThing(def);
thing.stackCount = stackCount > 0 ? stackCount : Count;
if (HitPoints > 0) thing.HitPoints = HitPoints;
SetFaction(thing, isColonist && !needPirate);
CompQuality compQuality = thing.TryGetComp<CompQuality>();
if (compQuality != null)
{
compQuality.SetQuality((QualityCategory)Quality, ArtGenerationContext.Outsider);
}
if (WornByCorpse)
{
Apparel thingA = thing as Apparel;
if (thingA != null)
{
typeof(Apparel)
.GetField("wornByCorpseInt", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(thingA, true);
}
}
thing.Rotation = new Rot4(Rotation);
Plant thingP = thing as Plant;
if (thingP != null) thingP.Growth = Growth;
thing.Position = Position.Get();
return thing;
}
19
View Source File : GameUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static XmlWriter GetWriter(this ScribeSaver scribeSaver)
{
FieldInfo fieldInfo = typeof(ScribeSaver).GetField("writer", BindingFlags.Instance | BindingFlags.NonPublic);
XmlWriter result = (XmlWriter)fieldInfo.GetValue(scribeSaver);
return result;
}
19
View Source File : GameUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static void SetWriter(this ScribeSaver scribeSaver, XmlWriter writer)
{
FieldInfo fieldInfo = typeof(ScribeSaver).GetField("writer", BindingFlags.Instance | BindingFlags.NonPublic);
fieldInfo.SetValue(scribeSaver, writer);
}
19
View Source File : PrefixWriter.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollection<PatternPart> parts, Dictionary<string, (int offset, int length)> stringMap)
{
var method = new DynamicMethod("WritePrefix", typeof(void), new[] { typeof(PrefixWriter), typeof(ILogEventHeader) }, typeof(PrefixWriter), false)
{
InitLocals = false
};
var il = method.GetILGenerator();
var stringBufferLocal = il.DeclareLocal(typeof(StringBuffer));
var stringsLocal = il.DeclareLocal(typeof(char).MakeByRefType(), true);
var dateTimeLocal = default(LocalBuilder);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_stringBuffer), BindingFlags.Instance | BindingFlags.NonPublic)!);
il.Emit(OpCodes.Stloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_strings), BindingFlags.Instance | BindingFlags.NonPublic)!);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ldelema, typeof(char));
il.Emit(OpCodes.Stloc, stringsLocal);
foreach (var part in parts)
{
switch (part.Type)
{
case PatternPartType.String:
{
// _stringBuffer.Append(&_strings[0] + offset * sizeof(char), length);
var (offset, length) = stringMap[part.Value!];
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldloc, stringsLocal);
il.Emit(OpCodes.Conv_U);
il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldc_I4, length);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(char*), typeof(int) })!);
break;
}
case PatternPartType.Date:
{
// _stringBuffer.Append(logEventHeader.Timestamp, new StringView(&_strings[0] + offset * sizeof(char), length));
var (offset, length) = stringMap[_dateFormat];
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
il.Emit(OpCodes.Ldloc, stringsLocal);
il.Emit(OpCodes.Conv_U);
il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldc_I4, length);
il.Emit(OpCodes.Newobj, typeof(StringView).GetConstructor(new[] { typeof(char*), typeof(int) })!);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(DateTime), typeof(StringView) })!);
break;
}
case PatternPartType.Time:
{
// _stringBuffer.Append(logEventHeader.Timestamp.TimeOfDay, StringView.Empty);
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
il.Emit(OpCodes.Stloc, dateTimeLocal ??= il.DeclareLocal(typeof(DateTime)));
il.Emit(OpCodes.Ldloca, dateTimeLocal);
il.Emit(OpCodes.Call, typeof(DateTime).GetProperty(nameof(DateTime.TimeOfDay))?.GetGetMethod()!);
il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty))!);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(TimeSpan), typeof(StringView) })!);
break;
}
case PatternPartType.Thread:
{
// AppendThread(logEventHeader.Thread);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Thread))?.GetGetMethod()!);
il.Emit(OpCodes.Call, typeof(PrefixWriter).GetMethod(nameof(AppendThread), BindingFlags.Instance | BindingFlags.NonPublic)!);
break;
}
case PatternPartType.Level:
{
// _stringBuffer.Append(LevelStringCache.GetLevelString(logEventHeader.Level));
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Level))?.GetGetMethod()!);
il.Emit(OpCodes.Call, typeof(LevelStringCache).GetMethod(nameof(LevelStringCache.GetLevelString))!);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
break;
}
case PatternPartType.Logger:
{
// _stringBuffer.Append(logEventHeader.Name);
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Name))?.GetGetMethod()!);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
il.Emit(OpCodes.Ret);
return (Action<PrefixWriter, ILogEventHeader>)method.CreateDelegate(typeof(Action<PrefixWriter, ILogEventHeader>));
}
19
View Source File : MixedRealityInspectorUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static Rect GetEditorMainWindowPos()
{
var containerWinType = AppDomain.CurrentDomain.GetAllDerivedTypes(typeof(ScriptableObject)).FirstOrDefault(t => t.Name == "ContainerWindow");
if (containerWinType == null)
{
throw new MissingMemberException("Can't find internal type ContainerWindow. Maybe something has changed inside Unity");
}
var showModeField = containerWinType.GetField("m_ShowMode", BindingFlags.NonPublic | BindingFlags.Instance);
var positionProperty = containerWinType.GetProperty("position", BindingFlags.Public | BindingFlags.Instance);
if (showModeField == null || positionProperty == null)
{
throw new MissingFieldException("Can't find internal fields 'm_ShowMode' or 'position'. Maybe something has changed inside Unity");
}
var windows = Resources.FindObjectsOfTypeAll(containerWinType);
foreach (var win in windows)
{
var showMode = (int)showModeField.GetValue(win);
if (showMode == 4) // main window
{
var pos = (Rect)positionProperty.GetValue(win, null);
return pos;
}
}
throw new NotSupportedException("Can't find internal main window. Maybe something has changed inside Unity");
}
19
View Source File : AwaiterExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static List<Type> GenerateObjectTrace(IEnumerable<IEnumerator> enumerators)
{
var objTrace = new List<Type>();
foreach (var enumerator in enumerators)
{
// NOTE: This only works with scripting engine 4.6
// And could easily stop working with unity updates
var field = enumerator.GetType().GetField("$this", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (field == null)
{
continue;
}
var obj = field.GetValue(enumerator);
if (obj == null)
{
continue;
}
var objType = obj.GetType();
if (!objTrace.Any() || objType != objTrace.Last())
{
objTrace.Add(objType);
}
}
objTrace.Reverse();
return objTrace;
}
19
View Source File : AddRTTUtility.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public static void SetPrivateVariable(System.Type t, string varName, object varValue, object objInstance)
{
BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
FieldInfo fieldInfo = t.GetField(varName, eFlags);
if (fieldInfo != null)
{
fieldInfo.SetValue(objInstance, varValue);
}
else
{
Debug.LogError("Property `"+varName+"` not found");
}
}
19
View Source File : QueryableExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static string ToSql<TEnreplacedy>(this IQueryable<TEnreplacedy> query)
{
var enumerator = query.Provider.Execute<IEnumerable<TEnreplacedy>>(query.Expression).GetEnumerator();
var enumeratorType = enumerator.GetType();
var selectFieldInfo = enumeratorType.GetField("_selectExpression", BindingFlags.NonPublic | BindingFlags.Instance) ?? throw new InvalidOperationException($"cannot find field _selectExpression on type {enumeratorType.Name}");
var sqlGeneratorFieldInfo = enumeratorType.GetField("_querySqlGeneratorFactory", BindingFlags.NonPublic | BindingFlags.Instance) ?? throw new InvalidOperationException($"cannot find field _querySqlGeneratorFactory on type {enumeratorType.Name}");
var selectExpression = selectFieldInfo.GetValue(enumerator) as SelectExpression ?? throw new InvalidOperationException($"could not get SelectExpression");
var factory = sqlGeneratorFieldInfo.GetValue(enumerator) as IQuerySqlGeneratorFactory ?? throw new InvalidOperationException($"could not get IQuerySqlGeneratorFactory");
var sqlGenerator = factory.Create();
var command = sqlGenerator.GetCommand(selectExpression);
var sql = command.CommandText;
return sql;
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private static object Private(this object obj, string privateField) => obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj);
19
View Source File : Utils.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private static T Private<T>(this object obj, string privateField) => (T)obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj);
19
View Source File : ErrorNotifierModule.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string GetTraceByReflection(TraceContext trace)
{
// temporarily enable PageOutput (via the _isEnabled field) so that calling Render produces output
var isEnabledField = typeof(TraceContext).GetField("_isEnabled", BindingFlags.NonPublic | BindingFlags.Instance);
var originalIsEnabledValue = isEnabledField.GetValue(trace);
trace.IsEnabled = true;
try
{
var sb = new StringBuilder();
using (var htw = new Html32TextWriter(new StringWriter(sb, CultureInfo.InvariantCulture)))
{
typeof(TraceContext)
.GetMethod("Render", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(trace, new object[] { htw });
}
return sb.ToString();
}
finally
{
// reset the _isEnabled field
isEnabledField.SetValue(trace, originalIsEnabledValue);
}
}
19
View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
public static FieldInfo GetFieldInfoFromPath(object source, string path)
{
FieldInfo field = null;
var kvp = new KeyValuePair<object, string>(source, path);
if (!s_FieldInfoFromPaths.TryGetValue(kvp, out field))
{
var splittedPath = path.Split('.');
var type = source.GetType();
foreach (var t in splittedPath)
{
field = type.GetField(t, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (field == null)
break;
type = field.FieldType;
}
s_FieldInfoFromPaths.Add(kvp, field);
}
return field;
}
19
View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
public static object GetFieldValue(object source, string name)
{
var type = source.GetType();
while (type != null)
{
var f = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (f != null)
return f.GetValue(source);
type = type.BaseType;
}
return null;
}
19
View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
public static object GetFieldValueFromPath(object source, ref Type baseType, string path)
{
var splittedPath = path.Split('.');
object srcObject = source;
foreach (var t in splittedPath)
{
var fieldInfo = baseType.GetField(t, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (fieldInfo == null)
{
baseType = null;
break;
}
baseType = fieldInfo.FieldType;
srcObject = GetFieldValue(srcObject, t);
}
return baseType == null
? null
: srcObject;
}
19
View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
public static object GetParentObject(string path, object obj)
{
var fields = path.Split('.');
if (fields.Length == 1)
return obj;
var info = obj.GetType().GetField(fields[0], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
obj = info.GetValue(obj);
return GetParentObject(string.Join(".", fields, 1, fields.Length - 1), obj);
}
19
View Source File : GhostBoss.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public override void drawAboveAllLayers(SpriteBatch b)
{
int offset = (int)GetType().BaseType.GetField("yOffset", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
b.Draw(this.Sprite.Texture, base.getLocalPosition(Game1.viewport) + new Vector2(width*2, (float)(21 + offset)), new Microsoft.Xna.Framework.Rectangle?(this.Sprite.SourceRect), Color.White, 0f, new Vector2(width/2, width), scale * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0f, drawOnTop ? 0.991f : (getStandingY() / 10000f)));
b.Draw(Game1.shadowTexture, base.getLocalPosition(Game1.viewport) + new Vector2(width*2, width*4), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), 3f + offset / 20f * width/16, SpriteEffects.None, (getStandingY() - 1) / 10000f);
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private void UpdateTicking(object sender, UpdateTickingEventArgs e)
{
if (!Context.IsWorldReady)
return;
GameLocation location = Game1.getPlayerOrEventFarmer().currentLocation;
Netcode.NetCollection<Debris> debris = location.debris;
GameTime time = new GameTime();
float rangeMult = magnetRangeMult;
bool infRange = (rangeMult < 0 ? true : false);
int speedMult = magnetSpeedMult;
bool noBounce = noLootBounce;
bool noWave = noLootWave;
for (int j = 0; j < debris.Count; j++)
{
Debris d = debris[j];
NetObjectShrinkList<Chunk> chunks = (NetObjectShrinkList<Chunk>) typeof(Debris).GetField("chunks", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(d);
if (chunks.Count == 0)
{
continue;
}
d.timeSinceDoneBouncing += (float)time.ElapsedGameTime.Milliseconds;
if (d.timeSinceDoneBouncing >= (d.floppingFish ? 2500f : ((d.debrisType == Debris.DebrisType.SPRITECHUNKS || d.debrisType == Debris.DebrisType.NUMBERS) ? 1800f : (noBounce ? 0f : 600f))))
{
if (d.debrisType == Debris.DebrisType.LETTERS || d.debrisType == Debris.DebrisType.NUMBERS || d.debrisType == Debris.DebrisType.SQUARES || d.debrisType == Debris.DebrisType.SPRITECHUNKS || (d.debrisType == Debris.DebrisType.CHUNKS && chunks[0].debrisType - chunks[0].debrisType % 2 != 8))
{
continue;
}
if (d.debrisType == Debris.DebrisType.ARCHAEOLOGY || d.debrisType == Debris.DebrisType.OBJECT || d.debrisType == Debris.DebrisType.RESOURCE || d.debrisType == Debris.DebrisType.CHUNKS)
{
d.chunksMoveTowardPlayer = true;
}
d.timeSinceDoneBouncing = 0f;
}
if (location.farmers.Count == 0)
{
continue;
}
Vector2 total = default(Vector2);
foreach (Chunk chunk in chunks)
{
total += chunk.position.Value;
}
Vector2 position = total / (float)chunks.Count;
if (d.player.Value != null && (d.player.Value.currentLocation != location || !infRange && !(Math.Abs(position.X + 32f - (float)d.player.Value.getStandingX()) <= (float)d.player.Value.MagneticRadius * rangeMult && Math.Abs(position.Y + 32f - (float)d.player.Value.getStandingY()) <= (float)d.player.Value.MagneticRadius * rangeMult)))
{
d.player.Value = null;
}
Farmer farmer = d.player.Value;
if (farmer == null && (Game1.IsMasterGame || location.isTemp()))
{
float bestDistance = float.MaxValue;
Farmer bestFarmer = null;
foreach (Farmer f in location.farmers)
{
bool pir = infRange || (Math.Abs(position.X + 32f - (float)f.getStandingX()) <= (float)f.MagneticRadius * rangeMult && Math.Abs(position.Y + 32f - (float)f.getStandingY()) <= (float)f.MagneticRadius * rangeMult);
if ((f.UniqueMultiplayerID != d.DroppedByPlayerID || bestFarmer == null) && pir)
{
float distance = (f.Position - position).LengthSquared();
if (distance < bestDistance || (bestFarmer != null && bestFarmer.UniqueMultiplayerID == d.DroppedByPlayerID))
{
bestFarmer = f;
bestDistance = distance;
}
}
}
farmer = bestFarmer;
}
bool anyCouldMove = false;
for (int i = chunks.Count - 1; i >= 0; i--)
{
Chunk chunk = chunks[i];
chunk.position.UpdateExtrapolation(chunk.getSpeed());
if (chunk.alpha > 0.1f && (d.debrisType == Debris.DebrisType.SPRITECHUNKS || d.debrisType == Debris.DebrisType.NUMBERS) && d.timeSinceDoneBouncing > 600f)
{
chunk.alpha = (1800f - d.timeSinceDoneBouncing) / 1000f;
}
if (chunk.position.X < -128f || chunk.position.Y < -64f || chunk.position.X >= (float)(location.map.DisplayWidth + 64) || chunk.position.Y >= (float)(location.map.DisplayHeight + 64))
{
chunks.RemoveAt(i);
}
else
{
bool canMoveTowardPlayer = farmer != null;
if (canMoveTowardPlayer)
{
Debris.DebrisType value = d.debrisType.Value;
if (value - Debris.DebrisType.ARCHAEOLOGY > 1)
{
canMoveTowardPlayer = (value != Debris.DebrisType.RESOURCE || farmer.couldInventoryAcceptThisObject(chunk.debrisType - chunk.debrisType % 2, 1, 0));
}
else if (d.item != null)
{
canMoveTowardPlayer = farmer.couldInventoryAcceptThisItem(d.item);
}
else
{
if (chunk.debrisType < 0)
{
canMoveTowardPlayer = farmer.couldInventoryAcceptThisItem(new StardewValley.Object(Vector2.Zero, chunk.debrisType * -1, false));
}
else
{
canMoveTowardPlayer = farmer.couldInventoryAcceptThisObject(chunk.debrisType, 1, d.itemQuality);
}
if (chunk.debrisType == 102 && farmer.hasMenuOpen)
{
canMoveTowardPlayer = false;
}
}
anyCouldMove = (anyCouldMove || canMoveTowardPlayer);
if (canMoveTowardPlayer)
{
d.player.Value = farmer;
}
}
if ((d.chunksMoveTowardPlayer || d.isFishable) && canMoveTowardPlayer)
{
if (d.player.Value.IsLocalPlayer)
{
if(speedMult < 0)
{
chunk.position.X = d.player.Value.Position.X;
chunk.position.Y = d.player.Value.Position.Y;
}
else
{
for (int l = 1; l < speedMult; l++)
{
if (noWave)
{
if (chunk.position.X < d.player.Value.Position.X - 12f)
{
chunk.xVelocity.Value = 8f;
}
else if (chunk.position.X > d.player.Value.Position.X + 12f)
{
chunk.xVelocity.Value = -8f;
}
if (chunk.position.Y < d.player.Value.Position.Y - 12f)
{
chunk.yVelocity.Value = -8f;
}
else if (chunk.position.Y > d.player.Value.Position.Y + 12f)
{
chunk.yVelocity.Value = 8f;
}
}
else {
if (chunk.position.X < d.player.Value.Position.X - 12f)
{
chunk.xVelocity.Value = Math.Min(chunk.xVelocity + 0.8f, 8f);
}
else if (chunk.position.X > d.player.Value.Position.X + 12f)
{
chunk.xVelocity.Value = Math.Max(chunk.xVelocity - 0.8f, -8f);
}
if (chunk.position.Y + 32f < (float)(d.player.Value.getStandingY() - 12))
{
chunk.yVelocity.Value = Math.Max(chunk.yVelocity - 0.8f, -8f);
}
else if (chunk.position.Y + 32f > (float)(d.player.Value.getStandingY() + 12))
{
chunk.yVelocity.Value = Math.Min(chunk.yVelocity + 0.8f, 8f);
}
}
chunk.position.X += chunk.xVelocity;
chunk.position.Y -= chunk.yVelocity;
}
}
}
}
}
}
typeof(Debris).GetField("chunks", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(d, chunks);
}
}
19
View Source File : MobileTV.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public override void draw(SpriteBatch spriteBatch, int x, int y, float alpha = 1)
{
SetScreenScale();
TemporaryAnimatedSprite sprite = (TemporaryAnimatedSprite)typeof(TV).GetField("screen", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
if(sprite != null)
{
spriteBatch.Draw(backgroundTexture, ModEntry.api.GetScreenRectangle(), Color.White);
sprite.scale = GetScale(sprite.sourceRect);
typeof(TV).GetField("screen", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, sprite);
sprite.update(Game1.currentGameTime);
sprite.draw(spriteBatch, true, 0, 0, 1f);
TemporaryAnimatedSprite sprite2 = (TemporaryAnimatedSprite)typeof(TV).GetField("screenOverlay", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
if (sprite2 != null)
{
sprite2.scale = GetScale(sprite2.sourceRect);
typeof(TV).GetField("screenOverlay", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, sprite2);
sprite2.update(Game1.currentGameTime);
sprite2.draw(spriteBatch, true, 0, 0, 1f);
}
}
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private void MenuChanged(object sender, MenuChangedEventArgs e)
{
if (e.OldMenu is DialogueBox)
{
DialogueBox db2 = (DialogueBox)e.OldMenu;
FieldInfo fi = typeof(DialogueBox).GetField("selectedResponse", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo fi2 = typeof(DialogueBox).GetField("dialogues", BindingFlags.NonPublic | BindingFlags.Instance);
List<string> dialogues = (List<string>)fi.GetValue(db2);
}
}
19
View Source File : BillboardPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static IEnumerable<CodeInstruction> Billboard_draw_Transpiler(IEnumerable<CodeInstruction> instructions)
{
SMonitor.Log($"Transpiling Billboard.draw");
var codes = new List<CodeInstruction>(instructions);
for (int i = 0; i < codes.Count; i++)
{
if (codes[i].opcode == OpCodes.Ldsfld && (FieldInfo)codes[i].operand == typeof(Game1).GetField(nameof(Game1.dayOfMonth), BindingFlags.Public | BindingFlags.Static) && codes[i + 1].opcode == OpCodes.Ldloc_2 && codes[i + 2].opcode == OpCodes.Ldc_I4_1 && codes[i + 3].opcode == OpCodes.Add && codes[i + 4].opcode == OpCodes.Ble_S)
{
SMonitor.Log("Removing greyed out date covering");
codes[i + 2] = new CodeInstruction(OpCodes.Ldc_I4, 29);
}
}
return codes.AsEnumerable();
}
19
View Source File : Game1Patches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static IEnumerable<CodeInstruction> Game1__newDayAfterFade_Transpiler(IEnumerable<CodeInstruction> instructions)
{
SMonitor.Log($"Transpiling Game1._newDayAfterFade");
var codes = new List<CodeInstruction>(instructions);
for (int i = 0; i < codes.Count; i++)
{
if (codes[i].opcode == OpCodes.Ldsfld && (FieldInfo)codes[i].operand == typeof(Game1).GetField(nameof(Game1.dayOfMonth), BindingFlags.Public | BindingFlags.Static) && codes[i + 1].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i + 1].operand == 29)
{
SMonitor.Log($"Changing days per month to {Config.DaysPerMonth}");
codes[i + 1].operand = Config.DaysPerMonth + 1;
codes[i + 2].opcode = OpCodes.Blt_Un_S;
break;
}
}
return codes.AsEnumerable();
}
19
View Source File : SDatePatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private static void SDate_Postfix(SDate __instance)
{
typeof(SDate).GetField("DaysInSeason", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(__instance, Config.DaysPerMonth);
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private static bool Dialogue_randomName_Prefix(ref string __result)
{
string gender = Config.NeutralNameGender;
if(Game1.activeClickableMenu is NamingMenu)
{
string replacedle = (string)typeof(NamingMenu).GetField("replacedle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Game1.activeClickableMenu as NamingMenu);
if (replacedle == Game1.content.LoadString("Strings\\Events:BabyNamingreplacedle_Female"))
{
PMonitor.Log("Baby is female.");
gender = "female";
}
else if (replacedle == Game1.content.LoadString("Strings\\Events:BabyNamingreplacedle_Male"))
{
PMonitor.Log("Baby is male.");
gender = "male";
}
}
else if (!Config.RealNamesForAnimals)
{
return true;
}
string name = GetRandomName(gender);
if(name == "" || name == "error")
{
PMonitor.Log("Error getting random name, reverting to vanilla method.", LogLevel.Warn);
return true;
}
__result = name;
return false;
}
19
View Source File : SkullBoss.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public override void drawAboveAllLayers(SpriteBatch b)
{
if (!Utility.isOnScreen(Position, 128))
{
return;
}
previousPositions = (List<Vector2>)GetType().BaseType.GetField("previousPositions", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
seenPlayer.Value = ((NetBool)GetType().BaseType.GetField("seenPlayer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this)).Value;
Vector2 pos_offset = Vector2.Zero;
if (this.previousPositions.Count > 2)
{
pos_offset = base.Position - this.previousPositions[1];
}
int direction = (Math.Abs(pos_offset.X) > Math.Abs(pos_offset.Y)) ? ((pos_offset.X > 0f) ? 1 : 3) : ((pos_offset.Y < 0f) ? 0 : 2);
if (direction == -1)
{
direction = 2;
}
Vector2 offset = new Vector2(0f, width/2 * (float)Math.Sin(Game1.currentGameTime.TotalGameTime.TotalMilliseconds / 188.49555921538757));
b.Draw(Game1.shadowTexture, base.getLocalPosition(Game1.viewport) + new Vector2(width*2, height * 4), new Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), 3f * Scale + offset.Y / 20f, SpriteEffects.None, 0.0001f);
b.Draw(this.Sprite.Texture, base.getLocalPosition(Game1.viewport) + new Vector2((float)(width*2 + Game1.random.Next(-6, 7)), (float)(height*2 + Game1.random.Next(-6, 7))) + offset, new Rectangle?(Game1.getSourceRectForStandardTileSheet(this.Sprite.Texture, direction * 2 + ((this.seenPlayer && Game1.currentGameTime.TotalGameTime.TotalMilliseconds % 500.0 < 250.0) ? 1 : 0), width, height)), Color.Red * 0.44f, 0f, new Vector2(width/2f, height), Scale * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, (this.position.Y + 128f - 1f) / 10000f);
b.Draw(this.Sprite.Texture, base.getLocalPosition(Game1.viewport) + new Vector2((float)(width*2 + Game1.random.Next(-6, 7)), (float)(height*2 + Game1.random.Next(-6, 7))) + offset, new Rectangle?(Game1.getSourceRectForStandardTileSheet(this.Sprite.Texture, direction * 2 + ((this.seenPlayer && Game1.currentGameTime.TotalGameTime.TotalMilliseconds % 500.0 < 250.0) ? 1 : 0), width, height)), Color.Yellow * 0.44f, 0f, new Vector2(width/2, height), Scale * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, (this.position.Y + 128f) / 10000f);
for (int i = this.previousPositions.Count - 1; i >= 0; i -= 2)
{
b.Draw(this.Sprite.Texture, new Vector2(this.previousPositions[i].X - (float)Game1.viewport.X, this.previousPositions[i].Y - (float)Game1.viewport.Y + (float)this.yJumpOffset) + this.drawOffset + new Vector2(height*2, width*2) + offset, new Rectangle?(Game1.getSourceRectForStandardTileSheet(Sprite.Texture, direction * 2 + ((seenPlayer && Game1.currentGameTime.TotalGameTime.TotalMilliseconds % 500.0 < 250.0) ? 1 : 0), width, height)), Color.White * (0f + 0.125f * (float)i), 0f, new Vector2(width/2, height), scale * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, (this.position.Y + 128f - (float)i) / 10000f);
}
b.Draw(this.Sprite.Texture, base.getLocalPosition(Game1.viewport) + new Vector2(width*2, height*2) + offset, new Rectangle?(Game1.getSourceRectForStandardTileSheet(this.Sprite.Texture, direction * 2 + ((this.seenPlayer && Game1.currentGameTime.TotalGameTime.TotalMilliseconds % 500.0 < 250.0) ? 1 : 0), width, height)), Color.White, 0f, new Vector2(width/2, height), scale * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, (this.position.Y + 128f + 1f) / 10000f);
}
19
View Source File : SquidKidBoss.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public override void behaviorAtGameTick(GameTime time)
{
typeof(SquidKidBoss).BaseType.GetField("lastFireball", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this as SquidKid,1000f);
base.behaviorAtGameTick(time);
if (Health <= 0)
{
return;
}
if (this.withinPlayerThreshold(20))
{
this.lastIceBall = Math.Max(0f, this.lastIceBall - (float)time.ElapsedGameTime.Milliseconds);
this.lastLightning = Math.Max(0f, this.lastLightning - (float)time.ElapsedGameTime.Milliseconds);
if (!startedLightning && lastLightning < (ModEntry.IsLessThanHalfHealth(this) ? 500f : 1000f))
{
startedLightning = true;
List<Farmer> farmers = new List<Farmer>();
FarmerCollection.Enumerator enumerator = currentLocation.farmers.GetEnumerator();
while (enumerator.MoveNext())
{
farmers.Add(enumerator.Current);
}
playerPosition = farmers[Game1.random.Next(0, farmers.Count)].position;
Microsoft.Xna.Framework.Rectangle lightningSourceRect = new Rectangle(0, 0, 16, 16);
float markerScale = 8f;
Vector2 drawPosition = playerPosition + new Vector2(-16*markerScale/2 + 32f,-16*markerScale/ 2 + 32f);
Game1.currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite("TileSheets\\Projectiles", lightningSourceRect, 9999f, 1, 999, drawPosition, false, Game1.random.NextDouble() < 0.5, (playerPosition.Y + 32f) / 10000f + 0.001f, 0.025f, Color.White, markerScale, 0f, 0f, 0f, false)
{
light = true,
lightRadius = 2f,
delayBeforeAnimationStart = 200,
lightcolor = Color.Black
});
}
if (lastLightning == 0f)
{
startedLightning = false;
lightningStrike(playerPosition);
lastLightning = Game1.random.Next(1000, 2000) * (ModEntry.IsLessThanHalfHealth(this) ? 1 : 2);
}
if (lastIceBall == 0f)
{
Vector2 trajectory = ModEntry.VectorFromDegree(Game1.random.Next(0,360)) * 10f;
currentLocation.projectiles.Add(new BossProjectile((int)Math.Round(20 * difficulty), 9, 3, 4, 0f, trajectory.X, trajectory.Y, getStandingPosition(), "", "", true, false, currentLocation, this, false, null, 19));
projectileCount++;
if (projectileCount >= (ModEntry.IsLessThanHalfHealth(this) ? 8 : 4))
{
projectileCount = 0;
lastIceBall = Game1.random.Next(1200, 3500);
}
else
{
lastIceBall = 100;
}
if (lastIceBall != 0f && Game1.random.NextDouble() < 0.05)
{
Halt();
setTrajectory((int)Utility.getVelocityTowardPlayer(Utility.Vector2ToPoint(base.getStandingPosition()), 8f, base.Player).X, (int)(-(int)Utility.getVelocityTowardPlayer(Utility.Vector2ToPoint(base.getStandingPosition()), 8f, base.Player).Y));
}
}
}
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private void UpdateTicked(object sender, UpdateTickedEventArgs e)
{
if (!Context.IsWorldReady)
return;
if (drivingOff && !droveOff)
{
FieldInfo pos = typeof(BusStop).GetField("busPosition", BindingFlags.NonPublic | BindingFlags.Instance);
BusStop bs = (BusStop)Game1.getLocationFromName("BusStop");
if (((Vector2)pos.GetValue(bs)).X + 512f >= 0f)
{
FieldInfo mot = typeof(BusStop).GetField("busMotion", BindingFlags.NonPublic | BindingFlags.Instance);
mot.SetValue(bs, new Vector2(((Vector2)mot.GetValue(bs)).X - 0.075f, ((Vector2)mot.GetValue(bs)).Y));
}
else
{
droveOff = true;
drivingOff = false;
}
}
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private void OneSecondUpdateTicked(object sender, OneSecondUpdateTickedEventArgs e)
{
if (Game1.timeOfDay >= Config.LeaveTime && !droveOff && !drivingOff)
{
int gone = 0;
foreach (NPC npc in Game1.getLocationFromName("BusStop").characters)
{
if (npc.getTileLocation().X > 1000 && npc.getTileLocation().Y > 1000)
{
gone++;
}
if (npc.getTileLocation().X == 12 && npc.getTileLocation().Y == 9)
{
foreach (RNPC rnpc in RNPCs)
{
if (npc.name.Equals(rnpc.nameID))
{
Game1.warpCharacter(npc, "BusStop", new Vector2(10000, 10000));
}
}
}
}
if (!drivingOff && gone == RNPCs.Count)
{
//Alert("Driving off");
drivingOff = true;
FieldInfo door = typeof(BusStop).GetField("busDoor", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo pos = typeof(BusStop).GetField("busPosition", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo mot = typeof(BusStop).GetField("busMotion", BindingFlags.NonPublic | BindingFlags.Instance);
BusStop bs = (BusStop)Game1.getLocationFromName("BusStop");
door.SetValue(bs, new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Microsoft.Xna.Framework.Rectangle(288, 1311, 16, 38), (Vector2)pos.GetValue(bs) + new Vector2(16f, 26f) * 4f, false, 0f, Color.White)
{
interval = 999999f,
animationLength = 6,
holdLastFrame = true,
layerDepth = (((Vector2)pos.GetValue(bs)).Y + 192f) / 10000f + 1E-05f,
scale = 4f
});
((TemporaryAnimatedSprite)door.GetValue(bs)).timer = 0f;
((TemporaryAnimatedSprite)door.GetValue(bs)).interval = 70f;
((TemporaryAnimatedSprite)door.GetValue(bs)).endFunction = new TemporaryAnimatedSprite.endBehavior(delegate
{
bs.localSound("batFlap");
bs.localSound("busDriveOff");
});
bs.localSound("trashcanlid");
((TemporaryAnimatedSprite)door.GetValue(bs)).paused = false;
for (int i = 11; i < 19; i++)
{
for (int j = 7; j < 10; j++)
{
if (i == 12 && j == 9)
continue;
bs.removeTile(i, j, "Buildings");
//bs.setTileProperty(i, j, "Buildings", "Preplacedable", "T");
}
}
}
}
}
19
View Source File : EHHelper.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
private static bool BuildInternalPreserve(Type type)
{
try
{
const BindingFlags fl = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
var at = (string) typeof(Environment).InvokeMember("GetResourceString", fl, null, null, new object[] {"Word_At"});
var preserve = type.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
var field = type.GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
var stackTrace = type.GetProperty("StackTrace", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
var fmt = typeof(string).GetMethod("Format", new[] {typeof(string), typeof(object), typeof(object)});
var dm = new DynamicMethod("", typeof(void), new[] {typeof(Exception), typeof(string), typeof(bool)}, true);
var ilGen = dm.GetILGenerator();
var lbl = ilGen.DefineLabel();
var lbl2 = ilGen.DefineLabel();
var lbl3 = ilGen.DefineLabel();
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl2);
ilGen.Emit(System.Reflection.Emit.OpCodes.Callvirt, stackTrace);
ilGen.Emit(System.Reflection.Emit.OpCodes.Br, lbl3);
ilGen.MarkLabel(lbl2);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
ilGen.MarkLabel(lbl3);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Call, preserve);
ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
ilGen.Emit(System.Reflection.Emit.OpCodes.Brfalse, lbl);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldstr,
"{1}" + Environment.NewLine + " " + at + " DarksVM.Load() [{0}]" + Environment.NewLine);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
ilGen.Emit(System.Reflection.Emit.OpCodes.Call, fmt);
ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);
ilGen.MarkLabel(lbl);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);
rethrow = (Throw) dm.CreateDelegate(typeof(Throw));
}
catch(Exception ex)
{
Console.WriteLine(ex);
return false;
}
return true;
}
19
View Source File : PhotonPlayer.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
internal void InternalChangeLocalID(int newID)
{
if (!this.IsLocal)
{
Debug.LogError("ERROR You should never change PhotonPlayer IDs!");
return;
}
var info = GetType().GetField(nameof(ID), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (info != null)
{
info.SetValue(this, newID);
InitializeCounters();
}
targetArray[0] = ID;
}
19
View Source File : SettingsSetterViewController.cs
License : MIT License
Project Creator : Aeroluna
License : MIT License
Project Creator : Aeroluna
internal void Init(StartStandardLevelParameters startParameters, MenuTransitionsHelper menuTransitionsHelper)
{
if (startParameters.DifficultyBeatmap.beatmapData is CustomBeatmapData customBeatmapData)
{
Dictionary<string, object?>? settings = customBeatmapData.beatmapCustomData.Get<Dictionary<string, object?>>("_settings");
if (settings != null)
{
_contents.Clear();
_modifiedParameters = startParameters;
Dictionary<string, object?>? jsonPlayerOptions = settings.Get<Dictionary<string, object?>>("_playerOptions");
if (jsonPlayerOptions != null)
{
PlayerSpecificSettings playerSettings = startParameters.PlayerSpecificSettings;
List<Dictionary<string, object>> settablePlayerSettings = SettingSetterSettableSettingsManager.SettingsTable["_playerOptions"];
PlayerSpecificSettings modifiedPlayerSettings = playerSettings.CopyWith();
foreach (Dictionary<string, object> settablePlayerSetting in settablePlayerSettings)
{
string name = (string)settablePlayerSetting["_name"];
string fieldName = (string)settablePlayerSetting["_fieldName"];
object? json = jsonPlayerOptions.Get<object>(fieldName);
if (json != null)
{
FieldInfo field = typeof(PlayerSpecificSettings).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
object activeValue = field.GetValue(playerSettings);
if (json is string jsonString)
{
json = Enum.Parse(typeof(EnvironmentEffectsFilterPreset), jsonString);
}
else if (json is IConvertible)
{
json = Convert.ChangeType(json, activeValue.GetType());
}
if (!json.Equals(activeValue))
{
_contents.Add(new ListObject($"[Player Options] {name}", $"{activeValue} > {json}"));
field.SetValue(modifiedPlayerSettings, json);
}
}
}
_modifiedParameters.PlayerSpecificSettings = modifiedPlayerSettings;
}
Dictionary<string, object?>? jsonModifiers = settings.Get<Dictionary<string, object?>>("_modifiers");
if (jsonModifiers != null)
{
GameplayModifiers gameplayModifiers = startParameters.GameplayModifiers;
List<Dictionary<string, object>> settableGameplayModifiers = SettingSetterSettableSettingsManager.SettingsTable["_modifiers"];
GameplayModifiers modifiedGameplayModifiers = gameplayModifiers.CopyWith();
foreach (Dictionary<string, object> settableGameplayModifier in settableGameplayModifiers)
{
string name = (string)settableGameplayModifier["_name"];
string fieldName = (string)settableGameplayModifier["_fieldName"];
object? json = jsonModifiers.Get<object>(fieldName);
if (json != null)
{
FieldInfo field = typeof(GameplayModifiers).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
object activeValue = field.GetValue(gameplayModifiers);
if (json is string jsonString)
{
switch (fieldName)
{
case "_energyType":
json = Enum.Parse(typeof(GameplayModifiers.EnergyType), jsonString);
break;
case "_enabledObstacleType":
json = Enum.Parse(typeof(GameplayModifiers.EnabledObstacleType), jsonString);
break;
case "_songSpeed":
json = Enum.Parse(typeof(GameplayModifiers.SongSpeed), jsonString);
break;
}
}
else if (json is IConvertible)
{
json = Convert.ChangeType(json, activeValue.GetType());
}
if (!json.Equals(activeValue))
{
_contents.Add(new ListObject($"[Modifiers] {name}", $"{activeValue} > {json}"));
field.SetValue(modifiedGameplayModifiers, json);
}
}
}
_modifiedParameters.GameplayModifiers = modifiedGameplayModifiers;
}
Dictionary<string, object?>? jsonEnvironments = settings.Get<Dictionary<string, object?>>("_environments");
if (jsonEnvironments != null)
{
OverrideEnvironmentSettings? environmentOverrideSettings = startParameters.OverrideEnvironmentSettings;
if (environmentOverrideSettings != null)
{
Dictionary<string, object> settableEnvironmentSetting = SettingSetterSettableSettingsManager.SettingsTable["_environments"].First();
string name = (string)settableEnvironmentSetting["_name"];
string fieldName = (string)settableEnvironmentSetting["_fieldName"];
bool activeValue = environmentOverrideSettings.overrideEnvironments;
bool? json = jsonEnvironments.Get<bool>(fieldName);
if (json != null && json != activeValue)
{
_contents.Add(new ListObject($"[Environments] {name}", $"{activeValue} > {json}"));
// copy fields from original overrideenvironmentsettings to our new copy
OverrideEnvironmentSettings modifiedOverrideEnvironmentSettings = new OverrideEnvironmentSettings();
modifiedOverrideEnvironmentSettings.SetField("_data", environmentOverrideSettings.GetField<Dictionary<EnvironmentTypeSO, EnvironmentInfoSO>, OverrideEnvironmentSettings>("_data"));
modifiedOverrideEnvironmentSettings.overrideEnvironments = json.Value;
_modifiedParameters.OverrideEnvironmentSettings = modifiedOverrideEnvironmentSettings;
}
}
}
Dictionary<string, object?>? jsonColors = settings.Get<Dictionary<string, object?>>("_colors");
if (jsonColors != null)
{
ColorSchemesSettings? colorSchemesSettings = OverrideColorScheme;
if (colorSchemesSettings != null)
{
Dictionary<string, object> settableColorSetting = SettingSetterSettableSettingsManager.SettingsTable["_colors"].First();
string name = (string)settableColorSetting["_name"];
string fieldName = (string)settableColorSetting["_fieldName"];
bool activeValue = colorSchemesSettings.overrideDefaultColors;
bool? json = jsonColors.Get<bool>(fieldName);
if (json != null && json != activeValue)
{
_contents.Add(new ListObject($"[Colors] {name}", $"{activeValue} > {json}"));
_modifiedParameters.OverrideColorScheme = json.Value ? colorSchemesSettings.GetOverrideColorScheme() : null;
}
}
}
_modifiedMainSettings = null;
_cachedMainSettings = null;
Dictionary<string, object?>? jsonGraphics = settings.Get<Dictionary<string, object?>>("_graphics");
if (jsonGraphics != null)
{
MainSettingsModelSO mainSettingsModel = MainSettings;
List<Dictionary<string, object>> settableGraphicsSettings = SettingSetterSettableSettingsManager.SettingsTable["_graphics"];
_cachedMainSettings = new SettableMainSettings(
mainSettingsModel.mirrorGraphicsSettings,
mainSettingsModel.mainEffectGraphicsSettings,
mainSettingsModel.smokeGraphicsSettings,
mainSettingsModel.burnMarkTrailsEnabled,
mainSettingsModel.screenDisplacementEffectsEnabled,
mainSettingsModel.maxShockwaveParticles);
_modifiedMainSettings = _cachedMainSettings with { };
foreach (Dictionary<string, object> settableGraphicSetting in settableGraphicsSettings)
{
string name = (string)settableGraphicSetting["_name"];
string fieldName = (string)settableGraphicSetting["_fieldName"];
object? json = jsonGraphics.Get<object>(fieldName);
if (json != null)
{
// substring is to remove underscore
object valueSO = typeof(MainSettingsModelSO).GetField(fieldName.Substring(1), BindingFlags.Instance | BindingFlags.Public).GetValue(mainSettingsModel);
object activeValue = valueSO switch
{
BoolSO boolSO => boolSO.value,
IntSO intSO => intSO.value,
_ => throw new InvalidOperationException($"How the hell did you reach this? [{valueSO.GetType()}]"),
};
if (json is IConvertible)
{
json = Convert.ChangeType(json, activeValue.GetType());
}
if (!json.Equals(activeValue))
{
_contents.Add(new ListObject($"[Graphics] {name}", $"{activeValue} > {json}"));
typeof(SettableMainSettings).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(_modifiedMainSettings, json);
}
}
}
}
_settableSettingsToSet = null;
foreach (KeyValuePair<string, Dictionary<string, ISettableSetting>> groupSettingPair in SettingSetterSettableSettingsManager.SettableSettings)
{
Dictionary<string, object?>? jsonGroup = settings.Get<Dictionary<string, object?>>(groupSettingPair.Key);
if (jsonGroup != null)
{
_settableSettingsToSet = new List<Tuple<ISettableSetting, object>>();
foreach (KeyValuePair<string, ISettableSetting> settableSettingPair in groupSettingPair.Value)
{
object? json = jsonGroup.Get<object>(settableSettingPair.Key);
ISettableSetting settableSetting = settableSettingPair.Value;
object activeValue = settableSetting.TrueValue;
if (json != null && !json.Equals(activeValue))
{
_contents.Add(new ListObject($"[{settableSetting.GroupName}] {settableSetting.FieldName}", $"{activeValue} > {json}"));
_settableSettingsToSet.Add(new Tuple<ISettableSetting, object>(settableSetting, json));
}
}
}
}
if (_contents.Any())
{
if (_contentObject != null)
{
Destroy(_contentObject);
}
DoPresent = true;
_defaultParameters = startParameters;
_menuTransitionsHelper = menuTransitionsHelper;
_presentViewController(ActiveFlowCoordinator, this, null, AnimationDirection.Horizontal, false);
BeatSaberMarkupLanguage.BSMLParser.instance.Parse(ContentBSML, gameObject, this);
return;
}
}
}
19
View Source File : Platform.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private static void replacedignImplementations(Type platformDependant, string implementationName)
{
Type platformImplementation = platformDependant.GetNestedType(implementationName, bindings);
// if (platformImplementation == null) return;
FieldInfo[] fields = platformDependant.GetFields(bindings);
foreach (FieldInfo field in fields)
{
Type fieldType = field.FieldType;
string delegateName = fieldType.Name;
MethodInfo methodInfo__internal = null;
FieldInfo fieldInfo__internal = null;
// TODO: This is mapping sodium.crypto_box to sodium.crypto_box__Internal. Should we also map them to sodium.__Internal.crypto_box?
if (implementationName == "__Internal")
{
if (delegateName.EndsWith("_delegate"))
{
// YOU now have
// public static readonly crypto_box_delegate box = crypto_box;
// YOU need
// public static readonly crypto_box_delegate box = crypto_box__Internal;
delegateName = delegateName.Substring(0, delegateName.Length - "_delegate".Length);
if (delegateName.Length > 0)
{
methodInfo__internal = platformDependant.GetMethod(delegateName + "__Internal", bindings);
}
}
}
if (methodInfo__internal == null && platformImplementation != null)
{
if (delegateName.EndsWith("Delegate"))
{
// YOU now have
// public static readonly UnmanagedLibrary LoadUnmanagedLibraryDelegate;
// YOU need
// public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary
// = Platform.__Internal.LoadUnmanagedLibrary;
delegateName = delegateName.Substring(0, delegateName.Length - "Delegate".Length);
methodInfo__internal = platformImplementation.GetMethod(delegateName, bindings);
}
else
{
methodInfo__internal = platformImplementation.GetMethod(field.Name, bindings);
}
if (methodInfo__internal == null)
{
fieldInfo__internal = platformImplementation.GetField(field.Name, bindings);
}
}
if (methodInfo__internal != null)
{
var delegat = Delegate.CreateDelegate(fieldType, methodInfo__internal);
field.SetValue(null, delegat);
}
else if (fieldInfo__internal != null)
{
object value = fieldInfo__internal.GetValue(null);
field.SetValue(null, value);
}
// else { field.SetValue(null, null); }
}
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
public static object GetValue(this Type gameType, string field)
{
return gameType.GetField(field, BindingFlags.Public | BindingFlags.Static).GetValue(null);
}
See More Examples