diff --git a/README.md b/README.md index e32afdf..080df78 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,16 @@ WorldLink maimai DX Online C2C Multiplayer Mod > [!WARNING] > This mod is in public testing, please report any bugs you find. +## Experimental four-machine client (draft) + +The existing [mod](mod/README.md) now includes the experimental four-machine, +one-player-per-machine client. It includes recruitment guards, +live scores and preparation information. This is a review draft, pinned to one +game assembly, with incomplete four-real-machine validation and known shutdown +issues. See [integration status](mod/docs/UPSTREAM_REVIEW.md) before use. +Shared types and configuration parsing remain in the original project; the server +and frontend are unchanged. + ## Setting Up WorldLink ### On PC & Controller diff --git a/mod/.gitattributes b/mod/.gitattributes new file mode 100644 index 0000000..e9331a4 --- /dev/null +++ b/mod/.gitattributes @@ -0,0 +1,5 @@ +* text=auto +*.cs text eol=lf +*.md text eol=lf +*.ps1 text eol=crlf +*.toml text eol=lf diff --git a/mod/.gitignore b/mod/.gitignore index 9d77ad4..5a94888 100644 --- a/mod/.gitignore +++ b/mod/.gitignore @@ -1,382 +1,30 @@ - -# Created by https://www.toptal.com/developers/gitignore/api/git,visualstudio -# Edit at https://www.toptal.com/developers/gitignore?templates=git,visualstudio - -### Git ### -# Created by git for backups. To disable backups in Git: -# $ git config --global mergetool.keepBackup false -*.orig - -# Created by git when using merge tools for conflicts -*.BACKUP.* -*.BASE.* -*.LOCAL.* -*.REMOTE.* -*_BACKUP_*.txt -*_BASE_*.txt -*_LOCAL_*.txt -*_REMOTE_*.txt - -### VisualStudio ### -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Mono auto generated files -mono_crash.* - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ -[Ll]ogs/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUnit -*.VisualState.xml -TestResult.xml -nunit-*.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch +# Local game references and build tools must never be published. +refs/ +testrefs/ +.tools/ +bin/ +obj/ +dist/ +*.dll +*.exe *.pdb -*.ipdb -*.pgc -*.pgd +*.zip +*.nupkg *.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj *.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Coverlet is a free, cross platform Code Coverage Tool -coverage*[.json, .xml, .info] - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# NuGet Symbol Packages -*.snupkg -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx -*.appxbundle -*.appxupload - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!?*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ - -# End of https://www.toptal.com/developers/gitignore/api/git,visualstudio - -Output -.idea -Assembly-CSharp.dll -Assembly-CSharp-firstpass.dll -AMDaemon.NET.dll -packages -.DS_Store -._* -*.g.cs -tools \ No newline at end of file +*.user +.vs/ +.idea/ +.env* +WorldLink.toml +!WorldLink.toml +UserData/ +Errorlog/ +ModBackups/ +aime.txt +segatools.ini +enabled.flag +status.json + +Libs/ +BuildInfo.g.cs diff --git a/mod/CHANGELOG.md b/mod/CHANGELOG.md new file mode 100644 index 0000000..9320728 --- /dev/null +++ b/mod/CHANGELOG.md @@ -0,0 +1,33 @@ +# 变更记录 + +## 2.1.0-fourplayer.14 — 审查修订 + +- 整合进原有 mod 工程,复用 TomletShim、共享消息类型、日志和扩展方法。 +- 成绩栏复用采样对象,未变化的数据复用快照,避免重复格式化与排序属性写入。 +- 增加 10,000 次未变化更新的快照复用回归检查;289 项检查通过。 +- 未完成实机帧率测量,保留既有实机验证限制。 + +## 2.1.0-fourplayer.13 — 预发布 + +- 等待曲库加载和谱面目录建立后再解析招募曲目。 +- 校验歌曲、难度、谱面和一致的歌曲标识。 +- 过滤不可用房间;构建联机列表后提交,保留空房间等待项。 +- 显示曲目与房间映射保持一致,房间变化检测包含机器身份和顺序。 +- Freedom/Course 模式忽略招募和联机准备页。 +- 添加带本地歌曲/谱面数量的招募诊断。 +- 自动检查共 288 项通过;报告的白屏和 Freedom 闪退尚待实机回归。 + +## 2.1.0-fourplayer.12 + +- 大厅 HTTP 工作线程只处理文本,房间解析和变更转移到游戏线程。 +- 修正房间过期删除索引、空条目和客户端释放后的迟到更新。 +- 完成一台真实游戏加三个轻量客户端的准备、游玩、结算验证。 + +## 更早的四机修改 + +- 四机单人协议、成员与成绩映射、名次计算和传输隔离。 +- 实时两行成绩显示、50% 透明度、轨道遮挡及文字材质调整。 +- 准备页玩家难度、状态、历史成绩和资源头像。 +- 缺失 NPC 对手曲目时的崩溃防护,以及默认关闭的本地测试控制。 + +本记录整理自开发过程,不表示各中间版本均完成全面兼容性验证。 diff --git a/mod/CONTRIBUTING.md b/mod/CONTRIBUTING.md new file mode 100644 index 0000000..2443286 --- /dev/null +++ b/mod/CONTRIBUTING.md @@ -0,0 +1,7 @@ +# 贡献说明 + +提交问题时请写明插件版本、游戏程序集版本、加载器和其他插件版本、游玩模式、是否已加入房间、复现步骤及实际/预期结果。附上当次 Latest.log 的相关片段与异常调用栈,并先移除个人和机器标识。不要上传卡号、存档、密钥、整包游戏或曲包。 + +代码提交应说明变更行为、测试方法和剩余限制。涉及协议、房间列表、生命周期或显示模型时运行相关托管测试;涉及渲染和完整流程时同时说明实机验证环境。避免将自动测试通过描述为四台游戏均已验证。 + +游戏和第三方依赖放在被忽略的 refs/ 中,不纳入提交。安装包保持仅有 DLL、配置模板和许可证;维护者可在 GitHub Release 的预发布说明中提供使用方法、校验值和限制。 diff --git a/mod/Core.cs b/mod/Core.cs index 66a923f..c766ce9 100644 --- a/mod/Core.cs +++ b/mod/Core.cs @@ -1,27 +1,86 @@ -using MelonLoader; +using System.IO; +using System; +using System.Linq; +using System.Reflection; +using HarmonyLib; +using MelonLoader; namespace WorldLink; public class Config { - public string LobbyUrl { get; set; } - public string RelayUrl { get; set; } - public bool Debug { get; set; } + public string LobbyUrl { get; set; } + + public string RelayUrl { get; set; } + + public bool Debug { get; set; } } + public class Core : MelonMod { - public static Config Config; + public static Config Config; + private HarmonyLib.Harmony patches; - public override void OnInitializeMelon() - { - // Load config - LoggerInstance.Msg("Loading config..."); - Config = TomletShim.To(File.ReadAllText("WorldLink.toml")); + public override void OnInitializeMelon() + { + base.LoggerInstance.Msg("Loading config..."); + Config = TomletShim.To(File.ReadAllText("WorldLink.toml")); + base.LoggerInstance.Msg("Installing four-machine single-player patches..."); + patches = new HarmonyLib.Harmony("nyanlink.fourplayer.client.v1"); + try + { + FourMachineProtocol.Initialize(); + GhostSafetyPatch.Apply(patches); + FourPlayerMapping.Apply(patches); + LiveScoreOverlay.Apply(patches); + ReadyInfoProtocol.Apply(patches); + ReadyInfoOverlay.Apply(patches); + LocalTestControl.Apply(patches); + LobbyRecruitSync.Apply(patches); + RecruitSongSafety.Apply(patches); + Futari.OnBeforePatch(); + patches.PatchAll(typeof(Futari)); + VerifyLegacyHooks(); + base.LoggerInstance.Msg("NyanLink 4P initialized. All machines must use this plugin version and enter on 1P."); + } + catch + { + Futari.stopping = true; + LobbyRecruitSync.Shutdown(); + patches.UnpatchSelf(); + FourMachineProtocol.Rollback(); + throw; + } + } - LoggerInstance.Msg("Patching..."); - Futari.OnBeforePatch(); - HarmonyLib.Harmony.CreateAndPatchAll(typeof(Futari)); + public override void OnDeinitializeMelon() + { + Futari.stopping = true; + LobbyRecruitSync.Shutdown(); + LocalTestControl.Shutdown(); + ReadyInfoOverlay.Reset(); + LiveScoreOverlay.Reset(); + base.OnDeinitializeMelon(); + } - LoggerInstance.Msg("Initialized."); - } -} \ No newline at end of file + public override void OnUpdate() + { + LocalTestControl.Update(); + } + + private void VerifyLegacyHooks() + { + var installed = patches.GetPatchedMethods() + .Select(HarmonyLib.Harmony.GetPatchInfo) + .Where(info => info != null) + .SelectMany(info => info.Prefixes.Concat(info.Postfixes)) + .Where(patch => patch.owner == patches.Id) + .Select(patch => patch.PatchMethod).ToArray(); + var expected = typeof(Futari).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + .Where(method => method.IsDefined(typeof(HarmonyPrefix), false) || method.IsDefined(typeof(HarmonyPostfix), false)).ToArray(); + var missing = expected.Where(method => !installed.Contains(method)).Select(method => method.Name).ToArray(); + if (missing.Length != 0) + throw new InvalidOperationException("NyanLink hooks were not installed: " + string.Join(", ", missing)); + base.LoggerInstance.Msg("Verified " + expected.Length + " original NyanLink hooks, including status display and relay sockets."); + } +} diff --git a/mod/NOTICE.md b/mod/NOTICE.md new file mode 100644 index 0000000..752ffce --- /dev/null +++ b/mod/NOTICE.md @@ -0,0 +1,12 @@ +# 来源与修改说明 + +- 上游项目:[MuNET-OSS/NyanLink](https://github.com/MuNET-OSS/NyanLink)。 +- 上游 WorldLink:[MewoLab/worldlinkd](https://github.com/MewoLab/worldlinkd)。 +- 原始版权:Copyright (c) 2025 Azalea。 +- 本仓库保留上游 MIT 许可证全文,核对来源为提交 `fdce68e284a519041f271c248e146a2a7aa86555` 的 LICENSE(blob `3c3e16eb6c271e25147f691105cd6455ed0f27c2`)。 + +四机功能最初基于用户提供的插件恢复和修改;本分支保留上游 Git 历史,并将这些修改整合到原有 mod 工程。上述提交记录许可证来源,不代表当前源码与其逐字一致。插件保留 Azalea、Clansty、Japerz 的原有署名。本项目与上游无官方关联。 + +修改包含四机单人联机、协议容量与映射、成绩和准备页显示、崩溃防护、招募线程与曲目校验、模式隔离及默认关闭的本地测试控制。当前已知问题在 docs/KNOWN_ISSUES.md 中公开记录。 + +MIT 许可证针对本项目相应代码,不替代游戏本体、曲目、素材、加载器或其他依赖各自适用的授权。分发本插件或其重要部分时保留 LICENSE。 diff --git a/mod/Properties/AssemblyInfo.cs b/mod/Properties/AssemblyInfo.cs index a63c6c1..8e86540 100644 --- a/mod/Properties/AssemblyInfo.cs +++ b/mod/Properties/AssemblyInfo.cs @@ -1,11 +1,11 @@ -using System.Reflection; +using System.Reflection; using MelonLoader; [assembly: AssemblyTitle(WorldLink.BuildInfo.Name)] [assembly: AssemblyProduct(WorldLink.BuildInfo.Name)] [assembly: AssemblyCopyright(WorldLink.BuildInfo.Author)] [assembly: AssemblyVersion(WorldLink.BuildInfo.Version)] -[assembly: AssemblyFileVersion(WorldLink.BuildInfo.GitVersion)] +[assembly: AssemblyFileVersion(WorldLink.BuildInfo.Version)] [assembly: MelonInfo(typeof(WorldLink.Core), WorldLink.BuildInfo.Name, WorldLink.BuildInfo.GitVersion, WorldLink.BuildInfo.Author)] [assembly: MelonColor(0, 172, 181, 250)] [assembly: HarmonyDontPatchAll] diff --git a/mod/README.md b/mod/README.md new file mode 100644 index 0000000..6911325 --- /dev/null +++ b/mod/README.md @@ -0,0 +1,112 @@ +# NyanLink experimental four-machine client + +基于 [MuNET-OSS/NyanLink](https://github.com/MuNET-OSS/NyanLink) / WorldLink 的非官方四机联机修改版。目标是**四台电脑,每台仅一位玩家在 1P 登录**。 + +当前版本:`2.1.0-fourplayer.14`(预发布)。插件文件名仍为 `WorldLink.dll`,游戏内日志名称为 `NyanLink`。 + +> 此版本含针对招募白屏和 Freedom 模式的防护改动,但这些问题尚未在报告问题的电脑上完成回归确认。它不是“所有闪退均已修复”的稳定版。退出阶段继续重连的问题仍存在,详见[已知问题](docs/KNOWN_ISSUES.md)。 + +## 功能 + +- 四台独立机器、每台 1P 的成员信息、同步开局、成绩传输和结算名次。 +- 游玩时在中央偏下显示实时成绩和进度条:上排 1P/2P,下排 3P/4P,无黑色底板,文字与进度条透明度为 50%。这里的编号是显示槽位,不表示一台电脑登录两个玩家。 +- 准备阶段显示昵称、难度、准备状态、当前歌曲/难度的历史最佳成绩,以及按 IconID 加载的本地头像。缺少历史数据与未游玩分别显示。 +- 招募列表在游戏线程处理;修正空条目、过期删除索引和客户端释放后的迟到响应问题。 +- `.13` 校验招募歌曲、谱面和难度;先构建联机列表再更新显示;Freedom/Course 模式忽略联机招募。 + +## 适用环境 + +| 项目 | 当前适配范围 | +| --- | --- | +| 系统 | Windows x64 | +| 游戏 | 开发时使用的 SDEZ 1.70 构建,Unity 2018.4.7f1 | +| 加载器 | MelonLoader 0.6.4 | +| 游戏程序集 MVID | `24f6a64f-2eeb-42d4-b6f9-ae17d637d569` | +| 联机方式 | 普通模式,四台机器,每台只登录 1P | + +程序会检查适配的游戏程序集。仅版本名称相同不能保证程序集、曲包和其他插件兼容。所有玩家需要相同插件版本,并拥有联机歌曲及所选难度对应的资源。 + +客户端安装包不提供游戏本体、曲包、Unity/MelonLoader 等第三方 DLL、账号存档或卡号,也不包含联机服务端。仓库保留上游服务端源码;连接房间需要可用且兼容的大厅与中继服务。 + +## 安装与更新 + +1. **完全退出 `Sinmai.exe`**。更新时不要覆盖仍在运行进程中映射的 DLL。 +2. 把旧 `WorldLink.dll` 与现有 `WorldLink.toml` 备份到 `Mods` 以外的目录。 +3. 此上游审查草稿尚未发布安装包,请进入 `mod/` 并按[构建说明](docs/BUILDING.md)自行构建;GitHub 的 “Source code” ZIP 是源码,不能直接安装。 +4. 将文件放置为: + +```text +Package/ +├── Sinmai.exe +├── WorldLink.toml +└── Mods/ + └── WorldLink.dll +``` + +5. 升级时保留自己已配置的 `WorldLink.toml`。首次安装可从 `config/WorldLink.toml` 复制模板。 +6. 启动游戏,在 `Package/MelonLoader/Latest.log` 中确认显示 `NyanLink v2.1.0-fourplayer.14` 且初始化成功。 + +分发包只包含 DLL、配置模板和 MIT 许可证。无需安装开发测试工具;此插件不会代替你配置读卡器。保留现有实体刷卡设置即可。 + +## 配置 + +配置在 `Package/WorldLink.toml`,与 `Sinmai.exe` 同级。 + +```toml +LobbyUrl = "https://link.mumur.net:20100" +Debug = false +``` + +| 字段 | 说明 | +| --- | --- | +| `LobbyUrl` | 兼容的大厅服务地址。示例是继承的第三方地址;本项目不运营该服务,也不保证其可用性。 | +| `RelayUrl` | 可选,中继地址覆盖项;一般保持未设置,由大厅提供连接信息。 | +| `Debug` | 调试日志开关,日常使用建议 `false`。提交日志前应脱敏。 | + +所有参与机器应连接同一大厅。不要直接复制其他机器的卡号、账号配置或机器身份;重复的联机身份可能导致加入失败。 + +## 四人联机步骤 + +1. 每台电脑只用 1P 登录,进入**普通模式**。 +2. 房主选择所有参与者都有的普通歌曲,创建店内联机招募。 +3. 其他三台电脑在联机分类中选择该房间加入。 +4. 在准备页核对玩家、难度和准备状态;所有人完成准备后开始歌曲。 +5. 游玩中查看实时达成率,结算时核对四人的成绩和名次。 + +Freedom/Course 为本版的独立游玩模式,不提供四机联机。不要使用轻量测试客户端的结果替代四台真实游戏的兼容性验证。 + +## 测试与限制 + +- `.12` 曾完成一台真实游戏 + 三个轻量协议客户端的开局、游玩、结算验证,并验证不同成绩对应 1st–4th;这不是四台真实游戏的完整验证。 +- `.14` 的七组托管自动检查共 **289 项通过**,涵盖协议、传输、成绩模型、准备信息、招募处理及模式隔离。 +- 本仓库整理后的构建与测试脚本会再次验证这些检查;它们不启动 Unity 原生渲染,也不代表已完成 `.13` 的真实四机回归。 +- 已知退出重连错误和白屏/Freedom 回归状态见[已知问题](docs/KNOWN_ISSUES.md)。 + +## 故障排查 + +| 现象 | 检查方式 | +| --- | --- | +| 找不到房间/不能加入 | 核对大厅地址、网络、插件版本、各机 1P 登录状态和机器身份。 | +| 提示招募歌曲不可用 | 对照歌曲 ID、难度和本地资源。`.13` 的 `[NyanLink Recruit]` 会记录 `localSongs` 与 `localNotes`;缺一首歌不等于整个曲库为空。 | +| 收到招募后白屏 | 保留当次日志,注明是否在加入前发生、普通/Freedom 模式、其他插件版本。不要仅凭提示重新安装曲包或清空存档。 | +| 状态栏没有显示 | 查看 DLL 是否实际加载、初始化是否失败、是否误放多个版本。 | +| 头像或历史成绩缺失 | 本地可能没有对应 IconID 资源,或对方没有提供该歌曲/难度历史。历史值不是实时成绩。 | + +日志位置: + +- `Package/MelonLoader/Latest.log` +- `Package/Errorlog/` 中对应时刻的 `.log` 或 `AquaMaiErrorReport_*.zip` + +出错后**先复制日志,再重启**,避免 `Latest.log` 被覆盖。白屏不一定生成崩溃报告。公开提交前删除卡号、账号标识、机器标识、私人地址、令牌及个人昵称等信息。 + +## 开发与贡献 + +见[构建与自动测试](docs/BUILDING.md)、[贡献说明](CONTRIBUTING.md)和[变更记录](CHANGELOG.md)。`WorldLink/` 包含整合后的四机逻辑;`.14` 减少成绩数据未变化时的分配、格式化和重复排序属性写入,尚无实机帧率提升测量。 + +默认关闭的本地测试控制代码见 `WorldLink/LocalTestControl.cs`。只有主动创建 `Package/UserData/WorldLinkControl/enabled.flag` 才启用;普通安装不需要此标记。不要公开卡文件或将测试控制目录共享给不信任的用户。 + +## 来源与许可证 + +采用 [MIT License](../LICENSE),保留 `Copyright (c) 2025 Azalea`。 + +这个实验客户端的源码快照基于用户提供的 WorldLink 插件恢复、修改和整理,现已按审查意见整合进原有 `mod/`,复用原有配置解析、消息类型、日志及扩展方法。仍需继续审查与实机回归。上游为 [NyanLink](https://github.com/MuNET-OSS/NyanLink),其来源包括 [WorldLink](https://github.com/MewoLab/worldlinkd)。提交草稿不代表上游认可或正式发布,详见 [NOTICE](NOTICE.md)及[整合状态](docs/UPSTREAM_REVIEW.md)。游戏和第三方依赖的授权独立适用。 diff --git a/mod/WorldLink/FourMachineProtocol.cs b/mod/WorldLink/FourMachineProtocol.cs new file mode 100644 index 0000000..d3baf43 --- /dev/null +++ b/mod/WorldLink/FourMachineProtocol.cs @@ -0,0 +1,339 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using DB; +using HarmonyLib; +using MAI2.Util; +using Manager; +using Manager.Party.Party; +using PartyLink; + +namespace WorldLink +{ + // Four independent machines, one entered player on each machine's 1P side. + public static class FourMachineProtocol + { + public const int MachineCapacity = 4; + public const int LocalPlayerCapacity = 2; + public const int RoomGroup = 0x4e4c3401; + public const uint WireVersion = 0x4e4c3401; + public const int PacketCapacity = 16384; + private const string HarmonyId = "worldlink.fourmachine.protocol.v1"; + public static readonly Guid SupportedGameModule = new Guid("24f6a64f-2eeb-42d4-b6f9-ae17d637d569"); + private static bool initialized; + private static readonly Dictionary originalCapacities = new Dictionary(); + + public static void Initialize() + { + if (initialized) return; + if (typeof(Host).Module.ModuleVersionId != SupportedGameModule) + throw new NotSupportedException("Four-machine mode requires the game build used to validate this patch."); + var harmony = new HarmonyLib.Harmony(HarmonyId); + try + { + SetCapacity(typeof(PartyLink.Party), "c_maxMecha", MachineCapacity); + foreach (string name in new[] { "c_packetBufferSize", "c_encodeBufferSize", "c_serializeBufferSize", "c_deserializeBufferSize" }) + SetCapacity(typeof(Packet), name, PacketCapacity); + SetCapacity(typeof(SizeDef), "CBufferSize", PacketCapacity); + SetCapacity(typeof(SocketBase), "c_recvBufferSize", PacketCapacity * 2); + foreach (ConstructorInfo constructor in typeof(PartyPlayInfo).GetConstructors()) + harmony.Patch(constructor, postfix: PatchMethod("AfterPartyPlayInfoConstructor")); + Patch(harmony, typeof(PartyPlayInfo), "CopyFrom", "CopyPartyPlayInfo", null); + foreach (ConstructorInfo constructor in typeof(RecruitInfo).GetConstructors()) + harmony.Patch(constructor, postfix: PatchMethod("AfterRecruitConstructor")); + foreach (ConstructorInfo constructor in typeof(RequestJoin).GetConstructors()) + harmony.Patch(constructor, postfix: PatchMethod("AfterRequestJoinConstructor")); + Patch(harmony, typeof(Client), "RecvStartRecruit", "ReceiveStartRecruit", null); + Patch(harmony, typeof(Client), "RecvFinishRecruit", "ReceiveFinishRecruit", null); + Patch(harmony, typeof(Host), "RequestJoin", "BeforeRequestJoin", null); + Patch(harmony, typeof(Member), "RecvMechaInfo", "BeforeUpdateMechaInfo", null); + Patch(harmony, typeof(Host), "SendPartyPlayInfo", "SendPartyPlayInfo", null); + Patch(harmony, typeof(Host), "Enter_FinishRecruit", "RemoveUnjoinedConnections", null); + Patch(harmony, typeof(Host), "Execute_Play", "RemoveUnjoinedConnections", null); + Patch(harmony, typeof(Packet), "getAppRomVersion", "GetWireVersion", null); + Patch(harmony, typeof(Packet), "getAppDataVersion", "GetWireVersion", null); + initialized = true; + } + catch + { + harmony.UnpatchSelf(); + RestoreCapacities(); + throw; + } + } + + // Startup rollback only. It must run before game connection objects are created. + public static void Rollback() + { + if (!initialized) return; + new HarmonyLib.Harmony(HarmonyId).UnpatchSelf(); + RestoreCapacities(); + initialized = false; + } + + private static void SetCapacity(System.Type type, string name, int value) + { + FieldInfo field = AccessTools.Field(type, name); + if (field == null) throw new MissingFieldException(type.FullName, name); + originalCapacities.Add(field, (int)field.GetValue(null)); + field.SetValue(null, value); + if ((int)field.GetValue(null) != value) + throw new InvalidOperationException("Cannot initialize protocol capacity " + type.FullName + "." + name); + } + + private static void RestoreCapacities() + { + foreach (KeyValuePair item in originalCapacities) + item.Key.SetValue(null, item.Value); + originalCapacities.Clear(); + } + + private static HarmonyMethod PatchMethod(string name) + { + return new HarmonyMethod(typeof(FourMachineProtocol).GetMethod(name, + BindingFlags.Static | BindingFlags.NonPublic)); + } + + private static void Patch(HarmonyLib.Harmony harmony, System.Type type, string name, string prefix, string postfix) + { + MethodInfo method = AccessTools.Method(type, name); + if (method == null) throw new MissingMethodException(type.FullName, name); + harmony.Patch(method, prefix == null ? null : PatchMethod(prefix), + postfix == null ? null : PatchMethod(postfix)); + } + + private static bool GetWireVersion(ref uint __result) + { + __result = WireVersion; + return false; + } + + public static bool IsCompatiblePacket(Packet packet) + { + return packet != null && packet.getRomVersion() == WireVersion + && packet.getDataVersion() == WireVersion; + } + + private static void AfterPartyPlayInfoConstructor(PartyPlayInfo __instance, object[] __args) + { + PartyPlayInfo source = __args.Length == 1 ? __args[0] as PartyPlayInfo : null; + MemberPlayInfo[] members = source != null ? source.Member : __instance.Member; + __instance.Member = NormalizeMembers(members); + } + + public static MemberPlayInfo[] NormalizeMembers(MemberPlayInfo[] source) + { + var result = new MemberPlayInfo[MachineCapacity]; + for (int i = 0; i < result.Length; i++) + result[i] = source != null && i < source.Length && source[i] != null + ? new MemberPlayInfo(source[i]) : new MemberPlayInfo(); + return result; + } + + private static bool CopyPartyPlayInfo(PartyPlayInfo __instance, PartyPlayInfo src) + { + if (src == null) throw new ArgumentNullException("src"); + if (ReferenceEquals(__instance, src)) return false; + __instance.Member = NormalizeMembers(src.Member); + for (int i = 0; i < __instance.ChainHistory.Length; i++) + { + __instance.ChainHistory[i].Clear(); + if (src.ChainHistory != null && i < src.ChainHistory.Length && src.ChainHistory[i] != null) + __instance.ChainHistory[i].CopyFrom(src.ChainHistory[i]); + } + __instance.Chain = src.Chain; + __instance.ChainMiss = src.ChainMiss; + __instance.MaxChain = src.MaxChain; + __instance.CalcStatus = src.CalcStatus; + __instance.IsFullChain = src.IsFullChain; + return false; + } + + private static void AfterRecruitConstructor(RecruitInfo __instance, object[] __args) + { + // Copies made while importing lobby records must retain their original protocol marker. + if (__args.Length != 1 || !(__args[0] is RecruitInfo)) __instance.GroupID = RoomGroup; + } + + private static void AfterRequestJoinConstructor(RequestJoin __instance) + { + __instance.GroupID = RoomGroup; + } + + public static bool IsSinglePlayerMachine(MechaInfo info) + { + return info != null && info.IpAddress != 0 && HasTwo(info.Entrys) + && info.Entrys[0] && !info.Entrys[1] + && HasTwo(info.UserIDs) && HasTwo(info.UserNames) && HasTwo(info.IconIDs) + && HasTwo(info.FumenDifs) && HasTwo(info.Rateing) && HasTwo(info.ClassValue) + && HasTwo(info.MaxClassValue) && HasTwo(info.UserType); + } + + private static bool HasTwo(T[] array) + { + return array != null && array.Length == LocalPlayerCapacity; + } + + public static bool CanJoin(RequestJoin request, IEnumerable joined, out string reason) + { + if (request == null || request.GroupID != RoomGroup) + { + reason = "The room requires the NyanLink four-machine protocol."; + return false; + } + if (!IsSinglePlayerMachine(request.MechaInfo)) + { + reason = "Four-machine rooms require exactly one player on 1P and two-element player fields."; + return false; + } + MechaInfo[] members = joined.Where(item => item != null).ToArray(); + if (members.Length >= MachineCapacity) + { + reason = "The four-machine room is full."; + return false; + } + if (members.Any(item => item.IpAddress == request.MechaInfo.IpAddress)) + { + reason = "This machine identity has already joined."; + return false; + } + reason = null; + return true; + } + + private static bool BeforeRequestJoin(RequestJoin info, MemberList ____memberList, + ref string ____message, ref PartyPartyJoinResultID __result) + { + string reason; + if (CanJoin(info, ____memberList.Where(member => member.IsJoin()).Select(member => member.GetMechaInfo()), out reason)) + return true; + ____message = reason; + __result = info != null && info.GroupID == RoomGroup + ? PartyPartyJoinResultID.Full : PartyPartyJoinResultID.DifferentGroup; + return false; + } + + private static bool ReceiveStartRecruit(Packet packet, Recruit ____recruit) + { + StartRecruit message = packet?.getParam(); + RecruitInfo info = message == null ? null : message.RecruitInfo; + var manager = Manager.Party.Party.Party.Get(); + if (info != null && info.GroupID == RoomGroup && IsSinglePlayerMachine(info.MechaInfo) + && manager != null && manager.GetEventMode() == info.EventModeID + && RecruitSongSafety.TryGetSong(info, out _, out _)) + { + info.RecvTime = DateTime.Now; + ____recruit.Add(info); + } + return false; + } + + private static bool ReceiveFinishRecruit(Packet packet, Recruit ____recruit) + { + FinishRecruit message = packet?.getParam(); + RecruitInfo info = message == null ? null : message.RecruitInfo; + if (info != null && info.GroupID == RoomGroup) ____recruit.Remove(info); + return false; + } + + private static bool BeforeUpdateMechaInfo(Member __instance, Packet packet) + { + UpdateMechaInfo message = packet.getParam(); + MechaInfo info = message == null ? null : message.MechaInfo; + if (!IsSinglePlayerMachine(info) || info.IpAddress != __instance.GetMechaInfo().IpAddress) + { + __instance.KickByCancel(); + return false; + } + return true; + } + + private static void RemoveUnjoinedConnections(MemberList ____memberList) + { + // A rejected or half-open connection must not abort the active game. + ____memberList.erase_if(member => !member.IsJoin()); + } + + public static void CalculateRanks(int[] scores, bool[] valid, bool[] trials, byte[] ranks) + { + if (scores == null || valid == null || trials == null || ranks == null + || scores.Length != valid.Length || scores.Length != trials.Length || scores.Length != ranks.Length) + throw new ArgumentException("Rank arrays must have the same length."); + for (int i = 0; i < scores.Length; i++) + { + if (!valid[i]) { ranks[i] = 0; continue; } + int rank = 1; + for (int j = 0; j < scores.Length; j++) + if (valid[j] && !trials[j] && scores[j] > scores[i]) rank++; + ranks[i] = (byte)rank; + } + } + + private static bool SendPartyPlayInfo(Host __instance, bool checkFullChain, MemberList ____memberList, + PartyPlayInfo ____partyPlayInfo, Queue ____chainHistory) + { + Member[] members = ____memberList.Where(member => member.IsJoin()).ToArray(); + // The join gate enforces capacity. Repair a stale oversized list before writing any arrays. + foreach (Member extra in members.Skip(MachineCapacity)) extra.KickByStart(); + members = members.Take(MachineCapacity).ToArray(); + ____partyPlayInfo.Member = NormalizeMembers(null); + var scores = new int[MachineCapacity * LocalPlayerCapacity]; + var valid = new bool[scores.Length]; + var trials = new bool[scores.Length]; + var ranks = new byte[scores.Length]; + int activePlayers = 0; + int fullComboPlayers = 0; + bool anyGameOverOrMiss = false; + for (int i = 0; i < members.Length; i++) + { + Member member = members[i]; + MechaInfo machine = member.GetMechaInfo(); + ClientPlayInfo play = member.GetLastClientPlayInfo(); + if (!IsSinglePlayerMachine(machine) || play == null) + { + member.KickByCancel(); + continue; + } + MemberPlayInfo snapshot = play.GetMemberPlayInfo(); + snapshot.IsActive = member.IsActive(); + snapshot.IpAddress = machine.IpAddress; + ____partyPlayInfo.Member[i] = snapshot; + // 2P remains an empty protocol slot, preserving the original per-machine layout. + int slot = i * LocalPlayerCapacity; + scores[slot] = snapshot.Achieves[0]; + valid[slot] = snapshot.IsActive && play.IsValids[0]; + trials[slot] = machine.UserType[0] == 4; + if (valid[slot]) + { + activePlayers++; + anyGameOverOrMiss |= play.GameOvers[0] || play.MissNums[0] > 0; + if (!play.GameOvers[0] && play.FullCombos[0] != 0 && play.MissNums[0] == 0) + fullComboPlayers++; + } + } + CalculateRanks(scores, valid, trials, ranks); + for (int i = 0; i < MachineCapacity; i++) + { + ____partyPlayInfo.Member[i].Rankings[0] = ranks[i * LocalPlayerCapacity]; + ____partyPlayInfo.Member[i].Rankings[1] = 0; + } + foreach (ChainHistory history in ____partyPlayInfo.ChainHistory) history.Clear(); + int historyIndex = 0; + foreach (ChainHistory history in ____chainHistory) + { + if (historyIndex >= ____partyPlayInfo.ChainHistory.Length) break; + ____partyPlayInfo.ChainHistory[historyIndex++].CopyFrom(history); + } + if (checkFullChain) + { + ____partyPlayInfo.IsFullChain = activePlayers >= 2 && ____partyPlayInfo.ChainMiss == 0 + && !anyGameOverOrMiss && activePlayers == fullComboPlayers; + ____partyPlayInfo.CalcStatus = 1; + } + foreach (Member member in members) + if (member.IsJoin()) member.NotifyPartyPlayInfo(new PartyPlayInfo(____partyPlayInfo)); + return false; + } + } +} diff --git a/mod/WorldLink/FourPlayerMapping.cs b/mod/WorldLink/FourPlayerMapping.cs new file mode 100644 index 0000000..065c1be --- /dev/null +++ b/mod/WorldLink/FourPlayerMapping.cs @@ -0,0 +1,318 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using HarmonyLib; +using MAI2.Util; +using Manager; +using Manager.Party.Party; +using Process; + +namespace WorldLink +{ + // Physical monitors and local save slots remain 0/1. Remote users occupy 2/3/4. + public static class FourPlayerMapping + { + public const int DataSlots = 5; + private static readonly Dictionary RemoteSlots = new Dictionary(); + [ThreadStatic] private static uint currentMachine; + private static string lastDifficultyState; + private static readonly Dictionary BoundCounts = new Dictionary(); + + public static void Initialize() + { + ResizeStaticArray(typeof(NotesManager), "_instance"); + GameManager.SelectMusicID = Grow(GameManager.SelectMusicID); + GameManager.SelectDifficultyID = Grow(GameManager.SelectDifficultyID); + GameManager.RandomSeed = Grow(GameManager.RandomSeed); + } + + public static void Apply(HarmonyLib.Harmony harmony) + { + Initialize(); + PatchPostfix(harmony, AccessTools.Constructor(typeof(UserDataManager)), nameof(UserManagerCreated)); + PatchPostfix(harmony, AccessTools.Constructor(typeof(GamePlayManager)), nameof(ScoreManagerCreated)); + var logType = AccessTools.Inner(typeof(GamePlayManager), "ScoreLogClass"); + PatchPostfix(harmony, AccessTools.Constructor(logType), nameof(ScoreLogCreated)); + + var singleBoundMethods = new[] { "GetPlayerNum", "GetPlayerIgnoreNpcNum", "GetPlayerIgnoreNpcNumWithoutTrial", "GetPlayerIgnoreNpcNumWithoutSpecialPlay", "GetVsAchieve", "GetGhostAchieve", "CheckSyncResult" }; + foreach (var name in singleBoundMethods) + PatchBounds(harmony, AccessTools.Method(typeof(GamePlayManager), name), 1); + PatchBounds(harmony, AccessTools.Method(typeof(GamePlayManager), "SetSyncResult"), 2); + PatchBounds(harmony, AccessTools.Method(typeof(GamePlayManager), "PlayLastUpdate"), 5); + PatchBounds(harmony, AccessTools.Method(typeof(GamePlayManager), "Initialize"), 1); + PatchBounds(harmony, AccessTools.Method(typeof(GameProcess), "UpdateNotes"), 1); + PatchBounds(harmony, AccessTools.Method(typeof(GameManager), "Clear"), 1); + PatchBounds(harmony, AccessTools.Method(typeof(GameManager), "UpdateRandom"), 1); + PatchPostfix(harmony, AccessTools.Method(typeof(GameManager), "Clear"), nameof(ClearRemotePlayers)); + + harmony.Patch(AccessTools.Method(typeof(GamePlayManager), "Initialize"), + prefix: H(nameof(BeforeInitialize)), transpiler: H(nameof(RemoteIndices))); + harmony.Patch(AccessTools.Method(typeof(GamePlayManager), "PlayLastUpdate"), transpiler: H(nameof(RemoteIndices))); + harmony.Patch(AccessTools.Method(typeof(GameProcess), "OnUpdate"), transpiler: H(nameof(RemoteIndices))); + harmony.Patch(AccessTools.Method(typeof(GameProcess), "IsTrackSkip"), transpiler: H(nameof(RemoteIndices))); + harmony.Patch(AccessTools.Method(typeof(ResultProcess), "OnStart"), transpiler: H(nameof(ResultSlots))); + PatchPostfix(harmony, AccessTools.Method(typeof(GameScoreList), "Initialize"), nameof(ScoreInitialized)); + harmony.Patch(AccessTools.Method(typeof(MusicSelectProcess), "UpdateChangeInfo"), prefix: H(nameof(UpdateDifficulties))); + var roomSummary = H(nameof(RoomSummary)); + roomSummary.priority = Priority.Last; + harmony.Patch(AccessTools.Method(typeof(MusicSelectProcess), "PartyExec"), postfix: roomSummary); + } + + private static HarmonyMethod H(string name) { return new HarmonyMethod(typeof(FourPlayerMapping), name); } + + private static void PatchPostfix(HarmonyLib.Harmony harmony, MethodBase method, string name) + { + if (method == null) throw new MissingMethodException("Missing mapping patch target " + name); + harmony.Patch(method, postfix: H(name)); + } + + private static T[] Grow(T[] source) + { + if (source.Length >= DataSlots) return source; + var result = new T[DataSlots]; + Array.Copy(source, result, source.Length); + return result; + } + + private static void ResizeStaticArray(System.Type type, string name) + { + var field = AccessTools.Field(type, name); + var source = (Array)field.GetValue(null); + if (source.Length >= DataSlots) return; + var result = Array.CreateInstance(field.FieldType.GetElementType(), DataSlots); + Array.Copy(source, result, source.Length); + field.SetValue(null, result); + } + + private static void UserManagerCreated(UserDataManager __instance) + { + var field = AccessTools.Field(typeof(UserDataManager), "_userData"); + var users = Grow((UserData[])field.GetValue(__instance)); + for (int i = 0; i < users.Length; i++) + if (users[i] == null) users[i] = new UserData(); + field.SetValue(__instance, users); + } + + private static void ScoreManagerCreated(GamePlayManager __instance) + { + foreach (var name in new[] { "_nowAchiveDiff", "_nowRank", "_debugGameScoreLists" }) + { + var field = AccessTools.Field(typeof(GamePlayManager), name); + var source = (Array)field.GetValue(__instance); + var result = Array.CreateInstance(field.FieldType.GetElementType(), DataSlots); + Array.Copy(source, result, source.Length); + field.SetValue(__instance, result); + } + } + + private static void ScoreLogCreated(object __instance) + { + var field = AccessTools.Field(__instance.GetType(), "_score"); + var scores = Grow((GameScoreList[])field.GetValue(__instance)); + for (int i = 0; i < scores.Length; i++) + if (scores[i] == null) scores[i] = new GameScoreList(i); + field.SetValue(__instance, scores); + } + + // Public, side-effect-free slot planner is also used by the regression harness. + public static Dictionary PlanSlots(uint localMachine, IEnumerable members) + { + var unique = members.Distinct().OrderBy(id => id).ToArray(); + if (unique.Length > 4) throw new InvalidOperationException("The room contains more than four machines."); + if (!unique.Contains(localMachine)) throw new InvalidOperationException("The local machine is missing from the room."); + var result = new Dictionary(); + int slot = 2; + foreach (uint id in unique) + result.Add(id, id == localMachine ? 0 : slot++); + return result; + } + + private static void BeforeInitialize(bool partyPlay) + { + Initialize(); + UserManagerCreated(Singleton.Instance); + ScoreManagerCreated(Singleton.Instance); + ClearRemotePlayers(); + if (!partyPlay) return; + if (Singleton.Instance.GetUserData(1).IsEntry) + throw new InvalidOperationException("Four-machine mode requires one player on side 1P per computer."); + var members = Manager.Party.Party.Party.Get().GetPartyMemberInfo().GetJoinMembers().ToArray(); + uint local = FutariExt.MyStubIP(); + var plan = PlanSlots(local, members.Select(member => member.IpAddress)); + foreach (uint id in plan.Keys.OrderBy(id => id)) + { + if (id != local) RemoteSlots[id] = plan[id]; + } + foreach (var member in members) + if (member.Entrys == null || member.Entrys.Length != 2 || !member.Entrys[0] || member.Entrys[1]) + throw new InvalidOperationException("A four-machine room received an invalid player layout."); + for (int side = 0; side < 2; side++) + GameManager.SelectGhostID[side] = GhostManager.GhostTarget.End; + } + + private static void ClearRemotePlayers() + { + RemoteSlots.Clear(); + lastDifficultyState = null; + for (int slot = 2; slot < DataSlots; slot++) + { + var user = Singleton.Instance.GetUserData(slot); + if (user != null) user.SetEntry(false); + } + } + + private static MechaInfo CaptureMecha(MechaInfo member) + { + currentMachine = member.IpAddress; + return member; + } + + private static MemberPlayInfo CapturePlay(MemberPlayInfo member) + { + currentMachine = member.IpAddress; + return member; + } + + private static int RemoteSide(int side) + { + // Side 2P is intentionally inactive, and remains outside all remote player slots. + if (side == 1) return 1; + int slot; + if (side != 0 || !RemoteSlots.TryGetValue(currentMachine, out slot)) + throw new InvalidOperationException("Received play data from an unassigned machine."); + return slot; + } + + private static void ScoreInitialized(GameScoreList __instance, int monitorIndex, bool isParty) + { + if (!isParty || monitorIndex == 1) return; + // PlayerIndex also selects local sound output in the game's life logic. + // Keep the local side identity and give each displayed remote a distinct tie-break index. + AccessTools.Property(typeof(GameScoreList), "PlayerIndex").SetValue(__instance, monitorIndex, null); + } + + private static bool LoadsLocal(CodeInstruction instruction) + { + var op = instruction.opcode; + return op == OpCodes.Ldloc || op == OpCodes.Ldloc_S || op == OpCodes.Ldloc_0 || op == OpCodes.Ldloc_1 || op == OpCodes.Ldloc_2 || op == OpCodes.Ldloc_3; + } + + public static IEnumerable RemoteIndices(IEnumerable source, MethodBase __originalMethod) + { + var code = source.Select(i => new CodeInstruction(i)).ToList(); + int captureCount = 0; + for (int i = 0; i < code.Count; i++) + { + var method = code[i].operand as MethodInfo; + if (method == null || method.Name != "get_Current") continue; + string capture = method.ReturnType == typeof(MechaInfo) ? nameof(CaptureMecha) : method.ReturnType == typeof(MemberPlayInfo) ? nameof(CapturePlay) : null; + if (capture == null) continue; + code.Insert(++i, new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FourPlayerMapping), capture))); + captureCount++; + } + int replacements = 0; + for (int i = 0; i + 2 < code.Count; i++) + { + if (code[i + 2].opcode != OpCodes.Add) continue; + if (LoadsLocal(code[i]) && code[i + 1].opcode == OpCodes.Ldc_I4_2) + { + code[i + 1].opcode = OpCodes.Nop; + code[i + 1].operand = null; + } + else if (code[i].opcode == OpCodes.Ldc_I4_2 && LoadsLocal(code[i + 1])) + { + code[i].opcode = OpCodes.Nop; + code[i].operand = null; + } + else continue; + code[i + 2].opcode = OpCodes.Call; + code[i + 2].operand = AccessTools.Method(typeof(FourPlayerMapping), nameof(RemoteSide)); + replacements++; + } + int expected = __originalMethod.DeclaringType == typeof(GameProcess) && __originalMethod.Name == "OnUpdate" ? 2 : 1; + if (replacements != expected || captureCount != expected) + throw new InvalidOperationException("Unsupported game IL for remote mapping: " + __originalMethod + " captures=" + captureCount + " indices=" + replacements); + return code; + } + + private static bool IsLessBranch(OpCode opcode) + { + return opcode == OpCodes.Blt || opcode == OpCodes.Blt_S || opcode == OpCodes.Blt_Un || opcode == OpCodes.Blt_Un_S; + } + + private static void PatchBounds(HarmonyLib.Harmony harmony, MethodBase method, int count) + { + if (method == null) throw new MissingMethodException("Missing player loop target"); + BoundCounts[method] = count; + harmony.Patch(method, transpiler: H(nameof(PlayerBounds))); + } + + public static IEnumerable PlayerBounds(IEnumerable source, MethodBase __originalMethod) + { + var code = source.Select(i => new CodeInstruction(i)).ToList(); + int count = 0; + for (int i = 0; i + 1 < code.Count; i++) + if (code[i].opcode == OpCodes.Ldc_I4_4 && IsLessBranch(code[i + 1].opcode)) + { + code[i].opcode = OpCodes.Ldc_I4_5; + count++; + } + if (count != BoundCounts[__originalMethod]) + throw new InvalidOperationException("Unsupported player loop IL: " + __originalMethod + " matches=" + count); + return code; + } + + public static IEnumerable ResultSlots(IEnumerable source) + { + var code = source.Select(i => new CodeInstruction(i)).ToList(); + int arrays = 0; + int loops = 0; + for (int i = 0; i + 1 < code.Count; i++) + { + if (code[i].opcode != OpCodes.Ldc_I4_4) continue; + if (code[i + 1].opcode == OpCodes.Newarr) + { + var element = code[i + 1].operand as System.Type; + if (element == typeof(UserData) || element == typeof(Manager.UserDatas.UserScore) || element == typeof(GameScoreList) || element == typeof(Datas.DebugData.DebugGameScoreListData)) + { + code[i].opcode = OpCodes.Ldc_I4_5; + arrays++; + } + } + else if (IsLessBranch(code[i + 1].opcode)) + { + // Audited order: course tracks, player data, rival players, course tracks, result players. + if (loops == 1 || loops == 2 || loops == 4) code[i].opcode = OpCodes.Ldc_I4_5; + loops++; + } + } + if (arrays != 4 || loops != 5) + throw new InvalidOperationException("Unsupported result IL arrays=" + arrays + " loops=" + loops); + return code; + } + + private static bool UpdateDifficulties(MusicSelectProcess __instance) + { + var members = Manager.Party.Party.Party.Get().GetPartyMemberInfo().GetJoinMembersWithoutMe().OrderBy(member => member.IpAddress).ToArray(); + string state = string.Join(";", members.Select(member => member.IpAddress + ":" + member.FumenDifs[0]).ToArray()); + if (state == lastDifficultyState) return false; + lastDifficultyState = state; + var sequences = (MusicSelectProcess.SubSequence[])AccessTools.Field(typeof(MusicSelectProcess), "_currentPlayerSubSequence").GetValue(__instance); + for (int side = 0; side < __instance.MonitorArray.Length; side++) + if (sequences[side] == MusicSelectProcess.SubSequence.Menu && !__instance.IsPreparationCompletes[side]) + __instance.MonitorArray[side].SetMenuReset(); + return false; + } + + private static void RoomSummary(MusicSelectProcess __instance) + { + var members = Manager.Party.Party.Party.Get().GetPartyMemberInfo().GetJoinMembers().OrderBy(member => member.IpAddress).ToArray(); + if (members.Length < 2) return; + string summary = "NyanLink 4P " + members.Length + "/4 " + string.Join(" | ", members.Select(member => member.UserNames[0] + " [" + ((MusicDifficultyID)member.FumenDifs[0]) + "]").ToArray()); + for (int side = 0; side < __instance.MonitorArray.Length; side++) + if (__instance.IsEntry(side)) __instance.MonitorArray[side].SetSideMessage(summary); + } + } +} diff --git a/mod/WorldLink/FutariClient.cs b/mod/WorldLink/FutariClient.cs index c3cc084..1abb01e 100644 --- a/mod/WorldLink/FutariClient.cs +++ b/mod/WorldLink/FutariClient.cs @@ -6,234 +6,251 @@ using System.Net; using System.Net.Sockets; using System.Text; -using HarmonyLib; -#if !UNITY_2018_1_OR_NEWER using System.Threading; -using AMDaemon; -using PartyLink; -using static Manager.Accounting; -#endif +using HarmonyLib; +using WorldLink; public class FutariClient { - public static string LOBBY_BASE => WorldLink.Core.Config.LobbyUrl; - public static string RELAY_BASE => WorldLink.Core.Config.RelayUrl; - public static FutariClient Instance { get; private set; } - - public FutariClient(string keychip, string host, int port, int _) - { - this.host = host; - this.port = port; - this.keychip = keychip; - } - - public FutariClient(string keychip, string host, int port) : this(keychip, host, port, 0) - { - Instance = this; - } - - public string keychip { get; set; } - - private TcpClient _tcpClient; - private StreamWriter _writer; - private StreamReader _reader; - - public readonly ConcurrentQueue sendQ = new(); - // - public readonly ConcurrentDictionary> tcpRecvQ = new(); - // - public readonly ConcurrentDictionary> udpRecvQ = new(); - // - public readonly ConcurrentDictionary> acceptQ = new(); - // - public readonly ConcurrentDictionary> acceptCallbacks = new(); - - private System.Threading.Thread _sendThread; - private System.Threading.Thread _recvThread; - - private bool _reconnecting = false; - - private readonly Stopwatch _heartbeat = new Stopwatch().Also(it => it.Start()); - private readonly long[] _delayWindow = new int[20].Select(_ => -1L).ToArray(); - public int _delayIndex = 0; - public long _delayAvg = 0; - - public string host { get; set; } - public int port { get; set; } - - public IPAddress StubIP => FutariExt.KeychipToStubIp(keychip).ToIP(); - - /// - /// -1: Failed to connect - /// 0: Not connect - /// 1: Connecting - /// 2: Connected - /// - public int StatusCode { get; private set; } = 0; - public string ErrorMsg { get; private set; } = ""; - - public void ConnectAsync() => new System.Threading.Thread(Connect) { IsBackground = true }.Start(); - - private void Connect() - { - _tcpClient = new TcpClient(); - - try - { - StatusCode = 1; - _tcpClient.Connect(host, port); - StatusCode = 2; - } - catch (Exception ex) - { - StatusCode = -1; - ErrorMsg = ex.Message; - Log.Error($"Error connecting to server:\nHost:{host}:{port}\n{ex.Message}"); - ConnectAsync(); - return; - } - var networkStream = _tcpClient.GetStream(); - _writer = new StreamWriter(networkStream, Encoding.UTF8) { AutoFlush = true }; - _reader = new StreamReader(networkStream, Encoding.UTF8); - _reconnecting = false; - - // Register - Send(new FutariMsg { FutariCmd = FutariCmd.CTL_START, data = keychip }); - Log.Info($"Connected to server at {host}:{port}"); - - // Start communication and message receiving in separate threads - _sendThread = 10.Interval(() => - { - if (_heartbeat.ElapsedMilliseconds > 1000) - { - _heartbeat.Restart(); - Send(new FutariMsg { FutariCmd = FutariCmd.CTL_HEARTBEAT }); - } - - // Send any data in the send queue - while (sendQ.TryDequeue(out var msg)) Send(msg); - - }, final: Reconnect, name: "SendThread", stopOnError: true); - - _recvThread = 10.Interval(() => - { - var line = _reader.ReadLine(); - if (line == null) return; - - var message = FutariMsg.FromString(line); - HandleIncomingMessage(message); - - }, final: Reconnect, name: "RecvThread", stopOnError: true); - } - - public void Bind(int bindPort, ProtocolType proto) - { - if (proto == ProtocolType.Tcp) - acceptQ.TryAdd(bindPort, new ConcurrentQueue()); - else if (proto == ProtocolType.Udp) - udpRecvQ.TryAdd(bindPort, new ConcurrentQueue()); - } - - private void Reconnect() - { - Log.Warn("Reconnect Entered"); - if (_reconnecting) return; - _reconnecting = true; - - try { _tcpClient.Close(); } - catch { /* ignored */ } - - try { _sendThread.Abort(); } - catch { /* ignored */ } - - try { _recvThread.Abort(); } - catch { /* ignored */ } - - _sendThread = null; - _recvThread = null; - _tcpClient = null; - - // Reconnect - Log.Warn("Reconnecting..."); - ConnectAsync(); - } - - private void HandleIncomingMessage(FutariMsg futariMsg) - { - if (futariMsg.FutariCmd != FutariCmd.CTL_HEARTBEAT) - Log.Info($"{StubIP} <<< {futariMsg.ToReadableString()}"); - - switch (futariMsg.FutariCmd) - { - // Server registration response with version - case FutariCmd.CTL_START: - if (!string.IsNullOrEmpty(futariMsg.data)) - { - Log.Info($"Server registration response: {futariMsg.data}"); - // Parse version if present (format: "version=X") - if (futariMsg.data.StartsWith("version=")) - { - var versionStr = futariMsg.data.Substring("version=".Length); - if (int.TryParse(versionStr, out var version)) - { - Log.Info($"Server protocol version: {version}"); - } - } - } - break; - - // Heartbeat - case FutariCmd.CTL_HEARTBEAT: - var delay = _heartbeat.ElapsedMilliseconds; - _delayWindow[_delayIndex] = delay; - _delayIndex = (_delayIndex + 1) % _delayWindow.Length; - _delayAvg = (long) _delayWindow.Where(x => x != -1).Average(); - Log.Info($"Heartbeat: {delay}ms, Avg: {_delayAvg}ms"); - break; - - // UDP message - case FutariCmd.DATA_SEND or FutariCmd.DATA_BROADCAST when futariMsg is { proto: ProtocolType.Udp, dPort: not null }: - udpRecvQ.Get(futariMsg.dPort.Value)?.Also(q => - { - Log.Info($"+ Added to UDP queue, there are {q.Count + 1} messages in queue"); - })?.Enqueue(futariMsg); - break; - - // TCP message - case FutariCmd.DATA_SEND when futariMsg.proto == ProtocolType.Tcp && futariMsg is { sid: not null, dPort: not null }: - tcpRecvQ.Get(futariMsg.sid.Value + futariMsg.dPort.Value)?.Also(q => - { - Log.Info($"+ Added to TCP queue, there are {q.Count + 1} messages in queue for port {futariMsg.dPort}"); - })?.Enqueue(futariMsg); - break; - - // TCP connection request - case FutariCmd.CTL_TCP_CONNECT when futariMsg.dPort != null: - acceptQ.Get(futariMsg.dPort.Value)?.Also(q => - { - Log.Info($"+ Added to Accept queue, there are {q.Count + 1} messages in queue"); - })?.Enqueue(futariMsg); - break; - - // TCP connection accept - case FutariCmd.CTL_TCP_ACCEPT when futariMsg is { sid: not null, dPort: not null }: - acceptCallbacks.Get(futariMsg.sid.Value + futariMsg.dPort.Value)?.Invoke(futariMsg); - break; - } - } - - private void Send(FutariMsg futariMsg) - { - // Check if msg's destination ip is the same as my local ip. If so, handle it locally - if (futariMsg.dst == StubIP.ToU32()) - { - Log.Debug($"Loopback @@@ {futariMsg.ToReadableString()}"); - HandleIncomingMessage(futariMsg); - return; - } - - _writer.WriteLine(futariMsg); - if (futariMsg.FutariCmd != FutariCmd.CTL_HEARTBEAT) - Log.Info($"{StubIP} >>> {futariMsg.ToReadableString()}"); - } + private TcpClient _tcpClient; + + private StreamWriter _writer; + + private StreamReader _reader; + + public readonly ConcurrentQueue sendQ = new ConcurrentQueue(); + + public readonly ConcurrentDictionary> tcpRecvQ = new ConcurrentDictionary>(); + + public readonly ConcurrentDictionary> udpRecvQ = new ConcurrentDictionary>(); + + public readonly ConcurrentDictionary> acceptQ = new ConcurrentDictionary>(); + + public readonly ConcurrentDictionary> acceptCallbacks = new ConcurrentDictionary>(); + public readonly ConcurrentDictionary closedStreams = new ConcurrentDictionary(); + + public static long ConnectionKey(int streamId, int port) + { + return ((long)(uint)streamId << 32) | (uint)port; + } + + private Thread _sendThread; + + private Thread _recvThread; + + private int _reconnecting; + + private readonly Stopwatch _heartbeat = new Stopwatch().Also(delegate(Stopwatch it) + { + it.Start(); + }); + + private readonly long[] _delayWindow = new int[20].Select((int num) => -1L).ToArray(); + + public int _delayIndex; + + public long _delayAvg; + + public static string LOBBY_BASE => Core.Config.LobbyUrl; + + public static string RELAY_BASE => Core.Config.RelayUrl; + + public static FutariClient Instance { get; private set; } + + public string keychip { get; set; } + + public string host { get; set; } + + public int port { get; set; } + + public IPAddress StubIP => FutariExt.KeychipToStubIp(keychip).ToIP(); + + public int StatusCode { get; private set; } + + public string ErrorMsg { get; private set; } = ""; + + public FutariClient(string keychip, string host, int port, int _) + { + this.host = host; + this.port = port; + this.keychip = keychip; + } + + public FutariClient(string keychip, string host, int port) + : this(keychip, host, port, 0) + { + Instance = this; + } + + public void ConnectAsync() + { + Thread thread = new Thread(Connect); + thread.IsBackground = true; + thread.Start(); + } + + private void Connect() + { + _tcpClient = new TcpClient(); + try + { + StatusCode = 1; + _tcpClient.Connect(host, port); + StatusCode = 2; + } + catch (Exception ex) + { + StatusCode = -1; + ErrorMsg = ex.Message; + Log.Error($"Error connecting to server:\nHost:{host}:{port}\n{ex.Message}"); + Thread.Sleep(2000); + ConnectAsync(); + return; + } + NetworkStream stream = _tcpClient.GetStream(); + _writer = new StreamWriter(stream, Encoding.UTF8) + { + AutoFlush = true + }; + _reader = new StreamReader(stream, Encoding.UTF8); + Interlocked.Exchange(ref _reconnecting, 0); + Send(new FutariMsg + { + FutariCmd = FutariCmd.CTL_START, + data = keychip + }); + Log.Info($"Connected to server at {host}:{port}"); + _sendThread = 10.Interval(delegate + { + if (_heartbeat.ElapsedMilliseconds > 1000) + { + _heartbeat.Restart(); + Send(new FutariMsg + { + FutariCmd = FutariCmd.CTL_HEARTBEAT + }); + } + FutariMsg result; + while (sendQ.TryDequeue(out result)) + { + Send(result); + } + }, stopOnError: true, null, Reconnect, "SendThread"); + _recvThread = 10.Interval(delegate + { + string text = _reader.ReadLine(); + if (text == null) throw new EndOfStreamException("Relay closed the connection."); + FutariMsg futariMsg = FutariMsg.FromString(text); + HandleIncomingMessage(futariMsg); + }, stopOnError: true, null, Reconnect, "RecvThread"); + } + + public void Bind(int bindPort, ProtocolType proto) + { + switch (proto) + { + case ProtocolType.Tcp: + acceptQ.TryAdd(bindPort, new ConcurrentQueue()); + break; + case ProtocolType.Udp: + udpRecvQ.TryAdd(bindPort, new ConcurrentQueue()); + break; + } + } + + private void Reconnect() + { + Log.Warn("Reconnect Entered"); + if (Interlocked.CompareExchange(ref _reconnecting, 1, 0) == 0) + { + foreach (long key in tcpRecvQ.Keys) closedStreams[key] = 1; + while (sendQ.TryDequeue(out _)) { } + foreach (var queue in acceptQ.Values) while (queue.TryDequeue(out _)) { } + acceptCallbacks.Clear(); + try + { + _tcpClient.Close(); + } + catch + { + } + try + { + if (_sendThread != null && _sendThread != Thread.CurrentThread) _sendThread.Abort(); + } + catch + { + } + try + { + if (_recvThread != null && _recvThread != Thread.CurrentThread) _recvThread.Abort(); + } + catch + { + } + _sendThread = null; + _recvThread = null; + _tcpClient = null; + Log.Warn("Reconnecting..."); + ConnectAsync(); + } + } + + private void HandleIncomingMessage(FutariMsg message) + { + switch (message.FutariCmd) + { + case FutariCmd.CTL_START: + Log.Info("Server registration response: " + message.data); + break; + case FutariCmd.CTL_HEARTBEAT: + _delayWindow[_delayIndex] = _heartbeat.ElapsedMilliseconds; + _delayIndex = (_delayIndex + 1) % _delayWindow.Length; + _delayAvg = (long)_delayWindow.Where(value => value >= 0).Average(); + break; + case FutariCmd.DATA_SEND: + case FutariCmd.DATA_BROADCAST: + if (!message.dPort.HasValue) break; + if (message.proto == ProtocolType.Udp) + { + udpRecvQ.Get(message.dPort.Value)?.Enqueue(message); + } + else if (message.proto == ProtocolType.Tcp && message.sid.HasValue) + { + tcpRecvQ.Get(ConnectionKey(message.sid.Value, message.dPort.Value))?.Enqueue(message); + } + break; + case FutariCmd.CTL_TCP_CONNECT: + if (message.dPort.HasValue) acceptQ.Get(message.dPort.Value)?.Enqueue(message); + break; + case FutariCmd.CTL_TCP_ACCEPT: + if (message.sid.HasValue && message.dPort.HasValue && + acceptCallbacks.TryRemove(ConnectionKey(message.sid.Value, message.dPort.Value), out var callback)) + { + callback(message); + } + break; + case FutariCmd.CTL_TCP_CLOSE: + if (message.sid.HasValue && message.dPort.HasValue) + { + closedStreams[ConnectionKey(message.sid.Value, message.dPort.Value)] = 1; + } + break; + } + } + + private void Send(FutariMsg futariMsg) + { + if (futariMsg.dst == StubIP.ToU32()) + { + Log.Debug("Loopback @@@ " + futariMsg.ToReadableString()); + HandleIncomingMessage(futariMsg); + return; + } + _writer.WriteLine(futariMsg); + if (futariMsg.FutariCmd != FutariCmd.CTL_HEARTBEAT) + { + Log.Info($"{StubIP} >>> {futariMsg.ToReadableString()}"); + } + } } diff --git a/mod/WorldLink/FutariPatch.cs b/mod/WorldLink/FutariPatch.cs index b3deab3..b9fc246 100644 --- a/mod/WorldLink/FutariPatch.cs +++ b/mod/WorldLink/FutariPatch.cs @@ -1,791 +1,694 @@ +using System; +using System.Collections.Generic; +using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; +using System.Threading; +using AMDaemon; using DB; using HarmonyLib; -using Manager; -using PartyLink; -using Process; -using Manager.Party.Party; using MAI2.Util; using Mai2.Mai2Cue; -using static Process.MusicSelectProcess; +using Manager; +using Manager.MaiStudio; +using Manager.Party.Party; using Monitor; +using PartyLink; +using Process; using TMPro; using UnityEngine; -using Object = System.Object; -#if !UNITY_2018_1_OR_NEWER -using MelonLoader.TinyJSON; -using System.Threading; -#endif +using UnityEngine.UI; +using WorldLink; public static class Futari { #if UNITY_2018_1_OR_NEWER public static bool Enabled => AquaMai.Enabled("Mods.WorldLink"); #endif + private static readonly Dictionary redirect = new Dictionary(); + + private static FutariClient client; + + private static bool checkAuthCalled = false; + + private static bool isInit = false; + + public static volatile bool stopping = false; + + private static int onlineUserCount = 0; + + private static MethodBase packetWriteUInt; + + private static System.Type StartUpStateType; + + private static Thread onlineUserCountThread; + + private static readonly MethodInfo SetRecruitData = typeof(MusicSelectProcess).GetProperty("RecruitData").SetMethod; + + private static int musicIdSum; + + private static bool sideMessageFlag; + private static RecruitList displayedRecruits = new RecruitList(); + + public static readonly MethodInfo SetConnectCategoryEnable = typeof(MusicSelectProcess).GetProperty("IsConnectCategoryEnable").SetMethod; + + public static bool Debug => WorldLink.Core.Config.Debug; + + private static IManager PartyMan => Manager.Party.Party.Party.Get(); + + public static void OnBeforePatch() + { + Log.Info("Starting NyanLink patch..."); + packetWriteUInt = typeof(Packet).GetMethod("write_uint", BindingFlags.Static | BindingFlags.NonPublic, null, new System.Type[3] + { + typeof(PacketType), + typeof(int), + typeof(uint) + }, null); + if (packetWriteUInt == null) + { + Log.Error("write_uint not found"); + } + StartUpStateType = typeof(StartupProcess).GetField("_state", BindingFlags.Instance | BindingFlags.NonPublic).FieldType; + if (StartUpStateType == null) + { + Log.Error("StartUpStateType not found"); + } + client = new FutariClient("A1234567890", "", 20101); + if (!string.IsNullOrEmpty(FutariClient.RELAY_BASE)) + { + try + { + Uri uri = new Uri(FutariClient.RELAY_BASE); + client.host = uri.Host; + client.port = ((uri.Port != -1) ? uri.Port : 20101); + Log.Info($"Using configured relay server: {client.host}:{client.port}"); + return; + } + catch (Exception ex) + { + Log.Error("Invalid RelayUrl format: " + FutariClient.RELAY_BASE + ". Error: " + ex.Message); + Log.Info("Falling back to lobby server relay info"); + GetRelayInfoFromLobby(); + return; + } + } + GetRelayInfoFromLobby(); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(OperationManager), "CheckAuth_Proc")] + public static bool CheckAuth_Proc() + { + if (checkAuthCalled) + { + return true; + } + checkAuthCalled = true; + if (isInit) + { + return true; + } + Log.Info("CheckAuth_Proc"); + string keychip = "W9" + new System.Random().Next(100000000, 999999999); + new Thread((ThreadStart)delegate + { + while (client.host == "" && !stopping) + { + Thread.Sleep(100); + } + if (!(client.host == "")) + { + client.keychip = keychip; + client.ConnectAsync(); + isInit = true; + Thread.Sleep(2000); + FetchOnlineUserCount(); + onlineUserCountThread = 30000.Interval(delegate + { + FetchOnlineUserCount(); + }, stopOnError: false, null, null, "OnlineUserCountThread"); + } + }).Start(); + return true; + } - private static readonly Dictionary redirect = new(); - private static FutariClient client; - private static bool checkAuthCalled = false; - private static bool isInit = false; - public static bool stopping = false; - private static int onlineUserCount = 0; - - private static MethodBase packetWriteUInt; - private static System.Type StartUpStateType; - - // Thread management - private static System.Threading.Thread onlineUserCountThread; - private static System.Threading.Thread recruitListThread; - - public static bool Debug => WorldLink.Core.Config.Debug; - - #region Init - - private static readonly MethodInfo SetRecruitData = typeof(MusicSelectProcess).GetProperty("RecruitData")!.SetMethod; - public static void OnBeforePatch() - { - Log.Info("Starting NyanLink patch..."); - - packetWriteUInt = typeof(Packet).GetMethod("write_uint", BindingFlags.NonPublic | BindingFlags.Static, null, - new[] { typeof(PacketType), typeof(int), typeof(uint) }, null); - if (packetWriteUInt == null) Log.Error("write_uint not found"); - - StartUpStateType = typeof(StartupProcess).GetField("_state", BindingFlags.NonPublic | BindingFlags.Instance)!.FieldType; - if (StartUpStateType == null) Log.Error("StartUpStateType not found"); - - // Send HTTP request to get the futari client address - client = new FutariClient("A1234567890", "", 20101); - - // Check if RelayUrl is configured - if (!string.IsNullOrEmpty(FutariClient.RELAY_BASE)) - { - // Use configured RelayUrl directly - try - { - var relayUri = new Uri(FutariClient.RELAY_BASE); - client.host = relayUri.Host; - client.port = relayUri.Port != -1 ? relayUri.Port : 20101; // Default to 20101 if no port specified - Log.Info($"Using configured relay server: {client.host}:{client.port}"); - } - catch (Exception ex) - { - Log.Error($"Invalid RelayUrl format: {FutariClient.RELAY_BASE}. Error: {ex.Message}"); - Log.Info("Falling back to lobby server relay info"); - // Fall back to lobby server method - GetRelayInfoFromLobby(); - } - } - else - { - // Fall back to getting relay info from lobby server - GetRelayInfoFromLobby(); - } - } - - // Entrypoint - // private void CheckAuth_Proc() - [HarmonyPrefix] - [HarmonyPatch(typeof(OperationManager), "CheckAuth_Proc")] - public static bool CheckAuth_Proc() - { - // Prevent multiple calls - if (checkAuthCalled) return PrefixRet.RUN_ORIGINAL; - checkAuthCalled = true; - - if (isInit) return PrefixRet.RUN_ORIGINAL; - Log.Info("CheckAuth_Proc"); - - // Randomize keychip - var keychip = "W9" + new System.Random().Next(100000000, 999999999); - - // Wait until the client is initialized - new System.Threading.Thread(() => - { - while (client.host == "" && !stopping) Thread.Sleep(100); - if (client.host == "") return; - client.keychip = keychip; - client.ConnectAsync(); - isInit = true; - - // Wait a bit for game systems to fully initialize - Thread.Sleep(2000); - - // Fetch initial online user count - FetchOnlineUserCount(); - - // Start periodic online user count fetching with proper thread management - onlineUserCountThread = 30000.Interval(() => FetchOnlineUserCount(), name: "OnlineUserCountThread"); - }).Start(); - - return PrefixRet.RUN_ORIGINAL; - } - - #endregion - - #region Misc - - //Force Enable LanAvailable #if !UNITY_2018_1_OR_NEWER - [HarmonyPrefix] - [HarmonyPatch(typeof(AMDaemon.Network), "IsLanAvailable", MethodType.Getter)] - private static bool PreIsLanAvailable(ref bool __result) - { - __result = true; - return false; - } + [HarmonyPrefix] + [HarmonyPatch(typeof(AMDaemon.Network), "IsLanAvailable", MethodType.Getter)] + private static bool PreIsLanAvailable(ref bool __result) + { + __result = true; + return false; + } #endif - // Fetch online user count from server - private static void FetchOnlineUserCount() - { - if (stopping) return; // Don't fetch if we're shutting down - - try - { - // Check if the lobby URL is available - if (string.IsNullOrEmpty(FutariClient.LOBBY_BASE)) - { - Log.Debug("Lobby URL not available yet, skipping online user count fetch"); - return; - } - - var response = $"{FutariClient.LOBBY_BASE}/online".Get(); - if (string.IsNullOrEmpty(response)) - { - Log.Debug("Empty response from online endpoint"); - return; - } - - var onlineInfo = JsonUtility.FromJson(response); - if (onlineInfo != null) - { - onlineUserCount = onlineInfo.totalUsers; - } - } - catch (Exception ex) - { - Log.Error($"Failed to fetch online user count: {ex.Message}"); - onlineUserCount = 0; - } - } - - //Online Display - [HarmonyPostfix] - [HarmonyPatch(typeof(CommonMonitor), "ViewUpdate")] - public static void CommonMonitorViewUpdate(CommonMonitor __instance, TextMeshProUGUI ____buildVersionText, GameObject ____developmentBuildText) - { - ____buildVersionText.transform.position = ____developmentBuildText.transform.position; - ____buildVersionText.gameObject.SetActive(true); - switch (client.StatusCode) - { - case -1: - ____buildVersionText.text = $"NyanLink Offline"; - ____buildVersionText.color = Color.red; - break; - case 0: - ____buildVersionText.text = $"NyanLink Disconnect"; - ____buildVersionText.color = Color.gray; - break; - case 1: - ____buildVersionText.text = $"NyanLink Connecting"; - ____buildVersionText.color = Color.yellow; - break; - case 2: - var recruitCount = PartyMan == null ? 0 : PartyMan.GetRecruitList().Count; - if (onlineUserCount > 0) - { - ____buildVersionText.text = $"NyanLink Room: {recruitCount} Online: {onlineUserCount}"; - ____buildVersionText.color = new Color(172 / 256f, 181 / 256f, 250 / 256f); - } - else if (onlineUserCount == 0) - { - ____buildVersionText.text = $"NyanLink Online: 0"; - ____buildVersionText.color = Color.gray; - } - break; - } - } - - // Block irrelevant packets - [HarmonyPrefix] - [HarmonyPatch(typeof(SocketBase), "sendClass", typeof(ICommandParam))] - public static bool sendClass(SocketBase __instance, ICommandParam info) - { - switch (info) - { - // Block AdvocateDelivery, SettingHostAddress - case AdvocateDelivery or Setting.SettingHostAddress: - return PrefixRet.BLOCK_ORIGINAL; - - // If it's a Start/FinishRecruit message, send it using http instead - case StartRecruit or FinishRecruit: - var inf = info is StartRecruit o ? o.RecruitInfo : ((FinishRecruit)info).RecruitInfo; - var start = info is StartRecruit ? "start" : "finish"; - var msg = JsonUtility.ToJson(new RecruitRecord - { - Keychip = client.keychip, - RecruitInfo = inf - }, false); - $"{FutariClient.LOBBY_BASE}/recruit/{start}".PostAsync(msg); - Log.Info($"Sent {start} recruit message: {msg}"); - return PrefixRet.BLOCK_ORIGINAL; - - // Log the actual type of info and the actual type of this class - default: - Log.Debug($"SendClass: {Log.BRIGHT_RED}{info.GetType().Name}{Log.RESET} from {__instance.GetType().Name}"); - return PrefixRet.RUN_ORIGINAL; - } - } - - // Patch for error logging - // SocketBase:: protected void error(string message, int no) - [HarmonyPrefix] - [HarmonyPatch(typeof(SocketBase), "error", typeof(string), typeof(int))] - public static bool preError(string message, int no) - { - Log.Error($"Error: {message} ({no})"); - return PrefixRet.RUN_ORIGINAL; - } - - // Force isSameVersion to return true - // Packet:: public bool isSameVersion() + private static void FetchOnlineUserCount() + { + if (stopping) + { + return; + } + try + { + if (string.IsNullOrEmpty(FutariClient.LOBBY_BASE)) + { + Log.Debug("Lobby URL not available yet, skipping online user count fetch"); + return; + } + string text = (FutariClient.LOBBY_BASE + "/online").Get(); + if (string.IsNullOrEmpty(text)) + { + Log.Debug("Empty response from online endpoint"); + return; + } + OnlineUserInfo onlineUserInfo = JsonUtility.FromJson(text); + if (onlineUserInfo != null) + { + onlineUserCount = onlineUserInfo.totalUsers; + } + } + catch (Exception ex) + { + Log.Error("Failed to fetch online user count: " + ex.Message); + onlineUserCount = 0; + } + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(CommonMonitor), "ViewUpdate")] + public static void CommonMonitorViewUpdate(CommonMonitor __instance, TextMeshProUGUI ____buildVersionText, GameObject ____developmentBuildText) + { + ((TMP_Text)____buildVersionText).transform.position = ____developmentBuildText.transform.position; + ((Component)(object)____buildVersionText).gameObject.SetActive(value: true); + switch (client.StatusCode) + { + case -1: + ((TMP_Text)____buildVersionText).text = "NyanLink Offline"; + ((Graphic)(object)____buildVersionText).color = Color.red; + break; + case 0: + ((TMP_Text)____buildVersionText).text = "NyanLink Disconnect"; + ((Graphic)(object)____buildVersionText).color = Color.gray; + break; + case 1: + ((TMP_Text)____buildVersionText).text = "NyanLink Connecting"; + ((Graphic)(object)____buildVersionText).color = Color.yellow; + break; + case 2: + { + int num = ((PartyMan != null) ? PartyMan.GetRecruitList().Count : 0); + if (onlineUserCount > 0) + { + ((TMP_Text)____buildVersionText).text = $"NyanLink Room: {num} Online: {onlineUserCount}"; + ((Graphic)(object)____buildVersionText).color = new Color(43f / 64f, 0.70703125f, 125f / 128f); + } + else if (onlineUserCount == 0) + { + ((TMP_Text)____buildVersionText).text = "NyanLink Online: 0"; + ((Graphic)(object)____buildVersionText).color = Color.gray; + } + break; + } + } + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SocketBase), "sendClass", new System.Type[] { typeof(ICommandParam) })] + public static bool sendClass(SocketBase __instance, ICommandParam info) + { + if (!(info is AdvocateDelivery) && !(info is Setting.SettingHostAddress)) + { + if (info is StartRecruit || info is FinishRecruit) + { + RecruitInfo recruitInfo = ((info is StartRecruit startRecruit) ? startRecruit.RecruitInfo : ((FinishRecruit)info).RecruitInfo); + string text = ((info is StartRecruit) ? "start" : "finish"); + string text2 = JsonUtility.ToJson((object)new RecruitRecord + { + Keychip = client.keychip, + RecruitInfo = recruitInfo + }, false); + (FutariClient.LOBBY_BASE + "/recruit/" + text).PostAsync(text2); + Log.Info("Sent " + text + " recruit message: " + text2); + return false; + } + Log.Debug("SendClass: \u001b[91m" + info.GetType().Name + "\u001b[0m from " + __instance.GetType().Name); + return true; + } + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SocketBase), "error", new System.Type[] + { + typeof(string), + typeof(int) + })] + public static bool preError(string message, int no) + { + Log.Error($"Error: {message} ({no})"); + return true; + } + #if !UNITY_2018_1_OR_NEWER - [HarmonyPostfix] - [HarmonyPatch(typeof(Packet), "isSameVersion")] - public static void postIsSameVersion(ref bool __result) - { - Log.Debug($"isSameVersion (original): {__result}, forcing true"); - __result = true; - } + [HarmonyPostfix] + [HarmonyPatch(typeof(Packet), "isSameVersion")] + public static void postIsSameVersion(Packet __instance, ref bool __result) + { + __result = WorldLink.FourMachineProtocol.IsCompatiblePacket(__instance); + } #endif - // Patch my IP address to a stub - // public static IPAddress MyIpAddress(int mockID) - [HarmonyPrefix] - [HarmonyPatch(typeof(PartyLink.Util), "MyIpAddress", typeof(int))] - public static bool preMyIpAddress(int mockID, ref IPAddress __result) - { - __result = FutariExt.MyStubIP().ToIP(); - return PrefixRet.BLOCK_ORIGINAL; - } - - #endregion - - #region Recruit Information - - private static readonly MethodInfo RStartRecruit = typeof(Client) - .GetMethod("RecvStartRecruit", BindingFlags.NonPublic | BindingFlags.Instance); - private static readonly MethodInfo RFinishRecruit = typeof(Client) - .GetMethod("RecvFinishRecruit", BindingFlags.NonPublic | BindingFlags.Instance); - private static Dictionary lastRecruits = new(); - - private static string Identity(this RecruitInfo x) => $"{x.IpAddress} : {x.MusicID}"; - - // Client Constructor - // Client:: public Client(string name, PartyLink.Party.InitParam initParam) - [HarmonyPostfix] - [HarmonyPatch(typeof(Client), MethodType.Constructor, typeof(string), typeof(PartyLink.Party.InitParam))] - public static void postClientConstruct(Client __instance, string name, PartyLink.Party.InitParam initParam) - { - Log.Debug($"new Client({name}, {initParam})"); - recruitListThread = 10000.Interval(() => - { - if (stopping) return; // Don't process if we're shutting down - - try - { - // Add null checks to prevent crashes - if (__instance == null || lastRecruits == null) - { - Log.Debug("Client or lastRecruits is null, skipping recruit list update"); - return; - } - - var response = $"{FutariClient.LOBBY_BASE}/recruit/list".Get(); - if (string.IsNullOrEmpty(response)) - { - Log.Debug("Empty response from recruit list endpoint"); - return; - } - - var recruitRecords = response.Trim().Split('\n') - .Where(x => !string.IsNullOrEmpty(x)) - .Select(JsonUtility.FromJson) - .Where(x => x != null && x.RecruitInfo != null) // Filter out null records - .ToList(); - - // Process finished recruits - var currentIds = recruitRecords.Select(x => x.RecruitInfo.Identity()).ToList(); - var finishedRecruits = lastRecruits.Keys.Where(key => !currentIds.Contains(key)).ToList(); - - foreach (var key in finishedRecruits) - { - try - { - if (lastRecruits.ContainsKey(key) && lastRecruits[key] != null) - { - var packet = new Packet(lastRecruits[key].IpAddress); - packet.encode(new FinishRecruit(lastRecruits[key])); - RFinishRecruit?.Invoke(__instance, new object[] { packet }); - } - } - catch (Exception ex) - { - Log.Error($"Error processing finished recruit {key}: {ex.Message}"); - } - } - - // Process new recruits - foreach (var record in recruitRecords) - { - try - { - if (record.RecruitInfo != null) - { - var packet = new Packet(record.RecruitInfo.IpAddress); - packet.encode(new StartRecruit(record.RecruitInfo)); - RStartRecruit?.Invoke(__instance, new object[] { packet }); - } - } - catch (Exception ex) - { - Log.Error($"Error processing new recruit: {ex.Message}"); - } - } - - // Update lastRecruits dictionary - lastRecruits = recruitRecords - .Where(x => x.RecruitInfo != null) - .ToDictionary(x => x.RecruitInfo.Identity(), x => x.RecruitInfo); - } - catch (Exception ex) - { - Log.Error($"Error in recruit list update: {ex.Message}"); - } - }, name: "RecruitListThread"); - } - - // Block start recruit if the song is not available - // Client:: private void RecvStartRecruit(Packet packet) - [HarmonyPrefix] - [HarmonyPatch(typeof(Client), "RecvStartRecruit", typeof(Packet))] - public static bool preRecvStartRecruit(Packet packet) - { - var inf = packet.getParam().RecruitInfo; - Log.Info($"RecvStartRecruit: {JsonUtility.ToJson(inf)}"); - if (Singleton.Instance.GetMusic(inf.MusicID) == null) - { - Log.Error($"Recruit received but music {inf.MusicID} is not available."); - Log.Error($"If you want to play with {string.Join(" and ", inf.MechaInfo.UserNames)},"); - Log.Error("make sure you have the same game version and option packs installed."); - return PrefixRet.BLOCK_ORIGINAL; - } - return PrefixRet.RUN_ORIGINAL; - } - - #endregion - - private static IManager PartyMan => Manager.Party.Party.Party.Get(); - - //Skip StartupNetworkChecker - [HarmonyPostfix] - [HarmonyPatch(nameof(StartupProcess), nameof(StartupProcess.OnUpdate))] - public static void postStartupOnUpdate(ref byte ____state, string[] ____statusMsg, string[] ____statusSubMsg) - { - var msgCount = ____statusMsg.Length; - // Status code - ____statusMsg[msgCount - 3] = "NyanLink"; - ____statusSubMsg[msgCount - 3] = client.StatusCode switch - { - -1 => "BAD", - 0 => "Not Connect", - 1 => "Connecting", - 2 => "GOOD", - _ => "Waiting..." - }; - - // Delay - ____statusMsg[msgCount - 2] = "PING"; - ____statusSubMsg[msgCount - 2] = client._delayAvg == 0 ? "N/A" : $"{client._delayAvg} ms"; - - var isThursday = DateTime.Now.DayOfWeek == DayOfWeek.Thursday; - - ____statusMsg[msgCount - 1] = isThursday ? "CRAZY THURSDAY" : "CAT :3"; - ____statusSubMsg[msgCount - 1] = client._delayIndex % 2 == 0 ? "" : (isThursday ? "V50" : "MEOW"); - - // If it is in the wait link delivery state, change to ready immediately - if (____state != 0x04) return; - ____state = 0x08; - - // Start the services that would have been started by the StartupNetworkChecker - DeliveryChecker.get().start(true); - Setting.get().setData(new Setting.Data().Also(x => x.set(false, 4))); - Setting.get().setRetryEnable(true); - Advertise.get().initialize(MachineGroupID.ON); - PartyMan.Start(MachineGroupID.ON); - Log.Info("Skip Startup Network Check"); - } - - #region NFSocket - - [HarmonyPostfix] - [HarmonyPatch(typeof(NFSocket), MethodType.Constructor, typeof(AddressFamily), typeof(SocketType), typeof(ProtocolType), typeof(int))] - public static void postNFCreate(NFSocket __instance, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, int mockID) - { - Log.Debug($"new NFSocket({addressFamily}, {socketType}, {protocolType}, {mockID})"); - if (mockID == 3939) return; // Created in redirected NFAccept as a stub - var futari = new FutariSocket(addressFamily, socketType, protocolType, mockID); - redirect.Add(__instance, futari); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(NFSocket), MethodType.Constructor, typeof(Socket))] - public static void postNFCreate2(NFSocket __instance, Socket nfSocket) - { - Log.Error("new NFSocket(Socket) -- We shouldn't get here."); - throw new NotImplementedException(); - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "Poll")] - public static bool preNFPoll(NFSocket socket, SelectMode mode, ref bool __result) - { - __result = FutariSocket.Poll(redirect[socket], mode); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "Send")] - public static bool preNFSend(NFSocket __instance, byte[] buffer, int offset, int size, SocketFlags socketFlags, ref int __result) - { - __result = redirect[__instance].Send(buffer, offset, size, socketFlags); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "SendTo")] - public static bool preNFSendTo(NFSocket __instance, byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, ref int __result) - { - __result = redirect[__instance].SendTo(buffer, offset, size, socketFlags, remoteEP); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "Receive")] - public static bool preNFReceive(NFSocket __instance, byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, ref int __result) - { - __result = redirect[__instance].Receive(buffer, offset, size, socketFlags, out errorCode); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "ReceiveFrom")] - public static bool preNFReceiveFrom(NFSocket __instance, byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP, ref int __result) - { - __result = redirect[__instance].ReceiveFrom(buffer, socketFlags, ref remoteEP); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "Bind")] - public static bool preNFBind(NFSocket __instance, EndPoint localEndP) - { - Log.Debug("NFBind"); - redirect[__instance].Bind(localEndP); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "Listen")] - public static bool preNFListen(NFSocket __instance, int backlog) - { - Log.Debug("NFListen"); - redirect[__instance].Listen(backlog); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "Accept")] - public static bool preNFAccept(NFSocket __instance, ref NFSocket __result) - { - Log.Debug("NFAccept"); - var futariSocket = redirect[__instance].Accept(); - var mockSocket = new NFSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp, 3939); - redirect[mockSocket] = futariSocket; - __result = mockSocket; - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "ConnectAsync")] - public static bool preNFConnectAsync(NFSocket __instance, SocketAsyncEventArgs e, int mockID, ref bool __result) - { - Log.Debug("NFConnectAsync"); - __result = redirect[__instance].ConnectAsync(e, mockID); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "SetSocketOption")] - public static bool preNFSetSocketOption(NFSocket __instance, SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue) - { - redirect[__instance].SetSocketOption(optionLevel, optionName, optionValue); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "Close")] - public static bool preNFClose(NFSocket __instance) - { - Log.Debug("NFClose"); - redirect[__instance].Close(); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "Shutdown")] - public static bool preNFShutdown(NFSocket __instance, SocketShutdown how) - { - Log.Debug("NFShutdown"); - redirect[__instance].Shutdown(how); - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "RemoteEndPoint", MethodType.Getter)] - public static bool preNFGetRemoteEndPoint(NFSocket __instance, ref EndPoint __result) - { - Log.Debug("NFGetRemoteEndPoint"); - __result = redirect[__instance].RemoteEndPoint; - return PrefixRet.BLOCK_ORIGINAL; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(NFSocket), "LocalEndPoint", MethodType.Getter)] - public static bool preNFGetLocalEndPoint(NFSocket __instance, ref EndPoint __result) - { - Log.Debug("NFGetLocalEndPoint"); - __result = redirect[__instance].LocalEndPoint; - return PrefixRet.BLOCK_ORIGINAL; - } - - #endregion - - #region Packet codec - - // Disable encryption - [HarmonyPrefix] - [HarmonyPatch(typeof(Packet), "encrypt")] - public static bool prePacketEncrypt(Packet __instance, PacketType ____encrypt, PacketType ____plane) - { - ____encrypt.ClearAndResize(____plane.Count); - Array.Copy(____plane.GetBuffer(), 0, ____encrypt.GetBuffer(), 0, ____plane.Count); - ____encrypt.ChangeCount(____plane.Count); - packetWriteUInt.Invoke(null, new Object[] { ____plane, 0, (uint)____plane.Count }); - return PrefixRet.BLOCK_ORIGINAL; - } - - // Disable decryption - [HarmonyPrefix] - [HarmonyPatch(typeof(Packet), "decrypt")] - public static bool prePacketDecrypt(Packet __instance, PacketType ____encrypt, PacketType ____plane) - { - ____plane.ClearAndResize(____encrypt.Count); - Array.Copy(____encrypt.GetBuffer(), 0, ____plane.GetBuffer(), 0, ____encrypt.Count); - ____plane.ChangeCount(____encrypt.Count); - packetWriteUInt.Invoke(null, new Object[] { ____plane, 0, (uint)____plane.Count }); - return PrefixRet.BLOCK_ORIGINAL; - } - - #endregion - - #region Recruit UI - - private static int musicIdSum; - private static bool sideMessageFlag; - - [HarmonyPrefix] - [HarmonyPatch(typeof(MusicSelectProcess), "OnStart")] - public static bool preMusicSelectProcessOnStart(MusicSelectProcess __instance) - { - // 每次重新进入选区菜单之后重新初始化变量 - musicIdSum = 0; - sideMessageFlag = false; - return PrefixRet.RUN_ORIGINAL; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(MusicSelectProcess), "PartyExec")] - public static void postPartyExec(MusicSelectProcess __instance) - { - // 检查联机房间是否有更新,如果更新的话设置 IsConnectingMusic=false 然后刷新列表 - var checkDiff = PartyMan.GetRecruitListWithoutMe().Sum(item => item.MusicID); - if (musicIdSum != checkDiff) - { - musicIdSum = checkDiff; - __instance.IsConnectingMusic = false; - } - - if (__instance.IsConnectingMusic && __instance.RecruitData != null && __instance.IsConnectionFolder()) - { - // 设置房间信息显示 - var info = __instance.RecruitData.MechaInfo; - var players = "NyanLink Room! Players: " + - string.Join(" and ", info.UserNames.Where((_, i) => info.FumenDifs[i] != -1)); - - __instance.MonitorArray.Where((_, i) => __instance.IsEntry(i)) - .Each(x => x.SetSideMessage(players)); - - sideMessageFlag = true; - } - else if (!__instance.IsConnectionFolder() && sideMessageFlag) - { - __instance.MonitorArray.Where((_, i) => __instance.IsEntry(i)) - .Each(x => x.SetSideMessage(CommonMessageID.Scroll_Music_Select.GetName())); - - sideMessageFlag = false; - } - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(MusicSelectProcess), "RecruitData", MethodType.Getter)] - public static void postRecruitData(MusicSelectProcess __instance, ref RecruitInfo __result) - { - // 开歌时设置当前选择的联机数据 - if (!__instance.IsConnectionFolder() || __result == null) return; - - var list = PartyMan.GetRecruitListWithoutMe(); - if (list == null) return; - if (__instance.CurrentMusicSelect >= 0 && __instance.CurrentMusicSelect < list.Count) - { - __result = list[__instance.CurrentMusicSelect]; - } - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(MusicSelectProcess), "IsConnectStart")] - public static bool preIsConnectStart( - MusicSelectProcess __instance, - List ____connectCombineMusicDataList, - SubSequence[] ____currentPlayerSubSequence, - ref bool __result) - { - __result = false; - - // 修正 SetConnectData 触发条件,阻止原有 IP 判断重新设置 - var recruits = PartyMan.GetRecruitListWithoutMe(); - if (!__instance.IsConnectingMusic && recruits.Count > 0) - { - // var recruit = recruits.Count > 0 ? recruits[0] : null; - var recruit = recruits[0]; - Log.Debug($"MusicSelectProcess::IsConnectStart recruit data has been set to {recruit}"); - SetRecruitData.Invoke(__instance, new Object[] { recruit }); - preSetConnectData(__instance, ____connectCombineMusicDataList, ____currentPlayerSubSequence); - __result = true; - } - return PrefixRet.BLOCK_ORIGINAL; - } - - public static readonly MethodInfo SetConnectCategoryEnable = typeof(MusicSelectProcess).GetProperty("IsConnectCategoryEnable")!.SetMethod; - - [HarmonyPrefix] - [HarmonyPatch(typeof(MusicSelectProcess), "SetConnectData")] - public static bool preSetConnectData( - MusicSelectProcess __instance, - List ____connectCombineMusicDataList, - SubSequence[] ____currentPlayerSubSequence) - { - ____connectCombineMusicDataList.Clear(); - SetConnectCategoryEnable.Invoke(__instance, new Object[] { false }); - - // 遍历所有房间并且显示 - foreach (var item in PartyMan.GetRecruitListWithoutMe()) - { - var musicID = item.MusicID; - var combineMusicSelectData = new CombineMusicSelectData(); - var music = Singleton.Instance.GetMusic(musicID); - var notesList = Singleton.Instance.GetNotesList()[musicID].NotesList; - - switch (musicID) - { - case < 10000: - combineMusicSelectData.existStandardScore = true; - break; - case > 10000 and < 20000: - combineMusicSelectData.existDeluxeScore = true; - break; - } - - for (var i = 0; i < 2; i++) - { - combineMusicSelectData.musicSelectData.Add(new MusicSelectData(music, notesList, 0)); - } - ____connectCombineMusicDataList.Add(combineMusicSelectData); - try - { - var thumbnailName = music.thumbnailName; - for (var j = 0; j < __instance.MonitorArray.Length; j++) - { - if (!__instance.IsEntry(j)) continue; - - __instance.MonitorArray[j].SetRecruitInfo(thumbnailName); - SoundManager.PlaySE(Cue.SE_INFO_NORMAL, j); - } - } - catch - { /* 防止有可能的空 */ - } - - __instance.IsConnectingMusic = true; - } - - // No data available, add a dummy entry - if (PartyMan.GetRecruitListWithoutMe().Count == 0) - { - ____connectCombineMusicDataList.Add(new CombineMusicSelectData - { - musicSelectData = new List { null, null }, - isWaitConnectScore = true - }); - __instance.IsConnectingMusic = false; - } - - if (__instance.MonitorArray == null) return PrefixRet.BLOCK_ORIGINAL; - - for (var l = 0; l < __instance.MonitorArray.Length; l++) - { - if (____currentPlayerSubSequence[l] != SubSequence.Music) continue; - - __instance.MonitorArray[l].SetDeployList(false); - if (!__instance.IsConnectionFolder(0)) continue; - - __instance.ChangeBGM(); - if (!__instance.IsEntry(l)) continue; - - __instance.MonitorArray[l].SetVisibleButton(__instance.IsConnectingMusic, InputManager.ButtonSetting.Button04); - } - return PrefixRet.BLOCK_ORIGINAL; - } - - #endregion - - // Helper method to get relay info from lobby server - private static void GetRelayInfoFromLobby() - { - $"{FutariClient.LOBBY_BASE}/info".GetAsync((sender, e) => - { - if (e.Error != null) - { - Log.Error($"Failed to get NyanLink server address: {e.Error}"); - return; - } - // Response Format: {"relayHost": "google.com", "relayPort": 20101} - var info = JsonUtility.FromJson(e.Result); - client.host = info.relayHost; - client.port = info.relayPort; - Log.Info($"NyanLink server address: {info.relayHost}:{info.relayPort}"); - }); - } -} \ No newline at end of file + [HarmonyPrefix] + [HarmonyPatch(typeof(PartyLink.Util), "MyIpAddress", new System.Type[] { typeof(int) })] + public static bool preMyIpAddress(int mockID, ref IPAddress __result) + { + __result = FutariExt.MyStubIP().ToIP(); + return false; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(Client), MethodType.Constructor, new System.Type[] + { + typeof(string), + typeof(PartyLink.Party.InitParam) + })] + public static void postClientConstruct(Client __instance, string name, PartyLink.Party.InitParam initParam) + { + Log.Debug($"new Client({name}, {initParam})"); + WorldLink.LobbyRecruitSync.Start(__instance); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(Client), "RecvStartRecruit", new System.Type[] { typeof(Packet) })] + public static bool preRecvStartRecruit(Packet packet) + { + RecruitInfo recruitInfo = packet?.getParam()?.RecruitInfo; + if (recruitInfo == null || recruitInfo.GroupID != WorldLink.FourMachineProtocol.RoomGroup + || !WorldLink.FourMachineProtocol.IsSinglePlayerMachine(recruitInfo.MechaInfo)) return false; + Log.Info("RecvStartRecruit: " + JsonUtility.ToJson((object)recruitInfo)); + return RecruitSongSafety.TryGetSong(recruitInfo, out _, out _); + } + + [HarmonyPostfix] + [HarmonyPatch("StartupProcess", "OnUpdate")] + public static void postStartupOnUpdate(ref byte ____state, string[] ____statusMsg, string[] ____statusSubMsg) + { + int num = ____statusMsg.Length; + ____statusMsg[num - 3] = "NyanLink"; + int num2 = num - 3; + ____statusSubMsg[num2] = client.StatusCode switch + { + -1 => "BAD", + 0 => "Not Connect", + 1 => "Connecting", + 2 => "GOOD", + _ => "Waiting...", + }; + ____statusMsg[num - 2] = "PING"; + ____statusSubMsg[num - 2] = ((client._delayAvg == 0L) ? "N/A" : $"{client._delayAvg} ms"); + bool flag = DateTime.Now.DayOfWeek == DayOfWeek.Thursday; + ____statusMsg[num - 1] = (flag ? "CRAZY THURSDAY" : "CAT :3"); + ____statusSubMsg[num - 1] = ((client._delayIndex % 2 == 0) ? "" : (flag ? "V50" : "MEOW")); + if (____state == 4) + { + ____state = 8; + DeliveryChecker.get().start(isServer: true); + Setting.get().setData(new Setting.Data().Also(delegate(Setting.Data x) + { + x.set(isEventMode: false, 4); + })); + Setting.get().setRetryEnable(isRetry: true); + Advertise.get().initialize(MachineGroupID.ON); + PartyMan.Start(MachineGroupID.ON); + Log.Info("Skip Startup Network Check"); + } + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(NFSocket), MethodType.Constructor, new System.Type[] + { + typeof(AddressFamily), + typeof(SocketType), + typeof(ProtocolType), + typeof(int) + })] + public static void postNFCreate(NFSocket __instance, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, int mockID) + { + Log.Debug($"new NFSocket({addressFamily}, {socketType}, {protocolType}, {mockID})"); + if (mockID != 3939) + { + FutariSocket value = new FutariSocket(addressFamily, socketType, protocolType, mockID); + redirect.Add(__instance, value); + } + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(NFSocket), MethodType.Constructor, new System.Type[] { typeof(Socket) })] + public static void postNFCreate2(NFSocket __instance, Socket nfSocket) + { + Log.Error("new NFSocket(Socket) -- We shouldn't get here."); + throw new NotImplementedException(); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "Poll")] + public static bool preNFPoll(NFSocket socket, SelectMode mode, ref bool __result) + { + __result = FutariSocket.Poll(redirect[socket], mode); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "Send")] + public static bool preNFSend(NFSocket __instance, byte[] buffer, int offset, int size, SocketFlags socketFlags, ref int __result) + { + __result = redirect[__instance].Send(buffer, offset, size, socketFlags); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "SendTo")] + public static bool preNFSendTo(NFSocket __instance, byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, ref int __result) + { + __result = redirect[__instance].SendTo(buffer, offset, size, socketFlags, remoteEP); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "Receive")] + public static bool preNFReceive(NFSocket __instance, byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, ref int __result) + { + __result = redirect[__instance].Receive(buffer, offset, size, socketFlags, out errorCode); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "ReceiveFrom")] + public static bool preNFReceiveFrom(NFSocket __instance, byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP, ref int __result) + { + __result = redirect[__instance].ReceiveFrom(buffer, socketFlags, ref remoteEP); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "Bind")] + public static bool preNFBind(NFSocket __instance, EndPoint localEndP) + { + Log.Debug("NFBind"); + redirect[__instance].Bind(localEndP); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "Listen")] + public static bool preNFListen(NFSocket __instance, int backlog) + { + Log.Debug("NFListen"); + redirect[__instance].Listen(backlog); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "Accept")] + public static bool preNFAccept(NFSocket __instance, ref NFSocket __result) + { + Log.Debug("NFAccept"); + FutariSocket value = redirect[__instance].Accept(); + NFSocket nFSocket = new NFSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp, 3939); + redirect[nFSocket] = value; + __result = nFSocket; + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "ConnectAsync")] + public static bool preNFConnectAsync(NFSocket __instance, SocketAsyncEventArgs e, int mockID, ref bool __result) + { + Log.Debug("NFConnectAsync"); + __result = redirect[__instance].ConnectAsync(e, mockID); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "SetSocketOption")] + public static bool preNFSetSocketOption(NFSocket __instance, SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue) + { + redirect[__instance].SetSocketOption(optionLevel, optionName, optionValue); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "Close")] + public static bool preNFClose(NFSocket __instance) + { + Log.Debug("NFClose"); + redirect[__instance].Close(); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "Shutdown")] + public static bool preNFShutdown(NFSocket __instance, SocketShutdown how) + { + Log.Debug("NFShutdown"); + redirect[__instance].Shutdown(how); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "RemoteEndPoint", MethodType.Getter)] + public static bool preNFGetRemoteEndPoint(NFSocket __instance, ref EndPoint __result) + { + Log.Debug("NFGetRemoteEndPoint"); + __result = redirect[__instance].RemoteEndPoint; + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(NFSocket), "LocalEndPoint", MethodType.Getter)] + public static bool preNFGetLocalEndPoint(NFSocket __instance, ref EndPoint __result) + { + Log.Debug("NFGetLocalEndPoint"); + __result = redirect[__instance].LocalEndPoint; + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(Packet), "encrypt")] + public static bool prePacketEncrypt(Packet __instance, PacketType ____encrypt, PacketType ____plane) + { + ____encrypt.ClearAndResize(____plane.Count); + Array.Copy(____plane.GetBuffer(), 0, ____encrypt.GetBuffer(), 0, ____plane.Count); + ____encrypt.ChangeCount(____plane.Count); + packetWriteUInt.Invoke(null, new object[3] + { + ____plane, + 0, + (uint)____plane.Count + }); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(Packet), "decrypt")] + public static bool prePacketDecrypt(Packet __instance, PacketType ____encrypt, PacketType ____plane) + { + ____plane.ClearAndResize(____encrypt.Count); + Array.Copy(____encrypt.GetBuffer(), 0, ____plane.GetBuffer(), 0, ____encrypt.Count); + ____plane.ChangeCount(____encrypt.Count); + packetWriteUInt.Invoke(null, new object[3] + { + ____plane, + 0, + (uint)____plane.Count + }); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(MusicSelectProcess), "OnStart")] + public static bool preMusicSelectProcessOnStart(MusicSelectProcess __instance) + { + musicIdSum = 0; + sideMessageFlag = false; + displayedRecruits = new RecruitList(); + return true; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(MusicSelectProcess), "PartyExec")] + public static void postPartyExec(MusicSelectProcess __instance) + { + if (!RecruitSongSafety.AllowsRecruitment()) return; + // Include machine identity and order: different rooms can have equal song sums. + int num = 17; + foreach (var room in PartyMan.GetRecruitListWithoutMe()) + unchecked { num = (num * 31 + room.MusicID) * 31 + (int)room.IpU32; } + if (musicIdSum != num) + { + musicIdSum = num; + __instance.IsConnectingMusic = false; + } + if (__instance.IsConnectingMusic && __instance.RecruitData != null && __instance.IsConnectionFolder()) + { + MechaInfo info = __instance.RecruitData.MechaInfo; + string players = "NyanLink Room! Players: " + string.Join(" and ", info.UserNames.Where((string _, int i) => info.FumenDifs[i] != -1)); + __instance.MonitorArray.Where((MusicSelectMonitor _, int i) => __instance.IsEntry(i)).Each(delegate(MusicSelectMonitor x) + { + x.SetSideMessage(players); + }); + sideMessageFlag = true; + } + else if (!__instance.IsConnectionFolder() && sideMessageFlag) + { + __instance.MonitorArray.Where((MusicSelectMonitor _, int i) => __instance.IsEntry(i)).Each(delegate(MusicSelectMonitor x) + { + x.SetSideMessage(CommonMessageID.Scroll_Music_Select.GetName()); + }); + sideMessageFlag = false; + } + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(MusicSelectProcess), "RecruitData", MethodType.Getter)] + public static void postRecruitData(MusicSelectProcess __instance, ref RecruitInfo __result) + { + if (__result != null && RecruitSongSafety.AllowsRecruitment() && __instance.IsConnectionFolder()) + { + RecruitList recruitListWithoutMe = displayedRecruits; + if (recruitListWithoutMe != null && __instance.CurrentMusicSelect >= 0 && __instance.CurrentMusicSelect < recruitListWithoutMe.Count) + { + __result = recruitListWithoutMe[__instance.CurrentMusicSelect]; + } + else __result = null; + } + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(MusicSelectProcess), "IsConnectStart")] + public static bool preIsConnectStart(MusicSelectProcess __instance, List ____connectCombineMusicDataList, MusicSelectProcess.SubSequence[] ____currentPlayerSubSequence, ref bool __result) + { + __result = false; + if (!RecruitSongSafety.AllowsRecruitment()) return false; + RecruitList recruitListWithoutMe = PartyMan.GetRecruitListWithoutMe(); + if (!__instance.IsConnectingMusic && recruitListWithoutMe.Count > 0) + { + RecruitInfo recruitInfo = recruitListWithoutMe[0]; + Log.Debug($"MusicSelectProcess::IsConnectStart recruit data has been set to {recruitInfo}"); + preSetConnectData(__instance, ____connectCombineMusicDataList, ____currentPlayerSubSequence); + __result = __instance.IsConnectingMusic; + } + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(MusicSelectProcess), "SetConnectData")] + public static bool preSetConnectData(MusicSelectProcess __instance, List ____connectCombineMusicDataList, MusicSelectProcess.SubSequence[] ____currentPlayerSubSequence) + { + if (!RecruitSongSafety.AllowsRecruitment()) return false; + // Build and validate off to the side. No partial clear of the visible list. + var next = new List(); + var accepted = new RecruitList(); + foreach (RecruitInfo item in PartyMan.GetRecruitListWithoutMe()) + { + if (!RecruitSongSafety.TryGetSong(item, out MusicData music, out List notesList)) continue; + try + { + int musicID = item.MusicID; + MusicSelectProcess.CombineMusicSelectData combineMusicSelectData = new MusicSelectProcess.CombineMusicSelectData(); + if (musicID > 10000) + { + if (musicID < 20000) + { + combineMusicSelectData.existDeluxeScore = true; + } + } + else if (musicID < 10000) + { + combineMusicSelectData.existStandardScore = true; + } + for (int i = 0; i < 2; i++) + { + combineMusicSelectData.musicSelectData.Add(new MusicSelectProcess.MusicSelectData(music, notesList, 0)); + } + accepted.Add(new RecruitInfo(item)); + next.Add(combineMusicSelectData); + } + catch (Exception ex) + { + MelonLoader.MelonLogger.Warning("[NyanLink Recruit] Selection entry rejected for music=" + item.MusicID + ": " + ex); + } + } + if (next.Count == 0) + next.Add(new MusicSelectProcess.CombineMusicSelectData + { + musicSelectData = new List { null, null }, + isWaitConnectScore = true + }); + ____connectCombineMusicDataList.Clear(); + ____connectCombineMusicDataList.AddRange(next); + displayedRecruits = accepted; + SetRecruitData.Invoke(__instance, new object[] { accepted.FirstOrDefault() }); + SetConnectCategoryEnable.Invoke(__instance, new object[1] { false }); + __instance.IsConnectingMusic = accepted.Count > 0; + if (accepted.Count > 0) + { + try + { + string thumbnailName = next[0].musicSelectData[0].MusicData.thumbnailName; + for (int j = 0; j < __instance.MonitorArray.Length; j++) + { + if (__instance.IsEntry(j)) + { + __instance.MonitorArray[j].SetRecruitInfo(thumbnailName); + SoundManager.PlaySE(Cue.SE_INFO_NORMAL, j); + } + } + } + catch + { + } + } + if (__instance.MonitorArray == null) + { + return false; + } + for (int k = 0; k < __instance.MonitorArray.Length; k++) + { + if (____currentPlayerSubSequence[k] != MusicSelectProcess.SubSequence.Music) + { + continue; + } + __instance.MonitorArray[k].SetDeployList(isAnimation: false); + if (__instance.IsConnectionFolder()) + { + __instance.ChangeBGM(); + if (__instance.IsEntry(k)) + { + __instance.MonitorArray[k].SetVisibleButton(__instance.IsConnectingMusic, InputManager.ButtonSetting.Button04); + } + } + } + return false; + } + + private static void GetRelayInfoFromLobby() + { + (FutariClient.LOBBY_BASE + "/info").GetAsync(delegate(object sender, DownloadStringCompletedEventArgs e) + { + if (e.Error != null) + { + Log.Error($"Failed to get NyanLink server address: {e.Error}"); + } + else + { + ServerInfo serverInfo = JsonUtility.FromJson(e.Result); + client.host = serverInfo.relayHost; + client.port = serverInfo.relayPort; + Log.Info($"NyanLink server address: {serverInfo.relayHost}:{serverInfo.relayPort}"); + } + }); + } +} diff --git a/mod/WorldLink/FutariSocket.cs b/mod/WorldLink/FutariSocket.cs index fc3e94f..f71547c 100644 --- a/mod/WorldLink/FutariSocket.cs +++ b/mod/WorldLink/FutariSocket.cs @@ -3,214 +3,242 @@ using System.Net; using System.Net.Sockets; using System.Reflection; +using System.Threading; using HarmonyLib; -using PartyLink; public class FutariSocket { - private int _bindPort = -1; - private readonly FutariClient _client; - private readonly ProtocolType _proto; - private int _streamId = -1; - - // ConnectSocket.Enter_Active (doesn't seem to be actually used) - public EndPoint LocalEndPoint => new IPEndPoint(_client.StubIP, 0); - - // ConnectSocket.Enter_Active, ListenSocket.acceptClient (TCP) - // Each client's remote endpoint must be different - public EndPoint RemoteEndPoint { get; private set; } - - private FutariSocket(FutariClient client, ProtocolType proto) - { - _client = client; - _proto = proto; - RemoteEndPoint = new IPEndPoint(_client.StubIP, 0); - } - - // Compatibility constructor - public FutariSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, int mockID) : - this(FutariClient.Instance, protocolType) { } - - // ListenSocket.open (TCP) - public void Listen(int backlog) { } - - // ListenSocket.open, UdpRecvSocket.open - public void Bind(EndPoint localEndP) - { - if (localEndP is IPEndPoint ep) _client.Bind(_bindPort = ep.Port, _proto); - } - - // Only used in BroadcastSocket - public void SetSocketOption(SocketOptionLevel l, SocketOptionName n, bool o) { } - - // SocketBase.checkRecvEnable, checkSendEnable - // This is the Select step called before blocking calls (e.g. Accept) - public static bool Poll(FutariSocket socket, SelectMode mode) - { - if (mode == SelectMode.SelectRead) - { - return (socket._proto == ProtocolType.Udp) // Check is UDP - ? !socket._client.udpRecvQ.Get(socket._bindPort)?.IsEmpty ?? false - : (socket._streamId == -1) // Check is TCP stream or TCP server - ? !socket._client.acceptQ.Get(socket._bindPort)?.IsEmpty ?? false - : !socket._client.tcpRecvQ.Get(socket._streamId + socket._bindPort)?.IsEmpty ?? false; - } - // Write is always ready? - return mode == SelectMode.SelectWrite; - } - - private static readonly FieldInfo CompletedField = typeof(SocketAsyncEventArgs) - .GetField("Completed", BindingFlags.Instance | BindingFlags.NonPublic); - - // ConnectSocket.Enter_Connect (TCP) - // The destination address is obtained from a RecruitInfo packet sent by the host. - // The host should patch their PartyLink.Util.MyIpAddress() to return a mock address instead of the real one - // Returns true if IO is pending and false if the operation completed synchronously - // When it's false, e will contain the result of the operation - public bool ConnectAsync(SocketAsyncEventArgs e, int mockID) - { - if (e.RemoteEndPoint is not IPEndPoint remote) return false; - var addr = remote.Address.ToU32(); - - // Change Localhost to the local keychip address - if (addr is 2130706433 or 16777343) addr = _client.StubIP.ToU32(); - - // Random stream ID and port - _streamId = new Random().Next(); - _bindPort = new Random().Next(55535, 65535); - - _client.tcpRecvQ[_streamId + _bindPort] = new ConcurrentQueue(); - _client.acceptCallbacks[_streamId + _bindPort] = msg => - { - Log.Info("ConnectAsync: Accept callback, invoking Completed event"); - var events = (MulticastDelegate) CompletedField.GetValue(e); - foreach (var handler in events?.GetInvocationList() ?? Array.Empty()) - { - Log.Debug($"ConnectAsync: Invoking {handler.Method.Name}"); - handler.DynamicInvoke(e, new SocketAsyncEventArgs { SocketError = SocketError.Success }); - } - }; - _client.sendQ.Enqueue(new FutariMsg - { - FutariCmd = FutariCmd.CTL_TCP_CONNECT, - proto = _proto, - sid = _streamId, - src = _client.StubIP.ToU32(), sPort = _bindPort, - dst = addr, dPort = remote.Port - }); - RemoteEndPoint = new IPEndPoint(addr.ToIP(), remote.Port); - return true; - } - - // Accept is blocking - public FutariSocket Accept() - { - // Check if accept queue has any pending connections - if (!_client.acceptQ.TryGetValue(_bindPort, out var q) || - !q.TryDequeue(out var msg) || - msg.sid == null || msg.src == null || msg.sPort == null) - { - Log.Warn("Accept: No pending connections"); - return null; - } - - _client.tcpRecvQ[msg.sid.Value + _bindPort] = new ConcurrentQueue(); - _client.sendQ.Enqueue(new FutariMsg - { - FutariCmd = FutariCmd.CTL_TCP_ACCEPT, proto = _proto, sid = msg.sid, - src = _client.StubIP.ToU32(), sPort = _bindPort, - dst = msg.src, dPort = msg.sPort - }); - - return new FutariSocket(_client, _proto) - { - _streamId = msg.sid.Value, - _bindPort = _bindPort, - RemoteEndPoint = new IPEndPoint(msg.src.Value.ToIP(), msg.sPort.Value) - }; - } - - public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags) - { - if (RemoteEndPoint is not IPEndPoint remote) throw new InvalidOperationException("RemoteEndPoint is not set"); - Log.Debug($"Send: {size} bytes"); - // Remote EP is not relevant here, because the stream is already established, - // there can only be one remote endpoint - _client.sendQ.Enqueue(new FutariMsg - { - FutariCmd = FutariCmd.DATA_SEND, proto = _proto, data = buffer.View(offset, size).B64(), - sid = _streamId == -1 ? null : _streamId, - src = _client.StubIP.ToU32(), sPort = _bindPort, - dst = remote.Address.ToU32(), dPort = remote.Port - }); - return size; - } - - // Only used in BroadcastSocket - public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP) - { - Log.Error("SendTo: Blocked"); - return 0; - - Log.Debug($"SendTo: {size} bytes"); - if (remoteEP is not IPEndPoint remote) return 0; - _client.sendQ.Enqueue(new FutariMsg - { - FutariCmd = FutariCmd.DATA_BROADCAST, proto = _proto, data = buffer.View(offset, size).B64(), - src = _client.StubIP.ToU32(), sPort = _bindPort, - dst = remote.Address.ToU32(), dPort = remote.Port - }); - return size; - } - - // Only used in TCP ConnectSocket - public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode) - { - if (!_client.tcpRecvQ.TryGetValue(_streamId + _bindPort, out var q) || - !q.TryDequeue(out var msg)) - { - Log.Warn("Receive: No data to receive"); - errorCode = SocketError.WouldBlock; - return 0; - } - var data = msg.data!.B64(); - Log.Debug($"Receive: {data.Length} bytes, {q.Count} left in queue"); - - Buffer.BlockCopy(data, 0, buffer, 0, data.Length); - errorCode = SocketError.Success; - return data.Length; - } - - // Only used in UdpRecvSocket to receive from 0 (broadcast) - public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP) - { - Log.Error("ReceiveFrom: Blocked"); - return 0; - - if (!_client.udpRecvQ.TryGetValue(_bindPort, out var q) || - !q.TryDequeue(out var msg)) - { - Log.Warn("ReceiveFrom: No data to receive"); - return 0; - } - var data = msg.data?.B64() ?? Array.Empty(); - Log.Debug($"ReceiveFrom: {data.Length} bytes"); - - // Set remote endpoint to the sender - if (msg.src.HasValue) - remoteEP = new IPEndPoint(msg.src.Value.ToIP(), msg.sPort ?? 0); - - Buffer.BlockCopy(data, 0, buffer, 0, data.Length); - return data.Length; - } - - // Called everywhere, but only relevant for TCP - public void Close() - { - // TCP FIN/RST - if (_proto == ProtocolType.Tcp) - _client.sendQ.Enqueue(new FutariMsg { FutariCmd = FutariCmd.CTL_TCP_CLOSE, proto = _proto }); - } - - public void Shutdown(SocketShutdown how) => Close(); -} \ No newline at end of file + private int _bindPort = -1; + + private readonly FutariClient _client; + + private readonly ProtocolType _proto; + + private int _streamId = -1; + private static int nextStreamId = Guid.NewGuid().GetHashCode() & int.MaxValue; + private static int nextLocalPort; + private byte[] pendingReceive; + private int pendingOffset; + private bool closed; + + private static readonly MethodInfo CompletedMethod = typeof(SocketAsyncEventArgs).GetMethod("OnCompleted", BindingFlags.Instance | BindingFlags.NonPublic); + + public EndPoint LocalEndPoint => new IPEndPoint(_client.StubIP, 0); + + public EndPoint RemoteEndPoint { get; private set; } + + private FutariSocket(FutariClient client, ProtocolType proto) + { + _client = client; + _proto = proto; + RemoteEndPoint = new IPEndPoint(_client.StubIP, 0); + } + + public FutariSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, int mockID) + : this(FutariClient.Instance, protocolType) + { + } + + public void Listen(int backlog) + { + } + + public void Bind(EndPoint localEndP) + { + if (localEndP is IPEndPoint iPEndPoint) + { + _client.Bind(_bindPort = iPEndPoint.Port, _proto); + } + } + + public void SetSocketOption(SocketOptionLevel l, SocketOptionName n, bool o) + { + } + + public static bool Poll(FutariSocket socket, SelectMode mode) + { + if (mode == SelectMode.SelectRead) + { + if (socket._proto != ProtocolType.Udp) + { + if (socket._streamId != -1) + { + long key = FutariClient.ConnectionKey(socket._streamId, socket._bindPort); + if (socket.closed || socket.pendingReceive != null || socket._client.closedStreams.ContainsKey(key)) return true; + ConcurrentQueue? concurrentQueue = socket._client.tcpRecvQ.Get(key); + if (concurrentQueue == null) + { + return false; + } + return !concurrentQueue.IsEmpty; + } + ConcurrentQueue? concurrentQueue2 = socket._client.acceptQ.Get(socket._bindPort); + if (concurrentQueue2 == null) + { + return false; + } + return !concurrentQueue2.IsEmpty; + } + ConcurrentQueue? concurrentQueue3 = socket._client.udpRecvQ.Get(socket._bindPort); + if (concurrentQueue3 == null) + { + return false; + } + return !concurrentQueue3.IsEmpty; + } + return mode == SelectMode.SelectWrite; + } + + public bool ConnectAsync(SocketAsyncEventArgs e, int mockID) + { + if (!(e.RemoteEndPoint is IPEndPoint iPEndPoint)) + { + return false; + } + uint num = iPEndPoint.Address.ToU32(); + if ((num == 16777343 || num == 2130706433) ? true : false) + { + num = _client.StubIP.ToU32(); + } + _streamId = Interlocked.Increment(ref nextStreamId) & int.MaxValue; + _bindPort = 55535 + (Interlocked.Increment(ref nextLocalPort) & int.MaxValue) % 10000; + long connectionKey = FutariClient.ConnectionKey(_streamId, _bindPort); + _client.tcpRecvQ[connectionKey] = new ConcurrentQueue(); + _client.acceptCallbacks[connectionKey] = delegate + { + Log.Info("ConnectAsync: Accept callback, invoking Completed event"); + e.SocketError = SocketError.Success; + CompletedMethod.Invoke(e, new object[] { e }); + }; + _client.sendQ.Enqueue(new FutariMsg + { + FutariCmd = FutariCmd.CTL_TCP_CONNECT, + proto = _proto, + sid = _streamId, + src = _client.StubIP.ToU32(), + sPort = _bindPort, + dst = num, + dPort = iPEndPoint.Port + }); + RemoteEndPoint = new IPEndPoint(num.ToIP(), iPEndPoint.Port); + return true; + } + + public FutariSocket Accept() + { + if (!_client.acceptQ.TryGetValue(_bindPort, out var value) || !value.TryDequeue(out var result) || !result.sid.HasValue || !result.src.HasValue || !result.sPort.HasValue) + { + Log.Warn("Accept: No pending connections"); + return null; + } + _client.tcpRecvQ[FutariClient.ConnectionKey(result.sid.Value, _bindPort)] = new ConcurrentQueue(); + _client.sendQ.Enqueue(new FutariMsg + { + FutariCmd = FutariCmd.CTL_TCP_ACCEPT, + proto = _proto, + sid = result.sid, + src = _client.StubIP.ToU32(), + sPort = _bindPort, + dst = result.src, + dPort = result.sPort + }); + return new FutariSocket(_client, _proto) + { + _streamId = result.sid.Value, + _bindPort = _bindPort, + RemoteEndPoint = new IPEndPoint(result.src.Value.ToIP(), result.sPort.Value) + }; + } + + public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags) + { + if (closed) throw new SocketException((int)SocketError.NotConnected); + if (size == 0) return 0; + if (!(RemoteEndPoint is IPEndPoint iPEndPoint)) + { + throw new InvalidOperationException("RemoteEndPoint is not set"); + } + Log.Debug($"Send: {size} bytes"); + _client.sendQ.Enqueue(new FutariMsg + { + FutariCmd = FutariCmd.DATA_SEND, + proto = _proto, + data = buffer.View(offset, size).B64(), + sid = ((_streamId == -1) ? ((int?)null) : new int?(_streamId)), + src = _client.StubIP.ToU32(), + sPort = _bindPort, + dst = iPEndPoint.Address.ToU32(), + dPort = iPEndPoint.Port + }); + return size; + } + + public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP) + { + Log.Error("SendTo: Blocked"); + return 0; + } + + public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode) + { + if (buffer == null) throw new ArgumentNullException(nameof(buffer)); + if (offset < 0 || size < 0 || offset > buffer.Length - size) throw new ArgumentOutOfRangeException(nameof(size)); + errorCode = SocketError.Success; + if (size == 0 || closed) return 0; + long connectionKey = FutariClient.ConnectionKey(_streamId, _bindPort); + if (pendingReceive == null) + { + if (!_client.tcpRecvQ.TryGetValue(connectionKey, out var queue) || !queue.TryDequeue(out var message)) + { + if (!_client.closedStreams.ContainsKey(connectionKey)) errorCode = SocketError.WouldBlock; + return 0; + } + try { pendingReceive = Convert.FromBase64String(message.data ?? ""); } + catch (FormatException) { errorCode = SocketError.InvalidArgument; return 0; } + pendingOffset = 0; + } + int copied = Math.Min(size, pendingReceive.Length - pendingOffset); + Buffer.BlockCopy(pendingReceive, pendingOffset, buffer, offset, copied); + if ((socketFlags & SocketFlags.Peek) == 0) + { + pendingOffset += copied; + if (pendingOffset == pendingReceive.Length) pendingReceive = null; + } + return copied; + } + + public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP) + { + Log.Error("ReceiveFrom: Blocked"); + return 0; + } + + public void Close() + { + if (closed) return; + closed = true; + pendingReceive = null; + if (_proto == ProtocolType.Tcp && _streamId != -1 && RemoteEndPoint is IPEndPoint remote) + { + _client.sendQ.Enqueue(new FutariMsg + { + FutariCmd = FutariCmd.CTL_TCP_CLOSE, + proto = _proto, + sid = _streamId, + src = _client.StubIP.ToU32(), + sPort = _bindPort, + dst = remote.Address.ToU32(), + dPort = remote.Port + }); + long key = FutariClient.ConnectionKey(_streamId, _bindPort); + _client.tcpRecvQ.TryRemove(key, out _); + _client.acceptCallbacks.TryRemove(key, out _); + _client.closedStreams.TryRemove(key, out _); + } + } + + public void Shutdown(SocketShutdown how) + { + Close(); + } +} diff --git a/mod/WorldLink/GhostSafetyPatch.cs b/mod/WorldLink/GhostSafetyPatch.cs new file mode 100644 index 0000000..b9494a9 --- /dev/null +++ b/mod/WorldLink/GhostSafetyPatch.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using HarmonyLib; +using MAI2.Util; +using Manager; +using Manager.MaiStudio; +using MelonLoader; + +namespace WorldLink +{ + /// + /// Keeps the original downloaded ghosts and skips NPC generation when the + /// boss chart needed by RestoreGhost is absent from the loaded data packs. + /// + public static class GhostSafetyPatch + { + public static void Apply(HarmonyLib.Harmony harmony) + { + MethodInfo target = AccessTools.Method(typeof(Process.PlInformationProcess), + "RestoreGhost", new[] { typeof(int) }); + if (target == null) + throw new MissingMethodException("PlInformationProcess.RestoreGhost(int)"); + + harmony.Patch(target, transpiler: new HarmonyMethod(typeof(GhostSafetyPatch), + nameof(GuardNpcGeneration))); + } + + internal static IEnumerable GuardNpcGeneration( + IEnumerable instructions, ILGenerator generator) + { + var code = instructions.ToList(); + MethodInfo createScore = AccessTools.Method(typeof(NotesListManager), "CreateScore"); + MethodInfo shuffleGhosts = AccessTools.Method(typeof(GhostManager), "GhostRandomSet"); + MethodInfo notesManager = AccessTools.PropertyGetter(typeof(Singleton), "Instance"); + + int[] creationSites = code.Select((instruction, index) => new { instruction, index }) + .Where(item => item.instruction.Calls(createScore)) + .Select(item => item.index).ToArray(); + int[] shuffleSites = code.Select((instruction, index) => new { instruction, index }) + .Where(item => item.instruction.Calls(shuffleGhosts)) + .Select(item => item.index).ToArray(); + + if (creationSites.Length != 1 || shuffleSites.Length != 1) + throw new InvalidOperationException("Unsupported RestoreGhost body: NPC block markers changed."); + + int start = creationSites[0] - 1; + int end = shuffleSites[0] - 1; + if (start < 0 || end <= start || !code[start].Calls(notesManager) || + !IsLocalLoad(code[end])) + throw new InvalidOperationException("Unsupported RestoreGhost body: unsafe NPC branch boundary."); + + Label skipNpc = generator.DefineLabel(); + code[end].labels.Add(skipNpc); + var loadPlayer = new CodeInstruction(OpCodes.Ldarg_1); + loadPlayer.labels.AddRange(code[start].labels); + loadPlayer.blocks.AddRange(code[start].blocks); + code[start].labels.Clear(); + code[start].blocks.Clear(); + code.InsertRange(start, new[] + { + loadPlayer, + new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(GhostSafetyPatch), + nameof(CanGenerateNpcGhosts))), + new CodeInstruction(OpCodes.Brfalse, skipNpc) + }); + return code; + } + + private static bool IsLocalLoad(CodeInstruction instruction) + { + OpCode opcode = instruction.opcode; + return opcode == OpCodes.Ldloc || opcode == OpCodes.Ldloc_S || + opcode == OpCodes.Ldloc_0 || opcode == OpCodes.Ldloc_1 || + opcode == OpCodes.Ldloc_2 || opcode == OpCodes.Ldloc_3; + } + + internal static bool CanGenerateNpcGhosts(int playerIndex) + { + UserData user = Singleton.Instance.GetUserData(playerIndex); + if (user == null || user.RatingList == null || user.RatingList.Udemae == null) + { + MelonLogger.Warning("[NyanLink] Skipped NPC ghost generation: player rating data is unavailable."); + return false; + } + + int bossId = Manager.UserDatas.UserUdemae.GetRateToUdemaeID( + user.RatingList.Udemae.ClassValue).GetNpcParamBoss(); + DataManager data = Singleton.Instance; + UdemaeBossData boss = data.GetUdemaeBoss(bossId); + MusicData primaryMusic = boss?.music == null ? null : data.GetMusic(boss.music.id); + UdemaeBossData fallbackBoss = null; + MusicData fallbackMusic = null; + if (boss != null && primaryMusic == null) + { + fallbackBoss = data.GetUdemaeBoss(Math.Max(bossId - 1, 0)); + if (fallbackBoss?.music != null) + fallbackMusic = data.GetMusic(fallbackBoss.music.id); + } + + bool available = HasNpcSource(boss, primaryMusic, fallbackBoss, fallbackMusic); + if (!available) + { + MelonLogger.Warning("[NyanLink] Skipped NPC ghost generation: boss " + bossId + + " has no usable primary or fallback chart. Downloaded ghosts are retained."); + } + return available; + } + + internal static bool HasNpcSource(UdemaeBossData boss, MusicData primaryMusic, + UdemaeBossData fallbackBoss, MusicData fallbackMusic) + { + if (boss?.music == null || boss.difficulty == null) + return false; + + // RestoreGhost retains the original difficulty even when it falls + // back to the preceding boss. Validate precisely that access. + MusicData music = primaryMusic ?? fallbackMusic; + UdemaeBossData chosenBoss = primaryMusic == null ? fallbackBoss : boss; + int difficulty = boss.difficulty.id; + if (chosenBoss?.music == null || chosenBoss.daniId == null || music?.notesData == null || + difficulty < 0 || difficulty >= music.notesData.Count) + return false; + + Notes notes = music.notesData[difficulty]; + return notes != null && notes.isEnable; + } + } +} diff --git a/mod/WorldLink/LiveScoreCanvasRenderer.cs b/mod/WorldLink/LiveScoreCanvasRenderer.cs new file mode 100644 index 0000000..908d435 --- /dev/null +++ b/mod/WorldLink/LiveScoreCanvasRenderer.cs @@ -0,0 +1,332 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Monitor.Game; +using Process; +using UnityEngine; + +namespace WorldLink +{ + // Keep the judgement-counter sorting settings, but render geometry through + // the same scene-renderer/material path as slide arrows instead of UI batching. + internal sealed class LiveScoreCanvasRenderer + { + private static readonly FieldInfo MonitorsField = typeof(GameProcess).GetField("_monitors", BindingFlags.Instance | BindingFlags.NonPublic); + private static readonly FieldInfo MainField = typeof(MonitorBase).GetField("Main", BindingFlags.Instance | BindingFlags.NonPublic); + private static readonly FieldInfo ControllerField = typeof(Monitor.GameMonitor).GetField("GameController", BindingFlags.Instance | BindingFlags.NonPublic); + private static readonly FieldInfo ArrowsField = typeof(GameCtrl).GetField("_activeArrowList", BindingFlags.Instance | BindingFlags.NonPublic); + private static readonly Color[] Accents = { + new Color(0.32f, 0.90f, 0.94f, 0.5f), new Color(0.72f, 0.60f, 1f, 0.5f), + new Color(1f, 0.78f, 0.43f, 0.5f), new Color(1f, 0.53f, 0.70f, 0.5f) }; + private readonly Row[] cards = new Row[4]; + private readonly List graphics = new List(20); + private GameObject root; + private RectTransform main; + private Font ownedFont; + private Vector2 layoutSize; + private bool logged; + private Canvas indicatorCanvas; + private Material fontMaterial; + private Material barMaterial; + private Component gameController; + private int fontRevision; + private bool arrowLogged; + + private sealed class Row + { + public RectTransform Container; + public LiveScoreMeshLabel Name; + public LiveScoreMeshLabel Score; + public LiveScoreMeshLabel Rank; + public RectTransform Bar; + public LiveScoreMeshBar Filled; + public LiveScoreMeshBar Remaining; + public LiveScoreSample Previous; + public string LastName; + public decimal LastAchievement; + public int LastRank; + } + + public LiveScoreCanvasRenderer(GameProcess owner) + { + try { Create(owner); } + catch { try { Release(); } catch { } throw; } + } + + private void Create(GameProcess owner) + { + Array monitors = MonitorsField == null ? null : MonitorsField.GetValue(owner) as Array; + object first = monitors == null || monitors.Length == 0 ? null : monitors.GetValue(0); + var group = first == null || MainField == null ? null : MainField.GetValue(first) as CanvasGroup; + main = group == null ? null : group.transform as RectTransform; + if (main == null) throw new InvalidOperationException("1P Main canvas is unavailable."); + gameController = ControllerField == null ? null : ControllerField.GetValue(first) as Component; + var indicator = main.GetComponentsInChildren(true).SingleOrDefault(); + indicatorCanvas = indicator == null ? null : indicator.GetComponent(); + if (indicatorCanvas == null || indicatorCanvas.renderMode != RenderMode.WorldSpace) + throw new InvalidOperationException("1P judgement-counter world-space Canvas is unavailable."); + Camera camera = Camera.main; + if (camera == null) throw new InvalidOperationException("Game camera is unavailable."); + + root = new GameObject("WorldLink Live Scores 2x2", typeof(RectTransform)); + root.SetActive(false); + root.layer = indicator.gameObject.layer; + var rect = (RectTransform)root.transform; + rect.SetParent(main, false); + rect.anchorMin = Vector2.zero; + rect.anchorMax = Vector2.one; + rect.offsetMin = Vector2.zero; + rect.offsetMax = Vector2.zero; + // Match the indicator's actual depth as well as its sorting settings. + var position = rect.localPosition; + position.z = main.InverseTransformPoint(indicator.transform.position).z; + rect.localPosition = position; + ownedFont = Font.CreateDynamicFontFromOSFont(new[] { "Microsoft YaHei", "Microsoft YaHei UI", "Arial" }, 32); + if (ownedFont == null) throw new InvalidOperationException("No scoreboard font is available."); + Font.textureRebuilt += OnFontTextureRebuilt; + SpriteRenderer arrowPrefab = GameNotePrefabContainer.Arrow; + if (arrowPrefab == null || arrowPrefab.sharedMaterial == null) + throw new InvalidOperationException("Slide-arrow render material is unavailable."); + // Dynamic fonts use an alpha-only atlas. Keep Unity's own font + // sampling shader so glyphs retain their color, but put its scene + // renderer into the same transparent queue as the slide arrows. + fontMaterial = new Material(ownedFont.material) { + name = "WorldLink Score Font", renderQueue = arrowPrefab.sharedMaterial.renderQueue + }; + if (fontMaterial.HasProperty("_Color")) fontMaterial.SetColor("_Color", Color.white); + barMaterial = CopySpriteMaterial(arrowPrefab.sharedMaterial, "WorldLink Score Progress"); + barMaterial.mainTexture = Texture2D.whiteTexture; + + for (int index = 0; index < cards.Length; index++) + { + var card = new Row(); + cards[index] = card; + card.Container = NewRect("Player " + index, rect); + card.Name = NewText("Name", card.Container, FontStyle.Normal, new Color(0.87f, 0.91f, 0.97f, 0.5f)); + card.Score = NewText("Achievement", card.Container, FontStyle.Bold, new Color(1f, 1f, 1f, 0.5f)); + card.Rank = NewText("Rank", card.Container, FontStyle.Bold, Color.white); + // YaHei's line height exceeds 1.3 em. Numeric rows must never + // disappear because Unity truncates a slightly taller font line. + card.Score.horizontalOverflow = card.Rank.horizontalOverflow = HorizontalWrapMode.Overflow; + card.Score.verticalOverflow = card.Rank.verticalOverflow = VerticalWrapMode.Overflow; + card.Bar = NewRect("Progress", card.Container); + card.Filled = NewImage("Earned", card.Bar, Color.white); + card.Remaining = NewImage("Remaining", card.Bar, new Color(0.35f, 0.40f, 0.46f, 0.5f)); + card.Container.gameObject.SetActive(false); + } + } + + private RectTransform NewRect(string name, Transform parent) + { + var obj = new GameObject(name, typeof(RectTransform)); + obj.layer = root.layer; + var rect = (RectTransform)obj.transform; + rect.SetParent(parent, false); + return rect; + } + + private LiveScoreMeshLabel NewText(string name, Transform parent, FontStyle style, Color color) + { + var rect = NewRect(name, parent); + var text = new LiveScoreMeshLabel(rect, fontMaterial, style, color); + graphics.Add(text); + return text; + } + + private LiveScoreMeshBar NewImage(string name, Transform parent, Color color) + { + var rect = NewRect(name, parent); + var image = new LiveScoreMeshBar(rect, barMaterial, color); + graphics.Add(image); + return image; + } + + private static Material CopySpriteMaterial(Material source, string name) + { + var result = new Material(source) { name = name, renderQueue = source.renderQueue }; + if (result.HasProperty("_Color")) result.SetColor("_Color", Color.white); + if (result.HasProperty("_RendererColor")) result.SetColor("_RendererColor", Color.white); + if (result.HasProperty("_EnableExternalAlpha")) result.SetFloat("_EnableExternalAlpha", 0f); + result.DisableKeyword("ETC1_EXTERNAL_ALPHA"); + result.DisableKeyword("PIXELSNAP_ON"); + return result; + } + + private void OnFontTextureRebuilt(Font changed) + { + if (changed == ownedFont) fontRevision++; + } + + public void Show(LiveScoreSample[] rows) + { + if (root == null || main == null) throw new InvalidOperationException("Scoreboard canvas was destroyed."); + if (rows.Length < 2 || rows.Length > 4) { Hide(); return; } + Vector2 size = main.rect.size; + if (size.x <= 0f || size.y <= 0f) throw new InvalidOperationException("1P Main canvas has no visible area."); + if (layoutSize != size) Layout(size); + int occupied = 0; + foreach (LiveScoreSample row in rows) + occupied |= 1 << (row.Slot == 0 ? 0 : row.Slot - 1); + for (int index = 0; index < cards.Length; index++) + { + bool active = (occupied & (1 << index)) != 0; + if (cards[index].Container.gameObject.activeSelf != active) + cards[index].Container.gameObject.SetActive(active); + } + foreach (LiveScoreSample row in rows) + { + int index = row.Slot == 0 ? 0 : row.Slot - 1; + Row card = cards[index]; + Color accent = Accents[index]; + if (ReferenceEquals(card.Previous, row)) continue; + bool first = card.Previous == null; + card.Previous = row; + if (first || card.LastName != row.Name) + card.Name.text = (index + 1) + "P · " + row.Name; + if (first || card.LastAchievement != row.Achievement) + card.Score.text = LiveScoreModel.FormatAchievement(row.Achievement); + if (first || card.LastRank != row.Rank) + card.Rank.text = (row.Slot == 0 ? "YOU · " : "") + LiveScoreModel.FormatRank(row.Rank); + card.LastName = row.Name; card.LastAchievement = row.Achievement; card.LastRank = row.Rank; + card.Rank.color = accent; + card.Filled.color = accent; + float fraction = Mathf.Clamp01((float)(row.Achievement / 101m)); + // Adjacent segments avoid stacking two 50%-alpha images. + Stretch(card.Filled.rectTransform, 0f, fraction); + Stretch(card.Remaining.rectTransform, fraction, 1f); + } + foreach (var graphic in graphics) graphic.Prepare(ownedFont); + // Font atlas growth can invalidate UVs. Prepare all glyphs first, then + // rebuild every affected label using the same atlas revision. + for (int attempt = 0; attempt < 2; attempt++) + { + int revision = fontRevision; + fontMaterial.mainTexture = ownedFont.material.mainTexture; + foreach (var graphic in graphics) graphic.Render(ownedFont, revision); + if (revision == fontRevision) break; + if (attempt == 1) throw new InvalidOperationException("Scoreboard font atlas did not stabilize."); + } + if (!root.activeSelf) root.SetActive(true); + SynchronizeIndicatorSorting(); + if (!logged) + { + logged = true; + MelonLoader.MelonLogger.Msg("[NyanLink HUD] Live scoreboard visible: " + rows.Length + + " players; renderer=MeshRenderer; reference=" + indicatorCanvas.name + "; layer=" + graphics[0].Renderer.sortingLayerName + + "; order=" + graphics[0].Renderer.sortingOrder + "; referenceLayer=" + indicatorCanvas.sortingLayerName + + "; referenceOrder=" + indicatorCanvas.sortingOrder + "; shader=" + fontMaterial.shader.name + "; queue=" + fontMaterial.renderQueue + + "; sortingVerified=true; localZ=" + root.transform.localPosition.z + + "; layout=1P,2P/3P,4P; center=50%,60%; noteMask=off; textAlpha=0.5 barAlpha=0.5; background=none; mainSize=" + size); + } + LogActiveArrow(); + } + + private void SynchronizeIndicatorSorting() + { + if (indicatorCanvas == null) + throw new InvalidOperationException("Judgement-counter rendering reference was destroyed."); + foreach (var graphic in graphics) + { + var renderer = graphic.Renderer; + if (renderer.sortingLayerID != indicatorCanvas.sortingLayerID) renderer.sortingLayerID = indicatorCanvas.sortingLayerID; + if (renderer.sortingOrder != indicatorCanvas.sortingOrder) renderer.sortingOrder = indicatorCanvas.sortingOrder; + if (renderer.sortingLayerID != indicatorCanvas.sortingLayerID || renderer.sortingOrder != indicatorCanvas.sortingOrder) + throw new InvalidOperationException("Scoreboard rendering order does not match the judgement counter."); + } + } + + private void LogActiveArrow() + { + if (arrowLogged || gameController == null || ArrowsField == null) return; + var arrows = ArrowsField.GetValue(gameController) as IList; + if (arrows == null) return; + foreach (object item in arrows) + { + var arrow = item as SpriteRenderer; + if (arrow == null || !arrow.enabled || !arrow.gameObject.activeInHierarchy || arrow.color.a <= 0.01f) continue; + var material = arrow.sharedMaterial; + MelonLoader.MelonLogger.Msg("[NyanLink HUD] Active slide comparison: layer=" + arrow.sortingLayerName + + "; layerValue=" + SortingLayer.GetLayerValueFromID(arrow.sortingLayerID) + "; order=" + arrow.sortingOrder + + "; shader=" + (material == null ? "null" : material.shader.name) + "; queue=" + (material == null ? -1 : material.renderQueue) + + "; worldZ=" + arrow.transform.position.z + "; objectLayer=" + arrow.gameObject.layer + + "; HUDlayerValue=" + SortingLayer.GetLayerValueFromID(graphics[0].Renderer.sortingLayerID) + + "; HUDworldZ=" + root.transform.position.z + "; HUDobjectLayer=" + root.layer); + arrowLogged = true; + break; + } + } + + private void Layout(Vector2 area) + { + layoutSize = area; + // Preserve the previous four-player card and font sizes. Reflow the + // same four cells into two rows instead of enlarging two columns. + float previousWidth = area.x * 0.84f; + float previousGap = Mathf.Max(2f, previousWidth * 0.007f); + float cardWidth = (previousWidth - 3f * previousGap) / 4f; + int fontSize = Mathf.Clamp(Mathf.RoundToInt(cardWidth * 0.125f), 12, 32); + float height = fontSize * 3.15f; + float gap = fontSize * 0.75f; + float rowGap = fontSize * 0.45f; + float width = cardWidth * 2f + gap; + float left = (area.x - width) * 0.5f; + float top = area.y * 0.60f - (2f * height + rowGap) * 0.5f; + float padding = fontSize * 0.38f; + for (int index = 0; index < cards.Length; index++) + { + Row card = cards[index]; + Place(card.Container, left + (index % 2) * (cardWidth + gap), top + (index / 2) * (height + rowGap), cardWidth, height); + card.Name.fontSize = Mathf.Max(8, Mathf.RoundToInt(fontSize * 0.62f)); + card.Score.fontSize = fontSize; + card.Rank.fontSize = Mathf.Max(8, Mathf.RoundToInt(fontSize * 0.55f)); + Place(card.Name.rectTransform, padding, fontSize * 0.15f, cardWidth - 2f * padding, fontSize * 0.9f); + Place(card.Score.rectTransform, padding, fontSize * 0.94f, cardWidth - 2f * padding, fontSize * 1.3f); + Place(card.Rank.rectTransform, padding, fontSize * 2.17f, cardWidth - 2f * padding, fontSize * 0.8f); + Place(card.Bar, padding, height - Mathf.Max(2f, fontSize * 0.1f), cardWidth - 2f * padding, Mathf.Max(1.5f, fontSize * 0.07f)); + } + } + + private static void Place(RectTransform rect, float x, float y, float width, float height) + { + rect.anchorMin = rect.anchorMax = new Vector2(0f, 1f); + rect.pivot = new Vector2(0f, 1f); + rect.anchoredPosition = new Vector2(x, -y); + rect.sizeDelta = new Vector2(width, height); + } + + private static void Stretch(RectTransform rect, float left, float right) + { + rect.anchorMin = new Vector2(left, 0f); + rect.anchorMax = new Vector2(right, 1f); + rect.offsetMin = rect.offsetMax = Vector2.zero; + } + + public void Hide() { if (root != null && root.activeSelf) root.SetActive(false); } + + public void Release() + { + try + { + if (root != null) { root.SetActive(false); UnityEngine.Object.Destroy(root); } + } + finally + { + root = null; + main = null; + indicatorCanvas = null; + gameController = null; + Font.textureRebuilt -= OnFontTextureRebuilt; + foreach (var graphic in graphics) graphic.Release(); + graphics.Clear(); + if (fontMaterial != null) UnityEngine.Object.Destroy(fontMaterial); + if (barMaterial != null) UnityEngine.Object.Destroy(barMaterial); + fontMaterial = null; + barMaterial = null; + if (ownedFont != null) UnityEngine.Object.Destroy(ownedFont); + ownedFont = null; + } + } + } +} diff --git a/mod/WorldLink/LiveScoreMeshGraphic.cs b/mod/WorldLink/LiveScoreMeshGraphic.cs new file mode 100644 index 0000000..bd1732c --- /dev/null +++ b/mod/WorldLink/LiveScoreMeshGraphic.cs @@ -0,0 +1,138 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering; + +namespace WorldLink +{ + // Use normal scene renderers and the slide's sprite material, never a UI + // CanvasRenderer. This keeps text, bars and slide arrows in the same queue. + internal abstract class LiveScoreMeshGraphic + { + public readonly RectTransform rectTransform; + public readonly MeshRenderer Renderer; + protected readonly Mesh mesh; + public Color color; + + protected LiveScoreMeshGraphic(RectTransform rect, Material material, Color color) + { + rectTransform = rect; + this.color = color; + mesh = new Mesh { name = "WorldLink " + rect.name }; + mesh.MarkDynamic(); + rect.gameObject.AddComponent().sharedMesh = mesh; + Renderer = rect.gameObject.AddComponent(); + Renderer.sharedMaterial = material; + Renderer.shadowCastingMode = ShadowCastingMode.Off; + Renderer.receiveShadows = false; + Renderer.lightProbeUsage = LightProbeUsage.Off; + Renderer.reflectionProbeUsage = ReflectionProbeUsage.Off; + } + + public virtual void Prepare(Font font) { } + public abstract void Render(Font font, int fontRevision); + public virtual void Release() { if (mesh != null) UnityEngine.Object.Destroy(mesh); } + } + + internal sealed class LiveScoreMeshLabel : LiveScoreMeshGraphic + { + public string text = ""; + public int fontSize; + public readonly FontStyle fontStyle; + public HorizontalWrapMode horizontalOverflow = HorizontalWrapMode.Wrap; + public VerticalWrapMode verticalOverflow = VerticalWrapMode.Truncate; + private readonly TextGenerator generator = new TextGenerator(); + private string previousText; + private int previousSize; + private int previousRevision = -1; + private Vector2 previousExtents; + private Color previousColor; + private Vector3[] positions = new Vector3[0]; + private Vector2[] uvs = new Vector2[0]; + private Color32[] colors = new Color32[0]; + private int[] triangles = new int[0]; + + public LiveScoreMeshLabel(RectTransform rect, Material material, FontStyle style, Color color) + : base(rect, material, color) { fontStyle = style; } + + public override void Prepare(Font font) + { + if (!string.IsNullOrEmpty(text)) font.RequestCharactersInTexture(text, fontSize, fontStyle); + } + + public override void Render(Font font, int fontRevision) + { + Vector2 extents = rectTransform.rect.size; + if (previousText == text && previousSize == fontSize && previousRevision == fontRevision + && previousExtents == extents && previousColor == color) return; + if (previousRevision != fontRevision) generator.Invalidate(); + // Match the supplied Unity UI.Text generation settings and local units. + var settings = new TextGenerationSettings { + font = font, fontSize = fontSize, fontStyle = fontStyle, + color = color, textAnchor = TextAnchor.MiddleCenter, + generationExtents = extents, pivot = rectTransform.pivot, + scaleFactor = 1f, lineSpacing = 1f, richText = false, + resizeTextForBestFit = false, updateBounds = false, + horizontalOverflow = horizontalOverflow, verticalOverflow = verticalOverflow + }; + if (!generator.Populate(text ?? "", settings)) + throw new InvalidOperationException("Cannot generate scoreboard text mesh."); + var vertices = generator.verts; + int count = Math.Max(0, vertices.Count - 4); // Unity's trailing dummy quad. + if ((count & 3) != 0) throw new InvalidOperationException("Invalid font vertex count."); + if (positions.Length != count) + { + positions = new Vector3[count]; uvs = new Vector2[count]; colors = new Color32[count]; + triangles = new int[count / 4 * 6]; + for (int quad = 0; quad < count / 4; quad++) + { + int vertex = quad * 4, index = quad * 6; + triangles[index] = vertex; triangles[index + 1] = vertex + 1; triangles[index + 2] = vertex + 2; + triangles[index + 3] = vertex + 2; triangles[index + 4] = vertex + 3; triangles[index + 5] = vertex; + } + } + for (int i = 0; i < count; i++) + { positions[i] = vertices[i].position; uvs[i] = vertices[i].uv0; colors[i] = vertices[i].color; } + mesh.Clear(); + if (count > 0) + { + mesh.vertices = positions; mesh.uv = uvs; mesh.colors32 = colors; + mesh.triangles = triangles; mesh.RecalculateBounds(); + } + previousText = text; previousSize = fontSize; previousRevision = fontRevision; + previousExtents = extents; previousColor = color; + } + + public override void Release() + { + ((IDisposable)generator).Dispose(); + base.Release(); + } + } + + internal sealed class LiveScoreMeshBar : LiveScoreMeshGraphic + { + private Rect previousRect; + private Color previousColor; + private bool initialized; + private readonly Vector3[] positions = new Vector3[4]; + private readonly Color32[] colors = new Color32[4]; + private static readonly Vector2[] Uvs = { Vector2.zero, Vector2.up, Vector2.one, Vector2.right }; + private static readonly int[] Triangles = { 0, 1, 2, 2, 3, 0 }; + + public LiveScoreMeshBar(RectTransform rect, Material material, Color color) : base(rect, material, color) { } + + public override void Render(Font font, int fontRevision) + { + Rect rect = rectTransform.rect; + if (initialized && rect == previousRect && color == previousColor) return; + positions[0] = new Vector3(rect.xMin, rect.yMin, 0f); + positions[1] = new Vector3(rect.xMin, rect.yMax, 0f); + positions[2] = new Vector3(rect.xMax, rect.yMax, 0f); + positions[3] = new Vector3(rect.xMax, rect.yMin, 0f); + for (int i = 0; i < colors.Length; i++) colors[i] = color; + mesh.Clear(); mesh.vertices = positions; mesh.uv = Uvs; mesh.colors32 = colors; + mesh.triangles = Triangles; mesh.RecalculateBounds(); + previousRect = rect; previousColor = color; initialized = true; + } + } +} diff --git a/mod/WorldLink/LiveScoreModel.cs b/mod/WorldLink/LiveScoreModel.cs new file mode 100644 index 0000000..17e3a15 --- /dev/null +++ b/mod/WorldLink/LiveScoreModel.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace WorldLink +{ + public sealed class LiveScoreSample + { + public int Slot; + public string Name; + public decimal Achievement; + public int Rank; + public bool Connected; + } + + // Track-scoped view state. Values are copied exactly, never interpolated or + // forced to increase. The game remains the sole source of achievements/ranks. + public sealed class LiveScoreModel + { + public bool Active { get; private set; } + private readonly LiveScoreSample[] pending = new LiveScoreSample[4]; + private readonly string[] rawNames = new string[4]; + private readonly string[] cleanNames = new string[4]; + public LiveScoreSample[] Rows { get; private set; } = new LiveScoreSample[0]; + + public void BeginTrack(bool partyPlay) + { + Rows = new LiveScoreSample[0]; + Active = partyPlay; + } + + public void EndTrack() + { + Active = false; + Rows = new LiveScoreSample[0]; + } + + public void Publish(IEnumerable samples) + { + if (!Active) return; + Array.Clear(pending, 0, pending.Length); + int count = 0; + if (samples != null) foreach (var sample in samples) + { + if (sample == null || !(sample.Slot == 0 || sample.Slot >= 2 && sample.Slot <= 4)) continue; + int index = sample.Slot == 0 ? 0 : sample.Slot - 1; + if (pending[index] != null) throw new ArgumentException("Duplicate live-score player slot"); + pending[index] = sample; count++; + } + bool changed = Rows.Length != count; + int rowIndex = 0; + for (int i = 0; i < pending.Length; i++) + { + var sample = pending[i]; if (sample == null) continue; + if (cleanNames[i] == null || rawNames[i] != sample.Name) + { rawNames[i] = sample.Name; cleanNames[i] = CleanName(sample.Name); } + var old = rowIndex < Rows.Length ? Rows[rowIndex] : null; + changed |= old == null || old.Slot != sample.Slot || old.Name != cleanNames[i] + || old.Achievement != sample.Achievement || old.Rank != sample.Rank || old.Connected != sample.Connected; + rowIndex++; + } + if (!changed) return; + var next = new LiveScoreSample[count]; rowIndex = 0; + for (int i = 0; i < pending.Length; i++) + { + var sample = pending[i]; if (sample == null) continue; + next[rowIndex++] = new LiveScoreSample { Slot = sample.Slot, Name = cleanNames[i], + Achievement = sample.Achievement, Rank = sample.Rank, Connected = sample.Connected }; + } + Rows = next; + } + + public static string FormatAchievement(decimal value) + { + return value.ToString("0.0000", CultureInfo.InvariantCulture) + "%"; + } + + public static string FormatRank(int rank) + { + switch (rank) { case 1: return "1st"; case 2: return "2nd"; case 3: return "3rd"; case 4: return "4th"; default: return "--"; } + } + + private static string CleanName(string name) + { + string result = new string((name ?? "").Where(character => !char.IsControl(character)).Take(32).ToArray()); + return result.Length == 0 ? "PLAYER" : result; + } + } +} diff --git a/mod/WorldLink/LiveScoreOverlay.cs b/mod/WorldLink/LiveScoreOverlay.cs new file mode 100644 index 0000000..d0ea546 --- /dev/null +++ b/mod/WorldLink/LiveScoreOverlay.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using MAI2.Util; +using Manager; +using Process; + +namespace WorldLink +{ + public static class LiveScoreOverlay + { + private static readonly LiveScoreModel Model = new LiveScoreModel(); + private static readonly int[] Slots = { 0, 2, 3, 4 }; + private static readonly FieldInfo SequenceField = AccessTools.Field(typeof(GameProcess), "_sequence"); + private static GameProcess owner; + private static LiveScoreCanvasRenderer renderer; + private static bool visible; + private static bool faultReported; + private static readonly List Samples = new List(4); + private static readonly LiveScoreSample[] SlotSamples = { new LiveScoreSample(), new LiveScoreSample(), new LiveScoreSample(), new LiveScoreSample() }; + + public static void Apply(HarmonyLib.Harmony harmony) + { + if (SequenceField == null) throw new MissingFieldException("GameProcess._sequence"); + harmony.Patch(AccessTools.Method(typeof(GameProcess), "OnStart"), postfix: H(nameof(Begin))); + var update = H(nameof(Update)); + update.priority = Priority.Last; + harmony.Patch(AccessTools.Method(typeof(GameProcess), "OnUpdate"), postfix: update); + harmony.Patch(AccessTools.Method(typeof(GameProcess), "OnRelease"), prefix: H(nameof(End))); + harmony.Patch(AccessTools.Method(typeof(GameManager), "Clear"), postfix: H(nameof(Reset))); + } + + private static HarmonyMethod H(string name) { return new HarmonyMethod(typeof(LiveScoreOverlay), name); } + + private static void Begin(GameProcess __instance) + { + Reset(); + owner = __instance; + try + { + var party = Manager.Party.Party.Party.Get(); + Model.BeginTrack(party != null && party.IsJoinAndActive()); + } + catch (Exception error) { ReportFault(error); } + } + + private static void Update(GameProcess __instance) + { + if (!ReferenceEquals(owner, __instance) || !Model.Active) return; + try + { + // Actual game sequence: Start=2, StartWait=3, Play=4, PlayEnd=5. + int sequence = Convert.ToInt32(SequenceField.GetValue(__instance)); + visible = sequence >= 2 && sequence <= 5; + if (!visible) { if (renderer != null) renderer.Hide(); return; } + var manager = Singleton.Instance; + var users = Singleton.Instance; + Samples.Clear(); + for (int index = 0; index < Slots.Length; index++) + { + int slot = Slots[index]; + var user = users.GetUserData(slot); + var score = manager.GetGameScore(slot); + if (user == null || !user.IsEntry || score == null || !score.IsEnable || !score.IsHuman() || score.IsTrial()) continue; + var sample = SlotSamples[index]; + sample.Slot = slot; sample.Name = score.UserName; + sample.Achievement = score.GetAchivement(); sample.Rank = score.VsRank <= 4 ? (int)score.VsRank : 0; sample.Connected = true; + Samples.Add(sample); + } + Model.Publish(Samples); + visible = Model.Rows.Length >= 2; + if (visible) + { + if (renderer == null) renderer = new LiveScoreCanvasRenderer(owner); + renderer.Show(Model.Rows); + } + else if (renderer != null) renderer.Hide(); + } + catch (Exception error) { ReportFault(error); } + } + + private static void End(GameProcess __instance) + { + if (ReferenceEquals(owner, __instance)) Reset(); + } + + private static void ReleaseRenderer() + { + var previous = renderer; + renderer = null; + if (previous != null) + { + try { previous.Release(); } + catch (Exception error) { MelonLoader.MelonLogger.Warning("[NyanLink HUD] Cleanup: " + error.Message); } + } + } + + public static void Reset() + { + owner = null; + visible = false; + faultReported = false; + Model.EndTrack(); + ReleaseRenderer(); + } + + private static void ReportFault(Exception error) + { + visible = false; + Model.EndTrack(); + ReleaseRenderer(); + if (faultReported) return; + faultReported = true; + MelonLoader.MelonLogger.Warning("[NyanLink HUD] Display disabled for this track: " + error.GetType().Name + ": " + error.Message); + } + } +} diff --git a/mod/WorldLink/LiveScoreViewport.cs b/mod/WorldLink/LiveScoreViewport.cs new file mode 100644 index 0000000..e1a7a0d --- /dev/null +++ b/mod/WorldLink/LiveScoreViewport.cs @@ -0,0 +1,108 @@ +using System; +using System.Reflection; +using Process; +using UnityEngine; + +namespace WorldLink +{ + // IMGUI uses top-left coordinates; WorldToScreenPoint uses bottom-left. + // Resolve the existing 1P play area without creating or changing any Canvas. + public static class LiveScoreViewport + { + private static readonly FieldInfo MonitorsField = typeof(GameProcess).GetField("_monitors", BindingFlags.Instance | BindingFlags.NonPublic); + private static readonly FieldInfo MainField = typeof(MonitorBase).GetField("Main", BindingFlags.Instance | BindingFlags.NonPublic); + private static readonly Vector3[] Corners = new Vector3[4]; + + public static Rect Resolve(GameProcess owner) + { + int width; + int height; + try { width = Screen.width; height = Screen.height; } + catch { return new Rect(0f, 0f, 1f, 1f); } + if (width <= 0 || height <= 0) return new Rect(0f, 0f, Math.Max(1, width), Math.Max(1, height)); + + Camera camera = null; + try { camera = Camera.main; } + catch { } + try + { + if (owner != null && camera != null && MonitorsField != null && MainField != null) + { + Array monitors = MonitorsField.GetValue(owner) as Array; + if (monitors != null && monitors.Length > 0) + { + object first = monitors.GetValue(0); + CanvasGroup main = first == null ? null : MainField.GetValue(first) as CanvasGroup; + RectTransform transform = main == null ? null : main.transform as RectTransform; + if (transform != null) + { + transform.GetWorldCorners(Corners); + float left = float.PositiveInfinity; + float right = float.NegativeInfinity; + float top = float.PositiveInfinity; + float bottom = float.NegativeInfinity; + bool usable = true; + for (int i = 0; i < Corners.Length; i++) + { + Vector3 point = camera.WorldToScreenPoint(Corners[i]); + if (!Finite(point.x) || !Finite(point.y) || !Finite(point.z) || point.z <= 0f) + { usable = false; break; } + float guiY = height - point.y; + left = Math.Min(left, point.x); + right = Math.Max(right, point.x); + top = Math.Min(top, guiY); + bottom = Math.Max(bottom, guiY); + } + Rect clipped; + if (usable && TryClip(new Rect(left, top, right - left, bottom - top), width, height, out clipped)) + return clipped; + } + } + } + } + catch + { + // A monitor may be destroyed between scene teardown callbacks. + // The HUD must never turn a cosmetic failure into a game exception. + } + + float orthographicSize = 960f; + try + { + if (camera != null && camera.orthographic && Finite(camera.orthographicSize) && camera.orthographicSize > 0f) + orthographicSize = camera.orthographicSize; + } + catch { } + + // AquaMai SinglePlayer retains the original 1080-square main area at + // the bottom of a 1920-high view (orthographicSize=960). HideSubMonitor + // changes the size to 540, making that main area span the full height. + float projectedSize = height * (1080f / (2f * orthographicSize)); + float mainWidth = Math.Min(width, projectedSize); + float mainHeight = Math.Min(height, projectedSize); + Rect fallback; + if (TryClip(new Rect((width - mainWidth) * 0.5f, height - mainHeight, mainWidth, mainHeight), width, height, out fallback)) + return fallback; + return new Rect(0f, 0f, width, height); + } + + private static bool Finite(float value) + { + return !float.IsNaN(value) && !float.IsInfinity(value); + } + + private static bool TryClip(Rect value, int screenWidth, int screenHeight, out Rect clipped) + { + clipped = default(Rect); + if (!Finite(value.x) || !Finite(value.y) || !Finite(value.width) || !Finite(value.height) + || value.width <= 0f || value.height <= 0f) return false; + float left = Math.Max(0f, value.xMin); + float right = Math.Min(screenWidth, value.xMax); + float top = Math.Max(0f, value.yMin); + float bottom = Math.Min(screenHeight, value.yMax); + if (right - left < 1f || bottom - top < 1f) return false; + clipped = new Rect(left, top, right - left, bottom - top); + return true; + } + } +} diff --git a/mod/WorldLink/LobbyRecruitSync.cs b/mod/WorldLink/LobbyRecruitSync.cs new file mode 100644 index 0000000..1ff83d1 --- /dev/null +++ b/mod/WorldLink/LobbyRecruitSync.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Text; +using System.Threading; +using HarmonyLib; +using Manager.Party.Party; +using PartyLink; +using UnityEngine; + +namespace WorldLink +{ + // The HTTP worker owns only text. Game objects, JSON decoding and Packet's shared + // serialization buffers are accessed exclusively by the Client.Update thread. + internal sealed class LobbySnapshotMailbox + { + private readonly object gate = new object(); + private readonly int ownerThread = Thread.CurrentThread.ManagedThreadId; + private string pending; + private bool closed; + + public bool Publish(string text) + { + if (text == null) return false; // Failure is not an empty, successful snapshot. + lock (gate) + { + if (closed) return false; + pending = text; // Bounded: replace an unconsumed snapshot with the newest one. + return true; + } + } + + public bool TryTake(out string text) + { + if (Thread.CurrentThread.ManagedThreadId != ownerThread) + throw new InvalidOperationException("Lobby snapshots must be consumed on the game thread."); + lock (gate) + { + text = pending; + pending = null; + return !closed && text != null; + } + } + + public bool WaitForPoll(int milliseconds) + { + lock (gate) + { + if (!closed) System.Threading.Monitor.Wait(gate, milliseconds); + return !closed; + } + } + + public void Close() + { + lock (gate) + { + closed = true; + pending = null; + System.Threading.Monitor.PulseAll(gate); + } + } + } + + public static class LobbyRecruitSync + { + private static readonly object clientsGate = new object(); + private static readonly Dictionary clients = new Dictionary(); + private static readonly MethodInfo startRecruit = AccessTools.Method(typeof(Client), "RecvStartRecruit"); + private static readonly MethodInfo finishRecruit = AccessTools.Method(typeof(Client), "RecvFinishRecruit"); + + private sealed class PollState + { + public readonly LobbySnapshotMailbox Mailbox = new LobbySnapshotMailbox(); + // Only the owner thread reads or writes Applied. + public Dictionary Applied = new Dictionary(); + public int AppliedCount; + private readonly object requestGate = new object(); + private HttpWebRequest request; + private bool stopped; + + public bool SetRequest(HttpWebRequest value) + { + lock (requestGate) + { + if (stopped) return false; + request = value; + return true; + } + } + + public void Stop() + { + Mailbox.Close(); + HttpWebRequest active; + lock (requestGate) { stopped = true; active = request; request = null; } + if (active != null) active.Abort(); + } + } + + public static void Apply(HarmonyLib.Harmony harmony) + { + Patch(harmony, typeof(Client), "Update", "BeforeClientUpdate"); + Patch(harmony, typeof(Client), "DisposeImpl", "BeforeClientDispose"); + Patch(harmony, typeof(Recruit), "Update", "BeforeRecruitUpdate"); + } + + private static void Patch(HarmonyLib.Harmony harmony, Type type, string target, string prefix) + { + var method = AccessTools.Method(type, target); + if (method == null) throw new MissingMethodException(type.FullName, target); + harmony.Patch(method, prefix: new HarmonyMethod(typeof(LobbyRecruitSync), prefix)); + } + + public static void Start(Client client) + { + if (client == null || Futari.stopping) return; + var state = new PollState(); + lock (clientsGate) + { + PollState previous; + if (clients.TryGetValue(client, out previous)) previous.Stop(); + clients[client] = state; + } + new Thread(() => Poll(state)) { IsBackground = true, Name = "WorldLinkLobbyFetch" }.Start(); + } + + private static void Poll(PollState state) + { + while (!Futari.stopping && state.Mailbox.WaitForPoll(10000)) + { + if (Futari.stopping) break; + try + { + string endpoint = FutariClient.LOBBY_BASE; + if (string.IsNullOrEmpty(endpoint)) continue; + var request = (HttpWebRequest)WebRequest.Create(endpoint.TrimEnd('/') + "/recruit/list"); + request.Timeout = 5000; + request.ReadWriteTimeout = 5000; + if (!state.SetRequest(request)) break; + string text; + using (var response = request.GetResponse()) + using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) + { + var body = new StringBuilder(); + var buffer = new char[4096]; + int count; + while ((count = reader.Read(buffer, 0, buffer.Length)) != 0) + { + if (body.Length + count > 2 * 1024 * 1024) + throw new InvalidDataException("Lobby response exceeds the supported size."); + body.Append(buffer, 0, count); + } + text = body.ToString(); + } + state.Mailbox.Publish(text); + } + catch (WebException ex) + { + if (!Futari.stopping && ex.Status != WebExceptionStatus.RequestCanceled) + Log.Warn("Lobby fetch failed; retaining rooms until expiry: " + ex.Status); + } + catch (Exception ex) + { + if (!Futari.stopping) Log.Warn("Lobby fetch failed: " + ex.Message); + } + finally { state.SetRequest(null); } + } + } + + private static bool BeforeClientUpdate(Client __instance, Recruit ____recruit, bool ____alreadyDisposed) + { + if (____alreadyDisposed || Futari.stopping) return false; + PollState state; + lock (clientsGate) { if (!clients.TryGetValue(__instance, out state)) return true; } + // Do not consume the newest pending snapshot or query song tables during loading. + if (!RecruitSongSafety.CatalogLoaded()) return true; + string text; + if (!state.Mailbox.TryTake(out text)) return true; + try + { + // Parse the whole response before mutating anything. A malformed HTTP body + // must not be mistaken for a successful empty list of rooms. + var records = new List(); + foreach (string line in text.Split('\n')) + { + if (string.IsNullOrWhiteSpace(line)) continue; + var record = JsonUtility.FromJson(line); + if (record == null || record.RecruitInfo == null) + throw new InvalidDataException("Invalid lobby recruit record."); + records.Add(record.RecruitInfo); + } + var next = Normalize(records); + PruneExpired(____recruit.GetList(), DateTime.Now); + foreach (var pair in state.Applied) + { + RecruitInfo replacement; + if (!next.TryGetValue(pair.Key, out replacement) + || replacement.StartTime != pair.Value.StartTime || replacement.MusicID != pair.Value.MusicID) + { + var packet = new Packet(pair.Value.IpAddress); + packet.encode(new FinishRecruit(pair.Value)); + finishRecruit.Invoke(__instance, new object[] { packet }); + } + } + foreach (var info in next.Values) + { + var packet = new Packet(info.IpAddress); + packet.encode(new StartRecruit(info)); + startRecruit.Invoke(__instance, new object[] { packet }); + } + state.Applied = next; + state.AppliedCount++; + if (state.AppliedCount == 1 || state.AppliedCount % 6 == 0) + Log.Info("Lobby snapshot " + state.AppliedCount + " applied on game thread " + + Thread.CurrentThread.ManagedThreadId + "; rooms=" + next.Count + "."); + } + catch (Exception ex) + { + Log.Warn("Lobby snapshot rejected; retaining previous rooms until expiry: " + ex.Message); + } + return true; + } + + // The game stores one recruit per machine. Prefer the newest start when the + // lobby briefly contains duplicate records for that same machine. + public static Dictionary Normalize(IEnumerable source) + { + var result = new Dictionary(); + if (source == null) return result; + foreach (var info in source) + { + if (info == null || info.GroupID != FourMachineProtocol.RoomGroup + || !FourMachineProtocol.IsSinglePlayerMachine(info.MechaInfo) + || info.MusicID <= 0 || info.MusicID != info.MechaInfo.MusicID) continue; + DateTime start; + try { start = info.StartTime; } + catch (ArgumentOutOfRangeException) { continue; } + RecruitInfo previous; + if (!result.TryGetValue(info.IpU32, out previous) || start >= previous.StartTime) + result[info.IpU32] = info; + } + return result; + } + + public static void PruneExpired(RecruitList list, DateTime now) + { + if (list == null) return; + for (int i = list.Count - 1; i >= 0; --i) + { + bool expired = list[i] == null; + if (!expired) + { + try { expired = now.Ticks - list[i].RecvTime.Ticks >= TimeSpan.TicksPerMinute; } + catch (ArgumentOutOfRangeException) { expired = true; } + } + if (expired) list.RemoveAt(i); + } + } + + private static bool BeforeRecruitUpdate(RecruitList ____list, DateTime now) + { + PruneExpired(____list, now); + return false; + } + + private static void BeforeClientDispose(Client __instance) + { + PollState state; + lock (clientsGate) + { + if (!clients.TryGetValue(__instance, out state)) return; + clients.Remove(__instance); + } + state.Stop(); + } + + public static void Shutdown() + { + PollState[] active; + lock (clientsGate) { active = clients.Values.ToArray(); clients.Clear(); } + foreach (var state in active) state.Stop(); + } + } +} diff --git a/mod/WorldLink/LocalTestControl.cs b/mod/WorldLink/LocalTestControl.cs new file mode 100644 index 0000000..0459036 --- /dev/null +++ b/mod/WorldLink/LocalTestControl.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading; +using HarmonyLib; +using MAI2.Util; +using Manager; +using Monitor.Entry; +using Process; +using Process.Entry.State; +using UnityEngine; + +namespace WorldLink +{ + // Explicitly enabled per machine by a local marker. No socket, HTTP server, + // arbitrary code/path command, or card credential is exposed by this bridge. + public static class LocalTestControl + { + #pragma warning disable 0649 // Populated by Unity JsonUtility, not C# field assignments. + [Serializable] private sealed class Command + { + public string id; + public string action; + public string state; + public int mode; + public int button; + } + #pragma warning restore 0649 + [Serializable] private sealed class Status + { + public string utc; + public string lastId; + public string result; + public string entryState; + public int entryMode; + public bool readerPolling; + public string readerResult; + public bool foreground; + public bool playerEntered; + public string playerName; + public bool musicSelect; + public bool gameplay; + } + private static readonly FieldInfo EntryMonitors = AccessTools.Field(typeof(EntryProcess), "_monitors"); + private static readonly FieldInfo EntryContext = AccessTools.Field(typeof(EntryProcess), "_context"); + private static readonly string DirectoryPath = Path.GetFullPath(Path.Combine("UserData", "WorldLinkControl")); + private static EntryProcess entry; + private static bool gameplay; + private static float nextPoll; + private static int buttonFrame = -1; + private static int buttonIndex = -1; + private static string lastId = ""; + private static string result = "ready"; + private static volatile bool scanning; + private static volatile bool stopping; + private static bool reportedError; + + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId); + [DllImport("user32.dll")] private static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extraInfo); + + public static void Apply(HarmonyLib.Harmony harmony) + { + harmony.Patch(AccessTools.Method(typeof(EntryProcess), "OnStart"), postfix: H(nameof(EntryBegin))); + harmony.Patch(AccessTools.Method(typeof(EntryProcess), "OnRelease"), prefix: H(nameof(EntryEnd))); + harmony.Patch(AccessTools.Method(typeof(GameProcess), "OnStart"), prefix: H(nameof(GameBegin))); + harmony.Patch(AccessTools.Method(typeof(GameProcess), "OnRelease"), postfix: H(nameof(GameEnd))); + foreach (var method in new[] { "GetButtonDown", "GetButtonPush" }) + harmony.Patch(AccessTools.Method(typeof(InputManager), method, new[] { typeof(int), typeof(InputManager.ButtonSetting) }), postfix: H(nameof(Button))); + // Commands left by a previous run are never replayed after restart. + string commandPath = Path.Combine(DirectoryPath, "command.json"); + try { if (File.Exists(commandPath)) File.Delete(commandPath); } + catch (IOException) { result = "stale command could not be cleared"; stopping = true; } + catch (UnauthorizedAccessException) { result = "local control directory is not writable"; stopping = true; } + } + private static HarmonyMethod H(string name) { return new HarmonyMethod(typeof(LocalTestControl), name); } + private static void EntryBegin(EntryProcess __instance) { entry = __instance; } + private static void EntryEnd(EntryProcess __instance) { if (ReferenceEquals(entry, __instance)) entry = null; } + private static void GameBegin() { gameplay = true; buttonFrame = -1; } + private static void GameEnd() { gameplay = false; } + private static void Button(int monitorId, InputManager.ButtonSetting button, ref bool __result) + { + if (!gameplay && monitorId == 0 && Time.frameCount == buttonFrame && (int)button == buttonIndex) __result = true; + } + private static bool Foreground() + { + uint pid; GetWindowThreadProcessId(GetForegroundWindow(), out pid); + return pid == (uint)System.Diagnostics.Process.GetCurrentProcess().Id; + } + + public static void Update() + { + if (Time.unscaledTime < nextPoll || stopping) return; + nextPoll = Time.unscaledTime + .25f; + if (!File.Exists(Path.Combine(DirectoryPath, "enabled.flag"))) return; + try + { + string commandPath = Path.Combine(DirectoryPath, "command.json"); + if (File.Exists(commandPath)) + { + Command command; + using (var stream = new FileStream(commandPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + { + if (stream.Length > 2048) throw new InvalidDataException("Command is too large."); + using (var reader = new StreamReader(stream)) command = JsonUtility.FromJson(reader.ReadToEnd()); + } + File.Delete(commandPath); + if (command == null || string.IsNullOrEmpty(command.id) || command.id.Length > 80 || command.id == lastId) + throw new InvalidDataException("Invalid or duplicate command."); + lastId = command.id; + Execute(command); + } + SaveStatus(); + } + catch (Exception error) + { + result = "error: " + error.GetType().Name + ": " + error.Message; + if (!reportedError) MelonLoader.MelonLogger.Warning("[NyanLink LocalControl] " + result); + reportedError = true; + try { SaveStatus(); } catch { } + } + } + + private static void Execute(Command command) + { + reportedError = false; + if (command.action == "status") { result = "status updated"; return; } + if (command.action == "screenshot") + { + ScreenCapture.CaptureScreenshot(Path.Combine(DirectoryPath, "view.png")); + result = "screenshot requested"; return; + } + if (command.action == "scan") + { + var reader = SingletonStateMachine.Instance.AimeReader; + if (gameplay || scanning || !Foreground() || reader == null || !reader.EnableFlag || !reader.IsPollingState()) + throw new InvalidOperationException("Card scan requires the foreground game to be waiting for a card."); + scanning = true; + new Thread(delegate() + { + try + { + keybd_event(0x0D, 0, 0, UIntPtr.Zero); + for (int i = 0; i < 15 && !stopping && Foreground(); i++) Thread.Sleep(100); + } + finally { keybd_event(0x0D, 0, 2, UIntPtr.Zero); scanning = false; } + }) { IsBackground = true, Name = "WorldLinkCardKey" }.Start(); + result = "one card scan requested"; return; + } + if (command.action == "button") + { + if (gameplay || command.button < 1 || command.button > 8) throw new InvalidOperationException("Only menu buttons 1-8 are supported."); + buttonIndex = command.button - 1; buttonFrame = Time.frameCount + 1; + result = "one 1P menu button requested"; return; + } + if (command.action == "entry-yes") + { + if (entry == null) throw new InvalidOperationException("Entry screen is not active."); + StateType state; int mode; ReadEntryPhase(out state, out mode); + if (command.state != state.ToString() || command.mode != mode) + throw new InvalidOperationException("Entry screen changed; inspect it before confirming."); + var monitors = EntryMonitors.GetValue(entry) as List; + if (monitors == null || monitors.Count < 1) throw new InvalidOperationException("1P entry monitor unavailable."); + monitors[0].ResponseYes(); + result = command.action + " requested for 1P"; return; + } + throw new InvalidDataException("Unknown local control action."); + } + + private static void ReadEntryPhase(out StateType state, out int mode) + { + var context = EntryContext.GetValue(entry) as ContextEntry; + if (context == null) throw new InvalidOperationException("Entry context unavailable."); + StateEntry current; + context.GetCurrentStateObj(out state, out current); + mode = ReadEntryMode(current); + } + + // Some native states leave GetProcMode() at -1 even while switching + // confirmation dialogs. Read their actual ProcEnum to reject stale replies. + internal static int ReadEntryMode(StateEntry current) + { + if (current == null) return -1; + var field = AccessTools.Field(current.GetType(), "_mode"); + var value = field == null ? null : field.GetValue(current); + var property = value == null ? null : AccessTools.Property(value.GetType(), "Mode"); + return property == null ? current.GetProcMode() : Convert.ToInt32(property.GetValue(value, null)); + } + + private static void SaveStatus() + { + var status = new Status { utc = DateTime.UtcNow.ToString("o"), lastId = lastId, result = result, entryState = "none", + entryMode = -1, foreground = Foreground(), gameplay = gameplay, musicSelect = ReadyInfoOverlay.Current != null }; + if (entry != null) + { + StateType state; int mode; ReadEntryPhase(out state, out mode); + status.entryState = state.ToString(); status.entryMode = mode; + } + var user = Singleton.Instance.GetUserData(0); + if (user != null) { status.playerEntered = user.IsEntry; status.playerName = user.Detail.UserName; } + var reader = SingletonStateMachine.Instance.AimeReader; + if (reader != null) { status.readerPolling = reader.IsPollingState(); status.readerResult = reader.GetResult().ToString(); } + string path = Path.Combine(DirectoryPath, "status.json"); + File.WriteAllText(path + ".tmp", JsonUtility.ToJson(status, true)); + if (File.Exists(path)) File.Delete(path); + File.Move(path + ".tmp", path); + } + public static void Shutdown() { stopping = true; buttonFrame = -1; entry = null; } + } +} diff --git a/mod/WorldLink/ReadyInfoOverlay.cs b/mod/WorldLink/ReadyInfoOverlay.cs new file mode 100644 index 0000000..1ca8a93 --- /dev/null +++ b/mod/WorldLink/ReadyInfoOverlay.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using DB; +using HarmonyLib; +using Manager.Party.Party; +using Process; +using UnityEngine; + +namespace WorldLink +{ + public sealed class ReadyPlayerRow + { + public uint Address; + public int Number; + public string Name; + public int Difficulty; + public int IconId; + public bool Ready; + public bool Local; + public ReadyHistory History; + } + + public static class ReadyInfoOverlay + { + private static MusicSelectProcess owner; + private static ReadyInfoRenderer renderer; + private static float nextUpdate; + private static bool failed; + public static MusicSelectProcess Current { get { return owner; } } + + public static void Apply(HarmonyLib.Harmony harmony) + { + harmony.Patch(AccessTools.Method(typeof(MusicSelectProcess), "OnStart"), postfix: H(nameof(Begin))); + var update = H(nameof(Update)); update.priority = Priority.Last; + harmony.Patch(AccessTools.Method(typeof(MusicSelectProcess), "OnUpdate"), postfix: update); + harmony.Patch(AccessTools.Method(typeof(MusicSelectProcess), "OnRelease"), prefix: H(nameof(End))); + } + private static HarmonyMethod H(string name) { return new HarmonyMethod(typeof(ReadyInfoOverlay), name); } + private static void Begin(MusicSelectProcess __instance) { Reset(); owner = __instance; } + private static void End(MusicSelectProcess __instance) { if (ReferenceEquals(owner, __instance)) Reset(); } + + public static bool IsReadyState(PartyPartyClientStateID state) + { + return state >= PartyPartyClientStateID.FinishSetting && state <= PartyPartyClientStateID.Sync; + } + + public static ReadyPlayerRow[] BuildRows(PartyMemberInfo members, PartyMemberState states, uint local) + { + if (members == null || members.MechaInfo == null) return new ReadyPlayerRow[0]; + var rows = new List(); + for (int index = 0; index < members.MechaInfo.Length && index < 4; index++) + { + var info = members.MechaInfo[index]; + if (info == null || !info.IsJoin || !FourMachineProtocol.IsSinglePlayerMachine(info)) continue; + var state = states == null || states.StateList == null || index >= states.StateList.Length + ? PartyPartyClientStateID.Invalid : states.GetState(index); + rows.Add(new ReadyPlayerRow { Address = info.IpAddress, Local = info.IpAddress == local, Name = info.UserNames[0] ?? "", + Difficulty = info.FumenDifs[0], IconId = info.IconIDs[0], Ready = IsReadyState(state), History = ReadyInfoProtocol.Read(info) }); + } + rows = rows.OrderBy(row => row.Local ? 0 : 1).ThenBy(row => row.Address).ToList(); + for (int index = 0; index < rows.Count; index++) rows[index].Number = index + 1; + return rows.ToArray(); + } + + private static void Update(MusicSelectProcess __instance) + { + if (!ReferenceEquals(owner, __instance) || failed || Time.unscaledTime < nextUpdate) return; + nextUpdate = Time.unscaledTime + .2f; + try + { + if (!RecruitSongSafety.AllowsRecruitment()) + { if (renderer != null) renderer.Hide(); return; } + var party = Manager.Party.Party.Party.Get(); + if (party == null || (!party.IsHost() && !party.IsClient()) || __instance.ConnectMusicAllDecide) + { if (renderer != null) renderer.Hide(); return; } + uint local = FutariExt.MyStubIP(); + var members = party.GetPartyMemberInfo(); + var rows = BuildRows(members, party.GetPartyMemberState(), local); + foreach (var row in rows.Where(row => row.Local)) + { + var info = members.MechaInfo.First(member => member != null && member.IpAddress == local); + row.History = ReadyInfoProtocol.ReadLocal(info.MusicID, row.Difficulty); + if (__instance.IsPreparationCompletes != null && __instance.IsPreparationCompletes.Length > 0) + row.Ready = row.Ready || __instance.IsPreparationCompletes[0]; + } + if (rows.Length == 0) { if (renderer != null) renderer.Hide(); return; } + if (renderer == null) renderer = new ReadyInfoRenderer(owner); + renderer.Show(rows); + } + catch (Exception error) + { + failed = true; + ReleaseRenderer(); + MelonLoader.MelonLogger.Warning("[NyanLink Ready] Display disabled for this selection: " + error.GetType().Name + ": " + error.Message); + } + } + + public static void Reset() + { + owner = null; nextUpdate = 0; failed = false; + ReleaseRenderer(); + } + private static void ReleaseRenderer() + { + var previous = renderer; renderer = null; + if (previous == null) return; + try { previous.Release(); } + catch (Exception error) { MelonLoader.MelonLogger.Warning("[NyanLink Ready] Cleanup: " + error.GetType().Name); } + } + } +} diff --git a/mod/WorldLink/ReadyInfoProtocol.cs b/mod/WorldLink/ReadyInfoProtocol.cs new file mode 100644 index 0000000..0de3238 --- /dev/null +++ b/mod/WorldLink/ReadyInfoProtocol.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Reflection; +using HarmonyLib; +using MAI2.Util; +using Manager; +using Manager.Party.Party; + +namespace WorldLink +{ + public enum ReadyHistoryKind { Unknown, Unplayed, Played } + + public sealed class ReadyHistory + { + public ReadyHistoryKind Kind; + public uint Achievement; + public string DisplayText + { + get + { + if (Kind == ReadyHistoryKind.Unplayed) return "历史最佳 未游玩"; + if (Kind != ReadyHistoryKind.Played) return "历史最佳 未提供"; + return "历史最佳 " + (Achievement / 10000m).ToString("0.0000", CultureInfo.InvariantCulture) + "%"; + } + } + } + + // The four-machine protocol reserves local side 2P as inactive. Its name + // field is an optional extension envelope, already copied by both the JSON + // join/update messages and binary PartyMemberInfo serializer. We never mark + // that side entered or reuse any active player's identity/rating fields. + // Existing clients leave it blank; new clients show "not provided" for them. + public static class ReadyInfoProtocol + { + private const string Prefix = "WL4H1:"; + private static bool faultLogged; + + public static void Apply(HarmonyLib.Harmony harmony) + { + var target = AccessTools.Constructor(typeof(MechaInfo), new[] { + typeof(IReadOnlyList), typeof(IReadOnlyList), typeof(int), typeof(int) }); + if (target == null) throw new MissingMethodException("MechaInfo local constructor"); + harmony.Patch(target, postfix: new HarmonyMethod(typeof(ReadyInfoProtocol), nameof(LocalInfoCreated))); + } + + private static void LocalInfoCreated(MechaInfo __instance) + { + if (!HasReservedSlot(__instance)) return; + try { Attach(__instance, ReadLocal(__instance.MusicID, __instance.FumenDifs[0])); } + catch (Exception error) + { + if (!faultLogged) MelonLoader.MelonLogger.Warning("[NyanLink Ready] Local history unavailable: " + error.GetType().Name); + faultLogged = true; + } + } + + public static ReadyHistory ReadLocal(int musicId, int difficulty) + { + if (musicId <= 0 || difficulty < 0 || difficulty > 5) return new ReadyHistory(); + var user = Singleton.Instance.GetUserData(0); + if (user == null || !user.IsEntry || user.ScoreDic == null || difficulty >= user.ScoreDic.Length || user.ScoreDic[difficulty] == null) + return new ReadyHistory(); + Manager.UserDatas.UserScore score; + if (!user.ScoreDic[difficulty].TryGetValue(musicId, out score) || score == null || (score.playcount == 0 && score.achivement == 0)) + return new ReadyHistory { Kind = ReadyHistoryKind.Unplayed }; + if (score.achivement > 1010000) return new ReadyHistory(); + return new ReadyHistory { Kind = ReadyHistoryKind.Played, Achievement = score.achivement }; + } + + private static bool HasReservedSlot(MechaInfo info) + { + return info != null && info.Entrys != null && info.Entrys.Length == 2 && info.Entrys[0] && !info.Entrys[1] + && info.UserNames != null && info.UserNames.Length == 2 && info.FumenDifs != null && info.FumenDifs.Length == 2; + } + + public static bool Attach(MechaInfo info, ReadyHistory history) + { + if (!HasReservedSlot(info) || history == null || info.MusicID <= 0 || info.FumenDifs[0] < 0 || info.FumenDifs[0] > 5) + return false; + if (history.Kind < ReadyHistoryKind.Unknown || history.Kind > ReadyHistoryKind.Played || history.Achievement > 1010000) + return false; + info.UserNames[1] = Prefix + info.MusicID.ToString(CultureInfo.InvariantCulture) + ":" + info.FumenDifs[0].ToString(CultureInfo.InvariantCulture) + + ":" + ((int)history.Kind).ToString(CultureInfo.InvariantCulture) + ":" + + (history.Kind == ReadyHistoryKind.Played ? history.Achievement : 0).ToString(CultureInfo.InvariantCulture); + return true; + } + + public static ReadyHistory Read(MechaInfo info) + { + var unknown = new ReadyHistory(); + if (!HasReservedSlot(info)) return unknown; + string raw = info.UserNames[1]; + if (string.IsNullOrEmpty(raw) || raw.Length > 80 || !raw.StartsWith(Prefix, StringComparison.Ordinal)) return unknown; + string[] parts = raw.Split(':'); + int music, difficulty, kind; + uint achievement; + if (parts.Length != 5 || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out music) + || !int.TryParse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture, out difficulty) + || !int.TryParse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture, out kind) + || !uint.TryParse(parts[4], NumberStyles.None, CultureInfo.InvariantCulture, out achievement) + || music <= 0 || music != info.MusicID || difficulty < 0 || difficulty > 5 || difficulty != info.FumenDifs[0] + || kind < 0 || kind > 2 || achievement > 1010000 || (kind != 2 && achievement != 0)) return unknown; + return new ReadyHistory { Kind = (ReadyHistoryKind)kind, Achievement = achievement }; + } + } +} diff --git a/mod/WorldLink/ReadyInfoRenderer.cs b/mod/WorldLink/ReadyInfoRenderer.cs new file mode 100644 index 0000000..2ba18ae --- /dev/null +++ b/mod/WorldLink/ReadyInfoRenderer.cs @@ -0,0 +1,173 @@ +using System; +using System.Reflection; +using Manager; +using Process; +using UnityEngine; +using UnityEngine.UI; + +namespace WorldLink +{ + internal sealed class ReadyInfoRenderer + { + private readonly Card[] cards = new Card[4]; + private GameObject root; + private Font font; + private RectTransform main; + private AssetManager assets; + private Vector2 size; + private string lastState; + private Text title; + private sealed class Card + { + public RectTransform Root; + public RawImage Icon; + public Text Name, Difficulty, Ready, History; + public int IconId = int.MinValue; + public uint Address; + } + + public ReadyInfoRenderer(MusicSelectProcess owner) + { + try { Create(owner); } + catch { Release(); throw; } + } + + private void Create(MusicSelectProcess owner) + { + var field = typeof(MonitorBase).GetField("Main", BindingFlags.Instance | BindingFlags.NonPublic); + var group = owner.MonitorArray == null || owner.MonitorArray.Length == 0 ? null : field.GetValue(owner.MonitorArray[0]) as CanvasGroup; + main = group == null ? null : group.transform as RectTransform; + var containerField = typeof(ProcessBase).GetField("container", BindingFlags.Instance | BindingFlags.NonPublic); + var container = (ProcessDataContainer)containerField.GetValue(owner); + assets = container.assetManager; + if (main == null || assets == null) throw new InvalidOperationException("Preparation UI is unavailable."); + root = new GameObject("WorldLink Preparation Players", typeof(RectTransform), typeof(Canvas), typeof(CanvasGroup)); + root.SetActive(false); + var rect = (RectTransform)root.transform; + rect.SetParent(main, false); + rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one; + rect.offsetMin = rect.offsetMax = Vector2.zero; + root.layer = main.gameObject.layer; + var canvas = root.GetComponent(); + canvas.renderMode = RenderMode.WorldSpace; + canvas.overrideSorting = true; + canvas.sortingLayerID = SortingLayer.NameToID("Default"); + canvas.sortingOrder = 30000; + root.GetComponent().blocksRaycasts = false; + root.GetComponent().interactable = false; + font = Font.CreateDynamicFontFromOSFont(new[] { "Microsoft YaHei", "Microsoft YaHei UI", "Arial" }, 28); + if (font == null) throw new InvalidOperationException("Preparation font is unavailable."); + title = Label("Room members", rect, 19, new Color(.84f, .94f, 1f)); + title.alignment = TextAnchor.MiddleCenter; + for (int i = 0; i < 4; i++) + { + var card = cards[i] = new Card { Root = Rect("Player " + (i + 1), rect) }; + var panel = card.Root.gameObject.AddComponent(); + panel.color = new Color(.035f, .09f, .14f, .82f); panel.raycastTarget = false; + card.Icon = Rect("Icon", card.Root).gameObject.AddComponent(); + card.Icon.raycastTarget = false; + card.Name = Label("Name", card.Root, 17, Color.white); + card.Name.resizeTextForBestFit = true; + card.Name.resizeTextMinSize = 12; card.Name.resizeTextMaxSize = 17; + card.Name.verticalOverflow = VerticalWrapMode.Truncate; + card.Difficulty = Label("Difficulty", card.Root, 18, Color.white); + card.Ready = Label("Ready", card.Root, 17, Color.white); + card.History = Label("History", card.Root, 17, Color.white); + } + } + + private RectTransform Rect(string name, Transform parent) + { + var go = new GameObject(name, typeof(RectTransform)); go.layer = root.layer; + var rect = (RectTransform)go.transform; rect.SetParent(parent, false); return rect; + } + + private Text Label(string name, Transform parent, int pointSize, Color color) + { + var text = Rect(name, parent).gameObject.AddComponent(); + text.font = font; text.fontSize = pointSize; text.color = color; text.supportRichText = false; + text.alignment = TextAnchor.MiddleLeft; text.horizontalOverflow = HorizontalWrapMode.Wrap; + text.verticalOverflow = VerticalWrapMode.Overflow; text.raycastTarget = false; + return text; + } + + private static void Place(RectTransform rect, float x, float y, float width, float height) + { + rect.anchorMin = rect.anchorMax = new Vector2(0, 1); rect.pivot = new Vector2(0, 1); + rect.anchoredPosition = new Vector2(x, -y); rect.sizeDelta = new Vector2(width, height); + } + + private void Layout() + { + size = main.rect.size; + // The native monitor is circular. Keep the full row (including its + // outer top corners) inside that circle, above the selection ribbon. + float diameter = Math.Min(size.x, size.y), scale = diameter / 1080f; + float gap = diameter * .012f, rowWidth = diameter * .74f; + float margin = (size.x - rowWidth) * .5f; + float width = (rowWidth - gap * 3) / 4; + float top = (size.y - diameter) * .5f + diameter * .17f; + Place(title.rectTransform, (size.x - 360 * scale) * .5f, top, 360 * scale, 26 * scale); + for (int i = 0; i < 4; i++) + { + Card c = cards[i]; + Place(c.Root, margin + i * (width + gap), top + 28 * scale, width, 132 * scale); + Place(c.Icon.rectTransform, 10 * scale, 10 * scale, 43 * scale, 43 * scale); + Place(c.Name.rectTransform, 61 * scale, 7 * scale, width - 69 * scale, 29 * scale); + Place(c.Ready.rectTransform, 61 * scale, 32 * scale, width - 69 * scale, 24 * scale); + Place(c.Difficulty.rectTransform, 10 * scale, 60 * scale, width - 20 * scale, 28 * scale); + Place(c.History.rectTransform, 10 * scale, 92 * scale, width - 20 * scale, 29 * scale); + } + } + + public void Show(ReadyPlayerRow[] rows) + { + if (main.rect.size != size) Layout(); + title.text = "联机准备 " + rows.Length + " / 4"; + string state = ""; + for (int i = 0; i < cards.Length; i++) + { + var card = cards[i]; card.Root.gameObject.SetActive(i < rows.Length); + if (i >= rows.Length) continue; + var row = rows[i]; + card.Name.text = row.Number + "P " + row.Name; + card.Ready.text = row.Ready ? "已准备" : "准备中"; + card.Ready.color = row.Ready ? new Color(.37f, 1f, .6f) : new Color(.85f, .88f, .93f); + card.Difficulty.text = DifficultyName(row.Difficulty); + card.Difficulty.color = DifficultyColor(row.Difficulty); + card.History.text = row.History.DisplayText; + if (card.IconId != row.IconId || card.Address != row.Address) + { + card.Icon.texture = assets.GetIconTexture2D(row.Local ? 0 : i + 1, row.IconId); + card.Icon.color = card.Icon.texture == null ? Color.clear : Color.white; + card.IconId = row.IconId; card.Address = row.Address; + } + state += row.Number + ":" + row.Difficulty + ":" + row.Ready + ":" + row.IconId + ":" + row.History.Kind + ":" + row.History.Achievement + ";"; + } + root.SetActive(true); + if (state != lastState) + { + lastState = state; + MelonLoader.MelonLogger.Msg("[NyanLink Ready] " + rows.Length + " players; top row; main=" + size + "; players=" + state); + } + } + + public static string DifficultyName(int value) + { + string[] names = { "BASIC", "ADVANCED", "EXPERT", "MASTER", "Re:MASTER", "宴" }; + return value >= 0 && value < names.Length ? names[value] : "未知难度"; + } + private static Color DifficultyColor(int value) + { + Color[] colors = { new Color(.4f, 1f, .45f), new Color(1f, .86f, .3f), new Color(1f, .4f, .48f), + new Color(.82f, .5f, 1f), new Color(.94f, .78f, 1f), new Color(1f, .5f, .86f) }; + return value >= 0 && value < colors.Length ? colors[value] : Color.white; + } + public void Hide() { if (root != null) root.SetActive(false); } + public void Release() + { + if (root != null) { root.SetActive(false); UnityEngine.Object.Destroy(root); root = null; } + if (font != null) { UnityEngine.Object.Destroy(font); font = null; } + } + } +} diff --git a/mod/WorldLink/RecruitSongSafety.cs b/mod/WorldLink/RecruitSongSafety.cs new file mode 100644 index 0000000..e1f92d2 --- /dev/null +++ b/mod/WorldLink/RecruitSongSafety.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using HarmonyLib; +using MAI2.Util; +using Manager; +using Manager.MaiStudio; +using Manager.Party.Party; + +namespace WorldLink +{ + // Lobby advertisements are untrusted hints, not entries in the local song list. + public static class RecruitSongSafety + { + private static readonly Dictionary warnings = new Dictionary(); + + public static void Apply(HarmonyLib.Harmony harmony) + { + harmony.Patch(AccessTools.Method(typeof(Client), "GetRecruitListWithoutMe"), + postfix: new HarmonyMethod(typeof(RecruitSongSafety), nameof(FilterVisibleRooms))); + } + + public static bool CatalogLoaded() { return Singleton.Instance.IsLoaded(); } + public static bool AllowsRecruitment() { return !GameManager.IsFreedomMode && !GameManager.IsCourseMode; } + + public static bool TryGetSong(RecruitInfo room, out MusicData music, out List notes) + { + music = null; notes = null; + if (!AllowsRecruitment() || room == null || room.GroupID != FourMachineProtocol.RoomGroup + || !FourMachineProtocol.IsSinglePlayerMachine(room.MechaInfo) + || room.MusicID != room.MechaInfo.MusicID || !CatalogLoaded()) return false; + var data = Singleton.Instance; + var charts = Singleton.Instance.GetNotesList(); + // NotesList is populated later than DataManager. Wait for the next snapshot. + if (charts == null || charts.Count == 0) return false; + try + { + music = data.GetMusic(room.MusicID); + if (!charts.TryGetValue(room.MusicID, out var entry) || entry == null) + return Reject(room, "no local notes entry", data.GetMusics().Count, charts.Count); + notes = entry.NotesList; + if (!Validate(room.MusicID, room.MechaInfo.FumenDifs[0], music, notes)) + return Reject(room, "missing/unsupported song or host difficulty", data.GetMusics().Count, charts.Count); + return true; + } + catch (Exception ex) + { + return Reject(room, "local lookup failed: " + ex.GetType().Name, -1, charts.Count); + } + } + + public static bool Validate(int id, int difficulty, MusicData music, List notes) + { + // This adapter constructs only ordinary standard/DX selections, never utage. + return id > 0 && id != 10000 && id < 20000 && music != null && music.GetID() == id + && notes != null && notes.Count >= 5 && difficulty >= 0 && difficulty < notes.Count + && difficulty <= 4 && notes.All(note => note != null) + && notes[difficulty].isEnable; + } + + private static bool Reject(RecruitInfo room, string reason, int songs, int charts) + { + DateTime last; + if (!warnings.TryGetValue(room.MusicID, out last) || DateTime.UtcNow - last >= TimeSpan.FromSeconds(30)) + { + if (warnings.Count >= 256) warnings.Clear(); + warnings[room.MusicID] = DateTime.UtcNow; + MelonLoader.MelonLogger.Warning("[NyanLink Recruit] Ignored advertisement: music=" + room.MusicID + + ", host=" + room.MechaInfo.UserNames[0] + ", difficulty=" + room.MechaInfo.FumenDifs[0] + + ", reason=" + reason + ", localSongs=" + songs + ", localNotes=" + charts + + ". Local song lists are retained."); + } + return false; + } + + public static RecruitList Filter(IEnumerable source, Func usable) + { + var result = new RecruitList(); + if (source != null) + foreach (var room in source) + if (room != null && usable(room)) result.Add(room); + return result; + } + + private static void FilterVisibleRooms(ref RecruitList __result) + { + // Return a new list; never remove entries from the native client's backing list. + __result = Filter(__result, room => TryGetSong(room, out _, out _)); + } + } +} diff --git a/mod/docs/BUILDING.md b/mod/docs/BUILDING.md new file mode 100644 index 0000000..a42bcfd --- /dev/null +++ b/mod/docs/BUILDING.md @@ -0,0 +1,59 @@ +# 构建与自动测试 + +构建目标为 Windows 上的 Unity Mono 插件。使用 PowerShell 和支持 C# 12 的 Roslyn;当前验证的编译器为 Microsoft.Net.Compilers.Toolset 4.12.0,运行其 net472 编译器需要 .NET Framework 4.7.2 或更新版本。 + +## 准备依赖 + +1. 克隆仓库,进入 `mod/` 目录(以下路径均相对于此目录)。 +2. 运行 `powershell -NoProfile -ExecutionPolicy Bypass -File scripts/Prepare-Compiler.ps1`。脚本从 NuGet 官方地址下载固定版本,解压到 `.tools/roslyn/`,并输出下载文件的 SHA-256。若下载不可用,可自行准备 Microsoft.Net.Compilers.Toolset 4.12.0,并给构建脚本传入 `-CompilerPath`。本次构建验证使用本地准备好的该版本编译器。 +3. 创建 `refs/`,从你自己的适配游戏与已安装加载器中复制编译所需 DLL: + - `Sinmai_Data/Managed/` 中的 `Assembly-CSharp.dll`、`Assembly-CSharp-firstpass.dll`、`mscorlib.dll`、System/Unity 模块、`AMDaemon.NET.dll` 等; + - 与该游戏运行时一致的 `MelonLoader.dll`、`0Harmony.dll`、`Tomlet.dll` 及其需要的托管依赖,通常可在 `MelonLoader/net35/`、加载器依赖目录或 `UserLibs/` 找到; + - 自动测试还需要 `Mono.Cecil.dll` 及 Harmony 依赖。 + +不要混用不同游戏版本的 DLL。`refs/` 平铺保存这些文件;缺少引用时以编译器提示为准。游戏程序集 MVID 必须为 README 所列版本。仓库不下载、不分发这些第三方依赖。 + +## 编译 + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File scripts/Build.ps1 +``` + +输出为 `bin/WorldLink.dll`。也可使用外部依赖目录和编译器: + +```powershell +.\scripts\Build.ps1 -ReferencesDirectory 'D:\local-dependencies\refs' -CompilerPath 'D:\tools\roslyn\tasks\net472\csc.exe' +``` + +保留原有 `WorldLink.csproj` / `build.cake` 构建入口。`scripts/Build.ps1` 是无 SDK 时的本地验证入口,编译同一组生产源码,显式生成隐式 using 与版本元数据;测试源码放在仓库 `tests/mod/`,不会编入插件。原 Cake 构建使用 `Libs/` 引用和 Git 版本;本地验证构建使用 `refs/` 引用和 `.14` 版本。不同路径、编译器或依赖可能产生不同 DLL 哈希,不能把文件哈希不同直接当成功能差异。 + +## 托管回归测试 + +测试需要把依赖放在本仓库 `refs/` 中,即使编译时使用过外部目录。 + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File scripts/Test.ps1 +``` + +脚本只在 `testrefs/` 生成游戏程序集的测试副本(调整 ILOnly 标记并检查方法 IL 语义未改变),不会修改原游戏文件。临时测试文件、日志和编译产物均被 Git 忽略。 + +| 测试 | 检查数 | +| --- | ---: | +| RecruitSongChecks | 31 | +| LobbyRecruitChecks | 21 | +| LiveScoreChecks | 36 | +| ProtocolChecks | 33 | +| TransportChecks | 122 | +| HookInstallationChecks | 6 | +| ReadyInfoChecks | 40 | +| 合计 | 289 | + +测试不运行真实 Unity 渲染。Freedom 闪退、收到房间后白屏、完整四机联机仍需真人游戏环境验证。仓库不配置一个缺少游戏依赖却显示“构建成功”的托管 CI;在拥有合法本地依赖的开发环境执行测试。 + +## 打包 + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File scripts/Package.ps1 +``` + +`dist/` 输出 ZIP,仅含 `Mods/WorldLink.dll`、`WorldLink.toml` 和 `LICENSE`。脚本不覆盖已存在的包。发布时使用预发布标记,附带 SHA-256 和实际测试范围,勿把备份 DLL 或游戏依赖加入安装包。 diff --git a/mod/docs/KNOWN_ISSUES.md b/mod/docs/KNOWN_ISSUES.md new file mode 100644 index 0000000..2db79a1 --- /dev/null +++ b/mod/docs/KNOWN_ISSUES.md @@ -0,0 +1,21 @@ +# 已知问题与验证状态 + +## .13 招募防护尚需实机回归 + +曾收到两类报告:普通模式正常选曲时收到招募即白屏(尚未加入),以及服务器有招募时进入 Freedom 闪退。移除插件后正常。现有日志没有给出这两类问题的完整异常调用栈,因此未确认唯一根因。 + +`.13` 增加曲库加载门控、招募曲目/难度校验、临时列表构建与 Freedom/Course 模式隔离。31 项相关托管检查通过;需继续验证普通模式收到招募后、加入并结算,以及有招募时进入 Freedom 的实际表现。 + +## 退出时仍可能发起重连 + +`.12` 的日志与源码显示:退出标志已设置后,发送/接收循环的 finally 回调仍会触发 `Reconnect()`;连接失败后还可能创建新线程。可见 `ThreadAbortException`、连接错误及 `Thread creation failed`。`.13` 没有改动这条退出重连路径,问题仍待修复。 + +这些日志可以证明退出清理附近仍发生重连,不能单凭它们认定是最初退出的原因,也不能据此认定系统线程资源耗尽。 + +## 四台真实游戏的覆盖不足 + +已完成的实机测试主要是一台真实游戏配合三个轻量协议客户端;协议客户端不能覆盖其他三台电脑的资源、加载顺序、渲染与插件冲突。四台真实游戏的完整回归仍需进行。 + +## 资源和其他插件兼容性 + +相同游戏版本名称不保证曲库一致。未验证所有 AquaMai/MuNet 版本组合、第三方比赛插件、翻译插件及自定义资源。缺少对应资源的头像可能回退;不支持的招募会被过滤,不会自动下载歌曲。 diff --git a/mod/docs/UPSTREAM_REVIEW.md b/mod/docs/UPSTREAM_REVIEW.md new file mode 100644 index 0000000..79ed4a1 --- /dev/null +++ b/mod/docs/UPSTREAM_REVIEW.md @@ -0,0 +1,41 @@ +# Upstream review status + +The four-machine prototype is now integrated into the existing `mod/WorldLink.csproj` +following review feedback. The duplicate `mod-fourplayer/` source tree is removed. +`TomletShim.cs`, `FutariTypes.cs` (including messages and logging), `FutariExt.cs`, +`BuildInfo.cs`, and the original Cake build are reused. Existing conditional +hooks in FutariPatch are retained. The Unity/AquaMai embedding path is not validated. + +## Review map + +- `WorldLink/FutariPatch.cs`, `FutariClient.cs`, `FutariSocket.cs`: modifications to existing hooks and transport. +- `WorldLink/FourMachineProtocol.cs`, `FourPlayerMapping.cs`: four-machine protocol/mapping. +- `WorldLink/LobbyRecruitSync.cs`, `RecruitSongSafety.cs`, `GhostSafetyPatch.cs`: recruitment/chart guards. +- `WorldLink/LiveScore*`, `ReadyInfo*`: gameplay scores and preparation information. +- `WorldLink/LocalTestControl.cs`: optional local test bridge, disabled unless explicitly enabled. +- `../tests/mod/`: managed regression suites, excluded from production compilation. + +The initial prototype came from reconstructed user-supplied plugin source. This +branch retains upstream history and MIT attribution. No proprietary references, +assets, card files or live logs are committed. + +## Performance changes + +The HUD reuses its four sampling objects and list. Unchanged updates reuse the +published snapshot and formatted labels; unchanged renderer sort values are not +written again. Changed data still updates every frame with exact values. There is +no claim of zero allocation or measured FPS improvement. Font atlas refresh and +mesh invalidation remain active even when scores are unchanged. + +## Validation and remaining work + +The local SDK-free build compiles the production source. Seven managed suites +pass 289 checks, including 10,000 repeated unchanged score updates. These tests +do not execute native Unity rendering. The Cake/SDK pipeline has not been run +locally, and the repository's CI result must be assessed separately. + +Prior field tests used one real game plus three lightweight clients, not four real +games. White-screen/Freedom guards still need regression testing on affected games. +The known shutdown reconnect issue remains. Game assembly pinning, optional mode +configuration, Unity embedding compatibility and the test bridge need further review. +Keep the PR in draft until those questions and four-real-machine testing are resolved. diff --git a/mod/scripts/Build.ps1 b/mod/scripts/Build.ps1 new file mode 100644 index 0000000..ee5c281 --- /dev/null +++ b/mod/scripts/Build.ps1 @@ -0,0 +1,36 @@ +param( + [string]$ReferencesDirectory = (Join-Path $PSScriptRoot '..\refs'), + [string]$CompilerPath = (Join-Path $PSScriptRoot '..\.tools\roslyn\tasks\net472\csc.exe') +) +$ErrorActionPreference = 'Stop' +$root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +if (!(Test-Path -LiteralPath $CompilerPath)) { throw 'Compiler not found. Run scripts/Prepare-Compiler.ps1 or pass -CompilerPath.' } +foreach ($name in @('mscorlib.dll','Assembly-CSharp.dll','Assembly-CSharp-firstpass.dll','MelonLoader.dll','0Harmony.dll','Tomlet.dll','UnityEngine.CoreModule.dll','UnityEngine.UI.dll','Unity.TextMeshPro.dll','AMDaemon.NET.dll')) { + if (!(Test-Path -LiteralPath (Join-Path $ReferencesDirectory $name))) { throw "Missing reference: $name. See docs/BUILDING.md." } +} +$refs = (Resolve-Path -LiteralPath $ReferencesDirectory).Path +$output = Join-Path $root 'bin\WorldLink.dll' +New-Item -ItemType Directory -Path (Split-Path $output) -Force | Out-Null +$options = @('/nologo','/target:library','/langversion:12','/unsafe+','/nostdlib+','/optimize+','/deterministic+','/nullable:annotations',('/out:"' + $output + '"')) +$references = Get-ChildItem -LiteralPath $refs -Filter '*.dll' | ForEach-Object { '/reference:"' + $_.FullName + '"' } +# Compile the same production files as WorldLink.csproj; SDK implicit usings are +# emitted explicitly for this SDK-free validation path. +$generated = Join-Path $root 'bin\ValidationBuildInfo.cs' +@' +global using System; +global using System.IO; +global using System.Linq; +global using System.Collections.Generic; +namespace WorldLink { public static partial class BuildInfo { + public const string Version = "2.1.0.14"; + public const string GitVersion = "2.1.0-fourplayer.14"; + public const string BuildDate = "2026-12-05"; +} } +'@ | Set-Content $generated -Encoding UTF8 +$files = @(Get-ChildItem $root -Filter '*.cs' | Where-Object Name -ne 'BuildInfo.g.cs') + @(Get-ChildItem (Join-Path $root 'WorldLink') -Recurse -Filter '*.cs') + @(Get-ChildItem (Join-Path $root 'Properties') -Filter '*.cs') +$sources = @($files | ForEach-Object { '"' + $_.FullName + '"' }) + @('"' + $generated + '"') +$rsp = Join-Path $root 'bin\build.rsp' +$options + $references + $sources | Set-Content -LiteralPath $rsp -Encoding UTF8 +& $CompilerPath ('@' + $rsp) +if ($LASTEXITCODE -ne 0) { throw 'Compilation failed.' } +Get-FileHash -LiteralPath $output -Algorithm SHA256 diff --git a/mod/scripts/Package.ps1 b/mod/scripts/Package.ps1 new file mode 100644 index 0000000..a188033 --- /dev/null +++ b/mod/scripts/Package.ps1 @@ -0,0 +1,15 @@ +param([string]$Version = '2.1.0-fourplayer.14') +$ErrorActionPreference = 'Stop' +if($Version -notmatch '^[A-Za-z0-9._-]+$'){throw 'Invalid package version'} +$root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$dist = Join-Path $root 'dist' +New-Item -ItemType Directory $dist -Force | Out-Null +$zip = Join-Path $dist ('Nyanlink-next-'+$Version+'.zip') +if(Test-Path -LiteralPath $zip){throw 'Package already exists; preserve or rename it before retrying.'} +Add-Type -AssemblyName System.IO.Compression,System.IO.Compression.FileSystem +$items = @{'Mods/WorldLink.dll'='bin\WorldLink.dll';'WorldLink.toml'='WorldLink.toml';'LICENSE'='..\LICENSE'} +foreach($path in $items.Values){if(!(Test-Path (Join-Path $root $path))){throw "Missing package input: $path"}} +$archive = [IO.Compression.ZipFile]::Open($zip,[IO.Compression.ZipArchiveMode]::Create) +try { foreach($name in $items.Keys){[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive,(Join-Path $root $items[$name]),$name,[IO.Compression.CompressionLevel]::Optimal)|Out-Null} } +finally {$archive.Dispose()} +Get-FileHash $zip -Algorithm SHA256 diff --git a/mod/scripts/Prepare-Compiler.ps1 b/mod/scripts/Prepare-Compiler.ps1 new file mode 100644 index 0000000..e5af463 --- /dev/null +++ b/mod/scripts/Prepare-Compiler.ps1 @@ -0,0 +1,14 @@ +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$tools = Join-Path $root '.tools' +New-Item -ItemType Directory -Path $tools -Force | Out-Null +$package = Join-Path $tools 'microsoft.net.compilers.toolset.4.12.0.nupkg' +$url = 'https://api.nuget.org/v3-flatcontainer/microsoft.net.compilers.toolset/4.12.0/microsoft.net.compilers.toolset.4.12.0.nupkg' +Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $package -TimeoutSec 180 +Add-Type -AssemblyName System.IO.Compression.FileSystem +$destination = Join-Path $tools 'roslyn' +if (Test-Path -LiteralPath $destination) { throw 'Compiler directory already exists; inspect it before replacing.' } +[IO.Compression.ZipFile]::ExtractToDirectory($package, $destination) +Write-Output 'Microsoft compiler 4.12.0 prepared from the official NuGet package.' +Get-FileHash -LiteralPath $package -Algorithm SHA256 diff --git a/mod/scripts/Test.ps1 b/mod/scripts/Test.ps1 new file mode 100644 index 0000000..e0a5f46 --- /dev/null +++ b/mod/scripts/Test.ps1 @@ -0,0 +1,32 @@ +param([string]$CompilerPath = (Join-Path $PSScriptRoot '..\.tools\roslyn\tasks\net472\csc.exe')) +$ErrorActionPreference = 'Stop' +$root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$refs = Join-Path $root 'refs' +$tests = [IO.Path]::GetFullPath((Join-Path $root '..\tests\mod')) +$bin = Join-Path $root 'bin' +if (!(Test-Path (Join-Path $bin 'WorldLink.dll'))) { throw 'Run Build.ps1 first.' } +function Compile([string]$name, [string[]]$sources, [string]$target='exe', [string[]]$extra=@()) { + $out = Join-Path $bin ($name + '.' + $(if($target -eq 'library'){'dll'}else{'exe'})) + $opts = @('/nologo',('/target:'+$target),'/langversion:12','/nostdlib+','/unsafe+',('/out:"'+$out+'"')) + $references = @(Get-ChildItem $refs -Filter '*.dll' | ForEach-Object { '/reference:"'+$_.FullName+'"' }) + $references += @($extra | ForEach-Object { '/reference:"'+$_+'"' }) + $rsp = Join-Path $bin ($name+'.rsp') + $opts + $references + @($sources | ForEach-Object { '"'+$_+'"' }) | Set-Content $rsp -Encoding UTF8 + & $CompilerPath ('@'+$rsp) + if($LASTEXITCODE -ne 0){throw "Compilation failed: $name"} +} +# The fixture is a separate test-only copy. The supplied game assembly is never edited. +Compile 'NormalizeFixture' @((Join-Path $tests 'Support\NormalizeFixture.cs')) +Copy-Item (Join-Path $refs 'Mono.Cecil.dll') $bin -Force +New-Item -ItemType Directory (Join-Path $root 'testrefs') -Force | Out-Null +& (Join-Path $bin 'NormalizeFixture.exe') (Join-Path $refs 'Assembly-CSharp.dll') (Join-Path $root 'testrefs\Assembly-CSharp.dll') +if($LASTEXITCODE -ne 0){throw 'Test fixture preparation failed'} +$plugin = Join-Path $bin 'WorldLink.dll' +$web = Join-Path ([Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) 'System.Web.Extensions.dll' +Compile 'TestWireCodec' @((Join-Path $tests 'Support\PartyWireCodec.cs')) 'library' @($plugin,$web) +foreach($name in @('RecruitSongChecks','LobbyRecruitChecks','LiveScoreChecks','ProtocolChecks','TransportChecks','HookInstallationChecks','ReadyInfoChecks')) { + Compile $name @((Join-Path $tests ($name+'.cs'))) 'exe' @($plugin,(Join-Path $bin 'TestWireCodec.dll'),$web) + & (Join-Path $bin ($name+'.exe')) | Tee-Object (Join-Path $bin ($name+'.log')) + if($LASTEXITCODE -ne 0){throw "Test failed: $name"} +} +Write-Output 'All seven managed regression suites passed. Native game verification is still required.' diff --git a/tests/mod/HookInstallationChecks.cs b/tests/mod/HookInstallationChecks.cs new file mode 100644 index 0000000..5b0a486 --- /dev/null +++ b/tests/mod/HookInstallationChecks.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using HarmonyLib; +using Mono.Cecil; + +internal static class HookInstallationChecks +{ + private static void Check(bool condition, string message) + { + if (!condition) throw new Exception(message); + System.Console.WriteLine("PASS " + message); + } + + public static int Main() + { + AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs args) + { + string name = new AssemblyName(args.Name).Name; + Assembly loaded = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(item => item.GetName().Name == name); + if (loaded != null) return loaded; + string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "refs", name + ".dll"); + return File.Exists(file) ? Assembly.LoadFrom(file) : null; + }; + try { Run(); System.Console.WriteLine("HOOK INSTALLATION CHECKS PASSED 6"); return 0; } + catch (Exception error) { System.Console.WriteLine(error); return 1; } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Run() + { + var harmony = new HarmonyLib.Harmony("worldlink.tests.unannotated"); + Check(DummyTarget.Value() == 1, "fixture begins unpatched"); + harmony.CreateClassProcessor(typeof(UnannotatedHooks)).Patch(); + Check(DummyTarget.Value() == 1, "default class processor reproduces missing legacy hooks"); + harmony.PatchAll(typeof(UnannotatedHooks)); + Check(DummyTarget.Value() == 2, "PatchAll(Type) installs method-annotated legacy hooks"); + var info = HarmonyLib.Harmony.GetPatchInfo(typeof(DummyTarget).GetMethod("Value")); + Check(info.Prefixes.Any(patch => patch.owner == harmony.Id), "installed hook can be verified by owner"); + harmony.UnpatchSelf(); + using (var module = ModuleDefinition.ReadModule(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WorldLink.dll"))) + { + var core = module.Types.Single(type => type.FullName == "WorldLink.Core"); + var init = core.Methods.Single(method => method.Name == "OnInitializeMelon"); + var calls = init.Body.Instructions.Select(item => item.Operand).OfType().ToArray(); + Check(calls.Any(method => method.Name == "PatchAll" && method.Parameters.Count == 1 && method.Parameters[0].ParameterType.FullName == "System.Type"), "final DLL uses correct Harmony overload"); + Check(calls.Any(method => method.Name == "VerifyLegacyHooks"), "final DLL checks original hook installation before success"); + } + } + + private static class DummyTarget + { + [MethodImpl(MethodImplOptions.NoInlining)] + public static int Value() { return 1; } + } + + private static class UnannotatedHooks + { + [HarmonyPrefix] + [HarmonyPatch(typeof(DummyTarget), "Value")] + private static bool BeforeValue(ref int __result) { __result = 2; return false; } + } +} diff --git a/tests/mod/LiveScoreChecks.cs b/tests/mod/LiveScoreChecks.cs new file mode 100644 index 0000000..8099804 --- /dev/null +++ b/tests/mod/LiveScoreChecks.cs @@ -0,0 +1,204 @@ +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using WorldLink; + +internal static class LiveScoreChecks +{ + private static int checks; + private static void Check(bool ok, string message) + { + if (!ok) throw new InvalidOperationException(message); + checks++; + System.Console.WriteLine("PASS " + message); + } + + private static LiveScoreSample Row(int slot, decimal value = 60.1234m, int rank = 2) + { + return new LiveScoreSample { Slot = slot, Name = "Player" + slot, Achievement = value, Rank = rank, Connected = true }; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Run() + { + System.Console.WriteLine("Assembly: " + typeof(LiveScoreModel).Assembly.Location); + var model = new LiveScoreModel(); + Check(!model.Active && model.Rows.Length == 0, "HUD model starts inactive without prior scores"); + model.Publish(new[] { Row(0) }); + Check(model.Rows.Length == 0, "inactive model ignores a late score publish"); + model.BeginTrack(false); + model.Publish(new[] { Row(0) }); + Check(!model.Active && model.Rows.Length == 0, "solo track never enables the party model"); + model.BeginTrack(true); + Check(model.Active && model.Rows.Length == 0, "party track begins with an empty current-track snapshot"); + + var supplied = new[] { Row(4, 90.9876m, 1), Row(1, 100m, 1), null, Row(0, 45.1234m, 3), + Row(-1), Row(3, 0m, 4), Row(5), Row(2, 60m, 2) }; + model.Publish(supplied); + var stableSnapshot = model.Rows; + for (int i = 0; i < 10000; i++) model.Publish(supplied); + Check(ReferenceEquals(stableSnapshot, model.Rows), "10000 unchanged updates reuse the published snapshot"); + Check(model.Rows.Select(row => row.Slot).SequenceEqual(new[] { 0, 2, 3, 4 }), + "unordered inputs retain four stable gameplay slots and discard 2P and invalid slots"); + Check(model.Rows.Select(row => row.Achievement).SequenceEqual(new[] { 45.1234m, 60m, 0m, 90.9876m }), + "all four achievements preserve exact decimal game values"); + Check(model.Rows.Select(row => row.Rank).SequenceEqual(new[] { 3, 2, 4, 1 }), + "ranks remain attached to player slots rather than sorting players by rank"); + supplied[0].Name = "Mutated"; + supplied[0].Achievement = 0m; + supplied[0].Rank = 4; + supplied[0].Connected = false; + supplied[0].Slot = 0; + supplied[3] = Row(0, 999m); + Check(model.Rows[3].Slot == 4 && model.Rows[3].Name == "Player4" && model.Rows[3].Achievement == 90.9876m && + model.Rows[3].Rank == 1 && model.Rows[3].Connected && model.Rows[0].Achievement == 45.1234m, + "mutating source rows and array after Publish cannot alter the displayed snapshot"); + + model.Publish(new[] { Row(4, 20m, 4), Row(3, 100m, 1), Row(2, 60m, 2), Row(0, 59m, 3) }); + Check(model.Rows.Select(row => row.Slot).SequenceEqual(new[] { 0, 2, 3, 4 }) && model.Rows[3].Achievement == 20m && + model.Rows[3].Rank == 4 && model.Rows[2].Achievement == 100m && model.Rows[2].Rank == 1, + "rank changes and real score decreases update immediately without reordering identities"); + model.Publish(new[] { Row(0, -1.2345m), Row(2, 101.4321m), Row(3, 0m), Row(4, 999.9999m) }); + Check(model.Rows.Select(row => row.Achievement).SequenceEqual(new[] { -1.2345m, 101.4321m, 0m, 999.9999m }), + "model does not clamp, smooth, or invent achievement progression"); + var lastGood = model.Rows; + bool duplicateRejected = false; + try { model.Publish(new[] { Row(0), Row(2), Row(2, 90m) }); } + catch (ArgumentException) { duplicateRejected = true; } + Check(duplicateRejected && ReferenceEquals(lastGood, model.Rows), + "duplicate player slots are rejected atomically before replacing the last valid snapshot"); + model.Publish(new[] { Row(4), Row(0) }); + Check(model.Rows.Select(row => row.Slot).SequenceEqual(new[] { 0, 4 }), + "a missing remote does not renumber the surviving player's stable slot"); + var disconnected = Row(4); disconnected.Connected = false; + model.Publish(new[] { disconnected }); + Check(!model.Rows[0].Connected, "connection status is copied from the source instead of fabricated"); + model.Publish(null); + Check(model.Active && model.Rows.Length == 0, "missing current data removes rows instead of retaining stale scores"); + + model.Publish(new[] { new LiveScoreSample { Slot = 0, Name = null }, + new LiveScoreSample { Slot = 2, Name = "\r\n\t" }, + new LiveScoreSample { Slot = 3, Name = "测试\n玩家" }, + new LiveScoreSample { Slot = 4, Name = new string('X', 40) } }); + Check(model.Rows[0].Name == "PLAYER" && model.Rows[1].Name == "PLAYER" && + model.Rows[2].Name == "测试玩家" && model.Rows[3].Name.Length == 32, + "names retain Unicode, remove control characters, and obey their display limit"); + CultureInfo previousCulture = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); + Check(LiveScoreModel.FormatAchievement(0m) == "0.0000%" && + LiveScoreModel.FormatAchievement(60.1234m) == "60.1234%" && + LiveScoreModel.FormatAchievement(101m) == "101.0000%" && + LiveScoreModel.FormatAchievement(-1.2345m) == "-1.2345%", + "achievement text uses exact four-decimal invariant formatting including zero and declines"); + } + finally { CultureInfo.CurrentCulture = previousCulture; } + Check(Enumerable.Range(1, 4).Select(LiveScoreModel.FormatRank).SequenceEqual(new[] { "1st", "2nd", "3rd", "4th" }) && + LiveScoreModel.FormatRank(0) == "--" && LiveScoreModel.FormatRank(-1) == "--" && LiveScoreModel.FormatRank(5) == "--", + "rank labels represent only valid received positions and leave unknown ranks unset"); + model.EndTrack(); + Check(!model.Active && model.Rows.Length == 0, "track end hides and clears all score rows"); + model.Publish(new[] { Row(0, 88m) }); + Check(model.Rows.Length == 0, "late publication after track end cannot restore old scores"); + model.BeginTrack(true); + model.Publish(new[] { Row(0, 99m), Row(2, 50m) }); + model.BeginTrack(true); + Check(model.Active && model.Rows.Length == 0, "replaying the same track starts empty even without a song ID change"); + model.Publish(new[] { Row(0, 1m), Row(4, 2m) }); + Check(model.Rows[0].Achievement == 1m && model.Rows[1].Achievement == 2m, + "new track accepts low initial scores instead of preserving previous highs"); + model.BeginTrack(false); + Check(!model.Active && model.Rows.Length == 0, "switching from party to solo clears every previous party score"); + model.EndTrack(); model.EndTrack(); + Check(!model.Active && model.Rows.Length == 0, "repeated reset is safe and stays hidden"); + + CheckAdapterLifecycle(); + CheckViewportClipping(); + System.Console.WriteLine("LIVE SCORE CHECKS PASSED " + checks); + System.Console.WriteLine("Scope: actual managed model and hidden lifecycle adapter; no Unity-native drawing execution."); + } + + private static void CheckAdapterLifecycle() + { + Type overlay = typeof(LiveScoreOverlay); + const BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic; + var displayModel = (LiveScoreModel)overlay.GetField("Model", flags).GetValue(null); + FieldInfo owner = overlay.GetField("owner", flags); + FieldInfo visible = overlay.GetField("visible", flags); + object current = FormatterServices.GetUninitializedObject(owner.FieldType); + object stale = FormatterServices.GetUninitializedObject(owner.FieldType); + LiveScoreOverlay.Reset(); + Check(!displayModel.Active && displayModel.Rows.Length == 0 && !(bool)visible.GetValue(null), + "reset adapter is hidden with no current track data"); + owner.SetValue(null, current); + visible.SetValue(null, true); + displayModel.BeginTrack(true); + displayModel.Publish(new[] { Row(0), Row(2) }); + overlay.GetMethod("End", flags).Invoke(null, new[] { stale }); + Check(displayModel.Active && displayModel.Rows.Length == 2 && (bool)visible.GetValue(null), + "release from an old game-process instance cannot hide the current track"); + overlay.GetMethod("Update", flags).Invoke(null, new[] { stale }); + Check(displayModel.Active && displayModel.Rows.Length == 2, + "updates from an old game-process instance cannot publish into the current HUD"); + overlay.GetMethod("End", flags).Invoke(null, new[] { current }); + Check(!displayModel.Active && displayModel.Rows.Length == 0 && owner.GetValue(null) == null && !(bool)visible.GetValue(null), + "current game-process release clears owner, visibility, and all score data"); + LiveScoreOverlay.Reset(); + Check(!displayModel.Active && displayModel.Rows.Length == 0, "game reset remains safe after normal process release"); + } + + private static bool Clip(UnityEngine.Rect input, out UnityEngine.Rect output) + { + Type viewport = typeof(LiveScoreModel).Assembly.GetType("WorldLink.LiveScoreViewport", true); + object[] args = { input, 1920, 1080, default(UnityEngine.Rect) }; + bool result = (bool)viewport.GetMethod("TryClip", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, args); + output = (UnityEngine.Rect)args[3]; + return result; + } + + private static void CheckViewportClipping() + { + UnityEngine.Rect output; + Check(Clip(new UnityEngine.Rect(100, 200, 500, 600), out output) && output.x == 100 && output.y == 200 && + output.width == 500 && output.height == 600, "viewport clipping preserves an intact visible play area"); + Check(Clip(new UnityEngine.Rect(-100, -200, 500, 600), out output) && output.x == 0 && output.y == 0 && + output.width == 400 && output.height == 400, "viewport clips negative monitor coordinates to screen origin"); + Check(Clip(new UnityEngine.Rect(1800, 1000, 500, 600), out output) && output.x == 1800 && output.y == 1000 && + output.width == 120 && output.height == 80, "viewport clips monitor overflow at right and bottom edges"); + Check(!Clip(new UnityEngine.Rect(2000, 0, 20, 20), out output) && + !Clip(new UnityEngine.Rect(0, -100, 20, 20), out output), "fully off-screen monitor rectangles are rejected"); + Check(!Clip(new UnityEngine.Rect(0, 0, 0, 20), out output) && + !Clip(new UnityEngine.Rect(0, 0, -10, 20), out output) && + !Clip(new UnityEngine.Rect(0, 0, 10, 0), out output), "zero and reversed monitor dimensions are rejected"); + Check(!Clip(new UnityEngine.Rect(float.NaN, 0, 20, 20), out output) && + !Clip(new UnityEngine.Rect(0, float.PositiveInfinity, 20, 20), out output) && + !Clip(new UnityEngine.Rect(0, 0, float.NegativeInfinity, 20), out output), + "nonfinite monitor coordinates never reach HUD layout"); + Check(!Clip(new UnityEngine.Rect(0, 0, 0.5f, 20), out output) && + Clip(new UnityEngine.Rect(0, 0, 1, 1), out output), "viewport requires at least a one-pixel visible area"); + } + + public static int Main() + { + AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs args) + { + string name = new AssemblyName(args.Name).Name; + Assembly existing = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(assembly => assembly.GetName().Name == name); + if (existing != null) return existing; + string root = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..")); + foreach (string directory in new[] { "bin", "testrefs", "refs" }) + { + string file = Path.Combine(root, directory, name + ".dll"); + if (File.Exists(file)) return Assembly.LoadFrom(file); + } + return null; + }; + try { Run(); return 0; } + catch (Exception error) { System.Console.WriteLine(error); return 1; } + } +} diff --git a/tests/mod/LobbyRecruitChecks.cs b/tests/mod/LobbyRecruitChecks.cs new file mode 100644 index 0000000..ec6db47 --- /dev/null +++ b/tests/mod/LobbyRecruitChecks.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using System.Threading; +using HarmonyLib; +using Manager.Party.Party; +using WorldLink; + +internal static class LobbyRecruitChecks +{ + private static int count; + private static void Check(bool ok, string name) + { if (!ok) throw new Exception("FAIL " + name); count++; System.Console.WriteLine("PASS " + name); } + + private static RecruitInfo Room(uint ip, DateTime received, DateTime? start = null) + { + var info = new RecruitInfo { GroupID = FourMachineProtocol.RoomGroup, MusicID = 11968, + StartTime = start ?? received, RecvTime = received }; + info.MechaInfo.IpAddress = ip; info.MechaInfo.MusicID = info.MusicID; + info.MechaInfo.Entrys[0] = true; + return info; + } + + [MethodImpl(MethodImplOptions.NoInlining)] private static void Update(Recruit recruit, DateTime now) { recruit.Update(now); } + [MethodImpl(MethodImplOptions.NoInlining)] private static void Update(Client client) { client.Update(); } + private static Type mailboxType; + private static object NewMailbox() { return Activator.CreateInstance(mailboxType, true); } + private static bool Publish(object mailbox, string text) { return (bool)mailboxType.GetMethod("Publish").Invoke(mailbox, new object[] { text }); } + private static string Take(object mailbox) + { + object[] args = { null }; + return (bool)mailboxType.GetMethod("TryTake").Invoke(mailbox, args) ? (string)args[0] : null; + } + private static void Close(object mailbox) { mailboxType.GetMethod("Close").Invoke(mailbox, null); } + + [MethodImpl(MethodImplOptions.NoInlining)] private static void Run() + { + mailboxType = typeof(LobbyRecruitSync).Assembly.GetType("WorldLink.LobbySnapshotMailbox", true); + DateTime now = new DateTime(2026, 12, 2, 12, 0, 0); + var baseline = new Recruit("baseline"); + baseline.GetList().Add(null); + bool reproduced = false; + try { Update(baseline, now); } catch (NullReferenceException) { reproduced = true; } + Check(reproduced, "actual unpatched game Recruit.Update reproduces the reported null-reference crash"); + + baseline.GetList().Clear(); + baseline.Add(Room(1, now)); baseline.Add(Room(2, now.AddSeconds(-61))); + baseline.Add(Room(3, now)); baseline.Add(Room(4, now.AddSeconds(-70))); + Update(baseline, now); + Check(baseline.GetList().Select(r => r.IpU32).SequenceEqual(new uint[] { 3, 4 }), + "actual unpatched game removes a fresh room and retains an expired room"); + + var harmony = new HarmonyLib.Harmony("worldlink.tests.lobby"); + LobbyRecruitSync.Apply(harmony); + Check(harmony.GetPatchedMethods().Count() == 3, "all actual client-update, disposal and recruit-expiry hooks install"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] private static void RunRemaining() + { + DateTime now = new DateTime(2026, 12, 2, 12, 0, 0); + var fixedRecruit = new Recruit("fixed"); + fixedRecruit.GetList().Add(null); + fixedRecruit.GetList().Add(Room(1, now)); + fixedRecruit.GetList().Add(Room(2, now.AddSeconds(-61))); + fixedRecruit.GetList().Add(null); + fixedRecruit.GetList().Add(Room(3, now.AddSeconds(-59))); + fixedRecruit.GetList().Add(Room(4, now.AddSeconds(-60))); + fixedRecruit.GetList().Add(Room(5, now.AddSeconds(-70))); + Update(fixedRecruit, now); + Check(fixedRecruit.GetList().Select(r => r.IpU32).SequenceEqual(new uint[] { 1, 3 }), + "patched actual game update removes nulls and correct expired indexes, preserving fresh rooms and order"); + var badTime = Room(10, now); + AccessTools.Field(typeof(RecruitInfo), "_recvTimeTicks").SetValue(badTime, -1L); + fixedRecruit.GetList().Add(badTime); + fixedRecruit.GetList().Add(Room(11, DateTime.MaxValue)); + Update(fixedRecruit, now); + Check(fixedRecruit.GetList().Select(r => r.IpU32).SequenceEqual(new uint[] { 1, 3, 11 }), + "invalid timestamps are removed and DateTime.MaxValue cannot overflow expiry arithmetic"); + Update(fixedRecruit, DateTime.MaxValue); + Check(fixedRecruit.GetList().Count == 1 && fixedRecruit.GetList()[0].IpU32 == 11, "expiry at maximum DateTime remains safe"); + Update(new Recruit("empty"), now); + Check(true, "empty room list update is safe"); + + var older = Room(20, now, now.AddSeconds(-5)); + var latest = Room(20, now, now); + var otherProtocol = Room(21, now); otherProtocol.GroupID = 1; + var badLayout = Room(22, now); badLayout.MechaInfo.Entrys[1] = true; + var badSong = Room(23, now); badSong.MechaInfo.MusicID++; + var badStart = Room(24, now); AccessTools.Field(typeof(RecruitInfo), "_startTimeTicks").SetValue(badStart, -1L); + var normalized = LobbyRecruitSync.Normalize(new[] { latest, older, null, otherProtocol, badLayout, badSong, badStart, Room(25, now) }); + Check(normalized.Count == 2 && ReferenceEquals(normalized[20], latest) && normalized.ContainsKey(25), + "duplicate identities select newest room; invalid, foreign protocol and two-player records are rejected"); + Check(LobbyRecruitSync.Normalize(null).Count == 0, "empty normalization is supported"); + + object mailbox = NewMailbox(); + Check(Take(mailbox) == null, "a mailbox starts without a snapshot"); + Check(!Publish(mailbox, null) && Take(mailbox) == null, "failed HTTP request cannot publish a successful empty snapshot"); + Check(Publish(mailbox, "") && Take(mailbox) == "", "successful empty HTTP body remains distinguishable from failure"); + bool blocked = false; + var wrongThread = new Thread(() => { + Publish(mailbox, "worker text"); + try { Take(mailbox); } + catch (TargetInvocationException ex) { blocked = ex.InnerException is InvalidOperationException; } + }); + wrongThread.Start(); wrongThread.Join(); + Check(blocked && Take(mailbox) == "worker text", "HTTP worker can publish text but cannot consume or apply it"); + var producer = new Thread(() => { for (int i = 0; i < 10000; i++) Publish(mailbox, i.ToString()); }); + producer.Start(); producer.Join(); + Check(Take(mailbox) == "9999" && Take(mailbox) == null, "10000 pending responses coalesce to exactly one newest snapshot"); + Publish(mailbox, "before close"); Close(mailbox); + Check(!Publish(mailbox, "late HTTP completion") && Take(mailbox) == null, "closing discards pending work and rejects late responses"); + var waiterMailbox = NewMailbox(); + var waiting = new ManualResetEvent(false); bool exited = false; + var waiter = new Thread(() => { waiting.Set(); exited = !(bool)mailboxType.GetMethod("WaitForPoll").Invoke(waiterMailbox, new object[] { 10000 }); }); + waiter.Start(); waiting.WaitOne(); Close(waiterMailbox); + Check(waiter.Join(1000) && exited, "disposal wakes the poller immediately instead of waiting ten seconds"); + waiting.Dispose(); + + var client = (Client)FormatterServices.GetUninitializedObject(typeof(Client)); + GC.SuppressFinalize(client); + var disposed = AccessTools.Field(typeof(Client), "_alreadyDisposed"); + disposed.SetValue(client, true); + Update(client); + Check(true, "actual disposed Client.Update is skipped before dereferencing released game objects"); + var registry = (IDictionary)AccessTools.Field(typeof(LobbyRecruitSync), "clients").GetValue(null); + Futari.stopping = false; + LobbyRecruitSync.Start(client); + var oldState = registry[client]; + object oldMailbox = oldState.GetType().GetField("Mailbox").GetValue(oldState); + LobbyRecruitSync.Start(client); + Check(registry.Count == 1 && !Publish(oldMailbox, "late old generation"), "replacing a client poller closes the old generation"); + var newState = registry[client]; + object newMailbox = newState.GetType().GetField("Mailbox").GetValue(newState); + client.Dispose(); + Check(registry.Count == 0 && !Publish(newMailbox, "late disposed client"), "actual client disposal hook removes poller and rejects late responses"); + LobbyRecruitSync.Start(client); + newState = registry[client]; newMailbox = newState.GetType().GetField("Mailbox").GetValue(newState); + LobbyRecruitSync.Shutdown(); + Check(registry.Count == 0 && !Publish(newMailbox, "late shutdown"), "plugin shutdown closes every poller"); + Futari.stopping = true; LobbyRecruitSync.Start(client); + Check(registry.Count == 0, "no new polling is started during shutdown"); + Futari.stopping = false; + new HarmonyLib.Harmony("worldlink.tests.lobby").UnpatchSelf(); + System.Console.WriteLine("LOBBY RECRUIT CHECKS PASSED " + count); + } + + private static int Main() + { + AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { + string name = new AssemblyName(args.Name).Name; + var loaded = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == name); + if (loaded != null) return loaded; + string root = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..")); + foreach (string dir in new[] { "bin", "testrefs", "refs" }) { + string path = Path.Combine(root, dir, name + ".dll"); if (File.Exists(path)) return Assembly.LoadFrom(path); + } return null; + }; + try { Run(); RunRemaining(); return 0; } + catch (Exception error) { System.Console.WriteLine(error); return 1; } + } +} diff --git a/tests/mod/ProtocolChecks.cs b/tests/mod/ProtocolChecks.cs new file mode 100644 index 0000000..bcee30e --- /dev/null +++ b/tests/mod/ProtocolChecks.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using MAI2.Memory; +using Manager.Party.Party; +using PartyLink; +using WorldLink; + +internal static class ProtocolChecks +{ + private static int checks; + + private static int Main() + { + AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => + { + string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "testrefs", new AssemblyName(args.Name).Name + ".dll"); + if (!File.Exists(path)) path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "refs", new AssemblyName(args.Name).Name + ".dll"); + return File.Exists(path) ? Assembly.LoadFrom(path) : null; + }; + try { InitializeProtocol(); Run(); System.Console.WriteLine("PASS " + checks + " protocol checks"); return 0; } + catch (Exception error) { System.Console.WriteLine(error); return 1; } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Run() + { + + Check(PartyLink.Party.c_maxMecha == 4, "machine capacity"); + var source = new PartyPlayInfo(); + Check(source.Member.Length == 4, "PartyPlayInfo constructor"); + source.Chain = 123; + source.MaxChain = 456; + source.CalcStatus = 1; + source.IsFullChain = true; + for (int i = 0; i < 4; i++) + { + source.Member[i].IpAddress = (uint)(i + 100); + source.Member[i].IsActive = true; + source.Member[i].Achieves[0] = 1000000 + i; + source.Member[i].Rankings[0] = (byte)(4 - i); + } + var cloned = new PartyPlayInfo(source); + Check(cloned.Member.Length == 4 && cloned.Member[3].Achieves[0] == 1000003, "copy constructor retains fourth machine"); + source.Member[3].Achieves[0] = 999999; + Check(cloned.Member[3].Achieves[0] == 1000003, "copy constructor is independent"); + var copied = new PartyPlayInfo(); + copied.CopyFrom(source); + Check(copied.Member[3].Achieves[0] == 999999 && copied.Chain == 123 && copied.IsFullChain, "CopyFrom preserves fourth machine and chain"); + var normalized = FourMachineProtocol.NormalizeMembers(new[] { source.Member[0], source.Member[1] }); + Check(normalized.Length == 4 && normalized[2] != null && normalized[3].IpAddress == 0, "legacy two-member object normalization"); + + var allocator = new FixedAllocator(16384, 1); + Chunk chunk = allocator.allocate(); + int bytes = source.Serialize(0, chunk); + int cursor = 0; + var received = new PartyPlayInfo(); + received.Deserialize(ref cursor, chunk); + Check(cursor == bytes, "four-machine play packet consumes exact byte count"); + Check(received.Member[3].IpAddress == 103 && received.Member[3].Achieves[0] == 999999 + && received.Chain == 123 && received.MaxChain == 456 && received.IsFullChain, "four-machine play packet binary round trip"); + + var machineData = new PartyMemberInfo(); + Check(machineData.MechaInfo.Length == 4, "PartyMemberInfo constructor"); + for (int i = 0; i < 4; i++) machineData.MechaInfo[i] = Machine((uint)(i + 100)); + bytes = machineData.Serialize(0, chunk); + cursor = 0; + var receivedMachines = new PartyMemberInfo(); + receivedMachines.Deserialize(ref cursor, chunk); + Check(cursor == bytes && receivedMachines.MechaInfo[3].IpAddress == 103 + && receivedMachines.MechaInfo[3].UserNames[0] == "Player103", "four-machine member packet binary round trip"); + var clonedMachines = (PartyMemberInfo)machineData.Clone(); + Check(clonedMachines.MechaInfo.Length == 4 && clonedMachines.MechaInfo[3].UserNames[0] == "Player103", "member packet clone"); + foreach (MechaInfo machine in machineData.MechaInfo) + for (int side = 0; side < 2; side++) machine.UserNames[side] = new string('\u73a9', 256); + bytes = machineData.Serialize(0, chunk); + cursor = 0; + receivedMachines.Deserialize(ref cursor, chunk); + Check(bytes > 2048 && bytes < FourMachineProtocol.PacketCapacity && cursor == bytes + && receivedMachines.MechaInfo[3].UserNames[1].Length == 256, "large multibyte four-machine member packet round trip"); + Check(new PartyMemberState().StateList.Length == 4 && new PartyMemberPing().Ping.Length == 4, "state and ping capacity"); + Check(new RecruitInfo().GroupID == FourMachineProtocol.RoomGroup, "four-machine room marker"); + var legacyRecruit = new RecruitInfo { GroupID = 1 }; + Check(new StartRecruit(legacyRecruit).RecruitInfo.GroupID == 1, "legacy lobby record retains its marker when copied"); + var request = new RequestJoin { MechaInfo = Machine(200) }; + Check(request.GroupID == FourMachineProtocol.RoomGroup, "join protocol marker"); + var packet = new Packet(); + var packetBuffer = (byte[])typeof(Packet).GetField("_encodeBuffer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(packet); + Check(packetBuffer.Length == FourMachineProtocol.PacketCapacity, "packet encode buffer expanded before construction"); + Check((int)typeof(SizeDef).GetField("CBufferSize").GetValue(null) == FourMachineProtocol.PacketCapacity, + "receive scratch capacity fits expanded packet"); + byte[] header = new byte[16]; + Buffer.BlockCopy(BitConverter.GetBytes(FourMachineProtocol.WireVersion), 0, header, 4, 4); + Buffer.BlockCopy(BitConverter.GetBytes(FourMachineProtocol.WireVersion), 0, header, 8, 4); + packet.getPlane().Set(header, 0, header.Length); + Check(FourMachineProtocol.IsCompatiblePacket(packet), "four-machine wire header accepted"); + header[4] = 0; + packet.getPlane().Set(header, 0, header.Length); + Check(!FourMachineProtocol.IsCompatiblePacket(packet), "incompatible wire header rejected"); + string reason; + Check(FourMachineProtocol.CanJoin(request, machineData.MechaInfo.Take(3), out reason), "fourth distinct machine admitted"); + Check(!FourMachineProtocol.CanJoin(request, machineData.MechaInfo, out reason), "fifth machine rejected"); + request.MechaInfo.IpAddress = 100; + Check(!FourMachineProtocol.CanJoin(request, machineData.MechaInfo.Take(1), out reason), "duplicate identity rejected"); + request.MechaInfo.IpAddress = 200; + request.GroupID = 1; + Check(!FourMachineProtocol.CanJoin(request, new MechaInfo[0], out reason), "legacy protocol rejected"); + request.GroupID = FourMachineProtocol.RoomGroup; + request.MechaInfo.Entrys[1] = true; + Check(!FourMachineProtocol.CanJoin(request, new MechaInfo[0], out reason), "two local players rejected"); + request.MechaInfo.Entrys[1] = false; + request.MechaInfo.UserType = new int[3]; + Check(!FourMachineProtocol.CanJoin(request, new MechaInfo[0], out reason), "malformed player array rejected"); + + int[] scores = { 100, int.MaxValue, 300, int.MaxValue, 200, int.MaxValue, 300, int.MaxValue }; + bool[] valid = { true, false, true, false, true, false, true, false }; + var trials = new bool[8]; + var ranks = new byte[8]; + FourMachineProtocol.CalculateRanks(scores, valid, trials, ranks); + Check(ranks.SequenceEqual(new byte[] { 4, 0, 1, 0, 3, 0, 1, 0 }), "four-player ranks exclude unused sides and preserve ties"); + trials[2] = true; + FourMachineProtocol.CalculateRanks(scores, valid, trials, ranks); + Check(ranks[0] == 3 && ranks[4] == 2, "trial player excluded from competitor ranking"); + + var unjoined = new MemberList(); + for (int i = 0; i < 12; i++) + unjoined.Add((Member)FormatterServices.GetUninitializedObject(typeof(Member))); + MethodInfo sendPatch = typeof(FourMachineProtocol).GetMethod("SendPartyPlayInfo", BindingFlags.Static | BindingFlags.NonPublic); + sendPatch.Invoke(null, new object[] { null, false, unjoined, new PartyPlayInfo(), new Queue() }); + Check(true, "extra unjoined connections excluded from score-array writes"); + allocator.free(ref chunk); + FourMachineProtocol.Rollback(); + Check((int)typeof(PartyLink.Party).GetField("c_maxMecha").GetValue(null) == 2, "rollback restores original machine capacity"); + Check((int)typeof(SizeDef).GetField("CBufferSize").GetValue(null) == 1500, "rollback restores original receive capacity"); + Check(new PartyPlayInfo().Member.Length == 2, "rollback removes constructor patch"); + FourMachineProtocol.Rollback(); + Check(true, "rollback is idempotent"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void InitializeProtocol() { FourMachineProtocol.Initialize(); } + + private static MechaInfo Machine(uint identity) + { + var machine = new MechaInfo(); + machine.IsJoin = true; + machine.IpAddress = identity; + machine.Entrys[0] = true; + machine.UserNames[0] = "Player" + identity; + machine.UserNames[1] = ""; + machine.UserIDs[0] = identity; + return machine; + } + + private static void Check(bool condition, string name) + { + if (!condition) throw new InvalidOperationException("FAIL " + name); + checks++; + System.Console.WriteLine("PASS " + name); + } +} diff --git a/tests/mod/ReadyInfoChecks.cs b/tests/mod/ReadyInfoChecks.cs new file mode 100644 index 0000000..88cf41b --- /dev/null +++ b/tests/mod/ReadyInfoChecks.cs @@ -0,0 +1,118 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using DB; +using HarmonyLib; +using Manager.Party.Party; +using WorldLink; +using WorldLinkBots; + +internal static class ReadyInfoChecks +{ + private static int count; + private static void Check(bool value, string name) { if (!value) throw new Exception("FAIL " + name); count++; System.Console.WriteLine("PASS " + name); } + private static MechaInfo Machine(uint id, int diff) + { + var result = new MechaInfo { IsJoin = true, IpAddress = id, MusicID = 10235 }; + result.Entrys[0] = true; result.UserNames[0] = "Player" + id; + result.FumenDifs[0] = diff; result.IconIDs[0] = 100 + (int)id; + return result; + } + [MethodImpl(MethodImplOptions.NoInlining)] private static void Run() + { + PartyWireCodec.Initialize(); + var a = Machine(30, 3); + Check(ReadyInfoProtocol.Read(a).Kind == ReadyHistoryKind.Unknown, "older client with empty extension is unknown, not zero score"); + Check(ReadyInfoProtocol.Attach(a, new ReadyHistory { Kind = ReadyHistoryKind.Played, Achievement = 1001234 }), "attach actual historical best"); + Check(ReadyInfoProtocol.Read(a).Achievement == 1001234, "retain all four decimal score places"); + Check(a.UserNames[0] == "Player30" && a.IconIDs[0] == 130 && a.FumenDifs[0] == 3 && !a.Entrys[1] && a.UserIDs[1] == 0, + "active identity, difficulty, icon, account IDs and inactive 2P flag remain unchanged"); + Check(FourMachineProtocol.IsSinglePlayerMachine(a), "optional history retains valid four-machine single-player layout"); + Check(ReadyInfoProtocol.Read(new MechaInfo(a)).Achievement == 1001234, "game MechaInfo copy constructor preserves history"); + var joined = (RequestJoin)PartyWireCodec.Decode(PartyWireCodec.Encode(new RequestJoin { GroupID = FourMachineProtocol.RoomGroup, MechaInfo = a })).Payload; + Check(ReadyInfoProtocol.Read(joined.MechaInfo).Achievement == 1001234, "RequestJoin JSON framing preserves history"); + var update = (UpdateMechaInfo)PartyWireCodec.Decode(PartyWireCodec.Encode(new UpdateMechaInfo(a))).Payload; + Check(ReadyInfoProtocol.Read(update.MechaInfo).Achievement == 1001234, "difficulty update JSON framing preserves history"); + var all = new PartyMemberInfo(); + all.MechaInfo[0] = a; all.MechaInfo[1] = Machine(10, 2); all.MechaInfo[2] = Machine(40, 1); all.MechaInfo[3] = Machine(20, 0); + ReadyInfoProtocol.Attach(all.MechaInfo[1], new ReadyHistory { Kind = ReadyHistoryKind.Unplayed }); + ReadyInfoProtocol.Attach(all.MechaInfo[2], new ReadyHistory { Kind = ReadyHistoryKind.Played, Achievement = 0 }); + ReadyInfoProtocol.Attach(all.MechaInfo[3], new ReadyHistory { Kind = ReadyHistoryKind.Played, Achievement = 1010000 }); + var received = (PartyMemberInfo)PartyWireCodec.Decode(PartyWireCodec.Encode(all)).Payload; + Check(ReadyInfoProtocol.Read(received.MechaInfo[0]).Achievement == 1001234 && ReadyInfoProtocol.Read(received.MechaInfo[3]).Achievement == 1010000, + "binary four-member broadcast retains all independent historical bests"); + Check(ReadyInfoProtocol.Read(received.MechaInfo[1]).Kind == ReadyHistoryKind.Unplayed && ReadyInfoProtocol.Read(received.MechaInfo[2]).Kind == ReadyHistoryKind.Played, + "unplayed and played with zero achievement remain different"); + var cloned = (PartyMemberInfo)received.Clone(); + Check(ReadyInfoProtocol.Read(cloned.MechaInfo[3]).Achievement == 1010000, "host roster clone retains extension"); + a.FumenDifs[0] = 2; + Check(ReadyInfoProtocol.Read(a).Kind == ReadyHistoryKind.Unknown, "old difficulty history never displays for a changed chart"); + a.FumenDifs[0] = 3; a.MusicID++; + Check(ReadyInfoProtocol.Read(a).Kind == ReadyHistoryKind.Unknown, "old song history never displays for a new song"); + a.MusicID--; + foreach (string invalid in new[] { "WL4H1:10235:3:2:1010001", "WL4H1:10235:3:2:-1", "WL4H1:10235:3:7:0", "WL4H1:10235:3:1:123", "WL4H1:10235:3:2:1:extra", new string('x', 100), "WL4H1:10235:3:2:NaN" }) + { a.UserNames[1] = invalid; Check(ReadyInfoProtocol.Read(a).Kind == ReadyHistoryKind.Unknown, "reject malformed/unbounded history " + invalid.Substring(0, Math.Min(38, invalid.Length))); } + a.Entrys[1] = true; a.UserNames[1] = "Actual second player"; + Check(!ReadyInfoProtocol.Attach(a, new ReadyHistory { Kind = ReadyHistoryKind.Unplayed }) && a.UserNames[1] == "Actual second player", "never overwrite an active second player"); + var states = new PartyMemberState(); + states.SetState(0, PartyPartyClientStateID.Joined); states.SetState(1, PartyPartyClientStateID.FinishSetting); + states.SetState(2, PartyPartyClientStateID.ToReady); states.SetState(3, PartyPartyClientStateID.Request); + var rows = ReadyInfoOverlay.BuildRows(received, states, 30); + Check(rows.Select(r => r.Address).SequenceEqual(new uint[] { 30, 10, 20, 40 }), "local first and sorted remote identities match gameplay slot mapping"); + Check(rows.Select(r => r.Ready).SequenceEqual(new[] { false, true, false, true }), "readiness is matched by original member index, not visual order"); + Check(rows.Select(r => r.Difficulty).SequenceEqual(new[] { 3, 2, 0, 1 }), "each player keeps their chosen difficulty"); + Check(rows.Select(r => r.IconId).SequenceEqual(new[] { 130, 110, 120, 140 }), "each player keeps their resource icon ID"); + Check(rows[2].History.Achievement == 1010000 && rows[1].History.Kind == ReadyHistoryKind.Unplayed, "history stays attached to its player after sorting"); + received.MechaInfo[2].IsJoin = false; + Check(ReadyInfoOverlay.BuildRows(received, states, 30).Length == 3, "departed member immediately disappears"); + Check(ReadyInfoOverlay.BuildRows(null, null, 30).Length == 0 && ReadyInfoOverlay.BuildRows(received, null, 30).All(r => !r.Ready), "missing roster/state is handled without inventing readiness"); + Check(!ReadyInfoOverlay.IsReadyState(PartyPartyClientStateID.Disconnected) && !ReadyInfoOverlay.IsReadyState(PartyPartyClientStateID.Error) + && !ReadyInfoOverlay.IsReadyState(PartyPartyClientStateID.Play), "disconnected/error/playing are not preparation-ready states"); + var previousCulture = System.Threading.Thread.CurrentThread.CurrentCulture; + try { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR"); + Check(new ReadyHistory { Kind = ReadyHistoryKind.Played, Achievement = 1001234 }.DisplayText.Contains("100.1234%"), "display keeps invariant four-place percentage"); } + finally { System.Threading.Thread.CurrentThread.CurrentCulture = previousCulture; } + var harmony = new HarmonyLib.Harmony("ready.tests.hooks"); + ReadyInfoProtocol.Apply(harmony); + Check(harmony.GetPatchedMethods().Any(), "history constructor hook installs on actual game metadata"); + foreach (var type in new[] { typeof(Process.MusicSelectProcess), typeof(Process.EntryProcess), typeof(Process.GameProcess) }) + Check(AccessTools.Method(type, "OnStart") != null && AccessTools.Method(type, "OnRelease") != null, + type.Name + " lifecycle targets resolve; native Unity body execution requires the game"); + Check(AccessTools.Method(typeof(Process.MusicSelectProcess), "OnUpdate") != null, "preparation update target resolves"); + foreach (string method in new[] { "GetButtonDown", "GetButtonPush" }) + Check(AccessTools.Method(typeof(Manager.InputManager), method, new[] { typeof(int), typeof(Manager.InputManager.ButtonSetting) }) != null, "exact input overload resolves: " + method); + harmony.UnpatchSelf(); + var readMode = AccessTools.Method(typeof(LocalTestControl), "ReadEntryMode"); + Check((int)readMode.Invoke(null, new object[] { null }) == -1, "missing entry state cannot masquerade as a confirmation phase"); + foreach (var stateType in new[] { typeof(Process.Entry.State.ConfirmNewUser), typeof(Process.Entry.State.ConfirmEntry) }) + { + var stateObject = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(stateType); + var phaseField = AccessTools.Field(stateType, "_mode"); + var phase = Activator.CreateInstance(phaseField.FieldType, new object[] { null, null }); + phaseField.SetValue(stateObject, phase); + var modeProperty = AccessTools.Property(phase.GetType(), "Mode"); + modeProperty.SetValue(phase, Enum.ToObject(modeProperty.PropertyType, 0), null); + int before = (int)readMode.Invoke(null, new[] { stateObject }); + modeProperty.SetValue(phase, Enum.ToObject(modeProperty.PropertyType, 1), null); + int after = (int)readMode.Invoke(null, new[] { stateObject }); + Check(before == 0 && after == 1, stateType.Name + " exposes real subphase changes for stale-confirmation rejection"); + } + System.Console.WriteLine("READY INFO CHECKS PASSED " + count); + } + private static int Main() + { + AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { + string name = new AssemblyName(args.Name).Name; + var loaded = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == name); + if (loaded != null) return loaded; + string root = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..")); + foreach (string dir in new[] { "bin", "testrefs", "refs", "../worldlink-bots/bin" }) { + string path = Path.Combine(root, dir, name + ".dll"); if (File.Exists(path)) return Assembly.LoadFrom(path); + path = Path.ChangeExtension(path, ".exe"); if (File.Exists(path)) return Assembly.LoadFrom(path); + } return null; + }; + try { Run(); return 0; } catch (Exception error) { System.Console.WriteLine(error); return 1; } + } +} diff --git a/tests/mod/RecruitSongChecks.cs b/tests/mod/RecruitSongChecks.cs new file mode 100644 index 0000000..315a811 --- /dev/null +++ b/tests/mod/RecruitSongChecks.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using HarmonyLib; +using MAI2.Util; +using Manager; +using Manager.MaiStudio; +using Manager.Party.Party; +using Process; +using WorldLink; +using Util; +using MAI2System; +using Path = System.IO.Path; + +internal static class RecruitSongChecks +{ + static int count, lookups; + static bool loaded; + static DataManager data; + static NotesListManager notesManager; + static SortedDictionary songs = new SortedDictionary(); + static SortedDictionary charts = new SortedDictionary(); + static RecruitList rooms = new RecruitList(); + static IManager manager; + static void Check(bool value, string label) { if (!value) throw new Exception(label); count++; System.Console.WriteLine("PASS " + label); } + static void Set(object target, string property, object value) { target.GetType().GetProperty(property).GetSetMethod(true).Invoke(target, new[] { value }); } + static RecruitInfo Room(int id, uint ip = 1) + { + var r = new RecruitInfo { GroupID = FourMachineProtocol.RoomGroup, MusicID = id }; + r.MechaInfo.MusicID = id; r.MechaInfo.IpAddress = ip; r.MechaInfo.Entrys[0] = true; r.MechaInfo.FumenDifs[0] = 3; + return r; + } + static bool Data(ref DataManager __result) { __result = data; return false; } + static bool NotesManager(ref NotesListManager __result) { __result = notesManager; return false; } + static bool Loaded(ref bool __result) { __result = loaded; return false; } + static bool Music(int id, ref MusicData __result) { lookups++; songs.TryGetValue(id, out __result); return false; } + static bool Musics(ref Safe.ReadonlySortedDictionary __result) { __result = new Safe.ReadonlySortedDictionary(songs); return false; } + static bool Charts(ref SortedDictionary __result) { __result = charts; return false; } + static bool Manager(ref IManager __result) { __result = manager; return false; } + static bool Rooms(ref RecruitList __result) { __result = new RecruitList(rooms); return false; } + static bool Quiet() { return false; } + static void Patch(HarmonyLib.Harmony h, MethodBase target, string prefix) + { h.Patch(target, prefix: new HarmonyMethod(typeof(RecruitSongChecks), prefix)); } + + [MethodImpl(MethodImplOptions.NoInlining)] static void Setup() + { + data = (DataManager)FormatterServices.GetUninitializedObject(typeof(DataManager)); + notesManager = (NotesListManager)FormatterServices.GetUninitializedObject(typeof(NotesListManager)); + var client = (Client)FormatterServices.GetUninitializedObject(typeof(Client)); GC.SuppressFinalize(client); + var mt = typeof(Manager.Party.Party.Party).GetNestedType("Manager", BindingFlags.NonPublic); + manager = (IManager)FormatterServices.GetUninitializedObject(mt); GC.SuppressFinalize(manager); + AccessTools.Field(mt, "_client").SetValue(manager, client); + var h = new HarmonyLib.Harmony("worldlink.tests.songfixtures"); + Patch(h, AccessTools.PropertyGetter(typeof(Singleton), "Instance"), "Data"); + Patch(h, AccessTools.PropertyGetter(typeof(Singleton), "Instance"), "NotesManager"); + Patch(h, AccessTools.Method(typeof(DataManager), "IsLoaded"), "Loaded"); + Patch(h, AccessTools.Method(typeof(DataManager), "GetMusic"), "Music"); + Patch(h, AccessTools.Method(typeof(DataManager), "GetMusics"), "Musics"); + Patch(h, AccessTools.Method(typeof(NotesListManager), "GetNotesList"), "Charts"); + Patch(h, AccessTools.Method(typeof(Manager.Party.Party.Party), "Get"), "Manager"); + Patch(h, AccessTools.Method(typeof(Client), "GetRecruitListWithoutMe"), "Rooms"); + Patch(h, AccessTools.Method(typeof(MelonLoader.MelonLogger), "Warning", new[] { typeof(string) }), "Quiet"); + RecruitSongSafety.Apply(h); + Check(HarmonyLib.Harmony.GetPatchInfo(AccessTools.Method(typeof(Client), "GetRecruitListWithoutMe")).Postfixes + .Any(p => p.PatchMethod.DeclaringType == typeof(RecruitSongSafety)), "visible-room filter installs on actual game method"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] static void Run() + { + Core.Config = new WorldLink.Config(); + var song = new MusicData(); Set(song.name, "id", 11296); songs.Add(11296, song); + var wrapper = new NotesWrapper(); + for (int i = 0; i < 5; i++) { var note = new Notes(); Set(note, "isEnable", true); wrapper.NotesList.Add(note); } + charts.Add(11296, wrapper); + var room = Room(11296); + Check(!RecruitSongSafety.TryGetSong(room, out _, out _) && lookups == 0, "loading gate makes zero song queries"); + loaded = true; + Check(RecruitSongSafety.TryGetSong(room, out var actual, out var notes) && actual == song && notes == wrapper.NotesList, "loaded song and requested chart are accepted"); + charts.Clear(); lookups = 0; + Check(!RecruitSongSafety.TryGetSong(room, out _, out _) && lookups == 0, "unbuilt notes catalogue waits without querying music"); + charts.Add(11296, wrapper); + Check(!RecruitSongSafety.TryGetSong(Room(11931), out _, out _), "missing advertised song rejected without exception"); + Check(!RecruitSongSafety.Validate(11296, 3, null, wrapper.NotesList), "missing metadata rejected"); + Check(!RecruitSongSafety.Validate(11296, 3, song, null), "missing chart array rejected"); + Check(!RecruitSongSafety.Validate(11296, 3, song, wrapper.NotesList.Take(3).ToList()), "short chart array rejected"); + Check(!RecruitSongSafety.Validate(11296, -1, song, wrapper.NotesList) + && !RecruitSongSafety.Validate(11296, 5, song, wrapper.NotesList), "invalid difficulty rejected"); + Set(wrapper.NotesList[3], "isEnable", false); + Check(!RecruitSongSafety.TryGetSong(room, out _, out _), "disabled host difficulty rejected"); + Set(wrapper.NotesList[3], "isEnable", true); + Check(!RecruitSongSafety.Validate(11931, 3, song, wrapper.NotesList), "mismatched resolved song identity rejected"); + Check(!RecruitSongSafety.Validate(10000, 3, song, wrapper.NotesList) + && !RecruitSongSafety.Validate(20000, 3, song, wrapper.NotesList), "unsupported category boundaries rejected"); + var bad = Room(11296, 2); bad.MechaInfo.MusicID = 999; + Check(!RecruitSongSafety.TryGetSong(bad, out _, out _), "inconsistent room and machine song IDs rejected"); + rooms.Add(Room(11931, 3)); rooms.Add(room); rooms.Add(bad); + var filtered = manager.GetRecruitListWithoutMe(); + Check(filtered.Count == 1 && filtered[0] == room && rooms.Count == 3, "actual game getter exposes only valid room without changing source list"); + + // Exercise the real mod selection handler with game data types and no Unity renderer. + var select = (MusicSelectProcess)FormatterServices.GetUninitializedObject(typeof(MusicSelectProcess)); + var visible = new List(); + Futari.preSetConnectData(select, visible, null); + Check(visible.Count == 1 && visible[0].musicSelectData[0].MusicData == song && select.IsConnectingMusic, + "actual selection builder keeps valid song when missing advertisements precede it"); + Check(songs.Count == 1 && charts.Count == 1 && rooms.Count == 3, "selection refresh leaves source songs charts and advertisements intact"); + rooms.Clear(); rooms.Add(Room(11931)); + Futari.preSetConnectData(select, visible, null); + Check(visible.Count == 1 && visible[0].isWaitConnectScore && !select.IsConnectingMusic, + "all invalid advertisements yield a waiting slot rather than an empty selection list"); + Check(songs.Count == 1 && charts.Count == 1, "invalid-room refresh retains the local catalogue"); + rooms.Clear(); rooms.Add(room); + Futari.preSetConnectData(select, visible, null); + Check(select.IsConnectingMusic && visible[0].musicSelectData[0].MusicData == song, "valid room works after an invalid snapshot"); + loaded = false; lookups = 0; + Check(manager.GetRecruitListWithoutMe().Count == 0 && lookups == 0, "actual visible-room path also avoids lookups during reload"); + loaded = true; + foreach (bool freedom in new[] { true, false }) + { + GameManager.IsFreedomMode = freedom; GameManager.IsCourseMode = !freedom; + string mode = freedom ? "Freedom" : "Course"; + lookups = 0; + Check(!RecruitSongSafety.TryGetSong(room, out _, out _) && lookups == 0, mode + " ignores advertisements before reading song data"); + Check(manager.GetRecruitListWithoutMe().Count == 0, mode + " exposes no joinable advertisements"); + var sentinel = visible[0]; + Futari.preSetConnectData(null, visible, null); + Check(visible.Count == 1 && visible[0] == sentinel, mode + " cannot mutate selection lists even with a valid advertised song"); + bool connect = true; + Futari.preIsConnectStart(null, null, null, ref connect); + Check(!connect, mode + " cannot initiate automatic connection-category refresh"); + RecruitInfo selected = room; + Futari.postRecruitData(null, ref selected); Futari.postPartyExec(null); + Check(ReferenceEquals(selected, room), mode + " UI hooks do not access uninitialized category or monitor objects"); + } + GameManager.IsFreedomMode = false; GameManager.IsCourseMode = false; + Check(RecruitSongSafety.TryGetSong(room, out _, out _), "normal mode accepts valid rooms after leaving solo modes"); + System.Console.WriteLine("RECRUIT SONG CHECKS PASSED " + count); + } + + public static int RunAll() + { + try { Setup(); Run(); return 0; } catch(Exception ex) { System.Console.WriteLine(ex.GetType().FullName + ": " + ex.Message); if(ex.InnerException != null) System.Console.WriteLine(ex.InnerException.GetType().FullName + ": " + ex.InnerException.Message); return 1; } + } +} +internal static class RecruitSongEntry +{ + static int Main() + { + AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { + string name = new AssemblyName(args.Name).Name; + var existing = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == name); + if (existing != null) return existing; + string root = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..")); + foreach (var dir in new[] { "bin", "testrefs", "refs" }) { string p = Path.Combine(root, dir, name + ".dll"); if (File.Exists(p)) return Assembly.LoadFrom(p); } + return null; + }; + return RecruitSongChecks.RunAll(); + } +} diff --git a/tests/mod/Support/NormalizeFixture.cs b/tests/mod/Support/NormalizeFixture.cs new file mode 100644 index 0000000..b4a4bc4 --- /dev/null +++ b/tests/mod/Support/NormalizeFixture.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Mono.Cecil; +using Mono.Cecil.Cil; + +internal static class NormalizeFixture +{ + private static int Main(string[] args) + { + var resolver = new DefaultAssemblyResolver(); + resolver.AddSearchDirectory(Path.GetDirectoryName(Path.GetFullPath(args[0]))); + var parameters = new ReaderParameters { AssemblyResolver = resolver }; + using (var source = AssemblyDefinition.ReadAssembly(args[0], parameters)) + { + source.MainModule.Attributes |= ModuleAttributes.ILOnly; + source.Write(args[1]); + using (var normalized = AssemblyDefinition.ReadAssembly(args[1], parameters)) + { + var methods = AllTypes(normalized.MainModule.Types).SelectMany(type => type.Methods) + .ToDictionary(method => method.FullName); + int count = 0; + foreach (var method in AllTypes(source.MainModule.Types).SelectMany(type => type.Methods)) + { + MethodDefinition copy = methods[method.FullName]; + if (!method.HasBody) + { + if (copy.HasBody) throw new Exception("Unexpected body " + method.FullName); + continue; + } + if (Signature(method) != Signature(copy)) + throw new Exception("Method IL changed " + method.FullName); + count++; + } + System.Console.WriteLine("Normalized test-only assembly; identical IL semantics for " + count + " method bodies."); + } + } + return 0; + } + + private static IEnumerable AllTypes(IEnumerable roots) + { + foreach (var type in roots) + { + yield return type; + foreach (var nested in AllTypes(type.NestedTypes)) yield return nested; + } + } + + private static string Signature(MethodDefinition method) + { + string locals = string.Join("|", method.Body.Variables.Select(variable => variable.VariableType.FullName)); + string instructions = string.Join("\n", method.Body.Instructions.Select(instruction => + instruction.OpCode.Name + " " + Operand(instruction.Operand))); + string handlers = string.Join("\n", method.Body.ExceptionHandlers.Select(handler => + handler.HandlerType + " " + Operand(handler.TryStart) + " " + Operand(handler.TryEnd) + " " + + Operand(handler.HandlerStart) + " " + Operand(handler.HandlerEnd) + " " + + Operand(handler.FilterStart) + " " + Operand(handler.CatchType))); + return method.Body.InitLocals + "\n" + locals + "\n" + instructions + "\n" + handlers; + } + + private static string Operand(object value) + { + if (value == null) return "null"; + var targets = value as Instruction[]; + if (targets != null) return string.Join(",", targets.Select(target => target.Offset)); + var instruction = value as Instruction; + if (instruction != null) return "label:" + instruction.Offset; + var local = value as VariableDefinition; + if (local != null) return "local:" + local.Index; + var parameter = value as ParameterDefinition; + if (parameter != null) return "arg:" + parameter.Index; + var reference = value as MemberReference; + if (reference != null) return reference.FullName; + return value.ToString(); + } +} diff --git a/tests/mod/Support/PartyWireCodec.cs b/tests/mod/Support/PartyWireCodec.cs new file mode 100644 index 0000000..a14a340 --- /dev/null +++ b/tests/mod/Support/PartyWireCodec.cs @@ -0,0 +1,367 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text; +using System.Web.Script.Serialization; +using MAI2.Memory; +using Manager.Party.Party; +using PartyLink; + +namespace WorldLinkBots +{ + public sealed class PartyWirePacket + { + public Command Command { get; private set; } + public ICommandParam Payload { get; private set; } + // Binary messages retain their zero padding, matching Packet.getParam. + public byte[] RawPayload { get; private set; } + + internal PartyWirePacket(Command command, ICommandParam payload, byte[] rawPayload) + { + Command = command; + Payload = payload; + RawPayload = rawPayload; + } + } + + // Adapter for the already-installed WorldLink plaintext PartyLink transport. + // This test client uses the game's binary serializers but never calls JsonUtility, + // game logging, native sockets, or Unity lifecycle methods. + public static class PartyWireCodec + { + public const int MaxPacketSize = WorldLink.FourMachineProtocol.PacketCapacity; + public const uint WireVersion = WorldLink.FourMachineProtocol.WireVersion; + private static readonly object InitializeLock = new object(); + private static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true); + private static readonly Dictionary FieldCache = new Dictionary(); + private static bool initialized; + + public static void Initialize() + { + lock (InitializeLock) + { + if (initialized) return; + WorldLink.FourMachineProtocol.Initialize(); + initialized = true; + } + } + + public static byte[] Encode(ICommandParam payload) + { + if (payload == null) throw new ArgumentNullException("payload"); + Initialize(); + Command command = payload.getCommand(); + System.Type expected = CommandType(command); + if (payload.GetType() != expected) + throw new InvalidDataException("Wrong payload type for command " + (int)command + "."); + byte[] raw; + if (IsBinary(command)) + { + raw = new byte[MaxPacketSize]; + var chunk = new Chunk(0, raw.Length, raw); + int size; + switch (command) + { + case Command.ClientPlayInfo: size = ((ClientPlayInfo)payload).Serialize(0, chunk); break; + case Command.PartyPlayInfo: size = ((PartyPlayInfo)payload).Serialize(0, chunk); break; + case Command.PartyMemberInfo: size = ((PartyMemberInfo)payload).Serialize(0, chunk); break; + case Command.SettingHostAddress: size = ((Setting.SettingHostAddress)payload).serialize(0, chunk); break; + case Command.AdvocateDelivery: size = ((AdvocateDelivery)payload).serialize(0, chunk); break; + default: throw new InvalidDataException("Unsupported binary command."); + } + Array.Resize(ref raw, size); + } + else raw = Utf8.GetBytes(ToJson(payload)); + + // Packet.encode pads everything after the length word to an AES block, + // even though WorldLink's encrypt prefix copies the packet unchanged. + int packetSize = checked(4 + ((12 + raw.Length + 15) & ~15)); + ValidateLength(packetSize); + byte[] result = new byte[packetSize]; + WriteUInt32(result, 0, (uint)packetSize); + WriteUInt32(result, 4, WireVersion); + WriteUInt32(result, 8, WireVersion); + WriteUInt32(result, 12, (uint)command); + Buffer.BlockCopy(raw, 0, result, 16, raw.Length); + return result; + } + + public static PartyWirePacket Decode(byte[] packet) + { + if (packet == null) throw new ArgumentNullException("packet"); + Initialize(); + ValidateLength(packet.Length); + if (ReadUInt32(packet, 0) != packet.Length) + throw new InvalidDataException("Packet length does not match its frame."); + if (ReadUInt32(packet, 4) != WireVersion || ReadUInt32(packet, 8) != WireVersion) + throw new InvalidDataException("Room uses a different WorldLink wire version."); + Command command = (Command)ReadUInt32(packet, 12); + System.Type type = CommandType(command); + byte[] raw = new byte[packet.Length - 16]; + Buffer.BlockCopy(packet, 16, raw, 0, raw.Length); + ICommandParam payload; + try + { + if (IsBinary(command)) + { + int position = 0; + var chunk = new Chunk(0, raw.Length, raw); + switch (command) + { + case Command.ClientPlayInfo: payload = new ClientPlayInfo().Deserialize(ref position, chunk); break; + case Command.PartyPlayInfo: payload = new PartyPlayInfo().Deserialize(ref position, chunk); break; + case Command.PartyMemberInfo: payload = new PartyMemberInfo().Deserialize(ref position, chunk); break; + case Command.SettingHostAddress: payload = new Setting.SettingHostAddress().deserialize(ref position, chunk); break; + case Command.AdvocateDelivery: payload = new AdvocateDelivery().deserialize(ref position, chunk); break; + default: throw new InvalidDataException("Unsupported binary command."); + } + ValidatePadding(raw, position); + } + else + { + int count = raw.Length; + while (count > 0 && raw[count - 1] == 0) count--; + ValidatePadding(raw, count); + payload = (ICommandParam)FromJson(Utf8.GetString(raw, 0, count), type); + if (payload == null) throw new InvalidDataException("Null command payload."); + } + } + catch (Exception error) + { + if (error is InvalidDataException) throw; + throw new InvalidDataException("Invalid payload for command " + (int)command + ".", error); + } + return new PartyWirePacket(command, payload, raw); + } + + public static string ToJson(object value) + { + return NewJson().Serialize(ToJsonValue(value, 0)); + } + + public static T FromJson(string json) + { + return (T)FromJson(json, typeof(T)); + } + + public static object FromJson(string json, System.Type type) + { + if (json == null) throw new ArgumentNullException("json"); + if (type == null) throw new ArgumentNullException("type"); + return FromJsonValue(NewJson().DeserializeObject(json), type, 0); + } + + private static JavaScriptSerializer NewJson() + { + return new JavaScriptSerializer { MaxJsonLength = 1024 * 1024, RecursionLimit = 64 }; + } + + private static object ToJsonValue(object value, int depth) + { + if (depth > 32) throw new InvalidDataException("JSON nesting is too deep."); + if (value == null) return null; + System.Type type = value.GetType(); + if (type.IsEnum) return Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture); + if (type == typeof(string) || type.IsPrimitive || type == typeof(decimal)) return value; + IDictionary dictionary = value as IDictionary; + if (dictionary != null) + { + var converted = new Dictionary(); + foreach (DictionaryEntry entry in dictionary) + converted.Add((string)entry.Key, ToJsonValue(entry.Value, depth + 1)); + return converted; + } + IList list = value as IList; + if (list != null) + { + var converted = new object[list.Count]; + for (int i = 0; i < list.Count; i++) converted[i] = ToJsonValue(list[i], depth + 1); + return converted; + } + var fields = new Dictionary(); + foreach (FieldInfo field in JsonFields(type)) + fields.Add(field.Name, ToJsonValue(field.GetValue(value), depth + 1)); + return fields; + } + + private static object FromJsonValue(object value, System.Type type, int depth) + { + if (depth > 32) throw new InvalidDataException("JSON nesting is too deep."); + if (value == null) return type.IsValueType ? Activator.CreateInstance(type) : null; + if (type == typeof(object)) return value; + if (type.IsEnum) return Enum.ToObject(type, Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture)); + if (type == typeof(string) || type.IsPrimitive || type == typeof(decimal)) + return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); + IList list = value as IList; + if (type.IsArray) + { + if (list == null) throw new InvalidDataException("Expected a JSON array."); + System.Type itemType = type.GetElementType(); + Array converted = Array.CreateInstance(itemType, list.Count); + for (int i = 0; i < list.Count; i++) converted.SetValue(FromJsonValue(list[i], itemType, depth + 1), i); + return converted; + } + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) + { + if (list == null) throw new InvalidDataException("Expected a JSON array."); + IList converted = (IList)Activator.CreateInstance(type); + System.Type itemType = type.GetGenericArguments()[0]; + foreach (object item in list) converted.Add(FromJsonValue(item, itemType, depth + 1)); + return converted; + } + var dictionary = value as IDictionary; + if (dictionary == null) throw new InvalidDataException("Expected a JSON object."); + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>) + && type.GetGenericArguments()[0] == typeof(string)) + { + IDictionary converted = (IDictionary)Activator.CreateInstance(type); + System.Type itemType = type.GetGenericArguments()[1]; + foreach (KeyValuePair item in dictionary) + converted.Add(item.Key, FromJsonValue(item.Value, itemType, depth + 1)); + return converted; + } + // JsonUtility.FromJson does not execute constructors or field initializers. + // This also prevents a missing GroupID from inheriting the four-machine + // marker installed by the patched RecruitInfo constructor. + object result = type.IsValueType ? Activator.CreateInstance(type) : FormatterServices.GetUninitializedObject(type); + foreach (FieldInfo field in JsonFields(type)) + { + object raw; + if (dictionary.TryGetValue(field.Name, out raw)) + field.SetValue(result, FromJsonValue(raw, field.FieldType, depth + 1)); + } + return result; + } + + private static FieldInfo[] JsonFields(System.Type type) + { + lock (FieldCache) + { + FieldInfo[] cached; + if (FieldCache.TryGetValue(type, out cached)) return cached; + var fields = new List(); + for (System.Type current = type; current != null && current != typeof(object); current = current.BaseType) + { + foreach (FieldInfo field in current.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) + { + if (field.IsStatic || field.IsLiteral || field.IsInitOnly || field.IsNotSerialized) continue; + bool include = field.IsPublic; + if (!include) + foreach (CustomAttributeData attribute in field.GetCustomAttributesData()) + if (attribute.AttributeType.FullName == "UnityEngine.SerializeField") include = true; + if (include) fields.Add(field); + } + } + cached = fields.ToArray(); + FieldCache.Add(type, cached); + return cached; + } + } + + private static bool IsBinary(Command command) + { + return command == Command.ClientPlayInfo || command == Command.PartyPlayInfo || command == Command.PartyMemberInfo + || command == Command.SettingHostAddress || command == Command.AdvocateDelivery; + } + + private static System.Type CommandType(Command command) + { + int id = (int)command; + if (id <= 0 || id >= 32 || (id >= 2 && id <= 5)) + throw new InvalidDataException("Unknown PartyLink command " + id + "."); + // The game also has older nested PartyLink.Party DTOs. The active packet + // implementation uses Manager.Party.Party and must not select those aliases. + Assembly assembly = typeof(ICommandParam).Assembly; + string name = command.ToString(); + System.Type type = assembly.GetType("Manager.Party.Party." + name) + ?? assembly.GetType("PartyLink." + name) + ?? assembly.GetType("PartyLink.Setting+" + name) + ?? assembly.GetType("PartyLink.Advertise+" + name); + if (type == null || !typeof(ICommandParam).IsAssignableFrom(type)) + throw new InvalidDataException("No payload type for PartyLink command " + id + "."); + return type; + } + + internal static void ValidateLength(int length) + { + if (length < 20 || length > MaxPacketSize || ((length - 4) & 15) != 0) + throw new InvalidDataException("Invalid PartyLink packet length " + length + "."); + } + + private static void ValidatePadding(byte[] raw, int position) + { + if (position < 0 || position > raw.Length || raw.Length - position > 15) + throw new InvalidDataException("Invalid PartyLink payload length."); + for (int i = position; i < raw.Length; i++) + if (raw[i] != 0) throw new InvalidDataException("Nonzero PartyLink padding."); + } + + internal static uint ReadUInt32(byte[] buffer, int offset) + { + return (uint)(buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24); + } + + private static void WriteUInt32(byte[] buffer, int offset, uint value) + { + buffer[offset] = (byte)value; + buffer[offset + 1] = (byte)(value >> 8); + buffer[offset + 2] = (byte)(value >> 16); + buffer[offset + 3] = (byte)(value >> 24); + } + } + + public sealed class PartyWireFramer + { + private readonly byte[] buffer = new byte[PartyWireCodec.MaxPacketSize]; + private int buffered; + public int BufferedBytes { get { return buffered; } } + + public IEnumerable Feed(byte[] data) + { + if (data == null) throw new ArgumentNullException("data"); + return Feed(data, 0, data.Length); + } + + public IEnumerable Feed(byte[] data, int offset, int count) + { + if (data == null) throw new ArgumentNullException("data"); + if (offset < 0 || count < 0 || offset > data.Length - count) throw new ArgumentOutOfRangeException("count"); + var packets = new List(); + try + { + while (count > 0) + { + int needed = buffered < 4 ? 4 : checked((int)PartyWireCodec.ReadUInt32(buffer, 0)); + if (buffered >= 4) PartyWireCodec.ValidateLength(needed); + int take = Math.Min(count, needed - buffered); + Buffer.BlockCopy(data, offset, buffer, buffered, take); + offset += take; + count -= take; + buffered += take; + if (buffered >= 4) + { + int packetLength = checked((int)PartyWireCodec.ReadUInt32(buffer, 0)); + PartyWireCodec.ValidateLength(packetLength); + if (buffered == packetLength) + { + var packet = new byte[packetLength]; + Buffer.BlockCopy(buffer, 0, packet, 0, packetLength); + buffered = 0; + packets.Add(PartyWireCodec.Decode(packet)); + } + } + } + } + catch + { + buffered = 0; + throw; + } + return packets; + } + } +} diff --git a/tests/mod/TransportChecks.cs b/tests/mod/TransportChecks.cs new file mode 100644 index 0000000..1b29222 --- /dev/null +++ b/tests/mod/TransportChecks.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.CompilerServices; + +internal static class TransportChecks +{ + private static int checks; + private static readonly MethodInfo Dispatch = typeof(FutariClient).GetMethod("HandleIncomingMessage", BindingFlags.NonPublic | BindingFlags.Instance); + private static readonly ConstructorInfo SocketConstructor = typeof(FutariSocket).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(FutariClient), typeof(ProtocolType) }, null); + + private static void Check(bool condition, string name) + { + if (!condition) throw new Exception(name); + checks++; + System.Console.WriteLine("PASS " + name); + } + + private static FutariSocket Socket(FutariClient client) + { + return (FutariSocket)SocketConstructor.Invoke(new object[] { client, ProtocolType.Tcp }); + } + + private static void Route(FutariClient[] clients) + { + foreach (var client in clients) + { + FutariMsg message; + while (client.sendQ.TryDequeue(out message)) + { + var parsed = FutariMsg.FromString(message.ToString()); + var target = clients.Single(item => item.StubIP.ToU32() == parsed.dst); + Dispatch.Invoke(target, new object[] { parsed }); + } + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static void Run() + { + WorldLink.Core.Config = new WorldLink.Config { Debug = false }; + Check(FutariClient.ConnectionKey(1, 10) != FutariClient.ConnectionKey(2, 9), "stream and port pairs do not collide"); + var clients = Enumerable.Range(0, 4).Select(i => new FutariClient("FourPlayerTest" + i, "localhost", 20101, 0)).ToArray(); + var listener = Socket(clients[0]); + listener.Bind(new IPEndPoint(IPAddress.Any, 50100)); + listener.Listen(4); + var outgoing = new FutariSocket[3]; + var accepted = new FutariSocket[3]; + int completed = 0; + for (int i = 0; i < 3; i++) + { + outgoing[i] = Socket(clients[i + 1]); + var args = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(clients[0].StubIP, 50100) }; + args.Completed += delegate { completed++; }; + Check(outgoing[i].ConnectAsync(args, 0), "asynchronous connect queued " + i); + Route(clients); + Check(FutariSocket.Poll(listener, SelectMode.SelectRead), "host sees pending connection " + i); + accepted[i] = listener.Accept(); + Route(clients); + } + Check(completed == 3, "three remote connection callbacks completed"); + Check(clients[0].tcpRecvQ.Count == 3, "host retains three distinct receive streams"); + for (int i = 0; i < 3; i++) + { + byte[] payload = Enumerable.Range(0, 8192).Select(n => (byte)(n + i)).ToArray(); + outgoing[i].Send(payload, 0, payload.Length, SocketFlags.None); + Route(clients); + var received = new List(); + var buffer = new byte[261]; + SocketError error; + int peeked = accepted[i].Receive(buffer, 3, 257, SocketFlags.Peek, out error); + Check(peeked == 257 && error == SocketError.Success && buffer[0] == 0, "receive respects offset and peek " + i); + while (received.Count < payload.Length) + { + Check(FutariSocket.Poll(accepted[i], SelectMode.SelectRead), "buffered stream remains readable " + i + "/" + received.Count); + int count = accepted[i].Receive(buffer, 3, 257, SocketFlags.None, out error); + if (count <= 0 || error != SocketError.Success) throw new Exception("incomplete stream"); + received.AddRange(buffer.Skip(3).Take(count)); + } + Check(payload.SequenceEqual(received), "8192 byte payload survives bounded partial reads " + i); + Check(!FutariSocket.Poll(accepted[i], SelectMode.SelectRead), "drained stream not readable " + i); + Check(accepted[i].Receive(buffer, 0, buffer.Length, SocketFlags.None, out error) == 0 && error == SocketError.WouldBlock, "empty stream reports WouldBlock " + i); + accepted[i].Send(payload, 17, 99, SocketFlags.None); + Route(clients); + int returned = outgoing[i].Receive(buffer, 0, buffer.Length, SocketFlags.None, out error); + Check(returned == 99 && buffer.Take(99).SequenceEqual(payload.Skip(17).Take(99)), "host reply routes to correct client " + i); + } + outgoing[1].Close(); + Route(clients); + SocketError closeError; + Check(FutariSocket.Poll(accepted[1], SelectMode.SelectRead) && accepted[1].Receive(new byte[10], 0, 10, SocketFlags.None, out closeError) == 0 && closeError == SocketError.Success, "peer close produces EOF"); + Check(!FutariSocket.Poll(accepted[0], SelectMode.SelectRead) && !FutariSocket.Poll(accepted[2], SelectMode.SelectRead), "closing one client preserves other streams"); + System.Console.WriteLine("TRANSPORT CHECKS PASSED " + checks); + } +} + +internal static class TransportBootstrap +{ + public static int Main() + { + AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs args) + { + string name = new AssemblyName(args.Name).Name; + Assembly loaded = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == name); + if (loaded != null) return loaded; + string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "testrefs", name + ".dll"); + if (!File.Exists(file)) file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "refs", name + ".dll"); + return File.Exists(file) ? Assembly.LoadFrom(file) : null; + }; + try { TransportChecks.Run(); return 0; } + catch (Exception error) { System.Console.WriteLine(error); return 1; } + } +}