-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventSystem.cs
More file actions
539 lines (476 loc) · 20.5 KB
/
Copy pathEventSystem.cs
File metadata and controls
539 lines (476 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
using ADOFAI;
using HarmonyLib;
using Newtonsoft.Json;
using Outer_Swirl.Events;
using Outer_Swirl.Patch;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using UnityEngine;
using static UnityModManagerNet.UnityModManager.Param;
using ADOFAIPropInfo = ADOFAI.PropertyInfo;
namespace Outer_Swirl
{
public abstract class CustomEventBase
{
public virtual bool AllowFirstFloor => false;
public virtual LevelEventExecutionTime ExecutionTime => LevelEventExecutionTime.OnPrebar;
public virtual bool isDecoration => false;
public virtual void OnApply() { }
public virtual void OnFloor() { }
public virtual Sprite GetIcon() => null;
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class EventNameAttribute(string nameKey) : Attribute
{
public string NameKey { get; } = nameKey;
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class EventCategoryAttribute(params string[] categories) : Attribute
{
public string[] Categories { get; } = categories;
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class EventPropertyAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class PropertyToggleableAttribute(bool toggleable) : Attribute
{
public bool Toggleable { get; } = toggleable;
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class PropertyLabelAttribute : Attribute
{
public string LocalizationKey { get; set; }
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class PropertyGroupAttribute : Attribute
{
public string Name { get; set; }
}
public static class OuterSwirlEventSystem
{
public const int CustomEventTypeBase = 100000;
public static LevelEventType EventType { get; private set; }
public static LevelEventInfo EventInfo { get; private set; }
private static CustomEventBase _instance;
private static bool _initialized;
private static List<LevelEvent> _backup = new();
private static readonly Dictionary<int, Dictionary<string, object>> _floorCache = new();
private sealed class PropAccessor
{
public string Name;
public Type Type;
public MemberInfo Member;
public Func<CustomEventBase, object> Getter;
public Action<CustomEventBase, object> Setter;
}
private static readonly List<PropAccessor> _propAccessors = new();
internal static string _eventFullName;
private static List<LevelEventCategory> _eventCategories;
public static void Initialize(CustomEventBase ev)
{
try
{
if (_initialized) { Debug.Log("[OuterSwirl] Already initialized, skip"); return; }
_initialized = true;
Debug.Log("[OuterSwirl] Initialize start");
_instance = ev;
EventType = (LevelEventType)CustomEventTypeBase;
var type = ev.GetType();
var nameAttr = Attribute.GetCustomAttribute(type, typeof(EventNameAttribute)) as EventNameAttribute;
var fullName = nameAttr?.NameKey ?? type.Name;
Debug.Log($"[OuterSwirl] fullName={fullName}");
var categories = new List<LevelEventCategory>();
foreach (var rawName in Attribute.GetCustomAttributes(type, typeof(EventCategoryAttribute))
.Cast<EventCategoryAttribute>().SelectMany(a => a.Categories))
{
if (Enum.TryParse(rawName, true, out LevelEventCategory cat))
categories.Add(cat);
}
_propAccessors.Clear();
foreach (var prop in type.GetProperties())
{
if (prop.IsDefined(typeof(EventPropertyAttribute), false))
{
_propAccessors.Add(new PropAccessor
{
Name = prop.Name,
Type = prop.PropertyType,
Member = prop,
Getter = BuildGetter(prop, type),
Setter = BuildSetter(prop, type, prop.PropertyType)
});
}
}
foreach (var field in type.GetFields())
{
if (field.IsDefined(typeof(EventPropertyAttribute), false))
{
_propAccessors.Add(new PropAccessor
{
Name = field.Name,
Type = field.FieldType,
Member = field,
Getter = BuildGetter(field, type),
Setter = BuildSetter(field, type, field.FieldType)
});
}
}
Debug.Log($"[OuterSwirl] _propAccessors count={_propAccessors.Count}");
_eventFullName = fullName;
_eventCategories = categories;
}
catch (Exception ex)
{
Debug.LogError($"[OuterSwirl] Initialize failed: {ex}");
}
}
static void TryRegister()
{
if (OuterSwirlEventSystem._eventFullName == null) return;
var eventKey = OuterSwirlEventSystem.EventType.ToString();
if (GCS.levelEventsInfo != null && GCS.levelEventsInfo.ContainsKey(eventKey))
{
EventInfo = GCS.levelEventsInfo[eventKey];
return;
}
if (GCS.levelEventsInfo == null || GCS.levelEventTypeString == null)
{
Debug.Log("[OuterSwirl] TR: GCS not ready yet, will retry later");
return;
}
try
{
Debug.Log("[OuterSwirl] TR: start");
GCS.levelEventTypeString[EventType] = eventKey;
Debug.Log("[OuterSwirl] TR: levelEventTypeString ok");
EventInfo = new LevelEventInfo
{
name = eventKey,
type = EventType,
executionTime = _instance.ExecutionTime,
allowFirstFloor = _instance.AllowFirstFloor,
useGroups = false,
categories = _eventCategories,
};
Debug.Log("[OuterSwirl] TR: EventInfo created");
var propsInfo = new Dictionary<string, ADOFAIPropInfo>();
foreach (var accessor in _propAccessors)
{
var name = accessor.Name;
var member = accessor.Member;
var propType = accessor.Type;
Debug.Log($"[OuterSwirl] TR: processing prop '{name}'");
object defaultValue = null;
try { defaultValue = accessor.Getter(_instance); }
catch (Exception ex)
{
Debug.LogError($"[OuterSwirl] Getter for '{name}' failed: {ex}");
}
var labelAttr = Attribute.GetCustomAttribute(member, typeof(PropertyLabelAttribute)) as PropertyLabelAttribute;
var pDict = new Dictionary<string, object>
{
["name"] = name,
["type"] = MapPropertyTypeString(propType),
["default"] = defaultValue ?? "",
["key"] = labelAttr?.LocalizationKey ?? "",
["affectsFloors"] = true
};
Debug.Log("[OuterSwirl] TR: pDict ready");
var pInfo = new ADOFAIPropInfo(pDict, EventInfo);
Debug.Log("[OuterSwirl] TR: ADOFAIPropInfo created");
propsInfo[name] = pInfo;
}
EventInfo.propertiesInfo = propsInfo;
Debug.Log("[OuterSwirl] TR: propertiesInfo assigned");
GCS.levelEventsInfo[eventKey] = EventInfo;
Debug.Log($"[OuterSwirl] TR: event registered in GCS");
if (GCS.levelEventIcons != null)
{
try
{
var icon = _instance.GetIcon();
if (icon != null)
GCS.levelEventIcons[EventType] = icon;
}
catch (Exception ex)
{
Debug.LogError($"[OuterSwirl] Icon retrieval failed: {ex}");
}
}
Debug.Log($"[OuterSwirl] Registered event '{_eventFullName}' (ID={CustomEventTypeBase})");
if (GCS.levelEventsInfo.ContainsKey(eventKey))
RegisterSoloType();
}
catch (Exception ex)
{
Debug.LogError($"[OuterSwirl] Register event failed: {ex}");
}
}
private static void RegisterSoloType()
{
try
{
var getter = PatchManager.CreateStaticFieldGetter<HashSet<LevelEventType>>(
typeof(EditorConstants), nameof(EditorConstants.soloTypes));
var hashSet = getter();
if (hashSet == null)
{
Debug.LogError("[OuterSwirl] soloTypes is null");
return;
}
var customType = (LevelEventType)CustomEventTypeBase;
if (hashSet.Contains(customType))
{
Debug.Log($"[OuterSwirl] Type {customType} already in soloTypes");
return;
}
hashSet.Add(customType);
Debug.Log($"[OuterSwirl] Added event type {customType} to soloTypes");
}
catch (Exception ex)
{
Debug.LogError($"[OuterSwirl] Failed to register solo type: {ex}");
}
}
static Func<CustomEventBase, object> BuildGetter(MemberInfo member, Type declaringType)
{
var instanceParam = Expression.Parameter(typeof(CustomEventBase), "instance");
var castInstance = Expression.Convert(instanceParam, declaringType);
Expression memberAccess = member switch
{
System.Reflection.PropertyInfo pi => Expression.Property(castInstance, pi),
System.Reflection.FieldInfo fi => Expression.Field(castInstance, fi),
_ => throw new ArgumentException("Unsupported member")
};
var boxed = Expression.Convert(memberAccess, typeof(object));
return Expression.Lambda<Func<CustomEventBase, object>>(boxed, instanceParam).Compile();
}
static Action<CustomEventBase, object> BuildSetter(MemberInfo member, Type declaringType, Type memberType)
{
var instanceParam = Expression.Parameter(typeof(CustomEventBase), "instance");
var valueParam = Expression.Parameter(typeof(object), "value");
var castInstance = Expression.Convert(instanceParam, declaringType);
// 如果 raw 运行时类型 == memberType,直接 unbox;否则走 ChangeType
var isInstanceOf = Expression.TypeIs(valueParam, memberType);
var directCast = Expression.Convert(valueParam, memberType);
var changeTypeCall = Expression.Call(
typeof(Convert), nameof(Convert.ChangeType), null,
valueParam, Expression.Constant(memberType));
var convertedCast = Expression.Convert(changeTypeCall, memberType);
var finalValue = Expression.Condition(isInstanceOf, directCast, convertedCast);
Expression assign = member switch
{
System.Reflection.PropertyInfo pi => Expression.Assign(Expression.Property(castInstance, pi), finalValue),
System.Reflection.FieldInfo fi => Expression.Assign(Expression.Field(castInstance, fi), finalValue),
_ => throw new ArgumentException("Unsupported member")
};
return Expression.Lambda<Action<CustomEventBase, object>>(assign, instanceParam, valueParam).Compile();
}
static string MapPropertyTypeString(Type t)
{
if (t == typeof(bool)) return "Bool";
if (t == typeof(int)) return "Int";
if (t == typeof(float)) return "Float";
if (t == typeof(string)) return "String";
return "String";
}
// ===== Harmony Patch Classes =====
[HarmonyPatch(typeof(scnGame), "Awake")]
internal static class EditorAwakePatch
{
[HarmonyPrefix]
static void BeforeAwake()
{
TryRegister();
var locPath = Path.Combine(Main.Mod.Path, "Localization.json");
if (File.Exists(locPath))
OuterSwirlLocalization.RegisterLocalization(File.ReadAllText(locPath));
}
}
[HarmonyPatch(typeof(scnGame), nameof(scnGame.ApplyEvent))]
internal static class ApplyEventPatch
{
[HarmonyPrefix]
static bool Prefix(LevelEvent evnt, float bpm, float pitch, List<scrFloor> floors, float offset, int? customFloorID, ref ffxPlusBase __result)
{
if ((int)evnt.eventType != OuterSwirlEventSystem.CustomEventTypeBase)
return true;
if (scnGame.instance == null && evnt.eventType == LevelEventType.CustomBackground)
{
return true;
}
int index = customFloorID ?? evnt.floor;
scrFloor floor = floors[index];
GameObject floorGO = floor.gameObject;
// 获取或创建组件
var comp = floorGO.GetComponent<ffxOuterSwirl>() ?? floorGO.AddComponent<ffxOuterSwirl>();
// 设置组件属性
comp.floorID = index;
comp.floors = floors;
comp.crotchet = (float)(60.0 / (bpm * pitch * floor.speed));
comp.Decode(evnt);
comp.SetStartTime(bpm, offset);
comp.sourceLevelEvent = evnt;
floor.plusEffects.Add(comp);
__result = comp; // 必须返回
return false; // 拦截原方法
}
}
[HarmonyPatch(typeof(scnGame), nameof(scnGame.Play), new Type[] { typeof(int), typeof(bool) })]
internal static class ScnGamePlayOuterSwirlResetPatch
{
[HarmonyPrefix]
private static void Prefix()
{
ffxOuterSwirl.ResetEffect(false);
}
}
[HarmonyPatch(typeof(Enum), nameof(Enum.GetValues))]
internal static class EnumGetValuesPatch
{
private static bool _executeOriginal = false;
[HarmonyPrefix]
private static bool Prefix(Type enumType, ref Array __result)
{
if (enumType == typeof(LevelEventType) && !_executeOriginal)
{
_executeOriginal = true;
// 获取原版枚举值列表
var original = Enum.GetValues(typeof(LevelEventType)) as LevelEventType[];
var merged = original.Concat(new[] { (LevelEventType)OuterSwirlEventSystem.CustomEventTypeBase }).ToArray();
__result = merged;
_executeOriginal = false;
return false; // 跳过原方法
}
return true; // 其他类型正常处理
}
}
[HarmonyPatch]
internal static class ParseEnum
{
private static MethodBase TargetMethod()
{
MethodInfo methodDef = typeof(RDUtils).GetMethods(BindingFlags.Static | BindingFlags.Public).FirstOrDefault<MethodInfo>((MethodInfo m) => m.Name == "ParseEnum" && m.IsGenericMethodDefinition);
if (methodDef == null)
{
return null;
}
return methodDef.MakeGenericMethod(new Type[] { typeof(LevelEventType) });
}
[HarmonyPrefix]
private static bool Prefix(string str, ref LevelEventType __result)
{
if (str == _eventFullName)
{
__result = (LevelEventType)CustomEventTypeBase;
return false;
}
return true;
}
}
[HarmonyPatch(typeof(RDString), nameof(RDString.GetWithCheck))]
internal static class RDStringGetWithCheckPatch
{
[HarmonyPrefix]
private static bool Prefix(string key, out bool exists, ref string __result)
{
if (OuterSwirlLocalization.TryGetLocalizedString(key, out string value))
{
__result = value;
exists = true;
return false; // 跳过原方法
}
exists = false;
return true; // 继续原方法
}
}
[HarmonyPatch(typeof(LevelData), "Encode")]
internal static class LevelDataEncode
{
[HarmonyPrefix]
static void Prefix(LevelData __instance)
{
UpdateRequiredMods(__instance.levelEvents);
}
}
[HarmonyPatch(typeof(RDEditorUtils), "CheckModsDependency")]
internal static class RdEditorUtilsCheckModsDependency
{
[HarmonyPrefix]
static bool Prefix(object[] mods, ref bool __result)
{
return FindRequiredModsAndRemove(mods, ref __result);
}
}
[HarmonyPatch(typeof(Enum), "ToString", new Type[] { })]
internal static class LevelEventTypeToString
{
[HarmonyPrefix]
static bool Prefix(Enum __instance, ref string __result)
{
if (__instance is LevelEventType && (LevelEventType)__instance == (LevelEventType)CustomEventTypeBase)
{
__result = _eventFullName;
return false;
}
return true;
}
}
// ===== Helper =====
static void ApplyProperties(Dictionary<string, object> data)
{
if (data == null) return;
foreach (var accessor in _propAccessors)
{
var name = accessor.Name;
if (!data.TryGetValue(name, out var raw)) continue;
try
{
accessor.Setter(_instance, raw);
}
catch (Exception ex)
{
Debug.LogError($"[OuterSwirl] Setter for '{name}' failed: {ex}");
}
}
}
internal static void UpdateRequiredMods(EventsArray<LevelEvent> events)
{
object[] array = (object[])scnGame.instance.levelData.levelSettings["requiredMods"];
HashSet<object> set = new HashSet<object>(array);
if (events.Any<LevelEvent>((LevelEvent e) => e.eventType == (LevelEventType)CustomEventTypeBase))
{
if (!array.Contains(_eventFullName))
{
set.Add(_eventFullName);
}
}
else
{
set.Remove(_eventFullName);
}
scnGame.instance.levelData.levelSettings["requiredMods"] = set.ToArray<object>();
}
internal static bool FindRequiredModsAndRemove(object[] mods, ref bool __result)
{
bool runBaseMethod;
if (mods != null && mods.Contains(_eventFullName))
{
HashSet<object> hashSet = new HashSet<object>(mods);
hashSet.Remove(_eventFullName);
mods = hashSet.ToArray<object>();
__result = RDEditorUtils.CheckModsDependency(mods);
runBaseMethod = false;
}
else
{
runBaseMethod = true;
}
return runBaseMethod;
}
}
}