Skip to content

Commit 7354db0

Browse files
committed
perf: reduce manager startup and frame costs
1 parent f99b92c commit 7354db0

12 files changed

Lines changed: 354 additions & 272 deletions

File tree

‎StArray.ModManager.Android/Managed.cs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,13 +71,14 @@ public static int Entry(int argc, IntPtr argv)
7171
};
7272

7373
_ = RuntimeManager.Detect();
74+
var imguiStartup = new AndroidImGuiStartup();
7475
var loader = new ModLoader(modsPath, AssemblyPath is { } ap ? Path.GetDirectoryName(ap) : null);
7576
var picker = new AndroidModFilePicker(modsPath);
7677
var ui = new ModManagerUI(loader, Path.GetDirectoryName(AssemblyPath)!, picker.PickAsync);
7778
HookHelper.Instance = new DobbyHook();
78-
ImGuiEGLRender.OnRender += ui.Render;
79-
ImGuiEGLRender.OnRender += picker.Render;
80-
ImGuiEGLRender.Install();
79+
ImGuiEGLRenderer.OnRender += ui.Render;
80+
ImGuiEGLRenderer.OnRender += picker.Render;
81+
ImGuiEGLRenderer.Install(imguiStartup);
8182

8283
Logger.Info($"{nameof(Managed)}-Benchmark", $"=== Startup total: {Benchmark.End():F3}s ===");
8384
return 0;

‎StArray.ModManager.Android/Native/InputEvents.cs‎

