using System.Collections.Concurrent; using System.Text.Json; using System.Text.Json.Nodes; using System.Runtime.InteropServices; using XFEWarframe.Client; using XFEWarframe.Client.Runtime; using static XFEWarframe.Bridge.GameTestLua; namespace XFEWarframe.Bridge; /// Builds transient native UpgradeInfo cards with the original Flash renderer. Never changes inventory or opens the MOD screen. internal static class NativeCardCache { private const string Root = "XFEOriginalCardRender", Clip = "XFENativeCard"; private sealed record Wanted(string Type, string Fingerprint); private sealed record Region(int Left, int Top, int Width, int Height, float MovieWidth, float MovieHeight); private sealed record ActiveCard(string Key, Region Region); private sealed record Binding(bool Available, string Reason, string Message); private static readonly ConcurrentDictionary wanted = new(); private static readonly ConcurrentDictionary writing = new(); private static readonly ConcurrentDictionary failures = new(); private static readonly object queueGate = new(); private static string language = "zh", build = ""; private static Action log = _ => { }; private static Binding binding = new(false, "not-initialized", "原生卡面渲染组件尚未初始化。"); private static long nextUpdate, readyAt; private static int completed, generation, diagnosticSamples; // Only the engine thread touches the Flash movie and these request fields. private static List? activeCards; private static Task? capture; private static GraphicsFrameCapture.Frame? black; private static int activeGeneration; private static bool diagnostics; private static bool ownsMovie; private static long createdAt; private static nint exclusiveMovie; internal static bool Available => Volatile.Read(ref binding).Available; internal static NativeCardCacheStatus Status() { var state = Volatile.Read(ref binding); var pending = wanted.Count; var message = !state.Available ? state.Message : failures.Count > 0 ? "部分原版卡面渲染失败:" + failures.FirstOrDefault().Value : pending > 0 || !writing.IsEmpty ? $"正在自动渲染并缓存原版卡面,剩余 {pending} 张。无需打开游戏 MOD 页面。" : "原版卡面已缓存,可以离线显示。"; return new(state.Available, pending, writing.Count, language, build, "CardUtilitiesRedux/Direct3D11", message, state.Available && failures.Count > 0 ? "card-capture-failed" : state.Reason, completed, failures.Count); } internal static void Prepare(ClientConfiguration config, List hooks, Action logger) { log = logger; build = config.BuildLabel; language = config.Language; diagnostics = config.EnableGameTestControl; if (!GameAbi.Current.CardRenderingAvailable) { Volatile.Write(ref binding, new(false, "compatible-binding-required", "当前游戏版本没有已验证的原版卡面渲染绑定。")); return; } if (config.DirectX12) { Volatile.Write(ref binding, new(false, "direct3d11-required", "本次游戏使用 DirectX 12;原版卡面渲染需要在下次启动时使用 DirectX 11。")); return; } try { GraphicsFrameCapture.Prepare(hooks); PrepareExclusiveDraw(hooks); Volatile.Write(ref binding, new(true, "automatic-native-render", "")); } catch (Exception ex) { Volatile.Write(ref binding, new(false, "graphics-binding-failed", "原版卡面图形绑定失败:" + ex.Message)); log(ex.Message); } } internal static Task Dispatch(string operation, byte[] bytes, CancellationToken cancellation) { cancellation.ThrowIfCancellationRequested(); if (operation == "POST cards") { if (!Available) throw new InvalidOperationException(Status().Message); var body = JsonNode.Parse(bytes) as JsonObject ?? throw new InvalidDataException("Invalid card request."); var refreshExisting = body["refreshExisting"]?.GetValue() ?? false; if (body["language"]?.GetValue() != language) throw new InvalidOperationException("桌面语言与游戏语言不一致,请使用同一种语言后缓存卡面。"); var cards = body["cards"] as JsonArray ?? throw new InvalidDataException("Missing card list."); if (cards.Count is < 1 or > 200) throw new InvalidDataException("A card cache batch must contain 1 to 200 entries."); var entries = new Dictionary(); foreach (var card in cards) { var type = card?["type"]?.GetValue() ?? ""; var fp = card?["fingerprint"]?.GetValue() ?? ""; if (!type.StartsWith("/Lotus/", StringComparison.Ordinal) || type.Length > 240 || type.Contains("..", StringComparison.Ordinal) || type.Any(c => char.IsControl(c) || c is '\\' or '?' or '#') || fp.Length > NativeCardCacheRequest.MaximumFingerprintLength || fp.Contains('\0') || JsonNode.Parse(fp) is not JsonObject) throw new InvalidDataException("Invalid original card identity."); entries[VisualAssetCache.Key("card-compact", type, fp, language, build)] = new(type, fp); } lock (queueGate) { var missing = entries.Where(x => (refreshExisting || VisualAssetCache.Find(x.Key) is null) && !writing.ContainsKey(x.Key)).ToArray(); if (wanted.Count + missing.Count(x => !wanted.ContainsKey(x.Key)) > 4096) throw new InvalidOperationException("卡面缓存队列已满,请先完成当前批次。"); foreach (var item in missing) { failures.TryRemove(item.Key, out _); wanted.TryAdd(item.Key, item.Value); } } } else if (operation == "POST cancel") { lock (queueGate) { wanted.Clear(); Interlocked.Increment(ref generation); } } else if (operation != "GET cards") throw new InvalidDataException("Unknown visual cache operation."); return Task.FromResult(JsonSerializer.Serialize(Status(), VisualCacheJson.Default.NativeCardCacheStatus)); } internal static void Update() { if (!Available || (!ownsMovie && wanted.IsEmpty) || Environment.TickCount64 < nextUpdate) return; nextUpdate = Environment.TickCount64 + 16; try { using var lua = new Scope(); var globals = lua.Global("_T"); var root = lua.Field(globals, Root); if (activeCards is not null) { if (activeGeneration != Volatile.Read(ref generation)) { Clear(lua, globals, root); return; } if (Environment.TickCount64 < readyAt) return; capture ??= GraphicsFrameCapture.ReadAsync(CancellationToken.None); if (!capture.IsCompleted) return; var frame = capture.GetAwaiter().GetResult(); capture = null; if (black is null) { black = frame; Fill(lua, lua.Field(root, "movie"), 0xffffff); readyAt = Environment.TickCount64 + 120; return; } var batch = activeCards; var dark = black; var ticket = activeGeneration; activeCards = null; black = null; // One pair of native frames contains the whole batch. Each card's // PNG is encoded/saved independently on workers, never the UI thread. foreach (var card in batch) { writing.TryAdd(card.Key, 0); wanted.TryRemove(card.Key, out _); _ = Task.Run(() => SaveAsync(card.Key, card.Region, dark, frame, ticket)); } log($"Original card batch drawn: {batch.Count} cards, two native frames."); return; } if (wanted.IsEmpty) { if (lua.Kind(root) == 7) Clear(lua, globals, root); return; } if (writing.Count >= 20) return; // Bound memory while the previous batch is encoded. if (lua.Kind(root) != 7) { root = lua.Table(0, 8); lua.Set(globals, Root, root); var module = lua.Require("Lotus.Interface.CardUtilitiesRedux"); lua.Set(root, "module", module); var flash = lua.Field(lua.Require("EE.Interface.Utilities"), "0x5D5FD020", false); lua.Set(root, "flash", flash); var movieType = lua.Load("/Lotus/Interface/DialogWithCards.swf"); lua.Set(root, "type", movieType); var movie = lua.Method(lua.Global("gFlashMgr"), "0x297A9947", movieType); lua.Set(root, "movie", movie); ownsMovie = true; createdAt = Environment.TickCount64; Volatile.Write(ref exclusiveMovie, lua.Object(movie)); lua.Method(movie, "SetIgnoreInput", true); lua.Method(movie, "SetDrawAfterPostFX", true); lua.Method(movie, "SetDrawOverCinematics", true); lua.Method(movie, "SetVisible", true); readyAt = Environment.TickCount64 + 250; log("Original card renderer created an owned native graphics movie; no MOD screen opened."); return; } if (Environment.TickCount64 < readyAt) return; var renderMovie = lua.Field(root, "movie"); var flashFunction = lua.Field(root, "flash"); if (!lua.Boolean(lua.Field(root, "ready"))) { if (!lua.Boolean(lua.Method(renderMovie, "0x1DD8A236", "Card1.Card"))) { if (Environment.TickCount64 - createdAt > 10000) throw new TimeoutException("The native card template did not load."); return; } var stack = lua.Count; for (var i = 0; i < 20; i++) { lua.Call(flashFunction, renderMovie, "Card1.duplicateMovieClip", Clip + i, 10001 + i); lua.Rewind(stack); } lua.Set(root, "ready", true); } // These are stock dialog decorations, not card artwork. Only our // owned movie is changed; normal game dialogs retain their layout. foreach (var decoration in new[] { "LinesTop", "LinesBottom", "OmegaDecorations", "TopInfo", "Buttons", "TopCenterIcon", "ContentBg" }) Set(lua, renderMovie, decoration, "_visible", false); var mw = lua.Number(lua.Method(renderMovie, "GetMovieWidth")); var mh = lua.Number(lua.Method(renderMovie, "GetMovieHeight")); if (mw < 800 || mh < 450) throw new InvalidDataException("Native movie size is unavailable."); var columns = Math.Min(5, (int)(mw / 276)); var rows = Math.Min(4, (int)(mh / 184)); var items = wanted.Take(columns * rows).ToArray(); if (items.Length == 0) return; activeCards = []; activeGeneration = Volatile.Read(ref generation); var moduleRef = lua.Field(root, "module"); var environment = lua.Call(lua.Global("getfenv"), lua.Field(moduleRef, "CardFromArtifact")); var previousMovie = lua.Field(environment, "mMovie"); try { lua.Set(environment, "mMovie", renderMovie); Fill(lua, renderMovie, 0); Set(lua, renderMovie, "_root", "_alpha", 100); Set(lua, renderMovie, "_root", "_visible", true); var entries = lua.Table(20); lua.Set(root, "entries", entries); var stack = lua.Count; for (var i = 0; i < 20; i++) { Set(lua, renderMovie, Clip + i, "_visible", false); lua.Rewind(stack); } for (var i = 0; i < items.Length; i++) { var item = items[i]; var clip = Clip + i; try { var identity = new NativeCardIdentity(item.Value.Type, item.Value.Fingerprint).ToGame(); var upgrade = lua.Call(lua.Field(lua.Global("Lotus_Game"), "UpgradeInfo", false)); var set = lua.Field(lua.Call(lua.Global("getmetatable"), upgrade), "__newindex"); lua.Call(set, upgrade, "mItemType", lua.Load(identity.Type)); lua.Call(set, upgrade, "mUpgradeFingerprint", lua.Fingerprint(identity.Fingerprint)); lua.Call(set, upgrade, "mItemCount", 1); var card = lua.Call(lua.Field(moduleRef, "CardFromArtifact"), upgrade); if (lua.Kind(card) != 7 || string.IsNullOrWhiteSpace(lua.Text(lua.Field(card, "mName")))) throw new InvalidDataException("The native card could not be built."); var entry = lua.Table(0, 4); lua.Set(entry, "mMovie", renderMovie); lua.Set(entry, "mClipName", clip); lua.Set(entry, "Card", card); lua.Set(entries, i + 1, entry); var left = (int)((mw - columns * 276) / 2 + (i % columns) * 276); var top = (int)((mh - rows * 184) / 2 + (i / columns) * 184); Set(lua, renderMovie, clip, "_x", left + 138); Set(lua, renderMovie, clip, "_y", top + 76); Set(lua, renderMovie, clip, "_xscale", 100); Set(lua, renderMovie, clip, "_yscale", 100); Set(lua, renderMovie, clip, "_alpha", 100); Set(lua, renderMovie, clip, "_visible", true); lua.Call(lua.Field(moduleRef, "DrawCard"), entry, false, card, true); // Imported Rivens may contain dozens of repeated affixes. // Retain their native generated name, but bound this text // field so it cannot paint over another card in the batch. var nameHeight = lua.Number(lua.Field(card, "NameHeight")); if (nameHeight > 52) { var scale = 100 * 52 / nameHeight; Set(lua, renderMovie, clip + ".Card.Name", "_xscale", scale); Set(lua, renderMovie, clip + ".Card.Name", "_yscale", scale); lua.Set(card, "NameHeight", 52); } else { Set(lua, renderMovie, clip + ".Card.Name", "_xscale", 100); Set(lua, renderMovie, clip + ".Card.Name", "_yscale", 100); } // Material set 2 is the original screen-space/no-depth-test set. // Set 1 belongs to diegetic cards and can be occluded by the avatar. lua.Call(lua.Field(moduleRef, "ZoomCard"), entry, clip + ".Card", false, 0, null, null, card, 2, 1); Set(lua, renderMovie, clip + ".Card", "_alpha", 100); // _height includes invisible expanded contents (512); use the compact // original frame plus its edge/shadow, in native movie coordinates. activeCards.Add(new(item.Key, new(left, top, 276, 184, mw, mh))); } catch (Exception ex) { failures[item.Key] = ex.Message; wanted.TryRemove(item.Key, out _); Set(lua, renderMovie, clip, "_visible", false); log("Original card build failed: " + item.Value.Type + ": " + ex.Message); } finally { lua.Rewind(stack); } } readyAt = Environment.TickCount64 + 700; if (activeCards.Count == 0) activeCards = null; } finally { lua.Set(environment, "mMovie", previousMovie); } } catch (Exception ex) { var hadBatch = activeCards is not null; if (activeCards is { } batch) { foreach (var card in batch) { failures[card.Key] = ex.Message; wanted.TryRemove(card.Key, out _); } } // An error must not leave our opaque capture movie over normal play. try { using var cleanup = new Scope(); var globals = cleanup.Global("_T"); Clear(cleanup, globals, cleanup.Field(globals, Root)); } catch (Exception cleanupError) { log("Original card render cleanup failed: " + cleanupError.Message); } if (!hadBatch) Volatile.Write(ref binding, new(false, "native-render-failed", "原版卡面渲染失败:" + ex.Message)); log("Original card render failed: " + ex.Message); nextUpdate = Environment.TickCount64 + 1000; } } private static void Set(Scope lua, Ref movie, string clip, string property, object value) => lua.Method(movie, "SetVariable", clip, property, value); private static void Fill(Scope lua, Ref movie, int color) { // Native Flash has no ActionScript drawing API. Its background alpha is // expressed as 0..1 and is independent of the movie/clip's 0..100 alpha. lua.Method(movie, "SetBackgroundColor", color); lua.Method(movie, "SetBackgroundAlpha", 1); } private static void Clear(Scope lua, Ref globals, Ref root) { try { if (lua.Kind(root) == 7) { var movie = lua.Field(root, "movie"); try { if (lua.Object(movie) != 0) { lua.Method(movie, "SetVisible", false); lua.Method(movie, "Close"); } } finally { lua.Set(globals, Root, null); } } } finally { activeCards = null; capture = null; black = null; ownsMovie = false; Volatile.Write(ref exclusiveMovie, 0); } } private static unsafe void PrepareExclusiveDraw(List hooks) { var image = Native.GetModuleHandle(null); GameAbi.Check(image, 0x11E7630, "4885D20F846D050000535556574154"); var address = image + GameAbi.Rva(0x11E7630); hooks.Add(NativeHook.FilterSecondArgument(address, (nint)(delegate* unmanaged)&AllowMovie)); } [UnmanagedCallersOnly] private static int AllowMovie(nint manager, nint movie) { var own = Volatile.Read(ref exclusiveMovie); return own == 0 || movie == own ? 1 : 0; } private static async Task SaveAsync(string key, Region region, GraphicsFrameCapture.Frame dark, GraphicsFrameCapture.Frame light, int ticket) { try { if (ticket != Volatile.Read(ref generation)) return; if (diagnostics && Interlocked.Increment(ref diagnosticSamples) == 1) { var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEWarframe", "Diagnostics", "CardRender"); Directory.CreateDirectory(directory); await File.WriteAllBytesAsync(Path.Combine(directory, "dark.png"), GraphicsFrameCapture.Png(dark, 0, 0, dark.Width, dark.Height)).ConfigureAwait(false); await File.WriteAllBytesAsync(Path.Combine(directory, "light.png"), GraphicsFrameCapture.Png(light, 0, 0, light.Width, light.Height)).ConfigureAwait(false); } var png = GraphicsFrameCapture.CardPng(dark, light, region.Left, region.Top, region.Width, region.Height, region.MovieWidth, region.MovieHeight); if (ticket != Volatile.Read(ref generation)) return; await VisualAssetCache.StoreAsync(key, png).ConfigureAwait(false); failures.TryRemove(key, out _); Interlocked.Increment(ref completed); } catch (Exception ex) { failures[key] = ex.Message; log("Original card image was not cached: " + ex.Message); } finally { writing.TryRemove(key, out _); } } }