Lines changed: 6 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -213,11 +213,11 @@ private static void DispatchInputHandlers(
213213
Action<AndroidInputEventInfo> handlers,
214214
AndroidInputEventInfo input)
215215
{
216-
foreach (Delegate handler in handlers.GetInvocationList())
216+
foreach (var handler in Delegate.EnumerateInvocationList(handlers))
217217
{
218218
try
219219
{
220-
((Action<AndroidInputEventInfo>)handler)(input);
220+
handler(input);
221221
}
222222
catch (Exception exception)
223223
{
@@ -230,24 +230,11 @@ private static void DispatchTimestampHandlers(
230230
Action<TouchTimestampInfo> handlers,
231231
TouchTimestampInfo info)
232232
{
233-
if (Volatile.Read(ref s_touchTimestampSubscriberCount) == 1)
233+
foreach (var handler in Delegate.EnumerateInvocationList(handlers))
234234
{
235235
try
236236
{
237-
handlers(info);
238-
}
239-
catch (Exception exception)
240-
{
241-
LogOnce($"Touch timestamp subscriber threw: {exception}");
242-
}
243-
return;
244-
}
245-
246-
foreach (Delegate handler in handlers.GetInvocationList())
247-
{
248-
try
249-
{
250-
((Action<TouchTimestampInfo>)handler)(info);
237+
handler(info);
251238
}
252239
catch (Exception exception)
253240
{
@@ -260,24 +247,11 @@ private static void DispatchTouchHandlers(
260247
Action<TouchEventInfo> handlers,
261248
TouchEventInfo info)
262249
{
263-
if (Volatile.Read(ref s_touchSubscriberCount) == 1)
264-
{
265-
try
266-
{
267-
handlers(info);
268-
}
269-
catch (Exception exception)
270-
{
271-
LogOnce($"Touch event subscriber threw: {exception}");
272-
}
273-
return;
274-
}
275-
276-
foreach (Delegate handler in handlers.GetInvocationList())
250+
foreach (var handler in Delegate.EnumerateInvocationList(handlers))
277251
{
278252
try
279253
{
280-
((Action<TouchEventInfo>)handler)(info);
254+
handler(info);
281255
}
282256
catch (Exception exception)
283257
{

‎StArray.ModManager.Android/Native/JavaInputBridge.cs‎

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ internal static unsafe class AndroidJavaInputBridge
112112

113113
private static readonly ConcurrentQueue<AndroidInputEventInfo> ImGuiInputQueue = new();
114114
private static int s_queuedImGuiEventCount;
115+
private static int s_captureState = -1;
115116

116117
[StructLayout(LayoutKind.Sequential, Pack = 4)]
117118
internal struct NativeInputEventHeader
@@ -200,6 +201,7 @@ internal static bool RegisterCallback()
200201
try
201202
{
202203
SetInputCallback(Marshal.GetFunctionPointerForDelegate(s_callback));
204+
s_captureState = -1;
203205
return true;
204206
}
205207
catch (Exception exception) when (exception is DllNotFoundException
@@ -209,11 +211,16 @@ internal static bool RegisterCallback()
209211
}
210212
}
211213

212-
internal static void SetCaptureState(bool captureMouse, bool captureKeyboard)
214+
private static void SetCaptureState(bool captureMouse, bool captureKeyboard)
213215
{
216+
int state = (captureMouse ? 1 : 0) | (captureKeyboard ? 2 : 0);
217+
if (state == s_captureState)
218+
return;
219+
214220
try
215221
{
216-
SetCaptureStateNative(0, captureMouse ? 1 : 0, captureKeyboard ? 1 : 0);
222+
SetCaptureStateNative(0, state & 1, state >> 1);
223+
s_captureState = state;
217224
}
218225
catch (Exception exception) when (exception is DllNotFoundException
219226
or EntryPointNotFoundException or BadImageFormatException)
@@ -308,7 +315,8 @@ internal static AndroidInputEventInfo CopyEvent(NativeInputEventHeader* input)
308315
nativePointers, storedCount, input->FullDataIncluded != 0);
309316

310317
int storedHistoryCount = input->StoredHistorySampleCount;
311-
var history = new AndroidInputHistorySampleInfo[storedHistoryCount];
318+
AndroidInputHistorySampleInfo[] history = storedHistoryCount == 0
319+
? [] : new AndroidInputHistorySampleInfo[storedHistoryCount];
312320
NativeInputHistorySample* nativeHistory = (NativeInputHistorySample*)input->HistorySamples;
313321
for (int index = 0; index < storedHistoryCount; index++)
314322
{
@@ -380,9 +388,9 @@ private static AndroidInputPointerInfo[] CopyPointers(
380388
ReadOnlyMemory<float> axes = ReadOnlyMemory<float>.Empty;
381389
if (axisStorage != null)
382390
{
383-
for (int axis = 0; axis < AxisCount; axis++)
384-
axisStorage[index * AxisCount + axis] = pointer->AxisValues[axis];
385-
axes = new ReadOnlyMemory<float>(axisStorage, index * AxisCount, AxisCount);
391+
int offset = index * AxisCount;
392+
new ReadOnlySpan<float>(pointer->AxisValues, AxisCount).CopyTo(axisStorage.AsSpan(offset, AxisCount));
393+
axes = new ReadOnlyMemory<float>(axisStorage, offset, AxisCount);
386394
}
387395

388396
pointers[index] = new AndroidInputPointerInfo(
@@ -419,11 +427,15 @@ private static void EnqueueForImGui(AndroidInputEventInfo input)
419427

420428
private static AndroidInputEventInfo CreateImGuiSnapshot(AndroidInputEventInfo input)
421429
{
422-
ReadOnlySpan<AndroidInputPointerInfo> source = input.Pointers.Span;
423-
var pointers = new AndroidInputPointerInfo[source.Length];
424-
for (int index = 0; index < source.Length; index++)
425-
pointers[index] = source[index] with { AxisValues = ReadOnlyMemory<float>.Empty };
426-
430+
var pointers = input.Pointers;
431+
if (input.FullDataIncluded && !pointers.IsEmpty)
432+
{
433+
var compact = new AndroidInputPointerInfo[pointers.Length];
434+
ReadOnlySpan<AndroidInputPointerInfo> source = pointers.Span;
435+
for (int index = 0; index < source.Length; index++)
436+
compact[index] = source[index] with { AxisValues = ReadOnlyMemory<float>.Empty };
437+
pointers = compact;
438+
}
427439
return input with
428440
{
429441
Pointers = pointers,
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
using ImGuiNET;
2+
using StArray.ModManager.Manager;
3+
using StArray.ModManager.UI;
4+
5+
namespace StArray.ModManager.Android.UI;
6+
7+
internal sealed unsafe class AndroidImGuiStartup
8+
{
9+
private readonly Task<nint> _atlas = Task.Run(BuildAtlas);
10+
private nint _context;
11+
12+
internal bool TryInitializeContext()
13+
{
14+
if (!_atlas.IsCompleted)
15+
return false;
16+
if (_context != 0)
17+
{
18+
ImGui.SetCurrentContext(_context);
19+
return true;
20+
}
21+
22+
if (_atlas.IsCompletedSuccessfully)
23+
{
24+
_context = ImGui.CreateContext(new ImFontAtlasPtr((ImFontAtlas*)_atlas.Result));
25+
}
26+
else
27+
{
28+
Logger.Warn(nameof(AndroidImGuiStartup), $"Using the default font: {_atlas.Exception?.GetBaseException().Message}");
29+
_context = ImGui.CreateContext();
30+
}
31+
ImGui.SetCurrentContext(_context);
32+
var io = ImGui.GetIO();
33+
io.ConfigFlags |= ImGuiConfigFlags.NavEnableKeyboard | ImGuiConfigFlags.DockingEnable;
34+
if (_atlas.IsCompletedSuccessfully)
35+
ImGuiFonts.LogAtlas(io.Fonts);
36+
return true;
37+
}
38+
39+
private static nint BuildAtlas()
40+
{
41+
ImFontAtlas* atlas = ImGuiNative.ImFontAtlas_ImFontAtlas();
42+
try
43+
{
44+
ImGuiFonts.Build(new ImFontAtlasPtr(atlas), prepareRgbaTexture: true);
45+
return (nint)atlas;
46+
}
47+
catch
48+
{
49+
ImGuiNative.ImFontAtlas_destroy(atlas);
50+
throw;
51+
}
52+
}
53+
}

‎StArray.ModManager.Android/UI/ImGuiEGLRender.cs‎

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ public sealed unsafe class ImGuiEGLRenderer : IImGuiRenderer
3636
/// <summary> 静态安装入口(供原生宿主调用) </summary>
3737
public static bool Install() => (s_instance = new ImGuiEGLRenderer()).InstallInstance();
3838

39+
internal static bool Install(AndroidImGuiStartup startup) =>
40+
(s_instance = new ImGuiEGLRenderer { _startup = startup }).InstallInstance();
41+
3942
/// <summary> 静态 OnRender 事件(Install 之前订阅会缓存) </summary>
4043
private static Action? s_pendingOnRender;
4144

@@ -58,6 +61,7 @@ public static event Action OnRender
5861
}
5962

6063
private bool _initialized;
64+
private AndroidImGuiStartup? _startup;
6165
private Action _onRender = () => { };
6266

6367
event Action IImGuiRenderer.OnRender
@@ -74,18 +78,16 @@ event Action IImGuiRenderer.OnRender
7478

7579
private bool InstallInstance()
7680
{
77-
HookHelper.Instance = new DobbyHook();
78-
EglHooks.InstallHooks();
79-
EglHooks.OnEglSwapBuffers = OnSwapBuffers;
80-
81-
82-
81+
_startup ??= new AndroidImGuiStartup();
8382
// 回放 Install 之前缓存的静态事件订阅
8483
if (s_pendingOnRender != null)
8584
{
8685
_onRender += s_pendingOnRender;
8786
s_pendingOnRender = null;
8887
}
88+
HookHelper.Instance = new DobbyHook();
89+
EglHooks.InstallHooks();
90+
EglHooks.OnEglSwapBuffers = OnSwapBuffers;
8991
return true;
9092
}
9193

@@ -111,7 +113,9 @@ public static int OnSwapBuffers(IntPtr display, IntPtr surface)
111113

112114
if (!self._initialized)
113115
{
114-
self.InitImGui(display, surface);
116+
self.InitImGui();
117+
if (!self._initialized)
118+
return EglHooks.HookEglSwapBuffersOriginal(display, surface);
115119
}
116120

117121
// 使用官方 backend 的 NewFrame
@@ -132,7 +136,9 @@ public static int OnSwapBuffers(IntPtr display, IntPtr surface)
132136
StArray.ModManager.Android.Native.AndroidJavaInputBridge.UpdateCaptureState();
133137
// 渲染
134138
ImGui.Render();
135-
ImGuiImplOpenGL3.RenderDrawData((IntPtr)ImGui.GetDrawData().NativePtr);
139+
var drawData = ImGui.GetDrawData();
140+
if (drawData.CmdListsCount != 0)
141+
ImGuiImplOpenGL3.RenderDrawData((IntPtr)drawData.NativePtr);
136142

137143
// 渲染后检查 surface 是否已被废弃
138144
var err = Egl.GetError();
@@ -149,21 +155,12 @@ public static int OnSwapBuffers(IntPtr display, IntPtr surface)
149155
return EglHooks.HookEglSwapBuffersOriginal(display, surface);
150156
}
151157

152-
private void InitImGui(IntPtr display, IntPtr surface)
158+
private void InitImGui()
153159
{
154-
if (_initialized) return;
155-
// 从 EGL surface 获取 ANativeWindow
156-
if (!Egl.QuerySurface(display, surface, Egl.WIDTH, out var width) ||
157-
!Egl.QuerySurface(display, surface, Egl.HEIGHT, out var height))
158-
{
159-
Logger.Error(nameof(ImGuiEGLRenderer), "Failed to query EGL surface for initialization");
160+
if (!_startup!.TryInitializeContext())
160161
return;
161-
}
162-
// 创建 ImGui 上下文 + 加载嵌入式字体 msyh + FA 图标(共享接口)
163-
((IImGuiRenderer)this).InitImGui();
164-
ImGuiInputHandler.IsInitialized = true;
162+
165163
var io = ImGui.GetIO();
166-
io.ConfigFlags |= ImGuiConfigFlags.NavEnableKeyboard;
167164
io.FontGlobalScale = 3.0f;
168165

169166
// 设置样式
@@ -179,6 +176,7 @@ private void InitImGui(IntPtr display, IntPtr surface)
179176
}
180177

181178
ImGuiImplOpenGL3.Init();
179+
ImGuiInputHandler.IsInitialized = true;
182180
ImGuiInputHandler.InstallInputHooks();
183181
_initialized = true;
184182
}

‎StArray.ModManager/Behaviours/BehaviourManager.cs‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public static class BehaviourManager
1616
private static readonly List<GameBehaviour> _pendingAdd = new();
1717
private static readonly List<GameBehaviour> _pendingRemove = new();
1818
private static readonly object _lock = new();
19+
private static GameBehaviour[] _snapshot = [];
1920

2021
/// <summary>当前活跃的行为列表(只读快照)</summary>
2122
public static IReadOnlyList<GameBehaviour> Behaviours
@@ -116,11 +117,6 @@ internal static void SafeDisable(GameBehaviour b)
116117
catch (Exception ex) { LogFault(b, nameof(GameBehaviour.OnDisable), ex); }
117118
}
118119

119-
private static GameBehaviour[] Snapshot()
120-
{
121-
lock (_lock) return _behaviours.ToArray();
122-
}
123-
124120
// ── 内部驱动(由 ModManagerUI 每帧调用) ──
125121

126122
/// <summary>处理增删队列,派发 OnAwake/OnEnable 与 OnDisable/OnStop,在 Update 之前调用。</summary>
@@ -142,6 +138,7 @@ internal static void ProcessPending()
142138
foreach (var b in toRemove)
143139
_behaviours.Remove(b);
144140
_behaviours.AddRange(toAdd);
141+
Volatile.Write(ref _snapshot, _behaviours.ToArray());
145142
}
146143

147144
foreach (var b in toRemove)
@@ -169,7 +166,7 @@ internal static void ProcessPending()
169166
/// <summary>按 Unity 的阶段顺序派发 OnStart → OnUpdate → OnLateUpdate。</summary>
170167
internal static void Update(float delta)
171168
{
172-
var snapshot = Snapshot();
169+
var snapshot = Volatile.Read(ref _snapshot);
173170

174171
// Unity 会先跑完所有 Start,再进入 Update
175172
foreach (var b in snapshot)
@@ -198,7 +195,7 @@ internal static void Update(float delta)
198195
/// <summary>对所有行为调用 OnGUI(ImGui 窗口渲染之后)。</summary>
199196
internal static void GUI(ImDrawListPtr drawList)
200197
{
201-
foreach (var b in Snapshot())
198+
foreach (var b in Volatile.Read(ref _snapshot))
202199
{
203200
if (b.IsDestroyed || !b.EnabledRaw || !b.Started) continue;
204201
try { b.OnGUI(drawList); }

‎StArray.ModManager/Manager/ModEntry.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ public class ModEntry
2828
/// <summary>入口 DLL 或可执行文件路径</summary>
2929
public string? EntryPoint { get; set; }
3030

31+
internal (string Name, Guid ModuleId)? DiscoveredPlugin { get; init; }
32+
3133
/// <summary>是否已启用</summary>
3234
public bool IsEnabled { get; set; }
3335

0 commit comments

Comments
 (0)