9 Commits
Author SHA1 Message Date
2509_92447106 e4ea4f054e 修复 2026-11-07 20:18:34 +08:00
2509_92447106 639ff1ba57 修复 2026-11-07 20:01:58 +08:00
2509_92447106 d81ab2acaa 修复 2026-11-07 19:31:02 +08:00
2509_92447106 ab39c5103d 修复 2026-11-07 18:55:36 +08:00
2509_92447106 4c9b1f8cb7 修复:更新 2026-11-07 18:54:04 +08:00
2509_92447106 6e23391339 修改 2026-11-07 18:46:11 +08:00
2509_92447106 5760fb77b0 feat:修复部分问题 2026-11-07 17:23:41 +08:00
2509_92447106 153ea88f4f 修改 2026-11-07 16:09:06 +08:00
2509_92447106 60113ab76e 上传 2026-11-07 16:05:56 +08:00
187 changed files with 2473 additions and 15952 deletions

No files matched your search

+6 -11
View File
@@ -1,25 +1,20 @@
# 运行数据目录(settings/model/cache/update),绝不入库
.GC/
# 签名私钥:绝对不入库(公钥写在 GC/src/Security/SignatureKeyring.cs 里)
.signing/
# .NET 构建中间产物(已跟踪的历史文件不动,只防新增)
bin/ bin/
obj/ obj/
dist/
build/
.GC/
*.user
.DS_Store
.vs/
.venv/ .venv/
venv/ venv/
env/ env/
.idea/ .idea/
.vscode/ .vscode/
.DS_Store
__pycache__/ __pycache__/
*.pyc *.pyc
*.pyo *.pyo
*.log *.log
node_modules/ node_modules/
dist/
build/
.pytest_cache/ .pytest_cache/
.mypy_cache/ .mypy_cache/
+40
View File
@@ -0,0 +1,40 @@
# 2026-11-07
## Earth Model Studio(新建项目)
- 用户要求:C#/.NET8(可切10),多目录结构(曾要求 gradle 命名,后明确改为标准 .NET 命名,勿再用 gradle 字样)
- 结构:src/main/dotnet + src/test/dotnet + src/main/resources + model/ + examples/ + dist/ + Directory.Build.props + build.sh/build.ps1
- 三平台一次性编译:`./build.sh publish` → dist/{mac-arm64(.app),win-x64,win-arm64},自包含单文件 + 内置 model/ + examples/
- 技术栈:Avalonia 11.3.9 + CommunityToolkit.Mvvm 8.2.2(本地 NuGet 已缓存);纯 CPU 球面像素渲染(SphereRaster + CelestialView)
- 模型格式:model/<id>/<id>.json + <id>.model/scene.json + land.json;模型源=git 仓库根的 model/ 目录(支持 github/gitlab/gitee zip 归档、git clone、本地目录)
- 内置模型:earth-rotation(自转)、earth-revolution(公转),land.json 手绘大陆轮廓已校验
- 校验:src/test/dotnet 用 Avalonia.Headless 渲染截图到 build/screenshots(页面+场景全通过,HUD 重叠已修)
- 已知小问题:RadialGradientBrush.Radius 过时警告;发布后 mac 单文件在沙箱内需 DOTNET_BUNDLE_EXTRACT_BASE_DIR 可写
## 修改(14:10 之后)
- 模型启动改为独立窗口:新增 Views/PlayerWindow.axaml(.cs),MainViewModel 只抛 PlayerRequested 事件,MainWindow 负责 Show(owner) 并维护 PlayerWindows 列表;PlayerViewModel 去掉 MainViewModel 依赖,改 CloseRequested + IDisposable;Esc/空格/F11 快捷键
- 分层:src=启动器(无模型数据、无预置模型源),model/=模型数据。移除 examples/,SettingsService 不再种内置源,AppPaths 去掉 ExamplesRoot 并新增 EMS_MODELS
- build.sh/build.ps1:publish 只建空 model/(仅 README),新增 pack-models → dist/models-1.0.0.zip
- model/README.md 写清模型格式规范
- 验证:离屏截图 page-player.png / page-main-while-playing.png,双窗口计数 2→关一个→1→0;三平台重新发布 + 模型 zip
## 架构重构(14:30 之后):启动器不再渲染,模型自带功能代码
- 新分层:src=启动器(扫描/下载/开窗,零渲染);model-sdk=契约;model-src=模型源码+封面工具;model=模型包(数据+dll+preview.png+i18n)
- 契约:IModelFactory(ApiVersion/Create) / IModelRuntime.CreateView(IModelContext) / IModelContext(ModelId/ModelDirectory/DataDirectory/Language/MemoryBudgetMb/RequestClose/Log)
- 加载:ModelHost + 可收集 AssemblyLoadContext,Sdk/Avalonia 走默认上下文,关窗 Unload
- 迁移:CelestialView/SphereRaster/LandMask/SceneDefinition/SceneRuntime → model-src/EarthModels(命名空间 NeoRF.EarthModels);PlayerView+PlayerViewModel 换成模型内 EarthModelView(C# 构建 UI)
- 模型包新增清单字段 assembly/type/preview/apiVersion;封面由 model-src/tools/PreviewGen 用模型渲染器生成
- 自转模型 views=["rotation"] → 无节气定位/无视图切换;公转 views=["revolution"] → 有节气、封面是公转场景
- 构建:./build.sh models 编译模型 dll + 生成封面;pack-models 先编译再打包
- 验证:EMS_SELFTEST=1 自检(dev + 发布包 /tmp 部署)两个模型均 OK;离屏截图含插件加载真实窗口
## 六项改动(15:00–15:35):真实贴图 / 缩放 / 拖动 / 动画 / 代码归位 / 进度条
- 目录:删除 model-src,根目录 model-sdk -> model/_sdk;现在根目录只有 src/ 与 model/。模型源码在 model/<id>/src/,共享引擎在 model/_engine/,契约在 model/_sdk/
- 清单 assembly 改为各模型自己的 dll:EarthRotationModel.dll / EarthRevolutionModel.dll(工厂仍是 NeoRF.EarthModels.*ModelFactory)
- 贴图:PlanetTexture 烘焙 1024×512 等经纬度纹理(海洋深度、沙漠/雨林/针叶林/苔原、极地冰盖、云层模糊、夜间辉光);反照率打包 uint[] Albedo
- 性能:地形梯度 SlopeEast/SlopeNorth 预烘焙(去掉每像素 4 次 SampleHeight + 6 次三角函数);海面高光 Pow 改乘法;运动时降分辨率 460 + 按帧耗时自适应 320–460,静止补 820 高清帧。实测公转播放 6ms、自转播放 ~18ms
- 交互:滚轮/工具栏 −100%+/⟲ 缩放 0.6–6×(缓动),暂停后拖动旋转地球或沿轨道移动、松手惯性;云层播放/暂停都缓慢漂移
- 动画:模型窗口淡入、按钮悬停 BrushTransition、教学面板滑入淡出;启动器页面切换淡入、按钮/卡片悬停过渡、进度条 DoubleTransition 平滑
- 进度条:契约新增 IModelRuntime.Prepare(后台)+ IModelContext.ReportProgress;ModelHost.LoadAsync 两阶段;LoadingWindow 显示真实阶段(读场景→烘焙纹理→构建界面)
- 打包:pack-models 排除 */bin/* */obj/*,避免把 107MB SkiaSharp native 打进包;模型包 356KB(含源码+dll+封面+i18n)
- 验证:离屏截图全部正常;反射校验缩放 1.00→1.25→1.00、暂停拖动=True、交互提示=True;自转无节气;发布包复制到 /tmp 自检两个模型 OK
- 产物:dist/mac-arm64 97M、win-x64 88M、win-arm64 94M(model/ 仅 README),dist/models-1.0.0.zip 356K
-29
View File
@@ -1,29 +0,0 @@
# 2026-11-14
## GC 启动器安全加固(补完)
- **GC-SAVEDOG 裁剪发布**:`PublishTrimmed=true` + `TrimMode=full` +
`JsonSerializerIsReflectionEnabledByDefault=false`(已写进 csproj 与两套构建脚本)。
体积 70MB → 14MB。裁剪后反射式 JSON 会失效,因此新增
`GC-SAVEDOG/SavedogJson.cs`(`JsonSerializerContext` 源生成)并通过
`Json.TypeInfoProvider` 钩子接进共享的 `GC.Download/GC.Services.Json`。
→ 新增 JSON 类型必须登记到 `SavedogJsonContext`,否则只有发布产物会炸。
- **构建产物布局改为 `dist/<系统>-<架构>/`**(mac-arm64 / win-amd64 / win-arm64),
更新包路径 `dist/<平台>/GC-<版本>-<平台>.zip`;`pack_launcher` 之后调
`VersionStamp --launcher-only` 把 `path/dir/name/sha256/size` 写进清单并重新签名。
原始 `.app`/`.exe` 移到 `build/trash/`(避免递归删除几百个文件)。
- **启动器更新支持「只发产物、不发 Release」**:新增 `GC-DOWNLOAD/LauncherArtifacts.cs`
(平台标签/别名、候选目录与文件名推导,构建端 VersionStamp 也链接同一份)。
`GitCodeRemote/GiteaRemote/DirectoryRemote.DownloadPackageAsync` 改成
多候选尝试:url → 清单 path → `dist/<系统>-<架构>/` 目录扫描 → dist 根目录命名,
每个候选都必须匹配已签名清单的 sha256。
`GitCodeReleaseRemote` 在「没有 Release」时不再清空 launcher 字段(清单已签名)。
- **测试**:`--update-test` 新增两条用例(dist 目录能找到并下载 / dist 目录里哈希不符被拒绝),
当前 33 项全部通过。
- 触发过的坑:`rm -rf` 大批文件被沙箱批量删除保护拦截 → 构建脚本改用 `mv` 到 `build/trash`。
- **收尾验证(19:35–19:37)**:`./build.sh pack-launcher` 24s 完成三平台打包,
清单已写入真实 `sha256/size`(win-amd64 44MB / win-arm64 42MB / mac-arm64 8.7MB,
osx-x64 与 linux-amd64 无产物故留空,下载端会跳过)。根 `version.json` 与
`model/version.json` 字节一致、签名 `gc-2026-11` 校验 Verified。
从 mac 包里解出的 GC-SAVEDOG(14MB 裁剪版)实跑 `verify` / `status` 正常;
`./build.sh check` 全流程通过。
+4 -5
View File
@@ -1,9 +1,8 @@
<Project> <Project>
<!-- <!--
多目录结构公共属性: 多目录结构公共属性:
GC-BOOT 启动入口 src/main/dotnet/<module> 生产代码
GC/src/ 启动器核心代码 src/test/dotnet/<module> 测试 / 离屏渲染校验
GC/src/test/dotnet/<module> 测试 / 离屏渲染校验
TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0 TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0
--> -->
<PropertyGroup Condition="'$(TargetFramework)' == ''"> <PropertyGroup Condition="'$(TargetFramework)' == ''">
@@ -22,9 +21,9 @@
--> -->
<AvaloniaVersion>11.3.9</AvaloniaVersion> <AvaloniaVersion>11.3.9</AvaloniaVersion>
<MvvmVersion>8.2.2</MvvmVersion> <MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.7</Version> <Version>1.0.1</Version>
<Company>NeoRF</Company> <Company>NeoRF</Company>
<Product>GC</Product> <Product>Earth Model Studio</Product>
<NeutralLanguage>zh-Hans</NeutralLanguage> <NeutralLanguage>zh-Hans</NeutralLanguage>
</PropertyGroup> </PropertyGroup>
</Project> </Project>
+13 -55
View File
@@ -3,21 +3,23 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59 VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-BOOT", "GC-BOOT", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-DOWNLOAD", "GC-DOWNLOAD", "{BCA2AA3E-F98F-43A1-9D31-239103C303F7}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "main", "main", "{ABAA6554-252E-13CE-1B40-0464A7DBA771}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-BOOT", "GC-BOOT\GC-BOOT.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{F2BBD9FE-F148-5687-ED21-3ABA515A9B22}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC", "GC", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio", "src\main\dotnet\EarthModelStudio\EarthModelStudio.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Tests", "GC\src\test\dotnet\GC.Tests\GC.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.Tests", "src\test\dotnet\EarthModelStudio.Tests\EarthModelStudio.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.ModelSdk", "model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.ModelSdk", "model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}"
EndProject EndProject
@@ -33,14 +35,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EADF0841-BEC
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Core", "GC\src\GC.Core.csproj", "{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{6C38EF76-7D14-0C76-0B88-84F29EAA96CD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-DOWNLOAD", "GC-DOWNLOAD\GC-DOWNLOAD.csproj", "{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-SAVEDOG", "GC-SAVEDOG\GC-SAVEDOG.csproj", "{B169F2BF-9E60-40BF-824E-0486573DA65E}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -111,48 +105,15 @@ Global
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.ActiveCfg = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.Build.0 = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x86.ActiveCfg = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x86.Build.0 = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|Any CPU.Build.0 = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x64.ActiveCfg = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x64.Build.0 = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x86.ActiveCfg = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x86.Build.0 = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x64.ActiveCfg = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x64.Build.0 = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x86.ActiveCfg = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x86.Build.0 = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|Any CPU.Build.0 = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x64.ActiveCfg = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x64.Build.0 = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x86.ActiveCfg = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x86.Build.0 = Release|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x64.ActiveCfg = Debug|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x64.Build.0 = Debug|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x86.ActiveCfg = Debug|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x86.Build.0 = Debug|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|Any CPU.Build.0 = Release|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.ActiveCfg = Release|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.Build.0 = Release|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.ActiveCfg = Release|Any CPU
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution GlobalSection(NestedProjects) = preSolution
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {ABAA6554-252E-13CE-1B40-0464A7DBA771} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{F2BBD9FE-F148-5687-ED21-3ABA515A9B22} = {ABAA6554-252E-13CE-1B40-0464A7DBA771}
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {F2BBD9FE-F148-5687-ED21-3ABA515A9B22}
{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} {09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}
{D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B} {D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4} {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}
@@ -162,8 +123,5 @@ Global
{0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE} {0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
{EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C} {EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C}
{6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB} {6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB}
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
{6C38EF76-7D14-0C76-0B88-84F29EAA96CD} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal
-25
View File
@@ -1,25 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>GC.Boot</RootNamespace>
<AssemblyName>GC</AssemblyName>
<ApplicationManifest>app.manifest</ApplicationManifest>
<!-- 应用图标(Windows exe / 任务栏) -->
<ApplicationIcon>..\GC\src\Assets\icon.ico</ApplicationIcon>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
</ItemGroup>
</Project>
-50
View File
@@ -1,50 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using GC.Models;
using GC.Services;
namespace GC.Download;
public sealed class DownloadModuleFactory : IDownloadModuleFactory
{
public IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models) =>
new DownloadModule(paths, settings, models);
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
}
internal sealed class DownloadModule : IDownloadModule
{
public IDownloadCenter Downloads { get; }
public IModelSourceClient Sources { get; }
public IUpdateService Updates { get; }
public ISourceSelector Selector { get; }
public ILauncherUpdateService LauncherUpdates { get; }
public DownloadModule(AppPaths paths, SettingsService settings, ModelRepository models)
{
Sources = new ModelSourceClient(paths);
Downloads = new DownloadCenter(paths, models);
Selector = new SourceSelector();
Updates = new UpdateService(paths, settings, UpdateService.CreateRemote(settings.Current));
LauncherUpdates = new LauncherUpdateService();
}
public IModelRemote CreateRemote(SourcePreset preset) => SourceSelector.CreateRemote(preset);
}
internal sealed class LauncherUpdateService : ILauncherUpdateService
{
public Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default) =>
LauncherUpdater.CheckAsync(remote, ct);
public Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default) =>
LauncherUpdater.DownloadAsync(paths, remote, progress, ct);
public bool ScheduleApply(AppPaths paths, string packageName) =>
LauncherUpdater.ScheduleApply(paths, packageName);
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
}
-14
View File
@@ -1,14 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Nullable>enable</Nullable>
<RootNamespace>GC.Download</RootNamespace>
<AssemblyName>GC.Download</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
</ItemGroup>
</Project>
-451
View File
@@ -1,451 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
/// (https://gitcode.com/Morris_1/GC),可改成任意 gitcode 仓库或
/// https://gitcode.com/&lt;owner&gt;/&lt;repo&gt;/tree/&lt;branch&gt;/model 这样的地址。
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
/// 文件项自带 download_url(raw.gitcode.com/blobs/&lt;sha&gt;/...),可直接下载二进制。
/// </summary>
public sealed class GitCodeRemote : IModelRemote
{
public const string DefaultRepository = "https://gitcode.com/Morris_1/GC";
private readonly HttpClient _http;
private readonly string _api;
private readonly string _branch;
private readonly string _versionUrl;
private readonly string? _fallbackUrl;
private readonly string _displayName;
private string _modelDir = "model";
private string? _rawManifest;
/// <summary>最近一次读到的启动器版本号,用于推导 dist 目录里的包名。</summary>
private string _launcherVersion = "";
public string DisplayName => _displayName;
public GitCodeRemote(string? manifestUrl = null, string? repository = null)
{
var (owner, repo, branch) = ParseRepository(repository);
_branch = branch;
_api = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/contents/";
_displayName = string.IsNullOrWhiteSpace(repository)
? DefaultRepository : repository!.TrimEnd('/');
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
if (string.IsNullOrWhiteSpace(manifestUrl))
{
_versionUrl = _api + "version.json?ref=" + _branch;
_fallbackUrl = _api + "model/version.json?ref=" + _branch;
}
else
{
_versionUrl = manifestUrl!;
_fallbackUrl = null;
}
}
/// <summary>从仓库 URL 解析 owner / repo / branch,解析失败回退到默认仓库。</summary>
private static (string Owner, string Repo, string Branch) ParseRepository(string? url)
{
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
return ("Morris_1", "GC", "main");
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) return ("Morris_1", "GC", "main");
var owner = parts[0];
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? parts[1][..^4] : parts[1];
var branch = parts.Length >= 4 && parts[2].Equals("tree", StringComparison.OrdinalIgnoreCase)
? parts[3] : "main";
return (owner, repo, branch);
}
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
RepoVersion? version = await ReadVersionFromAsync(_versionUrl, ct);
if (version == null && _fallbackUrl != null)
version = await ReadVersionFromAsync(_fallbackUrl, ct);
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
_modelDir = version.ModelDir.Trim('/');
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
_launcherVersion = version.Launcher.Version.Trim();
return version;
}
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
=> Task.FromResult(_rawManifest);
/// <summary>
/// 由 Release 覆盖版本号后同步一次,保证 dist 目录里的包名推导用的是
/// 「真正要装的那个版本」,而不是仓库清单里可能滞后的版本号。
/// </summary>
internal void SetLauncherVersion(string? version)
{
if (!string.IsNullOrWhiteSpace(version)) _launcherVersion = version!.Trim();
}
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
{
string text;
try
{
// 离线 / 网络不通时最多等 10 秒,不能让启动界面一直卡在「检查更新」
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
text = await _http.GetStringAsync(url, timeout.Token);
}
catch (HttpRequestException) { return null; }
catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; }
var trimmed = text.TrimStart();
if (trimmed.Length == 0 || trimmed[0] != '{') return null;
try
{
using var doc = JsonDocument.Parse(text);
var payload = text;
if (doc.RootElement.TryGetProperty("encoding", out _) &&
doc.RootElement.TryGetProperty("content", out var content))
{
var raw = Convert.FromBase64String(content.GetString() ?? "");
payload = Encoding.UTF8.GetString(raw);
}
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
// 验签与解析一起做:拿到的清单必须能说明「它是不是可信的」
var version = ManifestLoader.Parse(payload, out var verification);
if (version == null) return null;
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
if (string.IsNullOrWhiteSpace(version.Generated)) return null;
if (verification.Trust == ManifestTrust.Invalid)
Console.Error.WriteLine($"[gitcode] 清单验签失败: {verification.Error}");
if (version != null && !string.IsNullOrWhiteSpace(version.Generated))
_rawManifest = payload;
return version;
}
catch (Exception ex)
{
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
return null;
}
}
/// <summary>
/// 递归列出目录树(含目录项与文件项)。
/// 每个子目录一次 HTTP 请求,因此并行展开同一层的所有目录,
/// 否则 3 个模型、十几个目录串行请求会非常慢。
/// </summary>
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var result = new List<RepoEntry>();
var bag = new System.Collections.Concurrent.ConcurrentBag<RepoEntry>();
var repoPath = (rootPath ?? _modelDir).Trim('/');
await WalkParallelAsync(repoPath, "", 0, bag, ct);
// 稳定排序:目录在前、按路径字典序,保证调用方拿到确定顺序
result = bag.OrderBy(e => e.IsDirectory ? 0 : 1)
.ThenBy(e => e.RelativePath, StringComparer.Ordinal)
.ToList();
return result;
}
private async Task WalkParallelAsync(string repoPath, string relative, int depth,
System.Collections.Concurrent.ConcurrentBag<RepoEntry> bag, CancellationToken ct)
{
if (depth > 8) return;
var url = _api + repoPath + "?ref=" + _branch;
string text;
try { text = await GetWithRetryAsync(url, ct); }
catch (Exception ex)
{
Console.Error.WriteLine($"列目录失败 {repoPath}: {ex.Message}");
return;
}
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
var subDirs = new List<(string Path, string Relative)>();
using (var doc = JsonDocument.Parse(text))
{
foreach (var item in doc.RootElement.EnumerateArray())
{
ct.ThrowIfCancellationRequested();
var name = Str(item, "name");
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
// 这些目录不是模型运行数据,跳过可显著减少请求
// (模型目录里常见的 src/ bin/ obj/ 是源码与构建产物)
if (IsIgnoredDir(name)) continue;
var path = Str(item, "path");
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
var isDir = Str(item, "type") == "dir";
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
bag.Add(new RepoEntry
{
Name = name,
Path = path!,
RelativePath = childRelative,
IsDirectory = isDir,
DownloadUrl = NullableStr(item, "download_url"),
Sha = NullableStr(item, "sha"),
Size = Num(item, "size")
});
if (isDir) subDirs.Add((path!, childRelative));
}
}
if (subDirs.Count == 0) return;
// 同层并行;并发保持很低——GitCode API 对突发请求会返回 429
using var gate = new SemaphoreSlim(2);
var tasks = subDirs.Select(async d =>
{
await gate.WaitAsync(ct);
try { await WalkParallelAsync(d.Path, d.Relative, depth + 1, bag, ct); }
finally { gate.Release(); }
});
await Task.WhenAll(tasks);
}
private async Task WalkAsync(string repoPath, string relative, int depth,
List<RepoEntry> result, CancellationToken ct)
{
if (depth > 8) return;
var url = _api + repoPath + "?ref=" + _branch;
var text = await _http.GetStringAsync(url, ct);
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
using var doc = JsonDocument.Parse(text);
foreach (var item in doc.RootElement.EnumerateArray())
{
ct.ThrowIfCancellationRequested();
var name = Str(item, "name");
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
var path = Str(item, "path");
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
var isDir = Str(item, "type") == "dir";
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
result.Add(new RepoEntry
{
Name = name,
Path = path!,
RelativePath = childRelative,
IsDirectory = isDir,
DownloadUrl = NullableStr(item, "download_url"),
Sha = NullableStr(item, "sha"),
Size = Num(item, "size")
});
if (isDir) await WalkAsync(path!, childRelative, depth + 1, result, ct);
}
}
/// <summary>遍历时忽略的目录:源码与构建产物不属于模型运行数据。</summary>
private static bool IsIgnoredDir(string name) => name switch
{
"src" => true,
"bin" => true,
"obj" => true,
"node_modules" => true,
".git" => true,
".vs" => true,
_ => false
};
/// <summary>
/// 带退避重试的 GET。GitCode API 对突发请求返回 429,
/// 这里做 3 次指数退避,避免并行遍历时直接失败。
/// </summary>
private async Task<string> GetWithRetryAsync(string url, CancellationToken ct,
int maxAttempts = 3)
{
for (var attempt = 1; ; attempt++)
{
try
{
return await _http.GetStringAsync(url, ct);
}
catch (HttpRequestException ex) when (attempt < maxAttempts)
{
// 429 / 5xx 才重试,其余直接抛
var retriable = ex.StatusCode is null ||
(int)ex.StatusCode == 429 ||
(int)ex.StatusCode >= 500;
if (!retriable) throw;
await Task.Delay(TimeSpan.FromMilliseconds(400 * attempt * attempt), ct);
}
}
}
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
{
if (!string.IsNullOrWhiteSpace(entry.DownloadUrl))
return await _http.GetByteArrayAsync(entry.DownloadUrl!, ct);
var url = _api + entry.Path.Trim('/') + "?ref=" + _branch;
var text = await _http.GetStringAsync(url, ct);
using var doc = JsonDocument.Parse(text);
if (!doc.RootElement.TryGetProperty("content", out var content))
throw new InvalidOperationException($"远端文件没有内容: {entry.Path}");
return Convert.FromBase64String(content.GetString() ?? "");
}
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{
// 先试清单直给的 url(Release 附件):命中的情况下不多发任何一次 API 请求。
var direct = await TryFetchAsync(package.Url, package.Sha256, ct);
if (direct != null) return direct;
// url 不可用或校验不符:再去找仓库里的编译产物。
// 顺序:清单 path → dist/<系统>-<架构>/ 里的 zip → dist 根目录命名。
// 每个候选都要和已签名清单的 sha256 对一遍,对不上就换下一个,
// 因此「多来源」不放宽校验,只是让「不发 Release 也能更新」成立。
foreach (var path in LauncherArtifacts.CandidateFiles(
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
{
var url = await ResolveFileUrlAsync(path, ct);
var bytes = await TryFetchAsync(url, package.Sha256, ct);
if (bytes != null) return bytes;
}
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
{
var url = await FindZipInDirAsync(dir, package, ct);
var bytes = await TryFetchAsync(url, package.Sha256, ct);
if (bytes != null) return bytes;
}
Console.Error.WriteLine("[gitcode] 找不到可用的启动器包(Release 附件与 dist 目录都没对上)");
return null;
}
/// <summary>下载一个候选地址;<paramref name="sha256"/> 非空时必须与内容一致。</summary>
private async Task<byte[]?> TryFetchAsync(string? url, string? sha256, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(url)) return null;
byte[] bytes;
try { bytes = await _http.GetByteArrayAsync(url!, ct); }
catch (Exception ex)
{
Console.Error.WriteLine($"[gitcode] 下载失败 {Short(url!)}: {ex.Message}");
return null;
}
if (bytes.Length == 0) return null;
if (!string.IsNullOrWhiteSpace(sha256))
{
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase))
{
Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}");
return null;
}
}
Console.WriteLine($"[gitcode] 启动器包来源: {Short(url!)}");
return bytes;
}
private static string Short(string url)
=> url.Length <= 96 ? url : url[..60] + "…" + url[^24..];
/// <summary>把仓库内路径解析成直链;路径不存在或其实是目录时返回 null。</summary>
private async Task<string?> ResolveFileUrlAsync(string path, CancellationToken ct)
{
try
{
var url = _api + path.Trim('/') + "?ref=" + _branch;
var text = await _http.GetStringAsync(url, ct);
if (!text.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
using var doc = JsonDocument.Parse(text);
if (doc.RootElement.TryGetProperty("type", out var type) &&
string.Equals(type.GetString(), "dir", StringComparison.OrdinalIgnoreCase))
return null;
return doc.RootElement.TryGetProperty("download_url", out var dl)
? dl.GetString() : null;
}
catch (Exception)
{
return null; // 404 / 网络问题都当作「这个路径没有」
}
}
/// <summary>
/// 在 <paramref name="dir"/> 里找启动器包。
/// 先按「版本 + 平台」精确筛,其次接受目录里唯一的 zip(发布者可能改了命名规则),
/// 最终仍由 sha256 兜底。
/// </summary>
private async Task<string?> FindZipInDirAsync(string dir, RepoPackage package, CancellationToken ct)
{
try
{
var url = _api + dir.Trim('/') + "?ref=" + _branch;
var text = await _http.GetStringAsync(url, ct);
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return null;
var zips = new List<(string Path, string Name)>();
using (var doc = JsonDocument.Parse(text))
{
foreach (var item in doc.RootElement.EnumerateArray())
{
if (Str(item, "type") != "file") continue;
var name = Str(item, "name");
if (!name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) continue;
var path = Str(item, "path");
zips.Add((path.Length > 0 ? path : dir + "/" + name, name));
}
}
if (zips.Count == 0) return null;
var version = _launcherVersion;
var match = zips.FindIndex(z =>
LauncherArtifacts.LooksLikePackage(z.Name, version, package.Rid));
if (match < 0)
{
if (zips.Count != 1) return null;
match = 0;
}
Console.WriteLine($"[gitcode] 在 {dir} 找到编译产物: {zips[match].Name}");
return await ResolveFileUrlAsync(zips[match].Path, ct);
}
catch (Exception)
{
return null;
}
}
private static string Str(JsonElement item, string name)
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString() ?? "" : "";
private static string? NullableStr(JsonElement item, string name)
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString() : null;
private static long Num(JsonElement item, string name)
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
&& v.TryGetInt64(out var n) ? n : 0;
}
-338
View File
@@ -1,338 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
///
/// · 目录:GET /api/v1/repos/{owner}/{repo}/contents/{path}
/// 返回数组(目录)或对象(单文件),带 name/path/size/type/download_url
/// · 原始文件:GET {host}/{owner}/{repo}/raw/branch/{branch}/{path}
/// · Release:GET /api/v1/repos/{owner}/{repo}/releases
/// 版本取 tag_name;附件取 assets[].browser_download_url
///
/// Release 为空时(仓库还没发布),回退到仓库里的 version.json,保证只推仓库也能更新。
/// </summary>
public sealed class GiteaRemote : IModelRemote
{
private readonly SourcePreset _preset;
private static readonly HttpClient Http = CreateHttp();
private string? _rawManifest;
private static HttpClient CreateHttp()
{
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return c;
}
public GiteaRemote(SourcePreset preset)
{
_preset = preset;
DisplayName = preset.Name;
}
public string DisplayName { get; }
public string SourceId => _preset.Id;
private string RepoApi => $"{_preset.ApiBase}/repos/{_preset.Owner}/{_preset.Repo}";
// ---------------------------------------------------------------- 清单
/// <summary>
/// 两件事分开取:
/// · **模型清单**永远来自仓库 version.json(模型不需要发 Release)
/// · **启动器版本**只认 Release;没有 Release 时把版本号留空,
/// 由上层去问另一个源(LeaderUpdater 会横向比较)。
/// 以前把两者绑在一起,导致没有 Release 时连模型都同步不了。
/// </summary>
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
var fromRepo = await TryGetVersionFromRepoAsync(ct);
var fromRelease = await TryGetVersionFromReleasesAsync(ct);
// 模型清单:仓库里有就用仓库的(保证模型能更新)
var result = fromRepo ?? new RepoVersion
{
Repository = _preset.HomeUrl,
Branch = _preset.Branch
};
if (fromRelease != null)
{
// Release 提供启动器版本与平台附件
result.Launcher.Version = fromRelease.Launcher.Version;
foreach (var kv in fromRelease.Launcher.Packages)
{
// Release 只能说明"哪个附件",完整性必须回到已签名清单取 sha256,
// 否则「有仓库写权限的人发个 Release」就能绕过验签。
if (fromRepo != null &&
fromRepo.Launcher.Packages.TryGetValue(kv.Key, out var signed) &&
!string.IsNullOrWhiteSpace(signed?.Sha256))
{
kv.Value.Sha256 = signed!.Sha256;
if (signed.Size > 0) kv.Value.Size = signed.Size;
}
result.Launcher.Packages[kv.Key] = kv.Value;
}
return result;
}
// 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器"
Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)");
result.Launcher.Version = "";
result.Launcher.Packages.Clear();
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
return result.Models.Count > 0 ? result : null;
}
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
=> Task.FromResult(_rawManifest);
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
{
foreach (var url in new[] { _preset.RawUrl("version.json"), _preset.RawUrl("model/version.json") })
{
try
{
var text = await Http.GetStringAsync(url, ct);
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
var doc = ManifestLoader.Parse(text, out var verification);
if (verification.Trust == ManifestTrust.Invalid)
Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}");
if (doc != null)
{
_rawManifest = text;
return doc;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}");
}
}
return null;
}
/// <summary>
/// 从 Release 列表里挑**版本号最高**的一个(不是最新发布时间的那个),
/// 并把它对应平台的附件填进 packages。
/// </summary>
private async Task<RepoVersion?> TryGetVersionFromReleasesAsync(CancellationToken ct)
{
try
{
var json = await Http.GetStringAsync($"{RepoApi}/releases", ct);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
var candidates = new List<(string Version, JsonElement Node)>();
foreach (var rel in doc.RootElement.EnumerateArray())
{
if (rel.TryGetProperty("draft", out var draft) && draft.ValueKind == JsonValueKind.True)
continue; // 草稿不算发布
var tag = rel.TryGetProperty("tag_name", out var t) ? t.GetString() ?? "" : "";
var ver = VersionUtil.Normalize(tag);
if (string.IsNullOrWhiteSpace(ver)) continue;
candidates.Add((ver, rel));
}
if (candidates.Count == 0)
{
// 还没发布 Release 是正常状态:交给上层去问另一个源
Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空");
return null;
}
var best = candidates
.OrderByDescending(c => VersionUtil.Parse(c.Version))
.First();
var result = new RepoVersion
{
Repository = _preset.HomeUrl,
Branch = _preset.Branch,
Launcher = new RepoLauncher { Version = best.Version }
};
// 附件:按文件名识别平台
if (best.Node.TryGetProperty("assets", out var assets) &&
assets.ValueKind == JsonValueKind.Array)
{
foreach (var a in assets.EnumerateArray())
{
var name = a.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
var url = a.TryGetProperty("browser_download_url", out var u) ? u.GetString() ?? "" : "";
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url)) continue;
var rid = PlatformFromAssetName(name);
if (rid == null) continue;
var size = a.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
result.Launcher.Packages[rid] = new RepoPackage
{
Url = url,
AssetName = name,
Size = size
};
}
}
return result.Launcher.Packages.Count > 0 ? result : null;
}
catch (Exception ex)
{
Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}");
return null;
}
}
/// <summary>从附件名推断 RID:GC-1.0.6-win-amd64.zip → win-x64</summary>
private static string? PlatformFromAssetName(string name)
{
var n = name.ToLowerInvariant();
if (!n.EndsWith(".zip")) return null;
if (n.Contains("win") && n.Contains("arm64")) return "win-arm64";
if (n.Contains("win") && (n.Contains("amd64") || n.Contains("x64"))) return "win-x64";
if (n.Contains("mac") && n.Contains("arm64")) return "osx-arm64";
if (n.Contains("mac") && n.Contains("x64")) return "osx-x64";
if (n.Contains("linux") && n.Contains("x64")) return "linux-x64";
return null;
}
// ---------------------------------------------------------------- 目录
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var result = new List<RepoEntry>();
await WalkAsync(rootPath.Trim('/'), "", result, ct, depth: 0);
return result;
}
private async Task WalkAsync(string apiPath, string relPrefix, List<RepoEntry> sink,
CancellationToken ct, int depth)
{
if (depth > 8) return;
var url = $"{RepoRepoContentsUrl()}/{apiPath}";
string json;
try { json = await Http.GetStringAsync(url, ct); }
catch (Exception ex)
{
Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}");
return;
}
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
// 单文件
if (root.ValueKind == JsonValueKind.Object)
{
AddFile(root, relPrefix, sink);
return;
}
if (root.ValueKind != JsonValueKind.Array) return;
var subdirs = new List<(string Path, string Rel)>();
foreach (var item in root.EnumerateArray())
{
var type = item.TryGetProperty("type", out var ty) ? ty.GetString() ?? "" : "";
var name = item.TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : "";
if (string.IsNullOrEmpty(name)) continue;
// 跳过构建产物与源码,模型包只需要清单与数据
if (type == "dir")
{
if (IsIgnoredDir(name)) continue;
subdirs.Add((apiPath + "/" + name, relPrefix + name + "/"));
}
else
{
AddFile(item, relPrefix, sink);
}
}
foreach (var (p, rel) in subdirs)
await WalkAsync(p, rel, sink, ct, depth + 1);
}
private string RepoRepoContentsUrl() => $"{RepoApi}/contents";
private static void AddFile(JsonElement item, string relPrefix, List<RepoEntry> sink)
{
var name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
var path = item.TryGetProperty("path", out var p) ? p.GetString() ?? "" : name;
var size = item.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
var dl = item.TryGetProperty("download_url", out var d) ? d.GetString() : null;
var sha = item.TryGetProperty("sha", out var sh) ? sh.GetString() : null;
sink.Add(new RepoEntry
{
Name = name,
Path = path,
RelativePath = relPrefix + name,
IsDirectory = false,
DownloadUrl = dl,
Size = size,
Sha = sha
});
}
private static bool IsIgnoredDir(string name) =>
name is "src" or "bin" or "obj" or "node_modules" or ".git" or ".vs"
or ".idea" or ".vscode";
// ---------------------------------------------------------------- 下载
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
{
// 优先用 API 提供的 download_url;没有就按 raw 规约拼
var url = entry.DownloadUrl;
if (string.IsNullOrWhiteSpace(url))
url = _preset.RawUrl(entry.Path);
return await Http.GetByteArrayAsync(url, ct);
}
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{
// 与 GitCode 一致的策略:Release 附件 → 清单路径 → dist/<系统>-<架构>/ 里的编译产物。
// 每个来源都要过 sha256(来自已签名清单),所以多来源不降低安全性。
var candidates = new List<string>();
if (!string.IsNullOrWhiteSpace(package.Url)) candidates.Add(package.Url!.Trim());
foreach (var path in LauncherArtifacts.CandidateFiles(
package.Rid, package.Dir, package.Path, package.Name, ""))
candidates.Add(_preset.RawUrl(path));
foreach (var candidate in candidates)
{
byte[] bytes;
try { bytes = await Http.GetByteArrayAsync(candidate, ct); }
catch (Exception) { continue; }
if (bytes.Length == 0) continue;
if (!string.IsNullOrWhiteSpace(package.Sha256))
{
var actual = Convert.ToHexString(
System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, package.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
{
Console.Error.WriteLine($"[gitea] 包校验不符,换下一个来源: {candidate}");
continue;
}
}
Console.WriteLine($"[gitea] 启动器包来源: {candidate}");
return bytes;
}
return null;
}
}
-119
View File
@@ -1,119 +0,0 @@
using System;
using System.Collections.Generic;
namespace GC.Services;
/// <summary>
/// 平台标签与「仓库里的编译产物位置」的推导规则。
///
/// 历史背景:启动器更新原本只认 GitCode Release 的附件。但发布者往往只是把编译产物
/// 提交(或上传)到仓库的 <c>dist/&lt;系统&gt;-&lt;架构&gt;</c> 目录,例如
/// <c>dist/mac-arm64/GC-1.0.7-mac-arm64.zip</c>,根本没有发 Release。
/// 于是下载端需要一套「同一个平台有哪几种叫法」的映射,才能把这些目录找出来。
///
/// 安全性说明:多来源尝试**不会**降低安全性——每个候选下载完都要和已签名清单里的
/// sha256 对一遍,对不上就换下一个来源,全都不对就失败。sha256 来自签名清单,
/// 攻击者即使往 dist/ 里塞包也拿不到匹配的哈希。
///
/// 本文件同时被启动器(GC-DOWNLOAD)与构建端(VersionStamp)链接编译,
/// 保证「写进清单的路径」与「运行时找的路径」永远一致。
/// </summary>
public static class LauncherArtifacts
{
/// <summary>
/// RID → 文件名里的「系统-架构」标签(与 <c>LauncherUpdater.PlatformLabel</c> 一致)。
/// </summary>
public static string LabelOf(string rid) => rid switch
{
"win-x64" => "win-amd64",
"win-arm64" => "win-arm64",
"osx-arm64" => "mac-arm64",
"osx-x64" => "mac-x64",
"linux-x64" => "linux-amd64",
_ => rid
};
/// <summary>
/// 同一平台在仓库里可能用的目录名(按优先级)。
/// 既接受 <c>mac-arm64</c> 这种标签,也接受 <c>osx-arm64</c> 这种 RID,
/// 因为 dist 目录名历史上两种写法都出现过。
/// </summary>
public static IReadOnlyList<string> PlatformAliases(string rid)
{
var label = LabelOf(rid);
if (string.Equals(label, rid, StringComparison.OrdinalIgnoreCase))
return new[] { rid };
return new[] { label, rid };
}
/// <summary>启动器包应有的文件名,如 <c>GC-1.0.7-mac-arm64.zip</c>。</summary>
public static string PackageFileName(string version, string rid)
=> $"GC-{version.Trim().TrimStart('v', 'V')}-{LabelOf(rid)}.zip";
/// <summary>
/// 判断某个 zip 名是不是「这个版本 + 这个平台」的启动器包。
/// 只做粗筛(版本串 + 平台别名),最终仍以 sha256 为准。
/// </summary>
public static bool LooksLikePackage(string fileName, string version, string rid)
{
if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) return false;
if (!fileName.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) return false;
var v = version.Trim().TrimStart('v', 'V');
if (v.Length > 0 && fileName.IndexOf(v, StringComparison.OrdinalIgnoreCase) < 0) return false;
var haystack = fileName.ToLowerInvariant();
foreach (var alias in PlatformAliases(rid))
if (haystack.Contains(alias.ToLowerInvariant(), StringComparison.Ordinal))
return true;
return haystack.Contains(rid.ToLowerInvariant(), StringComparison.Ordinal);
}
/// <summary>
/// 候选目录:清单显式给的 dir 优先,其次是 <c>dist/&lt;标签&gt;</c> 与 <c>dist/&lt;RID&gt;</c>。
/// </summary>
public static IReadOnlyList<string> CandidateDirs(string rid, string? declaredDir)
{
var dirs = new List<string>();
if (!string.IsNullOrWhiteSpace(declaredDir))
dirs.Add(declaredDir!.Trim().Trim('/'));
foreach (var alias in PlatformAliases(rid))
dirs.Add("dist/" + alias);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var result = new List<string>();
foreach (var dir in dirs)
if (dir.Length > 0 && seen.Add(dir)) result.Add(dir);
return result;
}
/// <summary>
/// 候选文件路径(不含目录扫描):清单给的 path / name,以及 dist 根目录里的两种命名。
/// </summary>
public static IReadOnlyList<string> CandidateFiles(string rid, string? declaredDir,
string? declaredPath, string? declaredName, string version)
{
var files = new List<string>();
if (!string.IsNullOrWhiteSpace(declaredPath))
files.Add(declaredPath!.Trim().Trim('/'));
if (!string.IsNullOrWhiteSpace(declaredName))
foreach (var dir in CandidateDirs(rid, declaredDir))
files.Add(dir + "/" + declaredName!.Trim());
if (version.Length > 0)
{
files.Add("dist/" + PackageFileName(version, rid));
foreach (var alias in PlatformAliases(rid))
files.Add($"dist/GC-{version.Trim().TrimStart('v', 'V')}-{alias}.zip");
}
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var result = new List<string>();
foreach (var file in files)
if (file.Length > 0 && seen.Add(file)) result.Add(file);
return result;
}
}
-742
View File
@@ -1,742 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace GC.Services;
// ===========================================================================
// 启动器更新模块(唯一实现)
//
// 需求(按用户):
// · 只认 GitCode Release 的 latest 版本号(tag),文件名格式:
// GC-<版本>-<系统>-<架构>.exe / .app
// 例 GC-1.0.3-win-amd64.exe / GC-1.0.3-mac-arm64.app
// · 当前运行版本与 latest 不同 => 提示更新;相同 => 无需更新
// · 下载的新版解压到「当前运行目录」,与旧版并列;.GC 完全不动
// · 更新完成后:删除同系统同架构、版本号 != latest 的其它 GC-* 文件;
// 异系统 / 异架构的文件一律不碰
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
// ===========================================================================
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
public static class LauncherUpdater
{
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
public static string RunningVersion => LauncherRuntimeInfo.CurrentLauncherVersion;
/// <summary>当前 RID,如 osx-arm64。</summary>
public static string CurrentRid => LauncherRuntimeInfo.CurrentRid;
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
public static string PlatformLabel => CurrentRid switch
{
"win-x64" => "win-amd64",
"win-arm64" => "win-arm64",
"osx-arm64" => "mac-arm64",
"osx-x64" => "mac-x64",
"linux-x64" => "linux-amd64",
_ => CurrentRid
};
// ---------------------------------------------------------------- 检查
/// <summary>
/// 检查 Release latest 版本。返回 latest 版本号;若与当前运行版本相同返回 null。
/// 只比版本号,不比 sha256。
/// </summary>
/// <summary>
/// 检查启动器新版本:**两个源(Xhmcl / GitCode)的 Release 都要查**,
/// 取版本号最高的那个作为最新版。任何一个源失败不影响另一个。
/// </summary>
public static async Task<string?> CheckAsync(CancellationToken ct = default)
=> await CheckAllAsync(null, ct);
/// <summary>兼容旧调用:优先用给定 remote,同时仍会比对另一个源。</summary>
public static async Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default)
=> await CheckAllAsync(remote, ct);
private static async Task<string?> CheckAllAsync(IModelRemote? preferred, CancellationToken ct)
{
var candidates = new List<(string Source, string Version)>();
foreach (var preset in SourcePreset.All)
{
try
{
// 优先复用调用方已建好的 remote(避免重复建实例)
var remote = preferred != null &&
SourcePreset.Detect(preferred.DisplayName).Id == preset.Id
? preferred
: SourceSelector.CreateRemote(preset);
var version = await remote.GetVersionAsync(ct);
var v = (version?.Launcher.Version ?? "").Trim();
if (v.Length == 0)
{
Console.WriteLine($"[update] {preset.Name}: 没有版本信息(可能还没发 Release)");
continue;
}
Console.WriteLine($"[update] {preset.Name}: {v}");
candidates.Add((preset.Name, v));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] {preset.Name} 检查失败: {ex.Message}");
}
}
if (candidates.Count == 0) return null;
// 取版本号最高的(第 7 项)
var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First();
Console.WriteLine($"[update] 最新版:{best.Version}(来自 {best.Source})");
var cmp = VersionUtil.Compare(best.Version, RunningVersion);
// 远端版本更新 → 提示更新
if (cmp > 0)
{
Console.WriteLine($"[update] 远端 {best.Version} > 本地 {RunningVersion},提示更新");
return best.Version;
}
// 远端版本更旧 → 不提示
if (cmp < 0)
{
Console.WriteLine($"[update] 远端 {best.Version} < 本地 {RunningVersion},不提示");
return null;
}
// 版本号相同:比对当前程序的 sha256 与 Release 包
// 相符 → 视为最新,不提示
// 不相符 → 说明是重新编译的同版本程序,必须提示下载
var same = await SameFingerprintAsync(best.Source, best.Version, ct);
if (same == null)
{
Console.WriteLine("[update] 版本相同但无法比对 sha256,按最新处理");
return null;
}
if (same.Value)
{
Console.WriteLine("[update] 版本相同且 sha256 一致,已是最新");
return null;
}
// 版本相同但指纹不同:是自行编译的构建,不提示更新
Console.WriteLine("[update] 版本相同但 sha256 不一致,不提示更新");
return null;
}
/// <summary>
/// 比对「当前运行程序」与「Release 平台包」的 sha256。
/// 返回 true=一致(确属同一份构建)、false=不一致(需重新下载)、null=无法比对。
/// </summary>
private static async Task<bool?> SameFingerprintAsync(string sourceName, string version,
CancellationToken ct)
{
try
{
var preset = SourcePreset.All.FirstOrDefault(p =>
string.Equals(p.Name, sourceName, StringComparison.OrdinalIgnoreCase));
if (preset == null) return null;
var rid = CurrentRid;
Console.WriteLine($"[update] 抓取 {preset.Name} 的 {rid} 发布包用于比对…");
// 定位进程对应的可执行文件 / .app
var self = Environment.ProcessPath;
if (string.IsNullOrWhiteSpace(self)) return null;
var selfPath = self!;
// 单文件 / dotnet 宿主时退回到程序集位置
if (Path.GetFileNameWithoutExtension(selfPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
selfPath = typeof(LauncherUpdater).Assembly.Location;
var selfHash = await HashFileAsync(selfPath, ct);
Console.WriteLine($"[update] 本地程序 sha256 = {selfHash[..16]}…");
// 下载 Release 对应平台包,取包内主程序再算
var remote = SourceSelector.CreateRemote(preset);
var v = await remote.GetVersionAsync(ct);
if (v == null || !v.Launcher.Packages.TryGetValue(rid, out var pkg) || pkg == null)
return null;
var bytes = await remote.DownloadPackageAsync(pkg, ct);
if (bytes == null || bytes.Length == 0) return null;
var remoteHash = await HashZipPayloadAsync(bytes, ct);
if (remoteHash == null) return null;
Console.WriteLine($"[update] 远端包 sha256 = {remoteHash[..16]}…");
return string.Equals(selfHash, remoteHash, StringComparison.OrdinalIgnoreCase);
}
catch (Exception ex)
{
Console.WriteLine($"[update] sha256 比对失败: {ex.Message}");
return null;
}
}
private static async Task<string> HashFileAsync(string path, CancellationToken ct)
{
await using var fs = File.OpenRead(path);
var hash = await System.Security.Cryptography.SHA256.HashDataAsync(fs, ct);
return Convert.ToHexString(hash);
}
/// <summary>从发布包(zip)里取出主程序并算 sha256。</summary>
private static async Task<string?> HashZipPayloadAsync(byte[] zip, CancellationToken ct)
{
try
{
using var ms = new MemoryStream(zip);
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
// 找主程序:app 内的可执行文件 / GC.dll / 单文件 exe
var entry = archive.Entries.FirstOrDefault(e =>
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e =>
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e =>
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
e.Name.StartsWith("GC", StringComparison.OrdinalIgnoreCase));
if (entry == null) return null;
await using var es = entry.Open();
using var buf = new MemoryStream();
await es.CopyToAsync(buf, ct);
var hash = System.Security.Cryptography.SHA256.HashData(buf.ToArray());
return Convert.ToHexString(hash);
}
catch { return null; }
}
/// <summary>
/// 遍历所有源的 Release,取**版本号最高且包含本平台发布包**的那个。
/// 某个源没有 Release(返回 null)时自动跳过。
/// </summary>
private static async Task<(RepoVersion Version, IModelRemote Remote)?> GetBestReleaseAsync(
IModelRemote fallback, CancellationToken ct)
{
var rid = CurrentRid;
var found = new List<(string Source, RepoVersion Version, IModelRemote Remote)>();
foreach (var preset in SourcePreset.All)
{
try
{
var remote = SourceSelector.CreateRemote(preset);
var v = await remote.GetVersionAsync(ct);
if (v == null)
{
Console.WriteLine($"[update] {preset.Name}: 无 Release");
continue;
}
if (string.IsNullOrWhiteSpace(v.Launcher.Version) || v.Launcher.Packages.Count == 0)
{
Console.WriteLine($"[update] {preset.Name}: 没有可用的启动器发布包");
continue;
}
var hasPkg = v.Launcher.Packages.ContainsKey(rid) ||
v.Launcher.Packages.ContainsKey("default");
if (!hasPkg)
{
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 缺少 {rid} 发布包");
continue;
}
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 可用");
found.Add((preset.Name, v, remote));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] {preset.Name} 读取失败: {ex.Message}");
}
}
if (found.Count == 0) return null;
var best = found.OrderByDescending(f => VersionUtil.Parse(f.Version.Launcher.Version)).First();
Console.WriteLine($"[update] 选中最新的可用发布包:v{best.Version.Launcher.Version}({best.Source})");
return (best.Version, best.Remote);
}
// ---------------------------------------------------------------- 下载
/// <summary>
/// 下载 latest 版本到当前运行目录(与旧版并列)。
/// 返回新版包名,供后续替换脚本使用。
/// </summary>
public static async Task<UpdateRunResult> DownloadAsync(
AppPaths paths, IModelRemote remote,
IProgress<UpdateProgressInfo>? progress = null,
CancellationToken ct = default)
{
try
{
progress?.Report(new UpdateProgressInfo { Value = 0.05, Stage = "正在读取最新版本" });
// 两个源都问一遍:某个源没发 Release 时自动换另一个,
// 与「检查更新」保持同一套规则,避免检查通过、下载却报无法读取。
var version = await remote.GetVersionAsync(ct);
// 当前源没有可用的启动器版本(没发 Release / 版本号为空)→ 换另一个源。
// 注意:模型清单可能仍然有效,但启动器升级必须有 Release。
var hasUsable = version != null &&
!string.IsNullOrWhiteSpace(version.Launcher.Version) &&
version.Launcher.Packages.Count > 0;
if (!hasUsable)
{
var tried = SourcePreset.Find(remote.SourceId)?.Name ?? remote.DisplayName;
Console.WriteLine($"[update] {tried} 没有可用的启动器发布包,换另一个源");
var pick = await GetBestReleaseAsync(remote, ct);
if (pick == null) return Fail("两个源都没有可用的 Release 发布包");
version = pick.Value.Version;
remote = pick.Value.Remote; // 后续下载必须用这个源的 remote
}
var latest = (version!.Launcher.Version ?? "").Trim();
var rid = CurrentRid;
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg) &&
!version.Launcher.Packages.TryGetValue("default", out pkg))
return Fail($"该平台({rid})没有对应发布包");
// ---- 信任闸门 ---------------------------------------------------
// 启动器更新会替换可执行文件,风险最高:清单没签名就一律不动。
// 只有显式设置 GC_ALLOW_UNSIGNED_MANIFEST=1(自建私有构建)才放行。
var allowUnsigned =
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
if (!version.IsTrusted && !allowUnsigned)
{
var reason = version.SignatureTrust == nameof(ManifestTrust.Invalid)
? "清单签名无效"
: "清单未签名";
Console.Error.WriteLine($"[update] 启动器更新被拒绝:{reason}");
return Fail($"{reason},已拒绝下载启动器更新");
}
if (string.IsNullOrWhiteSpace(pkg!.Sha256))
{
Console.Error.WriteLine("[update] 清单没有提供 sha256,拒绝下载启动器更新");
return Fail("清单缺少该平台的 sha256,已拒绝下载(无法校验完整性)");
}
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
// sha256 校验(清单已验签,这里的 sha256 就是"正版"的定义)
{
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
return Fail("下载文件校验失败(sha256 与已签名清单不符)");
}
progress?.Report(new UpdateProgressInfo { Value = 0.55, Stage = "正在校验更新包" });
var updateRoot = paths.UpdateRoot;
Directory.CreateDirectory(updateRoot);
// 更新包留在 .GC/update,交给 SAVEDOG 自己解压 —— 不信任"预解压目录",
// 避免「解压后被替换」的中间窗口。
var zip = Path.Combine(updateRoot, "package.zip");
if (File.Exists(zip)) File.Delete(zip);
await File.WriteAllBytesAsync(zip, bytes, ct);
try
{
var inspection = SafeArchive.Inspect(zip);
Console.WriteLine($"[update] 更新包检查通过:{inspection.Entries} 个条目," +
$"{inspection.UncompressedBytes / 1024 / 1024} MB");
}
catch (Exception ex)
{
try { File.Delete(zip); } catch { }
return Fail("更新包安全性检查失败: " + ex.Message);
}
// 二次验签用的清单副本:SAVEDOG 不信任"启动器说它验过了"
var rawManifest = await remote.GetRawVersionTextAsync(ct);
var manifestCopy = Path.Combine(updateRoot, "version.json");
if (!string.IsNullOrWhiteSpace(rawManifest))
File.WriteAllText(manifestCopy, rawManifest!);
else if (File.Exists(manifestCopy))
File.Delete(manifestCopy);
// 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)
var packageName = $"GC-{latest}-{PlatformLabel}" + (OperatingSystem.IsMacOS() ? ".app" : ".exe");
var request = new SavedogRequest
{
Version = latest,
Rid = rid,
PlatformLabel = PlatformLabel,
PackageName = packageName,
PackageZip = "package.zip",
PayloadDir = "payload",
ManifestPath = "version.json",
PackageSha256 = pkg.Sha256!.Trim().ToLowerInvariant(),
PackageSize = bytes.LongLength,
RequireSignature = version.IsTrusted,
InstallRelative = Path.GetRelativePath(updateRoot, paths.InstallDirectory),
CreatedAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
};
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
// 兼容兜底:没有 SAVEDOG 的旧安装,仍然按老方式预解压 + 脚本替换
string? legacyPath = null;
if (SavedogLauncher.Find(paths) == null)
{
Console.WriteLine("[update] 未找到 GC-SAVEDOG,使用兼容脚本流程");
progress?.Report(new UpdateProgressInfo { Value = 0.7, Stage = "正在解压更新包" });
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging);
SafeArchive.ExtractToDirectory(zip, staging);
FlattenStaging(staging);
var payload = Path.Combine(updateRoot, "payload");
if (Directory.Exists(payload)) Directory.Delete(payload, true);
Directory.CreateDirectory(payload);
var legacyName = MoveToPayload(staging, payload);
try { Directory.Delete(staging, true); } catch { }
if (legacyName == null) return Fail("解压结果里没有找到新版启动器");
packageName = legacyName;
request.PackageName = legacyName;
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
legacyPath = Path.Combine(payload, legacyName);
// 老脚本读这个纯文本标记,只含相对信息
File.WriteAllText(Path.Combine(updateRoot, "update.txt"),
$"NAME={legacyName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" +
$"INSTALL_REL={request.InstallRelative}\n");
}
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
return new UpdateRunResult
{
State = UpdateRunState.Ready,
Version = latest,
Message = $"v{latest} 已暂存到 .GC/update",
PackageName = packageName,
NewAppPath = legacyPath
};
}
catch (OperationCanceledException) { return Fail("已取消"); }
catch (Exception ex) { return Fail(ex.Message); }
}
private static UpdateRunResult Fail(string msg) => new()
{
State = UpdateRunState.Failed,
Message = msg
};
// ---------------------------------------------------------------- 应用(下次启动)
/// <summary>
/// 安排应用已下载的新版。
/// 首选 <b>GC-SAVEDOG</b>:二次验签、原子替换、启动后健康检查、失败自动回滚;
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
/// 返回 true 表示调用方应立即退出进程。
/// </summary>
public static bool ScheduleApply(AppPaths paths, string packageName)
{
// 安全阀:绝不在源码目录执行替换(防止误删源码)
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
{
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
return false;
}
if (File.Exists(Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest)))
{
string? savedogError = null;
if (SavedogLauncher.TryStart(paths, Environment.ProcessId, out savedogError))
return true;
Console.Error.WriteLine($"[update] {savedogError},改用兼容脚本");
}
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
if (!File.Exists(marker)) return false;
try
{
var isWin = OperatingSystem.IsWindows();
var script = Path.Combine(paths.UpdateRoot, isWin ? "apply.bat" : "apply.sh");
var content = isWin ? WindowsScript() : UnixScript();
File.WriteAllText(script, content, new System.Text.UTF8Encoding(false));
if (!isWin)
{
try
{
File.SetUnixFileMode(script,
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
catch { }
}
var psi = isWin
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
{ UseShellExecute = false, CreateNoWindow = true }
: new System.Diagnostics.ProcessStartInfo("/bin/sh")
{ UseShellExecute = false, CreateNoWindow = true };
if (isWin) psi.ArgumentList.Add("/c");
psi.ArgumentList.Add(script);
System.Diagnostics.Process.Start(psi);
return true;
}
catch (Exception ex)
{
Console.Error.WriteLine($"启动替换脚本失败: {ex.Message}");
return false;
}
}
/// <summary>启动时若有待应用更新:交给 SAVEDOG,由调用方退出进程。</summary>
public static bool TryApplyPending(AppPaths paths)
{
if (paths.IsDevelopment) return false;
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
// 新协议:apply-request.json + package.zip(SAVEDOG 自己解压 + 验签)
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
if (File.Exists(requestPath))
{
var request = Json.Read<SavedogRequest>(requestPath);
var zipPath = request == null
? null
: Path.Combine(paths.UpdateRoot, request.PackageZip);
if (request != null && zipPath != null && File.Exists(zipPath))
return ScheduleApply(paths, request.PackageName);
Console.Error.WriteLine("[update] 更新申请不完整,已清理");
try { File.Delete(requestPath); } catch { }
}
// 旧协议:update.txt + payload(从老版本升级时仍可能遇到)
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
if (!File.Exists(marker)) return false;
var name = ReadMarker(marker, "NAME");
if (string.IsNullOrWhiteSpace(name)) return false;
var payloadPath = Path.Combine(paths.UpdateRoot, "payload", name!);
if (!File.Exists(payloadPath) && !Directory.Exists(payloadPath))
return false; // 新版本不在了,放弃
return ScheduleApply(paths, name!);
}
// ---------------------------------------------------------------- 脚本(全部相对路径)
private static string UnixScript()
{
var s = new System.Text.StringBuilder();
s.AppendLine("#!/bin/sh");
s.AppendLine("# script lives in .GC/update/ ; install path is recorded relatively");
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
s.AppendLine("MARKER=\"$HERE/update.txt\"");
s.AppendLine();
s.AppendLine("# read marker");
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("INSTALLREL=$(sed -n 's/^INSTALL_REL=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ] || [ -z \"$INSTALLREL\" ]; then");
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
s.AppendLine("fi");
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/$INSTALLREL\" && pwd)");
s.AppendLine("PAYLOAD=\"$HERE/payload/$NEWNAME\"");
s.AppendLine("if [ ! -e \"$PAYLOAD\" ]; then");
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
s.AppendLine("fi");
s.AppendLine();
s.AppendLine("# wait for old process to exit (this script is started by it)");
s.AppendLine("sleep 2");
s.AppendLine();
s.AppendLine("# move the staged package into the install directory");
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
s.AppendLine("rm -rf \"$NEW\"");
s.AppendLine("mv \"$PAYLOAD\" \"$NEW\"");
s.AppendLine();
s.AppendLine("# launch new version");
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
s.AppendLine("fi");
s.AppendLine();
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
s.AppendLine("# files of OTHER platforms are NEVER touched");
s.AppendLine("for item in \"$DST\"/GC-*.app \"$DST\"/GC-*.exe; do");
s.AppendLine(" [ -e \"$item\" ] || continue");
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
s.AppendLine(" base=$(basename \"$item\")");
s.AppendLine(" stem=${base#GC-}");
s.AppendLine(" case \"$base\" in");
s.AppendLine(" *.app) stem=${stem%.app} ;;");
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
s.AppendLine(" *) continue ;;");
s.AppendLine(" esac");
s.AppendLine(" ver=${stem%%-*}");
s.AppendLine(" rest=${stem#*-}");
s.AppendLine(" plat=\"${rest%-*}-${rest##*-}\"");
s.AppendLine(" # skip other platforms entirely");
s.AppendLine(" [ \"$plat\" != \"$NEWPLAT\" ] && continue");
s.AppendLine(" # same platform: keep only latest version");
s.AppendLine(" if [ \"$ver\" = \"$NEWVER\" ]; then");
s.AppendLine(" echo \"keep: $base\"");
s.AppendLine(" else");
s.AppendLine(" echo \"remove (version $ver != $NEWVER): $base\"");
s.AppendLine(" rm -rf \"$item\" 2>/dev/null");
s.AppendLine(" fi");
s.AppendLine("done");
s.AppendLine();
s.AppendLine("rm -f \"$MARKER\"");
s.AppendLine("rm -f \"$HERE\"/*.sh 2>/dev/null");
return s.ToString();
}
private static string WindowsScript()
{
var s = new System.Text.StringBuilder();
s.AppendLine("@echo off");
s.AppendLine("chcp 65001 >nul 2>&1");
s.AppendLine("set \"HERE=%~dp0\"");
s.AppendLine("set \"MARKER=%~dp0update.txt\"");
s.AppendLine("timeout /t 2 /nobreak >nul");
s.AppendLine();
s.AppendLine("set \"NEWNAME=\"");
s.AppendLine("set \"NEWVER=\"");
s.AppendLine("set \"NEWPLAT=\"");
s.AppendLine("set \"INSTALLREL=\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"INSTALL_REL=\" \"%MARKER%\" 2^>nul') do set \"INSTALLREL=%%A\"");
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
s.AppendLine("if \"%INSTALLREL%\"==\"\" (echo install path missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
s.AppendLine("for %%I in (\"%HERE%%INSTALLREL%\") do set \"DST=%%~fI\"");
s.AppendLine("set \"PAYLOAD=%HERE%payload\\%NEWNAME%\"");
s.AppendLine("if not exist \"%PAYLOAD%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
s.AppendLine();
s.AppendLine("rem move the staged package into the install directory");
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" rmdir /S /Q \"%DST%\\%NEWNAME%\" 2>nul");
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" del /Q \"%DST%\\%NEWNAME%\" 2>nul");
s.AppendLine("move \"%PAYLOAD%\" \"%DST%\\%NEWNAME%\" >nul");
s.AppendLine("if errorlevel 1 (echo failed to install update & exit /b 1)");
s.AppendLine();
s.AppendLine("rem launch new version");
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
s.AppendLine();
s.AppendLine("rem delete old GC-* files: SAME platform only, version != latest");
s.AppendLine("powershell -NoProfile -ExecutionPolicy Bypass -Command \"^");
s.AppendLine("$dst='%DST%'; $new='%NEWNAME%'; $ver='%NEWVER%'; $plat='%NEWPLAT%';^");
s.AppendLine("Get-ChildItem -LiteralPath $dst -Filter 'GC-*' | ForEach-Object {^");
s.AppendLine(" $n=$_.Name; if($n -eq $new){return};^");
s.AppendLine(" $m=[regex]::Match($n,'^GC-(.+?)-([^-]+)-([^-]+)\\.(app|exe)$');^");
s.AppendLine(" if(-not $m.Success){return};^");
s.AppendLine(" $fver=$m.Groups[1].Value; $fplat=$m.Groups[2].Value+'-'+$m.Groups[3].Value;^");
s.AppendLine(" if($fplat -ne $plat){return};^");
s.AppendLine(" if($fver -eq $ver){ Write-Host \\\"keep: $n\\\" }^");
s.AppendLine(" else { Write-Host \\\"remove: $n\\\"; Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }^");
s.AppendLine("}\"");
s.AppendLine();
s.AppendLine("del /Q \"%MARKER%\" >nul 2>&1");
s.AppendLine("del /Q \"%~f0\" >nul 2>&1");
return s.ToString();
}
// ---------------------------------------------------------------- 内部工具
/// <summary>展平只有一个顶层目录、且不是 .app 的 zip。</summary>
private static void FlattenStaging(string dir)
{
var entries = Directory.GetFileSystemEntries(dir);
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
var inner = entries[0];
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
var flat = dir + "-flat";
if (Directory.Exists(flat)) Directory.Delete(flat, true);
Directory.Move(inner, flat);
Directory.Delete(dir, true);
Directory.Move(flat, dir);
}
/// <summary>
/// 把 staging 里的新版搬入下载目录的 payload。
/// 返回新版包名(GC-&lt;版本&gt;-&lt;平台&gt;.app/.exe)。
/// </summary>
private static string? MoveToPayload(string staging, string payload)
{
try
{
foreach (var entry in Directory.GetFileSystemEntries(staging))
{
var name = Path.GetFileName(entry);
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
var dest = Path.Combine(payload, name);
if (Directory.Exists(dest)) Directory.Delete(dest, true);
else if (File.Exists(dest)) File.Delete(dest);
if (Directory.Exists(entry)) Directory.Move(entry, dest);
else File.Move(entry, dest);
// 保证 .app 里可执行文件可执行
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(dest))
{
var macOs = Path.Combine(dest, "Contents", "MacOS");
if (Directory.Exists(macOs))
{
try
{
foreach (var f in Directory.GetFiles(macOs, "*", SearchOption.TopDirectoryOnly))
{
var mode = File.GetUnixFileMode(f);
File.SetUnixFileMode(f, mode | UnixFileMode.UserExecute);
}
}
catch { }
}
return name;
}
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"安装新版失败: {ex.Message}");
}
return null;
}
private static string? ReadMarker(string file, string key)
{
try
{
foreach (var line in File.ReadAllLines(file))
{
if (line.StartsWith(key + "=", StringComparison.Ordinal))
return line[(key.Length + 1)..].Trim();
}
}
catch { }
return null;
}
private static string Safe(string value)
{
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
return value.Replace('/', '-').Replace(' ', '-');
}
}
-121
View File
@@ -1,121 +0,0 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace GC.Services;
/// <summary>
/// 找到并启动 GC-SAVEDOG(启动器更新的守护进程)。
///
/// 为什么要独立进程:启动器正在运行时无法安全覆盖自己;一旦覆盖失败,
/// 启动器已退出,就没人能回滚。把"替换 + 看护"交给一个只做这件事的小程序,
/// 风险面被压缩到最小,也便于审计。
/// </summary>
public static class SavedogLauncher
{
/// <summary>在安装目录里寻找 SAVEDOG 可执行文件。</summary>
public static string? Find(AppPaths paths)
{
var name = SavedogFiles.ExecutableName;
var install = paths.InstallDirectory;
var direct = Path.Combine(install, name);
if (File.Exists(direct)) return direct;
// macOS:可能放在 .app 内部
try
{
foreach (var app in Directory.GetDirectories(install, "*.app"))
{
var inside = Path.Combine(app, "Contents", "MacOS", name);
if (File.Exists(inside)) return inside;
}
}
catch { }
var bin = Path.Combine(paths.HomeRoot, "bin", name);
if (File.Exists(bin)) return bin;
try
{
var exe = Environment.ProcessPath;
if (!string.IsNullOrWhiteSpace(exe))
{
var beside = Path.Combine(Path.GetDirectoryName(exe)!, name);
if (File.Exists(beside)) return beside;
}
}
catch { }
return null;
}
/// <summary>
/// 启动 SAVEDOG 应用更新。<paramref name="waitForPid"/> 是当前启动器进程,
/// SAVEDOG 会等它退出后再动文件。
/// </summary>
public static bool TryStart(AppPaths paths, int waitForPid, out string? error)
{
error = null;
var exe = Find(paths);
if (exe == null)
{
error = "未找到 GC-SAVEDOG";
return false;
}
try
{
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
if (!File.Exists(requestPath))
{
error = "缺少 apply-request.json";
return false;
}
var psi = new ProcessStartInfo(exe)
{
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = paths.InstallDirectory
};
psi.ArgumentList.Add("apply");
psi.ArgumentList.Add("--update");
psi.ArgumentList.Add(paths.UpdateRoot);
psi.ArgumentList.Add("--install");
psi.ArgumentList.Add(paths.InstallDirectory);
psi.ArgumentList.Add("--wait-pid");
psi.ArgumentList.Add(waitForPid.ToString());
psi.ArgumentList.Add("--timeout");
psi.ArgumentList.Add("45");
if (!OperatingSystem.IsWindows())
{
try
{
var mode = File.GetUnixFileMode(exe);
File.SetUnixFileMode(exe, mode | UnixFileMode.UserExecute);
}
catch { }
}
Process.Start(psi);
Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}");
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
/// <summary>读取 SAVEDOG 最近一次的执行结果(供界面展示)。</summary>
public static SavedogState? ReadState(AppPaths paths)
=> Json.Read<SavedogState>(Path.Combine(paths.UpdateRoot, SavedogFiles.State));
/// <summary>上次成功启动的版本(回滚依据)。</summary>
public static LastGoodVersion? ReadLastGood(AppPaths paths)
=> Json.Read<LastGoodVersion>(Path.Combine(paths.UpdateRoot, SavedogFiles.LastGood));
}
-130
View File
@@ -1,130 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
///
/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间,
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
/// 避免每次点下载都重新测速。
/// </summary>
public sealed class SourceSelector : ISourceSelector
{
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Probe/1.0");
return c;
}
private readonly object _lock = new();
private SourcePreset? _cached;
private DateTime _cachedAt = DateTime.MinValue;
private readonly TimeSpan _ttl = TimeSpan.FromMinutes(3);
/// <summary>最近一次选中的源(未探测时为空)。</summary>
public SourcePreset? Current { get { lock (_lock) return _cached; } }
/// <summary>每个源的探测耗时(毫秒),供界面展示。</summary>
public IReadOnlyDictionary<string, long> LastLatency { get; private set; } =
new Dictionary<string, long>();
/// <summary>
/// 探测两个源并返回最快的。force=true 时忽略缓存。
/// 两个都失败时返回 GitCode(默认源)。
/// </summary>
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
{
lock (_lock)
{
if (!force && _cached != null && DateTime.UtcNow - _cachedAt < _ttl)
return _cached;
}
var probes = SourcePreset.All.Select(async p =>
{
var sw = Stopwatch.StartNew();
var ok = await ProbeAsync(p, ct);
sw.Stop();
return (Preset: p, Ok: ok, Ms: sw.ElapsedMilliseconds);
});
var results = await Task.WhenAll(probes);
var latencies = results.ToDictionary(r => r.Preset.Id, r => r.Ms);
LastLatency = latencies;
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode;
lock (_lock)
{
_cached = chosen;
_cachedAt = DateTime.UtcNow;
}
Console.WriteLine("[selector] 测速:" + string.Join(" ",
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))
+ $" → 选择 {chosen.Name}");
return chosen;
}
/// <summary>
/// 探测:能拿到合法 JSON 才算可用。
/// 注意两个平台取文件的方式不同:
/// · Gitea(Xhmcl):raw/branch/{b}/{path} 直接返回文件内容
/// · GitCode:raw 地址返回的是 HTML 页面,必须走 API(内容为 base64)
/// 因此 GitCode 用 api/v5 contents + Accept: application/json 探测。
/// </summary>
private static async Task<bool> ProbeAsync(SourcePreset preset, CancellationToken ct)
{
if (preset.Kind == "gitcode")
{
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(5));
var api = $"{preset.ApiBase}/repos/{preset.Owner}/{preset.Repo}/contents/version.json?ref={preset.Branch}";
using var req = new HttpRequestMessage(HttpMethod.Get, api);
req.Headers.Accept.ParseAdd("application/json");
using var resp = await Http.SendAsync(req, cts.Token);
if (!resp.IsSuccessStatusCode) return false;
var text = await resp.Content.ReadAsStringAsync(cts.Token);
return text.TrimStart().StartsWith('{');
}
catch { return false; }
}
var urls = new[] { preset.RawUrl("version.json"), preset.RawUrl("model/version.json") };
foreach (var url in urls)
{
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(5));
var text = await Http.GetStringAsync(url, cts.Token);
if (text.TrimStart().StartsWith('{')) return true;
}
catch { /* 换下一个地址 */ }
}
return false;
}
/// <summary>为指定源创建对应的 remote 实现。</summary>
public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch
{
"gitea" => new GiteaRemote(preset),
_ => new GitCodeReleaseRemote(null, preset.HomeUrl)
};
}
-355
View File
@@ -1,355 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using GC.Models;
namespace GC.Services;
/// <summary>
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
/// .GC/model/&lt;id&gt;,本次启动立即生效。任何失败都保留本地已装模型。
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
/// </summary>
public sealed class UpdateService : IUpdateService
{
private readonly AppPaths _paths;
private readonly SettingsService _settings;
private IModelRemote _remote;
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
{
_paths = paths;
_settings = settings;
_remote = remote;
}
public IModelRemote Remote => _remote;
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
public void UseRemote(IModelRemote remote) => _remote = remote;
/// <summary>
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
/// </summary>
public static IModelRemote CreateRemote(AppSettings settings)
{
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
Directory.Exists(settings.UpdateLocalRoot!))
return new DirectoryRemote(settings.UpdateLocalRoot!);
return SourceSelector.CreateRemote(SourcePreset.Detect(settings.UpdateRepository));
}
/// <summary>
/// 异步版本:先探测 Xhmcl / GitCode 两个源,取最快的那个。
/// 启动更新、下载页、检查更新统一走这里,保证「用同一个源、同一种下载方式」。
/// </summary>
public static async Task<IModelRemote> CreateRemoteAsync(AppSettings settings,
SourceSelector selector, bool forceProbe = false, CancellationToken ct = default)
{
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
Directory.Exists(settings.UpdateLocalRoot!))
return new DirectoryRemote(settings.UpdateLocalRoot!);
var preset = await selector.PickFastestAsync(forceProbe, ct);
return SourceSelector.CreateRemote(preset);
}
public async Task<UpdateResult> RunAsync(bool force,
IProgress<UpdateProgress>? progress, CancellationToken ct = default)
{
// 开发态的 model/ 里有源码与工程文件,模型自动替换会破坏源码目录,
// 因此开发态只做「启动器版本检查」(下载到 .GC/update 暂存,可验证链路),
// 跳过模型替换。要用正式流程验证请跑 ./build.sh update-test。
var devMode = _paths.IsDevelopment &&
Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1";
if (!force && !_settings.Current.AutoUpdateOnStartup)
return new UpdateResult { Outcome = UpdateOutcome.Disabled, Message = L.I["update.disabled"] };
progress?.Report(new UpdateProgress
{
Value = 0.02,
Message = L.I["update.checking"],
Detail = _remote.DisplayName
});
RepoVersion? remote;
try
{
remote = await _remote.GetVersionAsync(ct);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
return new UpdateResult
{
Outcome = UpdateOutcome.Unavailable,
Message = L.I["update.offline"],
Error = ex.Message
};
}
if (remote == null)
return new UpdateResult
{
Outcome = UpdateOutcome.Unavailable,
Message = L.I["update.noManifest"]
};
// ---- 清单信任策略 --------------------------------------------------
// 签名有效 → 通过;没有签名 / 签名不符 → 默认拒绝(可用设置或环境变量放开)。
// 这一道闸门挡住的是「仓库被改、模型 dll 被换成木马」这类攻击。
var allowUnsigned = devMode ||
!_settings.Current.RequireSignedManifest ||
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
if (!remote.IsTrusted)
{
var reason = remote.SignatureTrust == nameof(ManifestTrust.Invalid)
? "清单签名无效(内容可能被篡改)"
: "清单未签名";
if (!allowUnsigned)
{
Console.Error.WriteLine($"[update] {reason},已拒绝本次更新");
return new UpdateResult
{
Outcome = UpdateOutcome.Unavailable,
Message = $"{reason},已拒绝更新",
Error = remote.SignatureError
};
}
Console.Error.WriteLine($"[update] {reason},当前为开发/放宽模式,继续");
}
else
{
Console.WriteLine($"[update] 清单验签通过({remote.SignatureKeyId})");
}
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
_settings.Save();
// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,
// 这里只做「模型同步到最新版」。
string? launcherMessage = null;
// ---- 同步所有模型到最新版 ----
// 开发态跳过:仓库 model/ 里有源码,整体替换会破坏工程目录。
var needed = devMode
? new List<RepoModel>()
: remote.Models.Where(NeedsModel).ToList();
var updated = new List<string>();
var errors = new List<string>();
for (var i = 0; i < needed.Count; i++)
{
var model = needed[i];
progress?.Report(new UpdateProgress
{
Value = 0.05 + 0.72 * i / Math.Max(1, needed.Count),
Message = L.I.F("update.downloadingModel", model.Id),
Detail = model.Version
});
try
{
await InstallModelAsync(model, progress, i, needed.Count, ct);
_settings.Current.InstalledModelVersions[model.Id] = model.Version;
_settings.Save();
updated.Add(model.Id);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
errors.Add($"{model.Id}: {ex.Message}");
Console.Error.WriteLine($"模型更新失败 {model.Id}: {ex.Message}");
}
}
progress?.Report(new UpdateProgress { Value = 1, Message = L.I["update.done"] });
var outcome = errors.Count > 0
? UpdateOutcome.Partial
: (updated.Count > 0 || launcherMessage != null)
? UpdateOutcome.Applied
: UpdateOutcome.NoChange;
var message = updated.Count > 0
? L.I.F("update.applied", updated.Count)
: launcherMessage != null
? L.I["update.modelsLatest"]
: devMode
? "开发态:已检查启动器,模型替换已跳过(保护仓库源码)"
: L.I["update.noChange"];
if (errors.Count > 0) message += L.I.F("update.partial", errors.Count);
return new UpdateResult
{
Outcome = outcome,
Message = message,
UpdatedModels = updated.Count,
ModelNames = updated,
LauncherMessage = launcherMessage,
Error = errors.Count > 0 ? string.Join("; ", errors) : null
};
}
private bool NeedsModel(RepoModel model)
{
if (string.IsNullOrWhiteSpace(model.Id) || string.IsNullOrWhiteSpace(model.Version)) return false;
var dir = Path.Combine(_paths.ModelRoot, model.Id);
if (!Directory.Exists(dir)) return true;
if (!File.Exists(Path.Combine(dir, model.Id + ".json"))) return true;
return !_settings.Current.InstalledModelVersions.TryGetValue(model.Id, out var local) ||
!string.Equals(local, model.Version, StringComparison.OrdinalIgnoreCase);
}
/// <summary>只下载模型清单与模型数据目录,源码 / 文档不进运行目录。</summary>
private static bool IsPayload(string id, string relative)
{
var rel = relative.Replace('\\', '/');
// 拒绝任何形式的父目录穿越与绝对路径
if (rel.StartsWith('/') || rel.Contains("..", StringComparison.Ordinal)) return false;
return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) ||
rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase);
}
private async Task InstallModelAsync(RepoModel model, IProgress<UpdateProgress>? progress,
int index, int count, CancellationToken ct)
{
var rootPath = string.IsNullOrWhiteSpace(model.Dir) ? "model/" + model.Id : model.Dir;
var entries = await _remote.ListTreeAsync(rootPath, ct);
var files = entries.Where(e => !e.IsDirectory && IsPayload(model.Id, e.RelativePath)).ToList();
if (!files.Any(e => e.RelativePath.Equals(model.Id + ".json", StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"远端缺少模型清单 {model.Id}.json");
if (!files.Any(e => e.RelativePath.StartsWith(model.Id + ".model/", StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"远端缺少模型数据 {model.Id}.model/");
var staging = Path.Combine(_paths.CacheRoot, "models", model.Id + "-" + Safe(model.Version));
if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging);
try
{
var total = files.Sum(f => Math.Max(1L, f.Size));
// 并行下载:模型包通常有几十个文件,串行下载会明显拖慢启动。
// 并发上限 6,避免被服务端限流;进度用原子计数汇总。
long done = 0;
var stagingFull = Path.GetFullPath(staging)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
using var gate = new SemaphoreSlim(6);
var tasks = files.Select(async entry =>
{
await gate.WaitAsync(ct);
try
{
ct.ThrowIfCancellationRequested();
var bytes = await _remote.DownloadAsync(entry, ct);
// 路径穿越防护
var dest = Path.GetFullPath(Path.Combine(staging,
entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)));
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}");
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await File.WriteAllBytesAsync(dest, bytes, ct);
var now = Interlocked.Add(ref done, bytes.Length);
progress?.Report(new UpdateProgress
{
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)now / Math.Max(1, total))) / Math.Max(1, count),
Message = L.I.F("update.downloadingModel", model.Id),
Detail = entry.RelativePath
});
}
finally { gate.Release(); }
});
await Task.WhenAll(tasks);
// ---- 完整性校验:清单是签过名的,里面的哈希就是"正版"的定义 --------
// 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装。
var computed = ModelIntegrity.Compute(staging, model.Id);
if (!string.IsNullOrWhiteSpace(model.ManifestSha256) &&
!string.Equals(computed.ManifestSha256, model.ManifestSha256,
StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(
$"模型清单哈希不符(期望 {Short(model.ManifestSha256)},实际 {Short(computed.ManifestSha256)})");
if (!string.IsNullOrWhiteSpace(model.FilesSha256) &&
!string.Equals(computed.FilesSha256, model.FilesSha256,
StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(
$"模型文件哈希不符(期望 {Short(model.FilesSha256)},实际 {Short(computed.FilesSha256)}),已丢弃");
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
Directory.CreateDirectory(_paths.ModelRoot);
var target = Path.Combine(_paths.ModelRoot, model.Id);
// 双保险:任何情况下都不允许把含 src/ 源码的模型目录整体换掉
if (Directory.Exists(Path.Combine(target, "src")))
throw new InvalidOperationException($"目标目录含模型源码 src/,拒绝覆盖: {target}");
var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
if (Directory.Exists(target)) Directory.Move(target, backup);
try
{
Directory.Move(staging, target);
}
catch
{
if (Directory.Exists(backup) && !Directory.Exists(target)) Directory.Move(backup, target);
throw;
}
if (Directory.Exists(backup))
{
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
}
// 安装成功:把完整性记录写进模型目录,加载 dll 前会再抽查一次
try
{
ModelIntegrity.Write(target, model.Id, new ModelIntegrityFile
{
Id = model.Id,
Version = model.Version,
ManifestSha256 = computed.ManifestSha256,
FilesSha256 = computed.FilesSha256,
Files = computed.Files,
InstalledAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
Source = _remote.DisplayName
});
}
catch (Exception ex)
{
Console.Error.WriteLine($"写入完整性记录失败 {model.Id}: {ex.Message}");
}
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
throw;
}
}
private static string Safe(string value)
{
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
return value.Replace('/', '-').Replace(' ', '-');
}
private static string Short(string? hash)
=> string.IsNullOrEmpty(hash) ? "(空)" : hash!.Length <= 8 ? hash : hash[..8];
}
-41
View File
@@ -1,41 +0,0 @@
using System;
using System.Globalization;
namespace GC.Services;
/// <summary>
/// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法,
/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。
/// </summary>
public static class VersionUtil
{
/// <summary>把 tag 规整成 "1.0.6" 这样的纯数字版本。</summary>
public static string Normalize(string? tag)
{
if (string.IsNullOrWhiteSpace(tag)) return "";
var s = tag!.Trim();
// 去掉前缀:v / V / GC- / release-
if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..];
else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..];
s = s.TrimStart('v', 'V');
// 只保留开头的 数字与点
var end = 0;
while (end < s.Length && (char.IsDigit(s[end]) || s[end] == '.')) end++;
s = s[..end].Trim('.');
return s;
}
/// <summary>解析成 Version;无法解析时返回 0.0。</summary>
public static Version Parse(string? tag)
{
var n = Normalize(tag);
if (string.IsNullOrWhiteSpace(n)) return new Version(0, 0);
return Version.TryParse(n, out var v) ? v : new Version(0, 0);
}
/// <summary>比较两个版本号,a>b 返回正、a&lt;b 返回负、相等返回 0。</summary>
public static int Compare(string? a, string? b) => Parse(a).CompareTo(Parse(b));
}
-22
View File
@@ -1,22 +0,0 @@
using System;
using System.IO;
namespace GC.Services;
/// <summary>
/// 安全解压的统一入口(实现在 <see cref="SafeArchive"/>)。
/// 保留这个名字是因为模型源导入 / 启动器更新两处都在用,
/// 真正的校验逻辑集中在一处,避免两套实现走偏。
/// </summary>
public static class ZipSafety
{
public static void ExtractToDirectory(string zipPath, string destination)
{
if (!File.Exists(zipPath))
throw new FileNotFoundException("压缩包不存在", zipPath);
SafeArchive.ExtractToDirectory(zipPath, destination);
}
/// <summary>只检查不落盘:给下载完成后的预检用。</summary>
public static SafeArchive.Inspection Inspect(string zipPath) => SafeArchive.Inspect(zipPath);
}
-642
View File
@@ -1,642 +0,0 @@
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Shapes = Avalonia.Controls.Shapes;
using Avalonia.VisualTree;
using GC.Models;
using GC.Services;
namespace GC.Views;
/// <summary>
/// 模型窗口:**只做窗口宿主**。
/// 内容完全来自模型程序集(<see cref="LoadedModel.View"/>),启动器不渲染任何东西。
/// 快捷键:Esc 关闭窗口,F11 全屏。
/// </summary>
public sealed class PlayerWindow : Window
{
private LoadedModel? _model;
private bool _closing;
private Button? _maximizeButton;
private Border? _frame;
private TextBlock? _titleText;
private Border? _titleBar;
private readonly List<Button> _titleButtons = new();
private readonly List<Shapes.Path> _titleGlyphs = new();
private Shapes.Path? _maximizeGlyph;
private Shapes.Path? _restoreGlyph;
private string _maxMaxPath = "";
private string _maxRestorePath = "";
private Button? _helpButton;
/// <summary>基准尺寸(1240×820 时的标题栏高度与按钮尺寸)。</summary>
private const double BaseWidth = 1240;
private const double BaseTitleBarHeight = 34;
private const double BaseButtonWidth = 38;
private const double BaseButtonHeight = 28;
private const double BaseTitleFont = 11.5;
private const double BaseHelpFont = 11.5;
public PlayerWindow(ModelPackage package, LoadedModel model)
{
_model = model;
Title = package.LocalizedName;
Width = 1240;
Height = 820;
MinWidth = 1000;
MinHeight = 680;
Background = Brushes.Transparent;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
WindowStartupLocation = WindowStartupLocation.CenterOwner;
// 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
// 标题栏配色来自模型清单,跟随模型自己的界面风格:
// 地球模型是深色舞台,比例尺计算器是浅色卡片,两者不能共用一套深色。
var chrome = package.Manifest.Chrome;
var barBg = ParseColor(chrome?.TitleBar, "#0C1828");
var barBorder = ParseColor(chrome?.TitleBorder, "#1B2740");
var barText = ParseColor(chrome?.TitleText, "#EAF2FF");
var btnText = ParseColor(chrome?.Button, "#9FB4D4");
var frameBg = ParseColor(chrome?.Frame, "#0A1524");
var titleText = new TextBlock
{
Text = package.LocalizedName,
Foreground = new SolidColorBrush(barText),
FontSize = 11.5,
Margin = new Thickness(14, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
[Grid.ColumnProperty] = 0
};
_titleText = titleText;
var helpButton = new Button
{
Content = IsEnglish() ? "How to use?" : "如何使用?",
Height = 26,
Padding = new Thickness(12, 0),
Background = Brushes.Transparent,
Foreground = new SolidColorBrush(btnText),
BorderThickness = new Thickness(0),
FontSize = 11.5,
CornerRadius = new CornerRadius(7),
Margin = new Thickness(0, 0, 6, 0),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand),
[Grid.ColumnProperty] = 1
};
helpButton.Click += (_, _) => ShowHelp(package, barBg, barBorder, barText, btnText, frameBg);
// 标题栏三键:最小化 / 最大化 / 关闭 —— 卡通画风。
// 每颗按钮 = 彩色实心圆底 + 粗圆头描边图标,像一颗小糖豆。
(Button Btn, Shapes.Path Icon) MakeBadge(int column, string iconPath)
{
// 纯矢量图标,没有彩色圆圈
var icon = new Shapes.Path
{
Data = Geometry.Parse(iconPath),
Stroke = new SolidColorBrush(btnText),
StrokeThickness = 1.5,
StrokeLineCap = PenLineCap.Round,
StrokeJoin = PenLineJoin.Round,
Fill = null,
Stretch = Stretch.None,
Width = 10,
Height = 10,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
var layer = new Grid
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
layer.Children.Add(icon);
var b = new Button
{
Width = 38,
Height = 28,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(9),
Padding = new Thickness(0),
Margin = new Thickness(2, 0, 0, 0),
Content = layer,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand),
[Grid.ColumnProperty] = column
};
var hoverBg = IsLight(barBg)
? new SolidColorBrush(Color.Parse("#EEF1F7"))
: new SolidColorBrush(Color.Parse("#1E2C46"));
var isCloseBtn = column == 4;
b.PointerEntered += (_, _) =>
{
b.Background = hoverBg;
icon.Stroke = new SolidColorBrush(isCloseBtn ? Colors.White
: IsLight(barBg) ? Color.Parse("#111A2E") : Colors.White);
};
b.PointerExited += (_, _) =>
{
b.Background = Brushes.Transparent;
icon.Stroke = new SolidColorBrush(btnText);
};
b.Classes.Add("model-titlebtn");
_titleButtons.Add(b);
_titleGlyphs.Add(icon);
return (b, icon);
}
// 卡通配色:暖黄 / 薄荷绿 / 珊瑚红
var minBadge = MakeBadge(2, "M1.5,5 L8.5,5");
var maxBadge = MakeBadge(3, "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
var closeBadge = MakeBadge(4, "M2,2 L8,8 M8,2 L2,8");
var minimizeButton = minBadge.Btn;
var maximizeButton = maxBadge.Btn;
var closeButton = closeBadge.Btn;
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
maximizeButton.Click += (_, _) => ToggleMaximize();
closeButton.Click += (_, _) => _ = CloseWithAnimationAsync();
_maximizeGlyph = maxBadge.Icon;
_restoreGlyph = maxBadge.Icon;
_maxRestorePath = "M2.6,3.6 L7.4,3.6 L7.4,8.4 L2.6,8.4 Z M2.6,3.6 L2.6,1.6 L7.4,1.6 L7.4,6.4";
_maxMaxPath = "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z";
var titleBar = new Border
{
Height = 34,
Background = new SolidColorBrush(barBg),
BorderBrush = new SolidColorBrush(barBorder),
BorderThickness = new Thickness(0, 0, 0, 1),
Child = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto,Auto,Auto"),
Margin = new Thickness(0, 0, 10, 0),
Children = { titleText, helpButton, minimizeButton, maximizeButton, closeButton }
}
};
titleBar.PointerPressed += OnTitleBarPointerPressed;
// 双击标题栏 = 最大化 / 还原(与系统标题栏一致)
titleBar.DoubleTapped += (_, e) =>
{
if (e.Source is Button) return;
ToggleMaximize();
};
_maximizeButton = maximizeButton;
_titleBar = titleBar;
_helpButton = helpButton;
_titleButtons.Add(minimizeButton);
_titleButtons.Add(maximizeButton);
_titleButtons.Add(closeButton);
var dock = new DockPanel { LastChildFill = true };
DockPanel.SetDock(titleBar, Dock.Top);
dock.Children.Add(titleBar);
dock.Children.Add(model.View);
Content = new Border
{
CornerRadius = new CornerRadius(16),
Background = new SolidColorBrush(frameBg),
ClipToBounds = true,
Child = dock
};
_frame = (Border)Content;
// 最大化 / 还原时同步圆角与按钮图标
PropertyChanged += (_, e) =>
{
if (e.Property == WindowStateProperty) UpdateMaximizeVisual();
};
// 窗口随心拉大 / 拉小时,标题栏文字与按钮同比缩放。
// 同时监听 Bounds 属性(不只是 SizeChanged),保证最大化/还原也立刻生效。
SizeChanged += (_, _) => ApplyChromeScale();
PropertyChanged += (_, e) =>
{
if (e.Property == BoundsProperty) ApplyChromeScale();
};
ApplyChromeScale();
KeyDown += OnKeyDown;
Closed += OnClosed;
}
/// <summary>
/// 让标题栏的文字与按钮尺寸跟随窗口大小。
/// 以 1240px 宽为基准线性缩放,限制在 0.85–1.9 倍,
/// 避免最大化到 4K 时按钮大得离谱、缩到最小又点不中。
/// </summary>
private void ApplyChromeScale()
{
if (Bounds.Width < 100) return;
var scale = Math.Clamp(Bounds.Width / BaseWidth, 0.85, 1.9);
if (_titleBar != null) _titleBar.Height = Math.Round(BaseTitleBarHeight * scale);
foreach (var b in _titleButtons)
{
b.Width = Math.Round(BaseButtonWidth * scale);
b.Height = Math.Round(BaseButtonHeight * scale);
b.FontSize = Math.Round(13 * scale, 1);
b.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
}
if (_helpButton != null)
{
_helpButton.Height = Math.Round(26 * scale);
_helpButton.FontSize = Math.Round(BaseHelpFont * scale, 1);
_helpButton.Padding = new Thickness(Math.Round(12 * scale), 0);
_helpButton.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
}
foreach (var g in _titleGlyphs)
{
g.Width = Math.Round(10 * scale, 1);
g.Height = Math.Round(10 * scale, 1);
g.StrokeThickness = Math.Round(1.5 * scale, 2);
}
if (_titleText != null)
{
_titleText.FontSize = Math.Round(BaseTitleFont * scale, 1);
_titleText.Margin = new Thickness(Math.Round(14 * scale), 0, 0, 0);
}
}
/// <summary>判断颜色是否属于浅色系(用于决定悬停用深色还是浅色)。</summary>
private static bool IsLight(Color c)
{
// 相对亮度(sRGB 近似)
var lum = (0.299 * c.R + 0.587 * c.G + 0.114 * c.B) / 255.0;
return lum > 0.6;
}
private void ToggleMaximize()
{
WindowState = WindowState == WindowState.Maximized
? WindowState.Normal
: WindowState.Maximized;
}
private void UpdateMaximizeVisual()
{
var max = WindowState == WindowState.Maximized || WindowState == WindowState.FullScreen;
if (_maximizeGlyph != null)
{
// 只换 Data,不换控件对象(换对象会触发 "already has a parent")
_maximizeGlyph.Data = Geometry.Parse(max ? _maxRestorePath : _maxMaxPath);
}
if (_maximizeButton != null)
{
Avalonia.Controls.ToolTip.SetTip(_maximizeButton, max
? (IsEnglish() ? "Restore" : "还原")
: (IsEnglish() ? "Maximize" : "最大化"));
}
// 最大化后同样保留圆角(用户要求:任何状态都要圆角)
if (_frame != null) _frame.CornerRadius = new CornerRadius(16);
}
private static Color ParseColor(string? hex, string fallback)
{
if (!string.IsNullOrWhiteSpace(hex))
{
try { return Color.Parse(hex!); }
catch { /* 模型写错颜色时退回默认 */ }
}
return Color.Parse(fallback);
}
private static bool IsEnglish() => L.I.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// 「如何使用?」:读取模型自带数据目录里的 help.json(中英双语),
/// 用与标题栏一致的配色弹出一个独立小窗。说明内容完全由模型提供,启动器不内置文案。
/// </summary>
private void ShowHelp(ModelPackage package, Color barBg, Color barBorder, Color barText,
Color btnText, Color frameBg)
{
var lang = IsEnglish() ? "en" : "zh-CN";
var file = Path.Combine(package.DataDirectory, "help.json");
string title = IsEnglish() ? "How to use" : "如何使用";
// 分节内容:每节一个标题 + 若干条说明;兼容旧的扁平 lines 格式
var sections = new List<(string Heading, List<string> Lines)>();
if (File.Exists(file))
{
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(file));
var root = doc.RootElement;
var node = root.TryGetProperty(lang, out var exact) ? exact
: root.TryGetProperty("zh-CN", out var zh) ? zh : root;
if (node.TryGetProperty("title", out var t)) title = t.GetString() ?? title;
if (node.TryGetProperty("sections", out var arr) && arr.ValueKind == JsonValueKind.Array)
{
foreach (var sec in arr.EnumerateArray())
{
var heading = sec.TryGetProperty("h", out var h) ? h.GetString() ?? "" : "";
var items = new List<string>();
if (sec.TryGetProperty("lines", out var ls) && ls.ValueKind == JsonValueKind.Array)
foreach (var item in ls.EnumerateArray())
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
if (items.Count > 0) sections.Add((heading, items));
}
}
else if (node.TryGetProperty("lines", out var flat) && flat.ValueKind == JsonValueKind.Array)
{
var items = new List<string>();
foreach (var item in flat.EnumerateArray())
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
if (items.Count > 0) sections.Add(("", items));
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取模型帮助失败 {file}: {ex.Message}");
}
}
if (sections.Count == 0)
sections.Add(("", new List<string>
{
IsEnglish() ? "This model has no usage notes yet." : "该模型暂未提供使用说明。"
}));
var body = new StackPanel { Spacing = 6 };
foreach (var (heading, items) in sections)
{
if (!string.IsNullOrWhiteSpace(heading))
body.Children.Add(new TextBlock
{
Text = heading,
Foreground = new SolidColorBrush(barText),
FontSize = 13.5,
FontWeight = FontWeight.SemiBold,
Margin = new Thickness(0, 12, 0, 2)
});
foreach (var line in items)
body.Children.Add(new TextBlock
{
Text = "• " + line,
Foreground = new SolidColorBrush(btnText),
FontSize = 12.5,
TextWrapping = TextWrapping.Wrap,
LineHeight = 19
});
}
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
// 纯矢量图标,无彩色圆底(与三个窗口按钮保持一致)
var helpCross = new Shapes.Path
{
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
Stroke = new SolidColorBrush(btnText),
StrokeThickness = 1.5,
StrokeLineCap = PenLineCap.Round,
Fill = null,
Stretch = Stretch.None,
Width = 10, Height = 10,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
var helpClose = new Button
{
Content = helpCross,
Width = 34,
Height = 26,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(9),
Padding = new Thickness(0),
Margin = new Thickness(6, 0, 0, 0),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand)
};
helpClose.PointerEntered += (_, _) =>
{
helpClose.Background = new SolidColorBrush(IsLight(frameBg)
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
helpCross.Stroke = new SolidColorBrush(Colors.White);
};
helpClose.PointerExited += (_, _) =>
{
helpClose.Background = Brushes.Transparent;
helpCross.Stroke = new SolidColorBrush(btnText);
};
var helpTitle = new TextBlock
{
Text = title,
Foreground = new SolidColorBrush(barText),
FontSize = 16,
FontWeight = FontWeight.SemiBold,
VerticalAlignment = VerticalAlignment.Center
};
var helpBarGrid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
Margin = new Thickness(22, 0, 14, 0)
};
helpBarGrid.Children.Add(helpTitle);
Grid.SetColumn(helpClose, 1);
helpBarGrid.Children.Add(helpClose);
var helpTitleBar = new Border
{
Height = 48,
Background = new SolidColorBrush(barBg),
BorderBrush = new SolidColorBrush(barBorder),
BorderThickness = new Thickness(0, 0, 0, 1),
Child = helpBarGrid
};
helpTitleBar.PointerPressed += (_, e) =>
{
if (e.GetCurrentPoint(helpTitleBar).Properties.IsLeftButtonPressed)
helpClose.FindAncestorOfType<Window>()?.BeginMoveDrag(e);
};
// ── 底部固定操作条:无论正文多长,「知道了」始终可见 ──
var ok = new Button
{
Content = IsEnglish() ? "Got it" : "知道了",
HorizontalAlignment = HorizontalAlignment.Right,
Padding = new Thickness(20, 8),
Background = new SolidColorBrush(Color.Parse("#2F6BFF")),
Foreground = new SolidColorBrush(Colors.White),
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(8),
Cursor = new Cursor(StandardCursorType.Hand)
};
var footer = new Border
{
Padding = new Thickness(24, 10, 24, 14),
BorderBrush = new SolidColorBrush(barBorder),
BorderThickness = new Thickness(0, 1, 0, 0),
Child = ok
};
// 标题栏(顶) + 正文(中,滚动) + 操作条(底,固定)
var rootPanel = new DockPanel { LastChildFill = true };
DockPanel.SetDock(helpTitleBar, Dock.Top);
rootPanel.Children.Add(helpTitleBar);
DockPanel.SetDock(footer, Dock.Bottom);
rootPanel.Children.Add(footer);
var scroll = new ScrollViewer
{
Content = new Border
{
Margin = new Thickness(24, 14, 24, 10),
Child = body
},
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled
};
rootPanel.Children.Add(scroll);
var win = new Window
{
Title = title,
Width = 660,
Height = Math.Min(760, 230 + sections.Sum(s => s.Lines.Count * 24 + 40)),
MinWidth = 480,
MinHeight = 320,
Background = Brushes.Transparent,
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent },
SystemDecorations = SystemDecorations.None,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Content = new Border
{
CornerRadius = new CornerRadius(16),
Background = new SolidColorBrush(frameBg),
BorderBrush = new SolidColorBrush(barBorder),
BorderThickness = new Thickness(1),
ClipToBounds = true,
Child = rootPanel
}
};
ok.Click += (_, _) => win.Close();
helpClose.Click += (_, _) => win.Close();
win.Show(this);
}
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
{
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
BeginMoveDrag(e);
}
private void OnKeyDown(object? sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Escape:
_ = CloseWithAnimationAsync();
e.Handled = true;
break;
case Key.F11:
WindowState = WindowState == WindowState.FullScreen
? WindowState.Normal
: WindowState.FullScreen;
e.Handled = true;
break;
}
}
/// <summary>
/// 关闭动画:淡出 + 轻微缩小,动画结束后再真正关闭窗口。
/// 与主窗口的关闭动画保持同一节奏(180ms)。
/// </summary>
private async Task CloseWithAnimationAsync()
{
if (_closing) return;
_closing = true;
Transitions = new Transitions
{
new DoubleTransition
{
Property = OpacityProperty,
Duration = TimeSpan.FromMilliseconds(180),
Easing = new CubicEaseIn()
}
};
Opacity = 0;
await Task.Delay(190);
Close();
}
private void OnClosed(object? sender, EventArgs e)
{
Content = null;
_model?.Dispose();
_model = null;
}
}
/// <summary>模型加载失败时显示的提示窗口(不含任何渲染逻辑)。</summary>
public sealed class ModelErrorWindow : Window
{
public ModelErrorWindow(string title, string message)
{
Title = title;
Width = 560;
Height = 340;
Background = Brushes.Transparent;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
WindowStartupLocation = WindowStartupLocation.CenterOwner;
var lines = new List<Control>
{
new TextBlock
{
Text = title,
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
FontSize = 16,
FontWeight = FontWeight.SemiBold
},
new TextBlock
{
Text = message,
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
FontSize = 12,
TextWrapping = TextWrapping.Wrap
},
new Button
{
Content = "确定",
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
Padding = new Thickness(18, 6)
}
};
var panel = new StackPanel
{
Margin = new Thickness(24),
Spacing = 14
};
foreach (var line in lines) panel.Children.Add(line);
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
Content = new Border
{
CornerRadius = new CornerRadius(12),
Background = new SolidColorBrush(Color.Parse("#0B1226")),
Child = panel
};
}
}
-552
View File
@@ -1,552 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using GC.Services;
namespace GC.Savedog;
internal sealed class ApplyOptions
{
public string UpdateDir { get; set; } = "";
public string? InstallDir { get; set; }
public int WaitPid { get; set; }
public int TimeoutSeconds { get; set; } = 45;
public bool RequireSignature { get; set; } = true;
public bool DryRun { get; set; }
public bool Force { get; set; }
}
/// <summary>
/// 应用一次启动器更新:验签 → 校验 → 原子替换 → 启动 → 看护 → 成功清场 / 失败回滚。
/// 任何一步失败都不会留下「删了旧版又没有新版」的状态。
/// </summary>
internal sealed class Applier
{
private static readonly Regex ArtifactPattern = new(
@"^GC-(?<ver>.+?)-(?<plat>[^\-]+-[^\-]+)\.(app|exe)$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private readonly ApplyOptions _options;
private readonly Log _log;
public Applier(ApplyOptions options, Log log)
{
_options = options;
_log = log;
}
public int Run()
{
var updateDir = Path.GetFullPath(_options.UpdateDir);
var requestPath = Path.Combine(updateDir, SavedogFiles.ApplyRequest);
if (!File.Exists(requestPath))
return Fail(updateDir, "找不到更新申请 " + SavedogFiles.ApplyRequest, 3);
var request = Json.Read<SavedogRequest>(requestPath);
if (request == null || string.IsNullOrWhiteSpace(request.Version))
return Fail(updateDir, "更新申请内容不完整", 3);
if (!ValidName(request.PackageName))
return Fail(updateDir, "更新包名不合法: " + request.PackageName, 3);
_log.Info($"开始应用 v{request.Version}({request.Rid},{request.PackageName})");
// 1. 等旧进程退出(否则 Windows 上文件还被占用)
if (_options.WaitPid > 0 && !WaitForExit(_options.WaitPid, TimeSpan.FromSeconds(60)))
_log.Warn($"等待进程 {_options.WaitPid} 退出超时,继续尝试");
// 2. 安装目录定位与安全检查
var installDir = string.IsNullOrWhiteSpace(_options.InstallDir)
? Path.GetFullPath(Path.Combine(updateDir, request.InstallRelative))
: Path.GetFullPath(_options.InstallDir!);
if (!Directory.Exists(installDir))
return Fail(updateDir, "安装目录不存在: " + installDir, 4);
if (!_options.Force && File.Exists(Path.Combine(installDir, "GC.sln")))
return Fail(updateDir, "检测到源码目录,拒绝在源码树里替换程序", 4);
// 3. 二次验签:不信任「启动器说它验过了」
var require = request.RequireSignature && SignatureKeyring.Enforced;
var manifestPath = Path.Combine(updateDir, request.ManifestPath);
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
var verification = ManifestSignature.Verify(manifestText, require);
if (verification.IsRejected)
{
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}");
return Refuse(updateDir, request, verification);
}
_log.Info($"清单可信度:{verification.Trust}" +
(verification.KeyId != null ? $"({verification.KeyId})" : ""));
// 4. 校验更新包
var zipPath = Path.Combine(updateDir, request.PackageZip);
if (!File.Exists(zipPath))
return Fail(updateDir, "更新包不存在: " + request.PackageZip, 5);
var zipInfo = new FileInfo(zipPath);
if (request.PackageSize > 0 && zipInfo.Length != request.PackageSize)
return Fail(updateDir, $"更新包体积不符(期望 {request.PackageSize},实际 {zipInfo.Length})", 5);
var actualSha = ContentHash.Sha256File(zipPath);
if (!string.IsNullOrWhiteSpace(request.PackageSha256) &&
!string.Equals(actualSha, request.PackageSha256, StringComparison.OrdinalIgnoreCase))
{
return Fail(updateDir, "更新包 sha256 与清单不符,已丢弃", 5);
}
if (string.IsNullOrWhiteSpace(request.PackageSha256))
_log.Warn("清单没有提供 sha256,仅依赖签名与解压校验");
SafeArchive.Inspection inspection;
try
{
inspection = SafeArchive.Inspect(zipPath);
_log.Info($"更新包检查通过:{inspection.Entries} 个条目," +
$"{inspection.UncompressedBytes / 1024 / 1024} MB,压缩比 {inspection.Ratio:0.0}:1");
}
catch (Exception ex)
{
return Fail(updateDir, "更新包安全性检查失败: " + ex.Message, 5);
}
// 5. 解压到暂存区(与安装目录同卷,后续 rename 才是原子的)
var stage = Path.Combine(updateDir, "stage");
ClearDirectory(stage);
try
{
SafeArchive.ExtractToDirectory(zipPath, stage);
FlattenSingleDirectory(stage);
}
catch (Exception ex)
{
ClearDirectory(stage);
return Fail(updateDir, "解压失败: " + ex.Message, 6);
}
var artifact = FindArtifact(stage, request.PackageName);
if (artifact == null)
{
ClearDirectory(stage);
return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6);
}
var target = Path.Combine(installDir, Path.GetFileName(artifact));
var alreadyInstalled = File.Exists(target) || Directory.Exists(target);
if (_options.DryRun)
{
_log.Info($"[dry-run] 校验全部通过,将安装到 {target}");
ClearDirectory(stage);
return 0;
}
if (alreadyInstalled)
{
// 同一版本重复下发:当成已安装,避免反复覆盖正在运行的文件
_log.Info("目标版本已存在,视为已安装");
ClearDirectory(stage);
TryDelete(zipPath);
TryDelete(requestPath);
WriteState(updateDir, new SavedogState
{
Status = "applied",
Version = request.Version,
PackageName = Path.GetFileName(artifact),
Verified = true,
Message = "目标版本已存在,无需替换"
});
return 0;
}
// 6. 移入安装目录(不覆盖任何已有文件)
try
{
Directory.CreateDirectory(installDir);
if (Directory.Exists(artifact)) Directory.Move(artifact, target);
else File.Move(artifact, target);
_log.Info("新版已就位: " + Path.GetFileName(target));
}
catch (Exception ex)
{
ClearDirectory(stage);
return Fail(updateDir, "移动到安装目录失败: " + ex.Message, 7);
}
// 7. 启动并看护
var previous = ReadLastGood(updateDir);
StartupHealth.Clear(updateDir);
Process? child;
try
{
child = Launch(target);
}
catch (Exception ex)
{
child = null;
_log.Error("启动新版失败: " + ex.Message);
}
var healthy = child != null && WaitForHealth(updateDir, request.Version, child,
TimeSpan.FromSeconds(_options.TimeoutSeconds));
if (healthy)
{
_log.Info($"v{request.Version} 启动正常,更新完成");
CleanupOldVersions(installDir, Path.GetFileName(target), request.PlatformLabel);
WriteLastGood(updateDir, request.Version, Path.GetFileName(target));
WriteState(updateDir, new SavedogState
{
Status = "applied",
Version = request.Version,
PreviousVersion = previous?.Version,
PackageName = Path.GetFileName(target),
Verified = true,
Message = "更新已应用"
});
ClearDirectory(stage);
TryDelete(zipPath);
TryDelete(requestPath);
return 0;
}
// 8. 回滚
_log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚");
TryKill(child);
var removed = RemoveNewVersion(target);
_log.Info(removed ? "已移除未通过检查的新版" : "新版文件被占用,未能完全移除");
var restored = TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
WriteState(updateDir, new SavedogState
{
Status = "rolledback",
Version = request.Version,
PreviousVersion = previous?.Version,
PackageName = Path.GetFileName(target),
Verified = true,
Message = restored
? "新版本未通过启动检查,已回滚到上一个版本"
: "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装"
});
ClearDirectory(stage);
TryDelete(zipPath);
TryDelete(requestPath);
return 8;
}
// ------------------------------------------------------------------ 校验辅助
private static bool ValidName(string name)
=> name.Length > 0 && name.Length < 200 &&
name.IndexOfAny(new[] { '/', '\\', ':', '\0' }) < 0 &&
(name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) ||
name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase));
private static bool WaitForExit(int pid, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
try
{
using var process = Process.GetProcessById(pid);
if (process.HasExited) return true;
}
catch (ArgumentException) { return true; } // 进程已不存在
catch { return true; }
Thread.Sleep(200);
}
return false;
}
private static void FlattenSingleDirectory(string stage)
{
var entries = Directory.GetFileSystemEntries(stage);
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
var inner = entries[0];
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
var temp = stage + "-flat";
if (Directory.Exists(temp)) Directory.Delete(temp, true);
Directory.Move(inner, temp);
Directory.Delete(stage, true);
Directory.Move(temp, stage);
}
private static string? FindArtifact(string stage, string packageName)
{
var direct = Path.Combine(stage, packageName);
if (File.Exists(direct) || Directory.Exists(direct)) return direct;
foreach (var entry in Directory.GetFileSystemEntries(stage))
{
var name = Path.GetFileName(entry);
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(entry))
return entry;
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(entry))
return entry;
}
return null;
}
// ------------------------------------------------------------------ 启动与看护
private Process? Launch(string target)
{
if (Directory.Exists(target))
{
// .app:优先直接启动内部可执行文件,这样才能拿到 pid 做看护
var macOs = Path.Combine(target, "Contents", "MacOS");
if (Directory.Exists(macOs))
{
var exe = Directory.GetFiles(macOs)
.OrderByDescending(f => Path.GetFileName(f) == "GC")
.FirstOrDefault();
if (exe != null)
{
MakeExecutable(exe);
return StartProcess(exe, Path.GetDirectoryName(exe)!);
}
}
MakeExecutable(Path.Combine(target, "Contents", "MacOS", "GC"));
var psi = new ProcessStartInfo("open") { UseShellExecute = false };
psi.ArgumentList.Add("-n");
psi.ArgumentList.Add(target);
return Process.Start(psi);
}
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
{
if (!OperatingSystem.IsWindows()) MakeExecutable(target);
return StartProcess(target, Path.GetDirectoryName(target)!);
}
return null;
}
private static Process? StartProcess(string exe, string workingDirectory)
{
var psi = new ProcessStartInfo(exe)
{
UseShellExecute = false,
WorkingDirectory = workingDirectory
};
return Process.Start(psi);
}
private static void MakeExecutable(string path)
{
if (OperatingSystem.IsWindows()) return;
try
{
if (!File.Exists(path)) return;
var mode = File.GetUnixFileMode(path);
File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute |
UnixFileMode.GroupExecute |
UnixFileMode.OtherExecute);
}
catch { }
}
private bool WaitForHealth(string updateDir, string version, Process child, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
var health = StartupHealth.Read(updateDir);
if (health != null && health.Ok && SameVersion(health.Version, version))
{
_log.Info($"收到健康标记(pid {health.Pid})");
return true;
}
if (child.HasExited)
{
_log.Error($"新版进程已退出(退出码 {child.ExitCode})");
return false;
}
Thread.Sleep(250);
}
// 超时但进程还活着:可能是尚未写入健康标记的旧构建,谨慎放行
if (!child.HasExited)
{
_log.Warn("未收到健康标记,但进程仍在运行,按成功处理");
return true;
}
return false;
}
private static bool SameVersion(string a, string b)
=> string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase);
private static string Normalize(string version)
{
var trimmed = version.Trim().TrimStart('v', 'V');
var parts = trimmed.Split('.');
var numbers = new List<string>();
foreach (var part in parts)
{
if (!int.TryParse(part, out var n)) break;
numbers.Add(n.ToString());
}
while (numbers.Count > 0 && numbers[^1] == "0") numbers.RemoveAt(numbers.Count - 1);
return numbers.Count == 0 ? trimmed : string.Join('.', numbers);
}
private static void TryKill(Process? process)
{
if (process == null) return;
try
{
if (!process.HasExited) process.Kill(entireProcessTree: true);
}
catch { }
}
// ------------------------------------------------------------------ 清理 / 回滚
private void CleanupOldVersions(string installDir, string keepName, string platformLabel)
{
foreach (var entry in Directory.GetFileSystemEntries(installDir))
{
var name = Path.GetFileName(entry);
if (string.Equals(name, keepName, StringComparison.OrdinalIgnoreCase)) continue;
var match = ArtifactPattern.Match(name);
if (!match.Success) continue;
var platform = match.Groups["plat"].Value;
if (!string.Equals(platform, platformLabel, StringComparison.OrdinalIgnoreCase))
{
_log.Info($"保留其它平台版本: {name}");
continue;
}
try
{
if (Directory.Exists(entry)) Directory.Delete(entry, true);
else File.Delete(entry);
_log.Info("清理旧版本: " + name);
}
catch (Exception ex)
{
_log.Warn($"清理旧版本失败 {name}: {ex.Message}");
}
}
}
private bool RemoveNewVersion(string target)
{
try
{
if (Directory.Exists(target)) Directory.Delete(target, true);
else if (File.Exists(target)) File.Delete(target);
return true;
}
catch (Exception ex)
{
_log.Warn("移除新版失败: " + ex.Message);
return false;
}
}
private bool TryLaunchPrevious(string installDir, string updateDir, LastGoodVersion? lastGood,
string platformLabel)
{
// 优先用上次成功的版本;否则挑一个同平台的其它版本
var candidates = new List<string>();
if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName))
candidates.Add(Path.Combine(installDir, lastGood.PackageName));
foreach (var entry in Directory.GetFileSystemEntries(installDir))
{
var name = Path.GetFileName(entry);
var match = ArtifactPattern.Match(name);
if (!match.Success) continue;
if (!string.Equals(match.Groups["plat"].Value, platformLabel, StringComparison.OrdinalIgnoreCase))
continue;
candidates.Add(entry);
}
foreach (var candidate in candidates)
{
if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue;
try
{
Launch(candidate);
_log.Info("已回滚启动: " + Path.GetFileName(candidate));
return true;
}
catch (Exception ex)
{
_log.Warn($"回滚启动失败 {Path.GetFileName(candidate)}: {ex.Message}");
}
}
return false;
}
// ------------------------------------------------------------------ 状态文件
private void WriteState(string updateDir, SavedogState state)
{
try { Json.Write(Path.Combine(updateDir, SavedogFiles.State), state); }
catch (Exception ex) { _log.Warn("写状态失败: " + ex.Message); }
}
private int Fail(string updateDir, string message, int code)
{
_log.Error(message);
WriteState(updateDir, new SavedogState { Status = "failed", Message = message });
return code;
}
private int Refuse(string updateDir, SavedogRequest request, ManifestVerification verification)
{
WriteState(updateDir, new SavedogState
{
Status = "refused",
Version = request.Version,
PackageName = request.PackageName,
Verified = false,
Message = $"清单验签失败:{verification.Error}"
});
return 2;
}
private static LastGoodVersion? ReadLastGood(string updateDir)
=> Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
private static void WriteLastGood(string updateDir, string version, string packageName)
{
try
{
Json.Write(Path.Combine(updateDir, SavedogFiles.LastGood), new LastGoodVersion
{
Version = version,
PackageName = packageName
});
}
catch { }
}
private static void ClearDirectory(string dir)
{
try
{
if (Directory.Exists(dir)) Directory.Delete(dir, true);
}
catch { }
}
private static void TryDelete(string path)
{
try { if (File.Exists(path)) File.Delete(path); } catch { }
}
}
-47
View File
@@ -1,47 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
GC-SAVEDOG —— 启动器更新守护进程。
为什么不把替换逻辑留在启动器里:
· 启动器正在运行,Windows 上无法覆盖自己的 exe;
· 覆盖失败(断电 / 占用 / 权限)时启动器已经退出,没人能回滚;
· 更新逻辑需要访问私钥验签,放在独立的最小进程里更容易审计。
本进程只做四件事:验签 → 校验 → 替换 → 看护(不健康就回滚)。
它不引用 Avalonia,也不引用启动器程序集,源码里只链接 GC/src/Security/ 下的
安全原语,保证「校验逻辑与启动器完全同一份实现」。
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<RootNamespace>GC.Savedog</RootNamespace>
<AssemblyName>GC-SAVEDOG</AssemblyName>
<InvariantGlobalization>true</InvariantGlobalization>
<!--
裁剪发布:自包含单文件不裁剪约 70MB,裁剪后 14MB 左右。
守护进程要跟着更新包一起下发,体积直接影响下载与校验时间。
裁剪的前提是**不用运行时反射**:JSON 全部走 SavedogJsonContext 的源生成类型信息
(见 SavedogJson.cs)。若给这里新加类型却忘了注册,未裁剪的调试构建看不出来,
只有发布产物会在运行时报 NotSupportedException —— 测试用例里有一次真实 apply,
会覆盖到。
-->
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>full</TrimMode>
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
<!-- 只保留必要的卫星资源,裁剪后再压一层体积 -->
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
<Compile Include="..\GC\src\Security\**\*.cs" Exclude="..\GC\src\Security\ManifestLoader.cs" LinkBase="Security" />
<Compile Include="..\GC\src\Services\Json.cs" Link="Shared\Json.cs" />
</ItemGroup>
</Project>
-34
View File
@@ -1,34 +0,0 @@
using System;
using System.IO;
namespace GC.Savedog;
/// <summary>同时写 stdout 与 .GC/update/savedog.log,便于用户离线排查。</summary>
internal sealed class Log
{
private readonly string? _path;
private readonly object _gate = new();
public Log(string? path) => _path = path;
public void Info(string message) => Write("INFO ", message);
public void Warn(string message) => Write("WARN ", message);
public void Error(string message) => Write("ERROR", message);
private void Write(string level, string message)
{
var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
Console.WriteLine(line);
if (string.IsNullOrWhiteSpace(_path)) return;
try
{
lock (_gate)
{
var dir = Path.GetDirectoryName(_path!);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.AppendAllText(_path!, line + "\n");
}
}
catch { /* 日志失败不能影响更新 */ }
}
}
-347
View File
@@ -1,347 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using GC.Services;
namespace GC.Savedog;
/// <summary>
/// GC-SAVEDOG 命令行。
///
/// GC-SAVEDOG apply --update &lt;.GC/update&gt; [--install &lt;dir&gt;] [--wait-pid N]
/// [--timeout 45] [--dry-run] [--json]
/// GC-SAVEDOG verify --manifest &lt;version.json&gt; [--require 1] [--json]
/// GC-SAVEDOG verify-model --dir &lt;model/&lt;id&gt;&gt; --id &lt;id&gt; [--json]
/// GC-SAVEDOG keygen [--out .signing] [--key-id gc-2026-11]
/// GC-SAVEDOG sign --manifest &lt;version.json&gt; [--key .signing/gc-signing.pem]
/// [--key-id ...] [--out &lt;file&gt;]
/// GC-SAVEDOG status --update &lt;.GC/update&gt; [--json]
/// </summary>
internal static class Program
{
private const string DefaultKeyId = "gc-2026-11";
private const string DefaultKeyPath = ".signing/gc-signing.pem";
private static int Main(string[] args)
{
try { Console.OutputEncoding = Encoding.UTF8; } catch { }
// 必须在任何 Json.Read/Write 之前接上源生成上下文(裁剪构建必需)
SavedogJson.Initialize();
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
{
Help();
return 0;
}
var command = args[0].ToLowerInvariant();
var rest = args.Skip(1).ToArray();
var options = Parse(rest);
return command switch
{
"apply" => Apply(options),
"verify" => Verify(options),
"verify-model" => VerifyModel(options),
"keygen" => Keygen(options),
"sign" => Sign(options),
"status" => Status(options),
"version" or "--version" => PrintVersion(),
_ => Unknown(command)
};
}
// ------------------------------------------------------------------ apply
private static int Apply(Dictionary<string, string> options)
{
var updateDir = Option(options, "update", "");
if (string.IsNullOrWhiteSpace(updateDir))
{
Console.Error.WriteLine("apply 需要 --update <.GC/update>");
return 3;
}
var log = new Log(Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.Log));
var applyOptions = new ApplyOptions
{
UpdateDir = updateDir,
InstallDir = Option(options, "install", null),
WaitPid = Int(options, "wait-pid", 0),
TimeoutSeconds = Int(options, "timeout", 45),
DryRun = Flag(options, "dry-run"),
Force = Flag(options, "force"),
RequireSignature = Int(options, "require-signature", 1) != 0
};
var applier = new Applier(applyOptions, log);
var code = applier.Run();
if (Flag(options, "json"))
{
if (applyOptions.DryRun)
{
// dry-run 不落盘,state.json 里是上一次的真实结果,直接打印会误导调用方
var request = Json.Read<SavedogRequest>(
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.ApplyRequest));
Console.WriteLine(Json.Serialize(new SavedogState
{
Status = code == 0 ? "checked" : "failed",
Version = request?.Version ?? "",
PackageName = request?.PackageName ?? "",
Verified = code == 0,
Message = code == 0 ? "校验全部通过(未安装,dry-run)" : "校验未通过(dry-run)"
}));
}
else
{
var state = Json.Read<SavedogState>(
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.State));
Console.WriteLine(Json.Serialize(state));
}
}
return code;
}
// ------------------------------------------------------------------ verify
private static int Verify(Dictionary<string, string> options)
{
var manifest = Option(options, "manifest", "");
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
{
Console.Error.WriteLine("verify 需要 --manifest <version.json>");
return 3;
}
var require = Int(options, "require", 1) != 0;
var text = File.ReadAllText(manifest);
var result = ManifestSignature.Verify(text, require);
if (Flag(options, "json"))
{
var report = new VerifyReport
{
Trust = result.Trust.ToString(),
KeyId = result.KeyId,
Error = result.Error
};
foreach (var key in SignatureKeyring.Keys)
report.TrustedKeys.Add(new TrustedKey
{
KeyId = key.KeyId,
Fingerprint = ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)
});
Console.WriteLine(Json.Serialize(report));
}
else
{
Console.WriteLine($"信任状态: {result.Trust}");
if (result.KeyId != null) Console.WriteLine($"密钥: {result.KeyId}");
if (result.Error != null) Console.WriteLine($"说明: {result.Error}");
foreach (var key in SignatureKeyring.Keys)
Console.WriteLine($"受信任公钥: {key.KeyId} ({ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)})");
}
return result.IsTrusted ? 0 : 2;
}
private static int VerifyModel(Dictionary<string, string> options)
{
var dir = Option(options, "dir", "");
var id = Option(options, "id", "");
if (string.IsNullOrWhiteSpace(dir) || string.IsNullOrWhiteSpace(id))
{
Console.Error.WriteLine("verify-model 需要 --dir <model 目录> --id <模型 id>");
return 3;
}
var result = ModelIntegrity.VerifyForLoad(Path.GetFullPath(dir), id);
if (Flag(options, "json"))
Console.WriteLine(Json.Serialize(new VerifyModelReport
{
Ok = result.Ok,
Present = result.Present,
Message = result.Message
}));
else
Console.WriteLine($"{(result.Ok ? "OK" : "FAIL")} 记录={(result.Present ? "有" : "无")} {result.Message}");
return result.Ok ? 0 : 2;
}
// ------------------------------------------------------------------ keygen / sign
private static int Keygen(Dictionary<string, string> options)
{
var outDir = Option(options, "out", ".signing")!;
var keyId = Option(options, "key-id", DefaultKeyId)!;
Directory.CreateDirectory(outDir);
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var privatePath = Path.Combine(outDir, "gc-signing.pem");
var publicPath = Path.Combine(outDir, "gc-signing.pub");
File.WriteAllText(privatePath, key.ExportPkcs8PrivateKeyPem());
var publicBase64 = ManifestSignature.ExportPublicKeyBase64(key);
File.WriteAllText(publicPath, publicBase64 + "\n");
try
{
if (!OperatingSystem.IsWindows())
File.SetUnixFileMode(privatePath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
catch { }
Console.WriteLine("已生成 ECDSA P-256 密钥对:");
Console.WriteLine(" 私钥(绝不要提交): " + privatePath);
Console.WriteLine(" 公钥(写进源码) : " + publicPath);
Console.WriteLine(" keyId : " + keyId);
Console.WriteLine(" 公钥 Base64 : " + publicBase64);
Console.WriteLine(" 公钥指纹 : " + ManifestSignature.PublicKeyFingerprint(publicBase64));
Console.WriteLine();
Console.WriteLine("把下面一行加进 GC/src/Security/SignatureKeyring.cs 的 Keys 列表:");
Console.WriteLine($" new KeyEntry(\"{keyId}\", \"{publicBase64}\"),");
return 0;
}
private static int Sign(Dictionary<string, string> options)
{
var manifest = Option(options, "manifest", "");
var keyPath = Option(options, "key", DefaultKeyPath)!;
var keyId = Option(options, "key-id",
Environment.GetEnvironmentVariable("GC_SIGNING_KEY_ID") ?? DefaultKeyId)!;
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
{
Console.Error.WriteLine("sign 需要 --manifest <version.json>");
return 3;
}
using var key = ManifestSignature.TryLoadPrivateKey(keyPath);
if (key == null)
{
Console.Error.WriteLine($"找不到可用的签名私钥: {Path.GetFullPath(keyPath)}");
return 4;
}
var text = File.ReadAllText(manifest);
var signed = ManifestSignature.SignDocument(text, key, keyId);
var output = Option(options, "out", manifest)!;
File.WriteAllText(output, signed);
var check = ManifestSignature.Verify(signed, requireSignature: true);
Console.WriteLine($"已签名: {output}({check.Trust})");
return check.Trust == ManifestTrust.Verified ? 0 : 5;
}
// ------------------------------------------------------------------ status
private static int Status(Dictionary<string, string> options)
{
var updateDir = Path.GetFullPath(Option(options, "update", ".GC/update")!);
var state = Json.Read<SavedogState>(Path.Combine(updateDir, SavedogFiles.State));
var lastGood = Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
var health = StartupHealth.Read(updateDir);
if (Flag(options, "json"))
{
Console.WriteLine(Json.Serialize(new StatusReport
{
State = state,
LastGood = lastGood,
Health = health
}));
return 0;
}
Console.WriteLine(state == null
? "没有更新记录"
: $"最近更新: {state.Status} v{state.Version} -> {state.Message}({state.At})");
Console.WriteLine(lastGood == null
? "上次成功版本: 未知"
: $"上次成功版本: v{lastGood.Version}({lastGood.PackageName})");
Console.WriteLine(health == null
? "健康标记: 无"
: $"健康标记: v{health.Version} pid={health.Pid} ok={health.Ok}");
return 0;
}
private static int PrintVersion()
{
Console.WriteLine("GC-SAVEDOG 1.0.0");
Console.WriteLine("签名算法: " + ManifestSignature.Algorithm);
return 0;
}
private static int Unknown(string command)
{
Console.Error.WriteLine($"未知命令: {command}");
Help();
return 3;
}
private static void Help()
{
Console.WriteLine("""
GC-SAVEDOG —— 启动器更新守护进程
apply --update <.GC/update> [--install <dir>] [--wait-pid N]
[--timeout 45] [--dry-run] [--force] [--json]
verify --manifest <version.json> [--require 1] [--json]
verify-model --dir <model/ID> --id <ID> [--json]
keygen [--out .signing] [--key-id gc-2026-11]
sign --manifest <version.json> [--key .signing/gc-signing.pem] [--out <file>]
status --update <.GC/update> [--json]
退出码:0 成功 / 2 验签失败(拒绝) / 3 参数或申请错误 / 5 包校验失败 / 8 已回滚
""");
}
// ------------------------------------------------------------------ 参数
private static Dictionary<string, string> Parse(string[] args)
{
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (!arg.StartsWith("--", StringComparison.Ordinal))
{
map[arg] = "1";
continue;
}
var name = arg[2..];
var eq = name.IndexOf('=');
if (eq > 0)
{
map[name[..eq]] = name[(eq + 1)..];
continue;
}
if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
{
map[name] = args[++i];
continue;
}
map[name] = "1";
}
return map;
}
private static string? Option(Dictionary<string, string> options, string name, string? fallback)
=> options.TryGetValue(name, out var value) ? value : fallback;
private static int Int(Dictionary<string, string> options, string name, int fallback)
=> options.TryGetValue(name, out var value) && int.TryParse(value, out var parsed)
? parsed : fallback;
private static bool Flag(Dictionary<string, string> options, string name)
=> options.TryGetValue(name, out var value) &&
(value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase));
}
-79
View File
@@ -1,79 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using GC.Services;
namespace GC.Savedog;
/// <summary>
/// GC-SAVEDOG 是裁剪发布的(PublishTrimmed),反射式序列化在裁剪后会失效:
/// trimmer 认为「没人 new 过」的构造函数会被删掉,运行时反序列化直接抛
/// <c>NotSupportedException</c>。因此守护进程把所有 JSON 类型都注册进源生成上下文,
/// 编译期生成类型信息,运行时零反射。
///
/// 新增需要读写的 JSON 类型时,记得在这里补一行 <c>[JsonSerializable]</c>,
/// 否则会在裁剪产物里报错(未裁剪的调试构建看不出问题)。
/// </summary>
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip)]
[JsonSerializable(typeof(SavedogRequest))]
[JsonSerializable(typeof(SavedogState))]
[JsonSerializable(typeof(LastGoodVersion))]
[JsonSerializable(typeof(StartupHealth.HealthRecord))]
[JsonSerializable(typeof(ModelIntegrityFile))]
[JsonSerializable(typeof(VerifyReport))]
[JsonSerializable(typeof(StatusReport))]
[JsonSerializable(typeof(VerifyModelReport))]
internal partial class SavedogJsonContext : JsonSerializerContext
{
// 源生成器已提供 (JsonSerializerOptions) 构造函数;实例化时传入启动器的那套选项,
// 让两边写出的 JSON 完全同款(中文不转成 \uXXXX、缩进一致),便于直接 diff 排查。
}
/// <summary><c>verify --json</c> 的输出。</summary>
internal sealed class VerifyReport
{
public string Trust { get; set; } = "";
public string? KeyId { get; set; }
public string? Error { get; set; }
public List<TrustedKey> TrustedKeys { get; set; } = new();
}
internal sealed class TrustedKey
{
public string KeyId { get; set; } = "";
public string Fingerprint { get; set; } = "";
}
/// <summary><c>status --json</c> 的输出。</summary>
internal sealed class StatusReport
{
public SavedogState? State { get; set; }
public LastGoodVersion? LastGood { get; set; }
public StartupHealth.HealthRecord? Health { get; set; }
}
/// <summary><c>verify-model --json</c> 的输出。</summary>
internal sealed class VerifyModelReport
{
public bool Ok { get; set; }
public bool Present { get; set; }
public string Message { get; set; } = "";
}
/// <summary>把共享的 <see cref="Json"/> 接到源生成上下文上。</summary>
internal static class SavedogJson
{
private static readonly SavedogJsonContext Context = new(new JsonSerializerOptions(Json.Options));
public static void Initialize()
{
Json.TypeInfoProvider = type => Context.GetTypeInfo(type);
}
}
-48
View File
@@ -1,48 +0,0 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:GC.ViewModels"
xmlns:views="using:GC.Views"
x:Class="GC.App"
RequestedThemeVariant="Light">
<Application.DataTemplates>
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<views:HomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:DownloadViewModel}">
<views:DownloadView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
<views:SettingsView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:AboutViewModel}">
<views:AboutView />
</DataTemplate>
</Application.DataTemplates>
<Application.Resources>
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
<!--
FluentTheme 的按钮模板在 :pointerover / :pressed 时会用这些主题资源
覆盖 ContentPresenter 的画刷。若与 AppTheme.axaml 里通过 Button 属性
设置的 hover 颜色不一致,两套机制会互相覆盖,导致光标移动时渲染错乱。
这里把它们统一指向与按钮样式相同的颜色。
-->
<SolidColorBrush x:Key="ButtonBackgroundPointerOver">#EDF2FC</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBackgroundPressed">#DDE7F8</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBorderBrushPointerOver">#BAC9E6</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBorderBrushPressed">#9FB4DD</SolidColorBrush>
<SolidColorBrush x:Key="ButtonForegroundPointerOver">#111A2E</SolidColorBrush>
<SolidColorBrush x:Key="ButtonForegroundPressed">#111A2E</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackground">#2F6BFF</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackgroundPointerOver">#1F4FD0</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackgroundPressed">#183FA8</SolidColorBrush>
</Application.Resources>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://GC.Core/Styles/AppTheme.axaml" />
</Application.Styles>
</Application>
-134
View File
@@ -1,134 +0,0 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using GC.Services;
using GC.ViewModels;
using GC.Views;
namespace GC;
public partial class App : Application
{
public override void Initialize() => AvaloniaXamlLoader.Load(this);
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var services = AppServices.Create();
// 诊断模式:只验证模型程序集能否加载(发布包里也用它做冒烟测试)
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1")
{
var code = SelfTest(services);
Avalonia.Threading.Dispatcher.UIThread.Post(
() => desktop.Shutdown(code), Avalonia.Threading.DispatcherPriority.Background);
return;
}
// 启动加速:先建空窗口并显示,再在首帧之后构造 ViewModel。
// MainViewModel 会扫描模型、加载封面、读设置,同步做会让
// 「双击到看见窗口」明显变慢;先出窗口,内容随后填充。
var window = new MainWindow();
window.Show();
// 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来,
// 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。
StartupHealth.MarkHealthy(services.Paths.UpdateRoot,
LauncherRuntimeInfo.CurrentLauncherVersion);
// 首帧之后再构造 ViewModel:Post 而非依赖 Opened,
// 因为 Opened 在某些情况下不触发(headless / 部分平台),
// 会导致 DataContext 一直是 null、主页面白屏。
// 扫描模型 / 加载封面在后台线程做,UI 线程只负责赋值,
// 这样窗口能立刻响应,不会卡在白屏。
MainViewModel vm = null!;
Task.Run(() => new MainViewModel(services))
.ContinueWith(t =>
{
vm = t.Result;
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
window.DataContext = vm;
WireMainViewModel(vm, window, services, desktop);
}, Avalonia.Threading.DispatcherPriority.Background);
}, System.Threading.Tasks.TaskScheduler.Default);
// 应用图标不依赖 ViewModel,先设好让窗口一出现就有图标
try
{
using var iconStream = Avalonia.Platform.AssetLoader.Open(
new Uri("avares://GC.Core/Assets/icon.png"));
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
}
catch { /* 图标缺失不影响启动 */ }
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
base.OnFrameworkInitializationCompleted();
}
/// <summary>
/// 主窗口显示后再接上 ViewModel:绑定对话框、启动后台更新检查。
/// 拆出来是为了让窗口先出现,模型扫描不影响「双击到出窗口」。
/// </summary>
private static void WireMainViewModel(MainViewModel vm, MainWindow window,
AppServices services, IClassicDesktopStyleApplicationLifetime desktop)
{
_ = desktop;
vm.ConfirmHandler = async message =>
{
var dialog = new ConfirmWindow(message);
return await dialog.ShowDialog<bool>(window);
};
// 发现启动器新版本:弹窗询问,用户选「更新」才下载并安排替换
vm.LauncherUpdateHandler = async newVersion =>
{
var dialog = new ConfirmWindow(
title: "发现新版本",
message: $"启动器有新版本 v{newVersion},是否立即更新?\n\n" +
"更新会下载新版程序,下次启动时自动替换当前版本;" +
"选择取消则继续使用当前版本,但模型仍会更新到最新。",
confirmText: "更新",
cancelText: "取消");
return await dialog.ShowDialog<bool>(window);
};
// 主窗口已显示,后台检查模型 / 启动器更新,不阻塞界面
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
{
Avalonia.Threading.Dispatcher.UIThread.Post(
() => _ = vm.RunStartupUpdateAsync(),
Avalonia.Threading.DispatcherPriority.Background);
}
}
/// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary>
private static int SelfTest(AppServices services)
{
var packages = services.Models.Scan();
Console.WriteLine($"模型库: {services.Paths.ModelRoot}");
Console.WriteLine($"模型数: {packages.Count}");
var failed = 0;
foreach (var package in packages)
{
try
{
using var loaded = services.ModelHost.Load(package, () => { });
Console.WriteLine($"OK {package.Id} -> {loaded.View.GetType().FullName}");
}
catch (Exception ex)
{
failed++;
Console.WriteLine($"FAIL {package.Id}: {ex.Message}");
}
}
return failed == 0 ? 0 : 1;
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 350 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

-67
View File
@@ -1,67 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace GC.Services;
/// <summary>
/// 规范化 JSON:签名与验签必须对完全相同的字节做运算,
/// 否则「同一份内容、不同缩进/键序」会得出不同签名。
///
/// 规则(写进 README,第三方可复现):
/// 1. 对象键按 Unicode 码点升序递归排序
/// 2. 无缩进、无多余空白,UTF-8 编码,不带 BOM
/// 3. 数字沿用源文本(不做浮点重排)
/// 4. 非 ASCII 字符不转义(Encoder = UnsafeRelaxedJsonEscaping)
/// 5. 签名时先移除根级 <c>signature</c> 字段
/// </summary>
public static class CanonicalJson
{
private static readonly JsonSerializerOptions Options = new()
{
WriteIndented = false,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
/// <summary>把 JSON 文本规范化;解析失败返回 null。</summary>
public static byte[]? Normalize(string text, bool dropSignatureField)
{
if (string.IsNullOrWhiteSpace(text)) return null;
try
{
var node = JsonNode.Parse(text);
if (node is not JsonObject obj) return null;
if (dropSignatureField) obj.Remove("signature");
var sorted = SortNode(obj);
return Encoding.UTF8.GetBytes(sorted?.ToJsonString(Options) ?? "{}");
}
catch (JsonException)
{
return null;
}
}
private static JsonNode? SortNode(JsonNode? node)
{
switch (node)
{
case JsonObject obj:
var result = new JsonObject();
foreach (var pair in obj.OrderBy(p => p.Key, StringComparer.Ordinal))
result[pair.Key] = SortNode(pair.Value);
return result;
case JsonArray array:
var list = new JsonArray();
foreach (var item in array) list.Add(SortNode(item));
return list;
default:
return node?.DeepClone();
}
}
}
-80
View File
@@ -1,80 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace GC.Services;
/// <summary>
/// 内容哈希(可复现的指纹算法)。
///
/// 算法固定如下,构建端与客户端必须完全一致,否则会误判为「被篡改」:
/// <code>
/// fileHash = SHA256(文件字节)
/// dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接
/// "<相对路径&gt;\0&lt;fileHash&gt;\n" )
/// </code>
/// 相对路径统一用 <c>/</c> 分隔;跳过以 <c>.</c> 开头的文件、<c>bin/</c>、<c>obj/</c>、
/// <c>*.user</c>;不包含时间戳、权限位、文件顺序等元数据 —— 同样内容必然同样哈希。
/// </summary>
public static class ContentHash
{
public static string Sha256Hex(byte[] data)
=> Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant();
public static string Sha256Hex(string text)
=> Sha256Hex(Encoding.UTF8.GetBytes(text));
public static string Sha256File(string path)
{
using var stream = File.OpenRead(path);
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
}
/// <summary>目录内所有参与分发的文件 -> { 相对路径 : sha256 }。</summary>
public static Dictionary<string, string> MapFiles(string directory)
{
var map = new Dictionary<string, string>(StringComparer.Ordinal);
if (!Directory.Exists(directory)) return map;
foreach (var file in Directory.GetFiles(directory, "*", SearchOption.AllDirectories))
{
var rel = Path.GetRelativePath(directory, file).Replace('\\', '/');
if (!Distributable(rel)) continue;
map[rel] = Sha256File(file);
}
return map;
}
/// <summary>按上述算法计算目录指纹。</summary>
public static string DirectoryHash(string directory)
=> DirectoryHash(MapFiles(directory));
public static string DirectoryHash(IReadOnlyDictionary<string, string> files)
{
var builder = new StringBuilder();
foreach (var pair in files.OrderBy(p => p.Key, StringComparer.Ordinal))
builder.Append(pair.Key).Append('\0').Append(pair.Value).Append('\n');
return Sha256Hex(Encoding.UTF8.GetBytes(builder.ToString()));
}
/// <summary>目录指纹;目录不存在时返回空串(区别于空目录的哈希)。</summary>
public static string DirectoryHashOrEmpty(string directory)
=> Directory.Exists(directory) ? DirectoryHash(directory) : "";
public static bool Distributable(string relativePath)
{
var rel = relativePath.Replace('\\', '/');
if (rel.StartsWith('.')) return false;
if (rel.Contains("/.")) return false;
if (rel.StartsWith("bin/", StringComparison.OrdinalIgnoreCase)) return false;
if (rel.StartsWith("obj/", StringComparison.OrdinalIgnoreCase)) return false;
if (rel.Contains("/bin/", StringComparison.OrdinalIgnoreCase)) return false;
if (rel.Contains("/obj/", StringComparison.OrdinalIgnoreCase)) return false;
if (rel.EndsWith(".user", StringComparison.OrdinalIgnoreCase)) return false;
return true;
}
}
-44
View File
@@ -1,44 +0,0 @@
using System;
using System.Text.Json;
namespace GC.Services;
/// <summary>
/// 把「远端拿到的清单文本」变成 <see cref="RepoVersion"/>,同时带上验签结论。
///
/// 设计上把「验签」和「允不允许用」分开:
/// · 本方法只负责**如实报告**信任状态;
/// · 允不允许安装由 <c>UpdateService</c> / <c>LauncherUpdater</c> 按策略决定。
/// 这样开发态可以「警告但继续」,发布版可以「直接拒绝」,而解析逻辑只有一份。
/// </summary>
public static class ManifestLoader
{
public static RepoVersion? Parse(string? text, out ManifestVerification verification)
{
verification = ManifestSignature.Verify(text, requireSignature: true);
if (string.IsNullOrWhiteSpace(text)) return null;
RepoVersion? version;
try
{
version = JsonSerializer.Deserialize<RepoVersion>(text!, Json.Options);
}
catch (Exception ex)
{
Console.Error.WriteLine($"版本清单解析失败: {ex.Message}");
return null;
}
if (version == null) return null;
// 平台键回填:RepoPackage 自己要能说出「我属于哪个 RID」,
// 否则下载端无法推导 dist/<系统>-<架构> 这类兜底路径。
foreach (var pair in version.Launcher.Packages)
if (pair.Value != null) pair.Value.Rid = pair.Key;
version.SignatureTrust = verification.Trust.ToString();
version.SignatureKeyId = verification.KeyId;
version.SignatureError = verification.Error;
return version;
}
}
-172
View File
@@ -1,172 +0,0 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace GC.Services;
/// <summary>清单可信度。</summary>
public enum ManifestTrust
{
/// <summary>签名有效,且密钥在受信任列表里。</summary>
Verified,
/// <summary>本机构建没有配置受信任密钥 —— 只能跳过验签(会打警告)。</summary>
Skipped,
/// <summary>清单没有签名,但客户端要求签名。</summary>
Unsigned,
/// <summary>有签名但验证失败:内容被改过 / 密钥不对 / 结构损坏。</summary>
Invalid
}
public sealed record ManifestVerification(ManifestTrust Trust, string? KeyId, string? Error)
{
public bool IsTrusted => Trust is ManifestTrust.Verified or ManifestTrust.Skipped;
public bool IsRejected => Trust is ManifestTrust.Unsigned or ManifestTrust.Invalid;
public static ManifestVerification Ok(string keyId) => new(ManifestTrust.Verified, keyId, null);
public static ManifestVerification Skip() => new(ManifestTrust.Skipped, null,
"未配置受信任公钥,已跳过验签");
public static ManifestVerification Bad(string error) => new(ManifestTrust.Invalid, null, error);
}
/// <summary>
/// 版本清单签名(ECDSA P-256 / SHA-256)。
///
/// 为什么不用 sha256 了事:sha256 只能证明「下载没坏」,不能证明「这份清单是我发的」。
/// 仓库被入侵时攻击者可以同时改清单和 sha256 —— 只有签名需要**没有放进仓库**的私钥,
/// 才能把「篡改清单」这条路堵死。
///
/// 为什么不自己实现 Ed25519:手写椭圆曲线实现出错就是静默失效。.NET 8 自带
/// ECDSA P-256,跨平台、无第三方依赖,安全性等价于工程需要。
///
/// 信任链:内置公钥 → 验证 version.json → 得到各发布包的 sha256 → 校验下载到的 zip
/// → 校验解压出的模型文件 → 加载 dll。
/// </summary>
public static class ManifestSignature
{
public const string Algorithm = "ECDSA-P256-SHA256";
private static readonly JsonSerializerOptions WriteOptions = new()
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
// ------------------------------------------------------------------ 验签
/// <summary>
/// 校验清单文本的签名。<paramref name="requireSignature"/> 为 true 时,
/// 无签名视为失败;为 false 时无签名只返回 <see cref="ManifestTrust.Unsigned"/>,
/// 由调用方决定是否放行(开发态用)。
/// </summary>
public static ManifestVerification Verify(string? text, bool requireSignature)
{
if (SignatureKeyring.Keys.Count == 0) return ManifestVerification.Skip();
if (string.IsNullOrWhiteSpace(text)) return ManifestVerification.Bad("清单内容为空");
JsonObject root;
try
{
root = JsonNode.Parse(text!) as JsonObject ?? throw new JsonException("根节点不是对象");
}
catch (Exception ex)
{
return ManifestVerification.Bad("清单不是合法 JSON: " + ex.Message);
}
if (root["signature"] is not JsonObject signature)
return requireSignature
? new ManifestVerification(ManifestTrust.Unsigned, null, "清单缺少签名")
: new ManifestVerification(ManifestTrust.Unsigned, null, "清单未签名");
var keyId = signature["keyId"]?.GetValue<string>() ?? "";
var value = signature["value"]?.GetValue<string>() ?? "";
var alg = signature["alg"]?.GetValue<string>() ?? Algorithm;
if (!string.Equals(alg, Algorithm, StringComparison.OrdinalIgnoreCase))
return new ManifestVerification(ManifestTrust.Invalid, keyId, $"不支持的签名算法: {alg}");
if (value.Length == 0)
return new ManifestVerification(ManifestTrust.Invalid, keyId, "签名为空");
var key = SignatureKeyring.Find(keyId);
if (key == null)
return new ManifestVerification(ManifestTrust.Invalid, keyId, $"未知签名密钥: {keyId}");
var payload = CanonicalJson.Normalize(text!, dropSignatureField: true);
if (payload == null)
return new ManifestVerification(ManifestTrust.Invalid, keyId, "无法规范化清单");
try
{
var sig = Convert.FromBase64String(value);
using var ecdsa = ECDsa.Create();
ecdsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(key.PublicKeyBase64), out _);
var ok = ecdsa.VerifyData(payload, sig, HashAlgorithmName.SHA256,
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
return ok
? ManifestVerification.Ok(key.KeyId)
: new ManifestVerification(ManifestTrust.Invalid, keyId, "签名与内容不符");
}
catch (Exception ex)
{
return new ManifestVerification(ManifestTrust.Invalid, keyId, "验签异常: " + ex.Message);
}
}
// ------------------------------------------------------------------ 签名
/// <summary>用私钥给清单签名,返回写入了 <c>signature</c> 字段的新清单文本。</summary>
public static string SignDocument(string text, ECDsa key, string keyId)
{
var payload = CanonicalJson.Normalize(text, dropSignatureField: true)
?? throw new InvalidOperationException("清单不是合法 JSON,无法签名");
var signature = key.SignData(payload, HashAlgorithmName.SHA256,
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
var contentHash = Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant();
var root = JsonNode.Parse(text) as JsonObject
?? throw new InvalidOperationException("清单根节点不是对象");
root["signature"] = new JsonObject
{
["alg"] = Algorithm,
["keyId"] = keyId,
["value"] = Convert.ToBase64String(signature),
["contentSha256"] = contentHash,
["signedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
};
return root.ToJsonString(WriteOptions) + "\n";
}
/// <summary>从 PEM 文件加载私钥(PKCS#8 或 SEC1 均可)。</summary>
public static ECDsa? TryLoadPrivateKey(string path)
{
try
{
if (!File.Exists(path)) return null;
var pem = File.ReadAllText(path);
if (pem.Contains("BEGIN", StringComparison.Ordinal) == false) return null;
var key = ECDsa.Create();
key.ImportFromPem(pem);
return key;
}
catch
{
return null;
}
}
/// <summary>导出公钥(SPKI / Base64),用于写入客户端受信任列表。</summary>
public static string ExportPublicKeyBase64(ECDsa key)
=> Convert.ToBase64String(key.ExportSubjectPublicKeyInfo());
/// <summary>公钥指纹,便于人工核对两边的公钥是否一致。</summary>
public static string PublicKeyFingerprint(string publicKeyBase64)
=> Convert.ToHexString(SHA256.HashData(Convert.FromBase64String(publicKeyBase64)))
.ToLowerInvariant()[..16];
}
-111
View File
@@ -1,111 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace GC.Services;
/// <summary>模型安装后落盘的完整性记录。</summary>
public sealed class ModelIntegrityFile
{
public int Schema { get; set; } = 1;
public string Id { get; set; } = "";
public string Version { get; set; } = "";
/// <summary>模型清单文件的 sha256。</summary>
public string ManifestSha256 { get; set; } = "";
/// <summary>&lt;id&gt;.model 目录的目录指纹。</summary>
public string FilesSha256 { get; set; } = "";
/// <summary>关键文件(dll / json)逐文件哈希,用于加载前快速校验。</summary>
public Dictionary<string, string> Files { get; set; } = new();
public string InstalledAt { get; set; } = "";
/// <summary>来源(远端源名 / 本地目录),便于排查。</summary>
public string Source { get; set; } = "";
}
public sealed record IntegrityResult(bool Ok, bool Present, string Message)
{
public static readonly IntegrityResult Missing =
new(true, false, "没有完整性记录(本地/开发模型),跳过校验");
}
/// <summary>
/// 模型包完整性校验:下载后复算、安装后落盘、加载前抽查。
///
/// 威胁模型:模型 dll 会被 <c>AssemblyLoadContext</c> 直接执行,等于任意代码。
/// 如果版本清单被篡改(或本地文件被替换),攻击者就能让启动器加载他的 dll。
/// 因此:
/// 1. version.json(已签名)里带 manifestSha256 / filesSha256;
/// 2. 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装;
/// 3. 安装成功后写 <c>&lt;id&gt;.integrity.json</c>;
/// 4. 每次加载 dll 前抽查 dll / json 的哈希。
/// </summary>
public static class ModelIntegrity
{
public const string FileNameSuffix = ".integrity.json";
public static string IntegrityPath(string modelDirectory, string id)
=> Path.Combine(modelDirectory, id + FileNameSuffix);
public static ModelIntegrityFile? Read(string modelDirectory, string id)
=> Json.Read<ModelIntegrityFile>(IntegrityPath(modelDirectory, id));
public static void Write(string modelDirectory, string id, ModelIntegrityFile data)
=> Json.Write(IntegrityPath(modelDirectory, id), data);
/// <summary>
/// 计算某个模型包(清单 + 数据目录)的哈希。
/// <paramref name="packageDirectory"/> 是包含 <c>&lt;id&gt;.json</c> 与
/// <c>&lt;id&gt;.model/</c> 的那一层。
/// </summary>
public static (string ManifestSha256, string FilesSha256, Dictionary<string, string> Files)
Compute(string packageDirectory, string id)
{
var manifestPath = Path.Combine(packageDirectory, id + ".json");
var dataDir = Path.Combine(packageDirectory, id + ".model");
var manifestSha = File.Exists(manifestPath) ? ContentHash.Sha256File(manifestPath) : "";
var files = ContentHash.MapFiles(dataDir);
var filesSha = ContentHash.DirectoryHash(files);
var critical = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var pair in files)
{
if (!IsCritical(pair.Key)) continue;
critical[id + ".model/" + pair.Key] = pair.Value;
}
if (manifestSha.Length > 0) critical[id + ".json"] = manifestSha;
return (manifestSha, filesSha, critical);
}
/// <summary>加载前校验:只查会被执行 / 解析的文件,保证 <c>OpenModel</c> 不被明显拖慢。</summary>
public static IntegrityResult VerifyForLoad(string packageDirectory, string id)
{
var record = Read(packageDirectory, id);
if (record == null) return IntegrityResult.Missing;
if (!string.Equals(record.Id, id, StringComparison.Ordinal))
return new IntegrityResult(false, true, $"完整性记录与模型 id 不符: {record.Id}");
foreach (var pair in record.Files)
{
var path = Path.Combine(packageDirectory, pair.Key.Replace('/', Path.DirectorySeparatorChar));
if (!File.Exists(path))
return new IntegrityResult(false, true, $"缺少文件: {pair.Key}");
var actual = ContentHash.Sha256File(path);
if (!string.Equals(actual, pair.Value, StringComparison.OrdinalIgnoreCase))
return new IntegrityResult(false, true, $"文件已被修改: {pair.Key}");
}
return new IntegrityResult(true, true, "完整性校验通过");
}
private static bool IsCritical(string relativePath)
{
var rel = relativePath.Replace('\\', '/');
return rel.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
rel.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ||
rel.EndsWith(".dylib", StringComparison.OrdinalIgnoreCase) ||
rel.EndsWith(".so", StringComparison.OrdinalIgnoreCase);
}
}
-143
View File
@@ -1,143 +0,0 @@
using System;
using System.IO;
using System.IO.Compression;
namespace GC.Services;
/// <summary>
/// 安全解压:更新包来自网络,必须当成不可信输入处理。
///
/// 拦截:
/// · zip slip(<c>../</c>、绝对路径、盘符、UNC)
/// · 符号链接 / 硬链接条目(解压后可指向系统任意文件)
/// · zip 炸弹(条目数过多、解压后总体积过大、压缩比异常)
/// 逐条校验通过后**自己写文件**,不使用 <see cref="ZipFile.ExtractToDirectory(string,string)"/>,
/// 避免框架在写入阶段才发现问题、留下半成品。
/// </summary>
public static class SafeArchive
{
/// <summary>单个包最多条目数。</summary>
public const int MaxEntries = 20000;
/// <summary>解压后总体积上限(2 GiB)。</summary>
public const long MaxUncompressedBytes = 2L * 1024 * 1024 * 1024;
/// <summary>单个条目解压上限(1 GiB)。</summary>
public const long MaxSingleEntryBytes = 1L * 1024 * 1024 * 1024;
/// <summary>压缩比上限:超过视为 zip 炸弹。</summary>
public const int MaxCompressionRatio = 200;
public sealed record Inspection(int Entries, long UncompressedBytes, long CompressedBytes)
{
public double Ratio => CompressedBytes <= 0 ? 0 : (double)UncompressedBytes / CompressedBytes;
}
/// <summary>只检查不解压:条目数、体积、路径、链接。发现问题抛异常。</summary>
public static Inspection Inspect(string zipPath)
{
using var archive = ZipFile.OpenRead(zipPath);
long total = 0;
var count = 0;
foreach (var entry in archive.Entries)
{
count++;
if (count > MaxEntries)
throw new InvalidOperationException($"压缩包条目过多(>{MaxEntries}),疑似恶意包");
ValidateName(entry.FullName);
AssertNotLink(entry);
if (entry.Length > MaxSingleEntryBytes)
throw new InvalidOperationException($"条目过大: {entry.FullName}");
total += entry.Length;
if (total > MaxUncompressedBytes)
throw new InvalidOperationException("解压后体积超出上限,疑似 zip 炸弹");
}
var compressed = new FileInfo(zipPath).Length;
var inspection = new Inspection(count, total, compressed);
if (compressed > 0 && inspection.Ratio > MaxCompressionRatio && total > 64L * 1024 * 1024)
throw new InvalidOperationException($"压缩比异常({inspection.Ratio:0.#}:1),疑似 zip 炸弹");
return inspection;
}
public static void ExtractToDirectory(string zipPath, string destination)
{
Inspect(zipPath);
Directory.CreateDirectory(destination);
var destFull = Path.GetFullPath(destination)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
using var archive = ZipFile.OpenRead(zipPath);
foreach (var entry in archive.Entries)
{
var name = entry.FullName.Replace('\\', '/');
if (name.EndsWith("/", StringComparison.Ordinal))
{
Directory.CreateDirectory(Path.GetFullPath(Path.Combine(destFull, name)));
continue;
}
var target = Path.GetFullPath(Path.Combine(destFull, name));
if (!target.StartsWith(destFull, StringComparison.Ordinal))
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
var dir = Path.GetDirectoryName(target);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
using (var source = entry.Open())
using (var output = new FileStream(target, FileMode.Create, FileAccess.Write,
FileShare.None, 81920, FileOptions.None))
{
source.CopyTo(output);
}
TryApplyUnixMode(entry, target);
}
}
/// <summary>校验条目名,拒绝一切能逃出目标目录的写法。</summary>
public static void ValidateName(string fullName)
{
var name = fullName.Replace('\\', '/');
if (name.Length == 0) throw new InvalidOperationException("压缩包含空文件名条目");
if (name.StartsWith('/')) throw new InvalidOperationException($"压缩包含绝对路径: {fullName}");
if (name.StartsWith("//")) throw new InvalidOperationException($"压缩包含 UNC 路径: {fullName}");
if (name.Length >= 2 && name[1] == ':')
throw new InvalidOperationException($"压缩包含盘符路径: {fullName}");
foreach (var segment in name.Split('/'))
{
if (segment == "..")
throw new InvalidOperationException($"压缩包含父目录穿越: {fullName}");
}
if (name.Contains('\0'))
throw new InvalidOperationException($"压缩包含非法字符: {fullName}");
}
/// <summary>Unix 模式下 S_IFLNK = 0xA000,符号链接条目一律拒绝。</summary>
private static void AssertNotLink(ZipArchiveEntry entry)
{
var mode = (entry.ExternalAttributes >> 16) & 0xF000;
if (mode == 0xA000)
throw new InvalidOperationException($"压缩包含符号链接条目: {entry.FullName}");
}
private static void TryApplyUnixMode(ZipArchiveEntry entry, string target)
{
if (OperatingSystem.IsWindows()) return;
try
{
var mode = (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1FF);
if (mode == 0) return;
File.SetUnixFileMode(target, mode);
}
catch { /* 权限位设置失败不影响文件内容 */ }
}
}
-95
View File
@@ -1,95 +0,0 @@
using System;
namespace GC.Services;
/// <summary>
/// 启动器 ↔ GC-SAVEDOG 的握手协议(都在 <c>.GC/update/</c> 下,全部相对路径)。
///
/// 流程:
/// <code>
/// launcher 下载并校验更新包
/// -> 解压到 update/payload/
/// -> 写 apply-request.json + 已验签的 version.json 副本
/// -> 启动 GC-SAVEDOG apply --wait-pid &lt;自己&gt;
/// -> 自己退出
///
/// GC-SAVEDOG
/// -> 等父进程退出
/// -> 重验签名 + 包 sha256 + 解压安全性
/// -> 把 payload 移到安装目录(绝不覆盖已有版本)
/// -> 启动新版,等 update/health.json
/// -> 健康:删同平台旧版本;不健康:删新版、重启旧版
/// -> 写 state.json(applied / rolledback / failed)
/// </code>
/// </summary>
public static class SavedogFiles
{
public const string ApplyRequest = "apply-request.json";
public const string State = "state.json";
public const string Log = "savedog.log";
public const string Health = StartupHealth.FileName;
public const string LastGood = "last-good.json";
/// <summary>SAVEDOG 可执行文件名(各平台一致,Windows 带 .exe)。</summary>
public static string ExecutableName =>
OperatingSystem.IsWindows() ? "GC-SAVEDOG.exe" : "GC-SAVEDOG";
}
/// <summary>启动器写入的更新申请。</summary>
public sealed class SavedogRequest
{
public int Schema { get; set; } = 1;
/// <summary>新版本号,如 1.0.8。</summary>
public string Version { get; set; } = "";
public string Rid { get; set; } = "";
/// <summary>文件名里的平台标签,如 mac-arm64。</summary>
public string PlatformLabel { get; set; } = "";
/// <summary>payload 里的新版本包名(GC-1.0.8-mac-arm64.app / .exe)。</summary>
public string PackageName { get; set; } = "";
/// <summary>payload 目录(相对 update 目录)。</summary>
public string PayloadDir { get; set; } = "payload";
/// <summary>已验签清单的副本(相对 update 目录),用于二次验签。</summary>
public string ManifestPath { get; set; } = "version.json";
/// <summary>更新包 zip 路径(相对 update 目录),SAVEDOG 自己解压,不信任预解压目录。</summary>
public string PackageZip { get; set; } = "package.zip";
/// <summary>更新包 sha256(来自已验签清单)。</summary>
public string? PackageSha256 { get; set; }
public long PackageSize { get; set; }
/// <summary>是否强制要求清单签名。</summary>
public bool RequireSignature { get; set; } = true;
/// <summary>安装目录(相对 update 目录),由启动器按实际路径算出。</summary>
public string InstallRelative { get; set; } = "../..";
public string CreatedAt { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
/// <summary>SAVEDOG 的执行结果,写入 state.json 供界面显示。</summary>
public sealed class SavedogState
{
public string Status { get; set; } = "unknown"; // applied | rolledback | failed | refused
public string Version { get; set; } = "";
public string? PreviousVersion { get; set; }
public string PackageName { get; set; } = "";
public string Message { get; set; } = "";
public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
public bool Verified { get; set; }
}
/// <summary>上次成功启动的版本信息,回滚时用。</summary>
public sealed class LastGoodVersion
{
public string Version { get; set; } = "";
public string PackageName { get; set; } = "";
public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
-79
View File
@@ -1,79 +0,0 @@
using System;
using System.Collections.Generic;
namespace GC.Services;
/// <summary>
/// 受信任的签名公钥。
///
/// 公钥是公开的,写在源码里没有问题;**私钥永远不进仓库**
/// (放在仓库根 <c>.signing/</c>,已在 .gitignore 中)。
///
/// 轮换密钥:用 <c>GC-SAVEDOG keygen</c> 生成新的一对,把新公钥追加到这里,
/// 旧公钥保留一个版本周期,避免老客户端直接失效。
/// 也可用环境变量临时注入(测试 / 私有构建):
/// <c>GC_TRUSTED_KEYS="id1:base64;id2:base64"</c>
/// </summary>
public static class SignatureKeyring
{
public sealed record KeyEntry(string KeyId, string PublicKeyBase64, string? Note = null);
private static readonly List<KeyEntry> KeysInternal = new()
{
// 生产密钥(2026-11 生成)。指纹 b41b1dd6259ea9ed
new KeyEntry(
"gc-2026-11",
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" +
"PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
"GC 主发布密钥")
};
static SignatureKeyring() => LoadFromEnvironment();
public static IReadOnlyList<KeyEntry> Keys => KeysInternal;
/// <summary>是否配置了受信任密钥(配置了就必须验签)。</summary>
public static bool Enforced => KeysInternal.Count > 0;
public static KeyEntry? Find(string? keyId)
{
if (KeysInternal.Count == 0) return null;
foreach (var key in KeysInternal)
if (string.Equals(key.KeyId, keyId, StringComparison.Ordinal))
return key;
// 未写 keyId 且只有一个密钥时容忍(早期构建产物)
if (string.IsNullOrWhiteSpace(keyId) && KeysInternal.Count == 1) return KeysInternal[0];
return null;
}
/// <summary>测试 / 私有分发用:追加一个受信任公钥。</summary>
public static void Add(KeyEntry key)
{
if (string.IsNullOrWhiteSpace(key.KeyId) || string.IsNullOrWhiteSpace(key.PublicKeyBase64)) return;
if (Find(key.KeyId) != null) return;
KeysInternal.Add(key);
}
/// <summary>测试用:替换整个密钥环。</summary>
public static void ReplaceAll(IEnumerable<KeyEntry> keys)
{
KeysInternal.Clear();
foreach (var key in keys) KeysInternal.Add(key);
}
private static void LoadFromEnvironment()
{
var raw = Environment.GetEnvironmentVariable("GC_TRUSTED_KEYS");
if (string.IsNullOrWhiteSpace(raw)) return;
foreach (var part in raw!.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
var idx = part.IndexOf(':');
if (idx <= 0 || idx >= part.Length - 1) continue;
var keyId = part[..idx].Trim();
var value = part[(idx + 1)..].Trim();
if (keyId.Length == 0 || value.Length == 0) continue;
if (Find(keyId) != null) continue;
KeysInternal.Add(new KeyEntry(keyId, value, "来自 GC_TRUSTED_KEYS"));
}
}
}
-58
View File
@@ -1,58 +0,0 @@
using System;
using System.IO;
namespace GC.Services;
/// <summary>
/// 启动成功的健康标记。
///
/// 新版启动器启动后写这个文件;GC-SAVEDOG 在替换完程序后会等它出现,
/// 等不到就回滚到旧版本 —— 这样「新版本一启动就崩」不会把用户卡死。
/// </summary>
public static class StartupHealth
{
public const string FileName = "health.json";
public static string PathFor(string updateRoot) => Path.Combine(updateRoot, FileName);
/// <summary>主窗口显示后调用:证明本次启动真的跑起来了。</summary>
public static void MarkHealthy(string updateRoot, string version)
{
try
{
Directory.CreateDirectory(updateRoot);
Json.Write(PathFor(updateRoot), new HealthRecord
{
Version = version,
Pid = Environment.ProcessId,
At = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
Ok = true
});
}
catch (Exception ex)
{
Console.Error.WriteLine($"写入健康标记失败: {ex.Message}");
}
}
public static HealthRecord? Read(string updateRoot)
=> Json.Read<HealthRecord>(PathFor(updateRoot));
public static void Clear(string updateRoot)
{
try
{
var path = PathFor(updateRoot);
if (File.Exists(path)) File.Delete(path);
}
catch { }
}
public sealed class HealthRecord
{
public string Version { get; set; } = "";
public int Pid { get; set; }
public string At { get; set; } = "";
public bool Ok { get; set; }
}
}
-331
View File
@@ -1,331 +0,0 @@
using System;
using System.Threading.Tasks;
using System.IO;
namespace GC.Services;
/// <summary>
/// 运行目录约定(可执行文件旁边,不内置任何模型):
/// <code>
/// &lt;安装目录&gt;/
/// GC(.exe | .app/...)
/// .GC/
/// settings.json 设置与已安装版本记录
/// model/ 模型(启动时下载)
/// cache/ 下载缓存 / 原子替换暂存
/// update/ 待下次启动应用的启动器更新包
/// </code>
/// 开发态同样使用仓库根 .GC/model,并自动同步仓库 model/ 的可分发部分。
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
/// </summary>
public sealed class AppPaths
{
private Task _developmentModelsSync = Task.CompletedTask;
/// <summary>安装目录(开发态为仓库根)。</summary>
public string AppRoot { get; private init; } = "";
/// <summary>可执行文件真正所在目录:启动器自更新时要覆盖这里。</summary>
public string InstallDirectory { get; private init; } = "";
/// <summary>.GC 目录。</summary>
public string HomeRoot { get; private init; } = "";
/// <summary>模型库。</summary>
public string ModelRoot { get; private init; } = "";
/// <summary>兼容旧代码:数据目录即 .GC。</summary>
public string DataRoot => HomeRoot;
public string CacheRoot => Path.Combine(HomeRoot, "cache");
public string UpdateRoot => Path.Combine(HomeRoot, "update");
/// <summary>用户配置目录(与可重建的缓存分开,删 cache 不会丢设置)。</summary>
public string ConfigRoot => Path.Combine(HomeRoot, "config");
public string SettingsFile => Path.Combine(ConfigRoot, "settings.json");
public bool IsDevelopment { get; private init; }
public bool IsPortableModelRoot { get; private init; }
public static AppPaths Discover()
{
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
// 判定「当前目录」:程序实际所在的位置。
// · 发布版:可执行文件所在目录(单文件时为 exe 旁,否则为 apphost 目录)
// · 源码版:仓库根(含 GC.sln 的目录)
//
// 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主,
// 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。
var explicitHome = Environment.GetEnvironmentVariable("EMS_HOME");
var repoRoot = explicitHome;
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
repoRoot = FindRepoRoot(baseDir);
var isDev = !string.IsNullOrEmpty(repoRoot) &&
File.Exists(Path.Combine(repoRoot!, "GC.sln"));
string installDir;
if (isDev)
{
// 源码版:安装目录 = 仓库根
installDir = repoRoot!;
}
else if (!string.IsNullOrWhiteSpace(explicitHome) && Directory.Exists(explicitHome))
{
installDir = explicitHome;
}
else
{
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
//
// <运行目录>/ ← 要的就是这一层
// GC-1.0.3-mac-arm64.app/ ← 程序包
// .GC/ ← 用户数据放这里
//
// 若直接返回 Contents/MacOS,.GC 会被塞进 app 包内部,
// 用户看不到,重装/替换时也会跟着包一起被删。
installDir = baseDir;
try
{
var exe = Environment.ProcessPath;
if (!string.IsNullOrWhiteSpace(exe))
{
var exeName = Path.GetFileNameWithoutExtension(exe);
var isDotnetHost = string.Equals(exeName, "dotnet", StringComparison.OrdinalIgnoreCase);
var exeDir = Path.GetDirectoryName(exe);
if (!isDotnetHost && !string.IsNullOrWhiteSpace(exeDir) && Directory.Exists(exeDir))
{
// 从可执行文件所在目录向上找:如果处在 Xxx.app/Contents/MacOS,
// 则运行目录是 Xxx.app 的**父目录**。
installDir = ResolveRunDirectory(exeDir!);
}
}
}
catch { /* 取不到就沿用 BaseDirectory */ }
}
// 运行目录 = 程序所在目录。.GC 永远紧挨着程序,不往系统目录放。
var appRoot = installDir;
// 只读安装位置(如 Program Files / /Applications)才回退到用户数据目录;
// 正常可写时一律用当前目录下的 .GC。
var explicitData = Environment.GetEnvironmentVariable("EMS_DATA");
string home;
if (!string.IsNullOrWhiteSpace(explicitData))
{
home = explicitData!;
}
else
{
var portableHome = Path.Combine(appRoot, ".GC");
home = CanWrite(portableHome)
? portableHome
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"GC", ".GC");
}
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
? envModels!
: Path.Combine(home, "model");
return new AppPaths
{
AppRoot = appRoot,
InstallDirectory = installDir,
HomeRoot = home,
ModelRoot = modelRoot,
IsDevelopment = isDev,
IsPortableModelRoot = string.IsNullOrWhiteSpace(envModels)
};
}
private static bool CanWrite(string dir)
{
try
{
Directory.CreateDirectory(dir);
var probe = Path.Combine(dir, ".write-test");
File.WriteAllText(probe, "ok");
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 从程序所在位置向上找仓库根(含 GC.sln 的目录)。
///
/// 关键:程序若位于 .app 包内(或 dist/ 等发布产物目录),**不算开发态**。
/// 否则把 .app 放在仓库的 dist/ 下运行时,会一路向上命中仓库根的 .sln,
/// 被误判为开发态,导致 .GC 跑到仓库根而不是程序旁边。
/// </summary>
private static string? FindRepoRoot(string start)
{
// 在 .app 包内(.../Xxx.app/Contents/MacOS)直接视为发布版
if (IsInsideAppBundle(start)) return null;
var dir = new DirectoryInfo(start);
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
{
// 碰到发布产物目录也停下:dist/ 输出、或带 .GC 的运行目录都不是源码树
var name = dir.Name;
if (string.Equals(name, "dist", StringComparison.OrdinalIgnoreCase)) return null;
if (File.Exists(Path.Combine(dir.FullName, "GC.sln")))
{
// 再确认不是从「发布输出目录」里往上找来的
if (IsUnderPublishOutput(start, dir.FullName)) return null;
return dir.FullName;
}
}
return null;
}
/// <summary>
/// 求「运行目录」:程序包所在的父目录。
/// · 若路径处在 Xxx.app/Contents/MacOS 里,返回 Xxx.app 的父目录
/// · 其它情况(Windows exe 目录)原样返回
/// </summary>
private static string ResolveRunDirectory(string exeDir)
{
var dir = new DirectoryInfo(exeDir);
// 走到 app 包根:.../Xxx.app
string? appRoot = null;
for (var cur = dir; cur != null; cur = cur.Parent)
{
if (cur.Name.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
{
appRoot = cur.FullName;
break;
}
if (cur.Parent == null) break;
}
if (appRoot != null)
{
// 返回 .app 的父目录(即用户双击时看到的那一层)
var parent = Path.GetDirectoryName(appRoot);
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
return parent!;
return appRoot;
}
return exeDir;
}
/// <summary>路径是否位于某个 .app 包内部。</summary>
private static bool IsInsideAppBundle(string path)
{
var p = path.Replace('\\', '/');
var idx = p.IndexOf(".app/", StringComparison.OrdinalIgnoreCase);
return idx >= 0;
}
/// <summary>
/// 从 start 到 repoRoot 之间是否经过了发布输出目录(dist / bin / publish)。
/// 经过则说明程序是打包产物,而非源码树里直接运行的进程。
/// </summary>
private static bool IsUnderPublishOutput(string start, string repoRoot)
{
try
{
var rel = Path.GetRelativePath(repoRoot, start).Replace('\\', '/');
foreach (var seg in rel.Split('/', StringSplitOptions.RemoveEmptyEntries))
{
if (string.Equals(seg, "dist", StringComparison.OrdinalIgnoreCase) ||
string.Equals(seg, "publish", StringComparison.OrdinalIgnoreCase) ||
string.Equals(seg, "Release", StringComparison.OrdinalIgnoreCase))
return true;
}
}
catch { }
return false;
}
public void EnsureCreated()
{
Directory.CreateDirectory(HomeRoot);
Directory.CreateDirectory(ConfigRoot);
Directory.CreateDirectory(CacheRoot);
Directory.CreateDirectory(ModelRoot);
Directory.CreateDirectory(UpdateRoot);
MigrateLegacySettings();
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)。
// 放到后台线程:这一步要复制 coastline.json 等大文件,同步做会拖慢启动。
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
{
var modelRoot = ModelRoot;
var source = Path.Combine(AppRoot, "model");
if (Directory.Exists(source))
_developmentModelsSync = Task.Run(() => SyncDevelopmentModels(modelRoot, source));
}
}
public void WaitForDevelopmentModels() => _developmentModelsSync.GetAwaiter().GetResult();
/// <summary>
/// 老版本把设置放在 .GC/settings.json。现在设置归到 .GC/config/,
/// 与 cache/ 分开(清缓存不会连带清掉语言、内存预算、离线源等配置)。
/// 迁移只做一次:新位置不存在时才搬旧的。
/// </summary>
private void MigrateLegacySettings()
{
try
{
var legacy = Path.Combine(HomeRoot, "settings.json");
if (!File.Exists(legacy) || File.Exists(SettingsFile)) return;
Directory.CreateDirectory(ConfigRoot);
File.Move(legacy, SettingsFile);
Console.WriteLine("[paths] 设置已迁移到 .GC/config/settings.json");
}
catch (Exception ex)
{
Console.Error.WriteLine($"迁移旧设置失败: {ex.Message}");
}
}
private static void SyncDevelopmentModels(string modelRoot, string source)
{
try
{
if (!Directory.Exists(source)) return;
foreach (var dir in Directory.GetDirectories(source))
{
var id = Path.GetFileName(dir);
if (id.StartsWith('_')) continue;
var manifest = Path.Combine(dir, id + ".json");
var data = Path.Combine(dir, id + ".model");
if (!File.Exists(manifest) || !Directory.Exists(data)) continue;
var dest = Path.Combine(modelRoot, id);
Directory.CreateDirectory(dest);
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
CopyTree(data, Path.Combine(dest, id + ".model"));
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"同步开发模型失败: {ex.Message}");
}
}
private static void CopyTree(string src, string dst)
{
Directory.CreateDirectory(dst);
foreach (var file in Directory.GetFiles(src, "*", SearchOption.AllDirectories))
{
if (Path.GetFileName(file).StartsWith('.')) continue;
var to = Path.Combine(dst, Path.GetRelativePath(src, file));
var parent = Path.GetDirectoryName(to);
if (!string.IsNullOrEmpty(parent)) Directory.CreateDirectory(parent);
File.Copy(file, to, true);
}
}
}
-106
View File
@@ -1,106 +0,0 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>GitCode 仓库的一位贡献者。</summary>
public sealed class Contributor
{
public string Name { get; set; } = "";
public string? Email { get; set; }
/// <summary>提交次数(API 里的 contributions)。</summary>
public int Contributions { get; set; }
/// <summary>
/// 登录名 -> 展示名。GitCode 的 contributors 接口只返回账号登录名,
/// 不返回真实姓名,这里做一层映射,让关于页显示作者想展示的名字。
/// </summary>
private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase)
{
["Morris_1"] = "Morris"
};
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
public string? AvatarUrl =>
string.IsNullOrWhiteSpace(Email)
? null
: $"https://cdn-img.gitcode.com/avatar/{Convert.ToHexString(
System.Security.Cryptography.MD5.HashData(
System.Text.Encoding.UTF8.GetBytes(Email!.Trim().ToLowerInvariant())))
.ToLowerInvariant()}";
public string DisplayName
{
get
{
if (string.IsNullOrWhiteSpace(Name)) return "匿名";
return DisplayNames.TryGetValue(Name.Trim(), out var mapped) ? mapped : Name;
}
}
}
/// <summary>
/// 读取 GitCode 仓库的贡献者列表(用于「关于」页面展示开发者)。
/// 失败时静默返回空列表,不影响关于页其它内容。
/// </summary>
public static class ContributorsService
{
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return c;
}
/// <summary>默认仓库的 contributors 接口地址。</summary>
public static string BuildUrl(string repository)
{
var raw = string.IsNullOrWhiteSpace(repository)
? SourcePreset.GitCode.HomeUrl : repository.Trim();
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? parts[1][..^4] : parts[1];
return $"https://api.gitcode.com/api/v5/repos/{parts[0]}/{repo}/contributors";
}
public static async Task<List<Contributor>> FetchAsync(string repository, CancellationToken ct = default)
{
var url = BuildUrl(repository);
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
var text = await Http.GetStringAsync(url, timeout.Token);
var trimmed = text.TrimStart();
if (trimmed.Length == 0 || trimmed[0] != '[') return new List<Contributor>();
var list = JsonSerializer.Deserialize<List<Contributor>>(text, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}) ?? new List<Contributor>();
// 按提交数从多到少,贡献最多的排最前
list.Sort((a, b) => b.Contributions.CompareTo(a.Contributions));
return list;
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取贡献者失败: {ex.Message}");
return new List<Contributor>();
}
}
}
-157
View File
@@ -1,157 +0,0 @@
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using GC.Models;
namespace GC.Services;
public enum DownloadState
{
Queued,
Running,
Completed,
Failed,
Canceled
}
public interface IDownloadJob : INotifyPropertyChanged
{
RemoteModel Model { get; }
string Id { get; }
string Name { get; }
string Version { get; }
CancellationTokenSource Cts { get; }
DownloadState State { get; set; }
double Progress { get; set; }
string StatusText { get; }
string DetailText { get; }
string? Error { get; set; }
bool IsActive { get; }
bool CanRetry { get; }
bool IsDone { get; }
void RefreshText();
}
public interface IDownloadCenter
{
ObservableCollection<IDownloadJob> Jobs { get; }
event Action? Installed;
IDownloadJob Enqueue(RemoteModel model);
void Cancel(IDownloadJob job);
void Retry(IDownloadJob job);
void Remove(IDownloadJob job);
void ClearFinished();
int ActiveCount { get; }
}
public interface IModelSourceClient
{
Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct);
}
public interface IUpdateService
{
IModelRemote Remote { get; }
void UseRemote(IModelRemote remote);
Task<UpdateResult> RunAsync(bool force, IProgress<UpdateProgress>? progress, CancellationToken ct = default);
}
public interface ISourceSelector
{
SourcePreset? Current { get; }
System.Collections.Generic.IReadOnlyDictionary<string, long> LastLatency { get; }
Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default);
}
public interface ILauncherUpdateService
{
Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default);
Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default);
bool ScheduleApply(AppPaths paths, string packageName);
bool TryApplyPending(AppPaths paths);
}
public enum UpdateRunState { UpToDate, Ready, Failed }
public sealed class UpdateProgressInfo
{
public double Value { get; init; }
public string Stage { get; init; } = "";
}
public sealed class UpdateRunResult
{
public UpdateRunState State { get; init; }
public string Version { get; init; } = "";
public string Message { get; init; } = "";
public string? PackageName { get; init; }
public string? NewAppPath { get; init; }
}
public interface IDownloadModule
{
IDownloadCenter Downloads { get; }
IModelSourceClient Sources { get; }
IUpdateService Updates { get; }
ISourceSelector Selector { get; }
ILauncherUpdateService LauncherUpdates { get; }
IModelRemote CreateRemote(SourcePreset preset);
}
public interface IDownloadModuleFactory
{
IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models);
bool TryApplyPending(AppPaths paths);
}
public static class DownloadModuleHost
{
public static IDownloadModuleFactory? Factory { get; set; }
}
public static class LauncherRuntimeInfo
{
private static string? _versionOverride;
public static string CurrentLauncherVersion
{
get
{
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
var assembly = typeof(AppServices).Assembly;
var version = assembly.GetName().Version;
if (version == null || (version.Major == 0 && version.Minor == 0 && version.Build == 0))
{
var info = System.Reflection.CustomAttributeExtensions.GetCustomAttribute<
System.Reflection.AssemblyInformationalVersionAttribute>(assembly)?.InformationalVersion;
if (!string.IsNullOrWhiteSpace(info) && Version.TryParse(info.Split('+')[0].Trim(), out var parsed))
version = parsed;
}
return version == null
? "0.0.0"
: $"{Math.Max(0, version.Major)}.{Math.Max(0, version.Minor)}.{Math.Max(0, version.Build)}";
}
}
public static string CurrentRid
{
get
{
var architecture = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch
{
System.Runtime.InteropServices.Architecture.Arm64 => "arm64",
System.Runtime.InteropServices.Architecture.X86 => "x86",
_ => "x64"
};
if (OperatingSystem.IsWindows()) return "win-" + architecture;
if (OperatingSystem.IsMacOS()) return "osx-" + architecture;
if (OperatingSystem.IsLinux()) return "linux-" + architecture;
return System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier;
}
}
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
}
-64
View File
@@ -1,64 +0,0 @@
using System;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace GC.Services;
public static class Json
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
/// <summary>
/// 源生成类型信息的提供者(可选)。
///
/// 启动器本身不做裁剪,走默认的反射序列化即可;GC-SAVEDOG 会被 PublishTrimmed
/// 裁掉无参构造,反射序列化在运行时直接抛 <c>NotSupportedException</c>。
/// 因此守护进程在启动时把本钩子指向 <c>JsonSerializerContext</c>,
/// 让所有读写都走编译期生成的 <see cref="JsonTypeInfo{T}"/>。
/// 这样「安全模块只有一份实现」的前提没有被破坏,只是换了元数据来源。
/// </summary>
public static Func<Type, JsonTypeInfo?>? TypeInfoProvider { get; set; }
public static T? Read<T>(string path)
{
if (!System.IO.File.Exists(path)) return default;
return Deserialize<T>(System.IO.File.ReadAllText(path));
}
public static void Write<T>(string path, T value)
{
var dir = System.IO.Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir);
var tmp = path + ".tmp";
System.IO.File.WriteAllText(tmp, Serialize(value));
System.IO.File.Move(tmp, path, true);
}
public static T? Deserialize<T>(string text)
{
if (string.IsNullOrWhiteSpace(text)) return default;
var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo<T>;
return info != null
? JsonSerializer.Deserialize(text, info)
: JsonSerializer.Deserialize<T>(text, Options);
}
public static string Serialize<T>(T value)
{
var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo<T>;
return info != null
? JsonSerializer.Serialize(value, info)
: JsonSerializer.Serialize(value, Options);
}
}
-124
View File
@@ -1,124 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using GC.Views;
namespace GC.Services;
/// <summary>
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
/// 1. 关闭主窗口与所有模型窗口;
/// 2. 弹出圆角进度窗;
/// 3. 下载最新版到当前目录(与旧版并列);
/// 4. 安排替换脚本、关进度窗、退出进程。
/// 失败时恢复主窗口,继续使用当前版本。
/// </summary>
public static class LauncherUpdateFlow
{
private static bool _running;
public static bool IsRunning => _running;
public static async Task RunAsync(AppServices services, string title)
{
if (_running) return;
_running = true;
var desktop = Application.Current?.ApplicationLifetime
as IClassicDesktopStyleApplicationLifetime;
var mainWindow = desktop?.MainWindow;
var progressWindow = new UpdaterWindow(title);
try
{
// 1. 关闭所有窗口
if (desktop != null) desktop.MainWindow = null;
try { mainWindow?.Close(); } catch { }
foreach (var w in OpenWindows().ToList())
{
try { w.Close(); } catch { }
}
// 2. 进度窗
progressWindow.Show();
progressWindow.Report(0, "准备更新…");
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
// 3. 下载
var progress = new Progress<UpdateProgressInfo>(p =>
progressWindow.Report(p.Value, p.Stage));
var result = await services.LauncherUpdates.DownloadAsync(
services.Paths, services.Updates.Remote, progress);
if (result.State == UpdateRunState.Failed)
{
progressWindow.Report(0, "更新失败", result.Message);
await Task.Delay(2200);
_running = false;
progressWindow.Close();
RestoreMainWindow(desktop, mainWindow);
return;
}
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
// 4. 安排替换(下次启动生效 / 脚本接管重启)
var scheduled = services.LauncherUpdates.ScheduleApply(
services.Paths, result.PackageName ?? "");
if (!scheduled)
{
progressWindow.Report(0, "无法安排更新", "请检查安装目录是否可写");
await Task.Delay(2200);
_running = false;
progressWindow.Close();
RestoreMainWindow(desktop, mainWindow);
return;
}
await Task.Delay(400);
progressWindow.Close();
desktop?.Shutdown();
}
catch (Exception ex)
{
Console.Error.WriteLine($"更新流程异常: {ex}");
_running = false;
try { progressWindow.Close(); } catch { }
RestoreMainWindow(desktop, mainWindow);
}
}
private static void RestoreMainWindow(
IClassicDesktopStyleApplicationLifetime? desktop, Window? mainWindow)
{
if (desktop == null || mainWindow == null) return;
try
{
desktop.MainWindow = mainWindow;
mainWindow.Show();
mainWindow.Activate();
}
catch (Exception ex)
{
Console.Error.WriteLine($"恢复主窗口失败: {ex.Message}");
}
}
private static IEnumerable<Window> OpenWindows()
{
if (Application.Current?.ApplicationLifetime
is not IClassicDesktopStyleApplicationLifetime d)
yield break;
foreach (var w in d.Windows)
{
if (w is UpdaterWindow) continue;
yield return w;
}
}
}
-87
View File
@@ -1,87 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GC.Models;
namespace GC.Services;
public sealed class SettingsService
{
private readonly AppPaths _paths;
public AppSettings Current { get; private set; } = new();
public event Action? Changed;
public SettingsService(AppPaths paths) => _paths = paths;
public void Load()
{
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
if (Current.UpdateRepository.Contains("gitcode.com/2509_92447106/GC", StringComparison.OrdinalIgnoreCase))
{
Current.UpdateRepository = Current.UpdateRepository.Replace(
"2509_92447106", "Morris_1", StringComparison.OrdinalIgnoreCase);
Save();
}
SeedDefaultSource();
if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
}
/// <summary>
/// 只允许两个内置源:Xhmcl 与 GitCode(同一份仓库的两个镜像)。
/// 不再支持用户自定义源 —— 每次加载都把 Sources 规整成这两条,
/// 老配置里的自定义源会被清理掉。
/// </summary>
public const string DefaultSourceId = "gitcode";
public const string DefaultSourceUrl = "https://gitcode.com/Morris_1/GC";
private void SeedDefaultSource()
{
var rebuilt = new List<ModelSource>();
foreach (var preset in SourcePreset.All)
{
// 保留用户对「启用/停用」的选择,其余字段以内置定义为准
var old = Current.Sources.FirstOrDefault(s =>
SourcePreset.Detect(s.Url).Id == preset.Id);
rebuilt.Add(new ModelSource
{
Id = preset.Id,
Name = preset.Name,
Url = preset.HomeUrl,
Enabled = old?.Enabled ?? true,
BuiltIn = true
});
}
var changed = Current.Sources.Count != rebuilt.Count ||
Current.Sources.Any(s => !s.BuiltIn);
Current.Sources = rebuilt;
if (changed) Save();
}
public void Save()
{
try
{
Json.Write(_paths.SettingsFile, Current);
}
catch (Exception ex)
{
Console.Error.WriteLine($"保存设置失败: {ex.Message}");
}
}
public void Apply(Action<AppSettings> mutate)
{
mutate(Current);
Save();
Changed?.Invoke();
}
public void Notify()
{
Save();
Changed?.Invoke();
}
}
-49
View File
@@ -1,49 +0,0 @@
using System;
using System.Diagnostics;
using System.IO;
namespace GC.Services;
public static class Shell
{
public static void OpenFolder(string path)
{
if (string.IsNullOrWhiteSpace(path)) return;
try
{
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
StartWith(path);
}
catch (Exception ex)
{
Console.Error.WriteLine($"打开目录失败: {ex.Message}");
}
}
/// <summary>用系统默认浏览器打开一个 URL。</summary>
public static void OpenUrl(string url)
{
if (string.IsNullOrWhiteSpace(url)) return;
try
{
StartWith(url);
}
catch (Exception ex)
{
Console.Error.WriteLine($"打开链接失败: {ex.Message}");
}
}
private static void StartWith(string argument)
{
var info = new ProcessStartInfo
{
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
: OperatingSystem.IsMacOS() ? "open"
: "xdg-open",
UseShellExecute = false
};
info.ArgumentList.Add(argument);
Process.Start(info);
}
}
-79
View File
@@ -1,79 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace GC.Services;
/// <summary>
/// 内置下载源。只允许这两个,不再支持用户自定义源。
///
/// 两个源的内容是同一份仓库(同一个 version.json、同一批模型),
/// 区别只是**托管在哪台服务器**上;启动时探测两者延迟,取快的那个下载。
/// </summary>
public sealed class SourcePreset
{
public string Id { get; init; } = "";
public string Name { get; init; } = "";
/// <summary>仓库主页(用于展示与打开)。</summary>
public string HomeUrl { get; init; } = "";
/// <summary>API 根地址(Gitea: /api/v1,GitCode: /api/v5)。</summary>
public string ApiBase { get; init; } = "";
/// <summary>原始文件下载前缀(用于拼 raw 地址)。</summary>
public string RawBase { get; init; } = "";
/// <summary>后端类型:gitea / gitcode。</summary>
public string Kind { get; init; } = "";
public string Owner { get; init; } = "";
public string Repo { get; init; } = "";
public string Branch { get; init; } = "main";
/// <summary>raw 地址风格:gitea 用 raw/branch/{b},gitcode 用 raw/{b}。</summary>
public string RawStyle { get; init; } = "branch";
public string Repository => HomeUrl;
/// <summary>拼 raw 文件下载地址(两个平台的 URL 结构不同)。</summary>
public string RawUrl(string path) => RawStyle == "plain"
? $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}"
: $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}";
public static readonly SourcePreset Xhmcl = new()
{
Id = "xhmcl",
Name = "Xhmcl",
HomeUrl = "https://git.xhmcl.com/Morris/GC",
ApiBase = "https://git.xhmcl.com/api/v1",
RawBase = "https://git.xhmcl.com",
Kind = "gitea",
RawStyle = "branch",
Owner = "Morris",
Repo = "GC",
Branch = "main"
};
public static readonly SourcePreset GitCode = new()
{
Id = "gitcode",
Name = "GitCode",
HomeUrl = "https://gitcode.com/Morris_1/GC",
ApiBase = "https://api.gitcode.com/api/v5",
RawBase = "https://gitcode.com",
Kind = "gitcode",
RawStyle = "plain",
Owner = "Morris_1",
Repo = "GC",
Branch = "main"
};
public static readonly SourcePreset[] All = { Xhmcl, GitCode };
public static SourcePreset? Find(string? id) =>
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
/// <summary>把任意仓库地址映射到这两个内置源之一(用于兼容旧配置)。</summary>
public static SourcePreset Detect(string? url)
{
if (string.IsNullOrWhiteSpace(url)) return GitCode;
var u = url!.ToLowerInvariant();
if (u.Contains("xhmcl.com")) return Xhmcl;
return GitCode;
}
}
-104
View File
@@ -1,104 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Services;
namespace GC.ViewModels;
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
public partial class AboutViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _loaded;
public ObservableCollection<ContributorItem> Contributors { get; } = new();
[ObservableProperty] private bool _isLoading = true;
[ObservableProperty] private string _statusText = "";
[ObservableProperty] private bool _hasContributors;
public AboutViewModel(AppServices services)
{
_services = services;
LoadCommand = new AsyncRelayCommand(() => LoadAsync(force: true));
}
public string AppName => "Morris GC";
/// <summary>启动器版本号,如 v1.0.2。</summary>
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
public string RepositoryText => _services.Settings.Current.UpdateRepository;
public string ContributorsTitle => "开发者";
public IAsyncRelayCommand LoadCommand { get; }
/// <summary>每次进入页面时调用(首次才真正联网拉取)。</summary>
public void OnShown()
{
if (_loaded) return;
_ = LoadAsync(force: false);
}
private async Task LoadAsync(bool force)
{
if (_loaded && !force) return;
_loaded = true;
IsLoading = true;
StatusText = "正在读取贡献者…";
try
{
var list = await ContributorsService.FetchAsync(_services.Settings.Current.UpdateRepository);
Contributors.Clear();
foreach (var c in list)
Contributors.Add(new ContributorItem(c));
HasContributors = Contributors.Count > 0;
StatusText = HasContributors ? $"{Contributors.Count} 位贡献者" : "暂无贡献者信息";
}
catch (Exception ex)
{
StatusText = "读取失败:" + ex.Message;
}
finally
{
IsLoading = false;
}
}
[RelayCommand]
private void OpenRepository() => Shell.OpenUrl(RepositoryText);
/// <summary>重新下载启动器:关闭所有窗口,进度窗下载新版,完成后重启。</summary>
[RelayCommand]
private async System.Threading.Tasks.Task ReinstallLauncher()
{
if (LauncherUpdateFlow.IsRunning) return;
await LauncherUpdateFlow.RunAsync(_services, "正在重新下载启动器");
}
}
/// <summary>一位贡献者的展示项。</summary>
public sealed class ContributorItem
{
public ContributorItem(Contributor c)
{
Name = c.DisplayName;
Contributions = c.Contributions;
AvatarUrl = c.AvatarUrl;
}
public string Name { get; }
public int Contributions { get; }
public string? AvatarUrl { get; }
public string ContributionsText => $"{Contributions} 次提交";
public bool HasAvatar => !string.IsNullOrWhiteSpace(AvatarUrl);
}
-127
View File
@@ -1,127 +0,0 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
xmlns:vm="using:GC.ViewModels"
x:Class="GC.Views.AboutView"
x:DataType="vm:AboutViewModel">
<ScrollViewer>
<StackPanel Margin="28,24" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
<StackPanel Spacing="4">
<TextBlock Classes="h1" Text="关于" />
<TextBlock Classes="muted" Text="版本信息与开发者" />
</StackPanel>
<!-- 应用信息 -->
<Border Classes="card" Padding="22,20">
<Grid ColumnDefinitions="Auto,*">
<Border Width="62" Height="62" CornerRadius="16" Background="#1C2C4C"
VerticalAlignment="Top">
<TextBlock Text="◎" FontSize="32" Foreground="#8FB6FF"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel Grid.Column="1" Margin="18,0,0,0" Spacing="10">
<StackPanel Spacing="2">
<TextBlock Text="{Binding AppName}" FontSize="19" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="{Binding PlatformText}" />
</StackPanel>
<Grid ColumnDefinitions="96,*" RowDefinitions="Auto,Auto">
<TextBlock Classes="h3" Text="版本" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}"
FontWeight="SemiBold" />
<TextBlock Grid.Row="1" Classes="h3" Text="仓库" Margin="0,8,0,0" />
<Button Grid.Row="1" Grid.Column="1" Classes="ghost small" Margin="0,6,0,0"
HorizontalAlignment="Left" Padding="0"
Command="{Binding OpenRepositoryCommand}"
Content="{Binding RepositoryText}" />
</Grid>
</StackPanel>
</Grid>
</Border>
<!-- 维护 -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="12">
<TextBlock Classes="h2" Text="启动器维护" />
<TextBlock Classes="muted" TextWrapping="Wrap"
Text="重新下载会关闭所有窗口,显示下载进度,完成后自动启动新版本并删除旧版本。" />
<Button Classes="primary" Content="重新下载启动器"
HorizontalAlignment="Left" Padding="18,8"
Command="{Binding ReinstallLauncherCommand}" />
</StackPanel>
</Border>
<!-- 感谢(样式抄「开发者」卡片,内容写死,不读取数据) -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="14">
<TextBlock Classes="h2" Text="感谢" />
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Background="{DynamicResource SurfaceAlt}"
BorderBrush="{DynamicResource Line}" BorderThickness="1"
CornerRadius="12" Padding="12,10" MinWidth="190">
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Width="34" Height="34" CornerRadius="17"
Background="{DynamicResource AccentSoft}">
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="地理洪老师" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="地理学科内容指导" />
</StackPanel>
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</Border>
<!-- 开发者 -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="14">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="h2" Text="{Binding ContributorsTitle}" />
<Button Grid.Column="1" Classes="ghost small" Content="刷新"
Command="{Binding LoadCommand}" IsEnabled="{Binding !IsLoading}" />
</Grid>
<TextBlock Classes="faint" Text="{Binding StatusText}" />
<ProgressBar IsIndeterminate="True" Height="3" IsVisible="{Binding IsLoading}" />
<ItemsControl ItemsSource="{Binding Contributors}" IsVisible="{Binding HasContributors}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="{DynamicResource SurfaceAlt}"
BorderBrush="{DynamicResource Line}" BorderThickness="1"
CornerRadius="12" Padding="12,10" Margin="0,0,10,10" MinWidth="190">
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Width="34" Height="34" CornerRadius="17"
Background="{DynamicResource AccentSoft}">
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="{Binding ContributionsText}" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
-11
View File
@@ -1,11 +0,0 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class AboutView : UserControl
{
public AboutView() => InitializeComponent();
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
}
-66
View File
@@ -1,66 +0,0 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
namespace GC.Views;
public partial class ConfirmWindow : Window
{
public ConfirmWindow() : this("") { }
public ConfirmWindow(string message) : this(null, message, null, null) { }
/// <summary>
/// 可定制标题与按钮文案的确认窗。
/// </summary>
public ConfirmWindow(string? title, string message, string? confirmText, string? cancelText)
{
AvaloniaXamlLoader.Load(this);
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
Background = Brushes.Transparent;
if (this.Content is Control content)
{
// 先把 content 从 Window 上摘下来,否则再赋给 Border.Child 会抛
// "The Control already has a parent."
this.Content = null;
this.Content = new Border
{
CornerRadius = new CornerRadius(14),
BorderBrush = (this.FindResource("Line") as IBrush) ?? Brushes.Gray,
BorderThickness = new Thickness(1),
Background = (this.FindResource("Surface") as IBrush) ?? Brushes.White,
ClipToBounds = true,
Child = content
};
}
var text = this.FindControl<TextBlock>("MessageText");
if (text != null) text.Text = message;
if (!string.IsNullOrWhiteSpace(title))
{
var titleBlock = this.FindControl<TextBlock>("TitleText");
if (titleBlock != null) titleBlock.Text = title;
}
if (!string.IsNullOrWhiteSpace(confirmText))
{
var ok = this.FindControl<Button>("ConfirmButton");
if (ok != null) ok.Content = confirmText;
}
if (!string.IsNullOrWhiteSpace(cancelText))
{
// 取消按钮是第一个("取消"),这里按名查找更稳
var cancel = this.FindControl<Button>("CancelButton");
if (cancel != null) cancel.Content = cancelText;
}
}
private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
private void OnConfirm(object? sender, RoutedEventArgs e) => Close(true);
}
-109
View File
@@ -1,109 +0,0 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using GC.Services;
namespace GC.Views;
/// <summary>
/// 启动器更新进度窗:更新期间主窗口已关闭,由这个独立小窗展示下载进度。
/// 窗口本身透明,圆角由内部 Border 裁出。
/// </summary>
public sealed class UpdaterWindow : Window
{
private readonly ProgressBar _bar;
private readonly TextBlock _stage;
private readonly TextBlock _detail;
private readonly TextBlock _percent;
public UpdaterWindow(string title)
{
Title = title;
Width = 460;
Height = 210;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.CenterScreen;
// 必须透明,否则会把内部 Border 的圆角填平
Background = Brushes.Transparent;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
SystemDecorations = SystemDecorations.None;
var titleBlock = new TextBlock
{
Text = title,
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
FontSize = 15,
FontWeight = FontWeight.SemiBold
};
_stage = new TextBlock
{
Text = "正在准备…",
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
FontSize = 12
};
_bar = new ProgressBar
{
Minimum = 0,
Maximum = 1,
Value = 0,
Height = 6,
CornerRadius = new CornerRadius(3),
Foreground = new SolidColorBrush(Color.Parse("#3B7BFF")),
Background = new SolidColorBrush(Color.Parse("#1B2740"))
};
_percent = new TextBlock
{
Text = "0%",
Foreground = new SolidColorBrush(Color.Parse("#6E86AD")),
FontSize = 11,
HorizontalAlignment = HorizontalAlignment.Right
};
_detail = new TextBlock
{
Text = "",
Foreground = new SolidColorBrush(Color.Parse("#4F6382")),
FontSize = 10.5
};
var panel = new StackPanel { Margin = new Thickness(24, 22), Spacing = 12 };
panel.Children.Add(titleBlock);
panel.Children.Add(_bar);
panel.Children.Add(_stage);
panel.Children.Add(_percent);
panel.Children.Add(_detail);
Content = new Border
{
CornerRadius = new CornerRadius(16),
Background = new SolidColorBrush(Color.Parse("#0B1226")),
BorderBrush = new SolidColorBrush(Color.Parse("#223252")),
BorderThickness = new Thickness(1),
ClipToBounds = true,
Child = panel
};
}
/// <summary>任意线程调用都可以。</summary>
public void Report(double value, string? stage, string? detail = null)
{
if (!Dispatcher.UIThread.CheckAccess())
{
Dispatcher.UIThread.Post(() => Report(value, stage, detail));
return;
}
var clamped = Math.Clamp(value, 0, 1);
_bar.Value = clamped;
_percent.Text = $"{clamped * 100:0}%";
if (!string.IsNullOrWhiteSpace(stage)) _stage.Text = stage;
if (!string.IsNullOrWhiteSpace(detail)) _detail.Text = detail;
}
}
+77 -192
View File
@@ -1,216 +1,110 @@
# GC # Earth Model Studio
天文教学模型**启动器**:管理/启动模型、启动时自动检查并下载最新版模型与启动器、设置语言与内存。 天文教学模型**启动器**:管理/启动模型、启动时自动检查并下载最新版模型与启动器、设置语言与内存。
> **分层约定(重要)** > **分层约定(重要)**
> - `GC/` = 启动器:扫描、下载、开窗口、显示加载进度。**不渲染、不含任何模型内容、发布包不内置模型**。 > - `src/` = 启动器:扫描、下载、开窗口、显示加载进度、自检更新。**不渲染、不含任何模型内容、发布包不内置模型**。
> - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。 > - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。
> - 模型相关代码全部直接存在模型目录里,仓库根没有 `model-src/` / `model-sdk/` 这类旁路目录。 > - 模型相关代码全部直接存在模型目录里,仓库根没有 `model-src/` / `model-sdk/` 这类旁路目录。
> - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,启动器一行都不用改,客户端启动自动更新。 > - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,`src` 一行都不用改,客户端启动自动更新。
> - `GC-SAVEDOG/` = 更新守护进程:验签、原子替换、启动后健康检查、失败回滚。
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台 - UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载 - 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**(Linux 可自行编译,未列入发布矩阵) - 目标平台:**macOS arm64 / Windows x64 / Windows arm64**,一条命令全部编译
- 更新仓库:<https://gitcode.com/Morris_1/GC>,模型目录 <https://gitcode.com/Morris_1/GC/tree/main/model> - 更新仓库:<https://gitcode.com/2509_92447106/GC>,模型目录 <https://gitcode.com/2509_92447106/GC/tree/main/model>
## 快速开始
```bash
# 依赖:.NET 8 SDK(macOS 另需 Xcode Command Line Tools,用于 .icns / ditto)
dotnet --version # 8.0.x
./build.sh build # 三平台完整发布 -> dist/
./build.sh run # 开发态直接运行(读仓库 model/,跳过在线替换)
./build.sh check # 编译 + 自检 + 离屏渲染 + 产物检查
```
Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run / test / update-test / pack-models / clean / doctor`)。
`build.sh test` 的离屏渲染需要图形栈:Linux CI 上用 `xvfb-run ./build.sh test`。
## 运行目录(发布包里就长这样) ## 运行目录(发布包里就长这样)
``` ```
<安装目录>/ <安装目录>/
GC.exe | GC.app/ EarthModelStudio.exe | EarthModelStudio.app/
GC-SAVEDOG[.exe] 更新守护进程(与主程序同目录,macOS 在 .app/Contents/MacOS 内)
.GC/ .GC/
config/settings.json 用户设置(与缓存分开:删 cache 不会丢配置) settings.json 设置 + 已安装版本记录
model/ 启动时下载的模型 model/ 启动时下载的模型
cache/ 下载暂存 / 原子替换 cache/ 下载暂存 / 原子替换
update/ 待应用的启动器更新(apply-request.json + package.zip) update/ 待下次启动应用的启动器更新
``` ```
**发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示; **发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示;
安装目录不可写时自动退回用户数据目录。`.GC/cache` 与 `.GC/model` 随时可删,程序会重新下载; 安装目录不可写时自动退回用户数据目录。`.GC/` 可以随程序一起搬迁,也可以整个删掉重新下载。
`.GC/config/settings.json` 删掉等于恢复出厂设置。
## 自动更新 ## 自动更新
| 检查项 | 不是最新版时 | 生效时机 | | 检查项 | 不是最新版时 | 生效时机 |
| --- | --- | --- | | --- | --- | --- |
| 模型 | 按文件清单下载到 `cache/`,校验哈希后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) | | 模型 | 从 gitcode 下载到 `cache/`,校验后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) |
| 启动器 | 下载对应平台 zip 到 `.GC/update/`,交给 `GC-SAVEDOG` | **下次启动时应用**(重启后自动替换) | | 启动器 | 下载对应平台 zip 到 `.GC/update/payload`,写 `pending.json` | **下次启动时应用**(独立脚本覆盖程序并重启) |
启动器更新的完整流程: - 默认更新仓库写在 `.GC/settings.json` 的 `updateRepository`:
`https://gitcode.com/2509_92447106/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
``` - 版本来自仓库根 `version.json`(由 `./build.sh stamp` 生成):模型版本 = **模型包内容指纹**,
启动器下载 zip -> 校验 sha256 -> 写 apply-request.json -> 启动 GC-SAVEDOG -> 自己退出 所以**改了模型文件,版本号自动变**;启动器版本 = 构建版本。
GC-SAVEDOG: 二次验签 -> 检查 zip 安全性 -> 解压到 .GC/update/stage - `settings.json` 记录 `installedModelVersions` / `pendingLauncherVersion` / `lastUpdateCheck`。
-> 移入安装目录(绝不覆盖已有版本) - 断网、仓库还没推 `version.json`、下载失败:**一律保留本地模型,绝不把模型库清空**,底部状态条说明原因。
-> 启动新版,等 .GC/update/health.json - 设置页可关闭自动更新;状态条可手动「检查更新」(忽略开关强制检查)。
-> 收到:删同平台旧版本,写 last-good.json
-> 没收到/进程退出:删新版、重启旧版,写 state.json = rolledback
```
也就是说:**新版本起不来,用户不会被卡死**。找不到 `GC-SAVEDOG` 的旧安装会退回脚本流程(过渡用)。
- 默认更新仓库写在 `.GC/config/settings.json` 的 `updateRepository`:
`https://gitcode.com/Morris_1/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
- 断网、仓库没推 `version.json`、下载失败:**一律保留本地模型,绝不清空模型库**,底部状态条说明原因
- 首次启动断网且本地无模型:状态条会明确提示「去下载页重试 / 手动放入 `.GC/model/`」,不会白屏干等
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填 - 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
`updateLocalRoot` 指向它,即可完全离线更新(同样会验签) `updateLocalRoot` 指向它,即可完全离线更新。
- 发新版:把 `dist/GC-<rid>.zip` 上传到 Release / 仓库 `dist/`,把直链填进 `version.json`
## 安全模型 对应平台的 `url`(`./build.sh publish` 会生成 zip 并自动写入 `sha256` / `size`)。
更新包只含程序文件,**不会覆盖 `.GC/` 里的模型与设置**。
威胁模型很直接:**模型 dll 会被 `AssemblyLoadContext` 直接执行**,启动器更新包会替换可执行文件。
只要仓库被入侵,攻击者就能让所有客户端跑他的代码。因此信任链是:
```
内置公钥(源码)
└─ 验证 version.json 的 ECDSA P-256 签名
├─ 得到启动器包 sha256 → 校验下载到的 zip
│ └─ GC-SAVEDOG 再次验签 + 复算 sha256 + 检查 zip 结构 → 原子替换
└─ 得到每个模型的 manifestSha256 / filesSha256
└─ 下载后复算,比对通过才安装
└─ 加载 dll 前抽查 dll / json 哈希(.integrity.json)
```
要点:
| 机制 | 防的是什么 | 代码位置 |
| --- | --- | --- |
| 清单签名(ECDSA P-256 / SHA-256) | 仓库被改、清单被替换 | `GC/src/Security/ManifestSignature.cs` |
| 规范化 JSON(键排序、去 signature) | 「同内容不同字节」导致签名不可复现 | `GC/src/Security/CanonicalJson.cs` |
| 包 sha256(取自已签名清单) | 下载被替换 / 传输损坏 | `GC/src/Security/ContentHash.cs` |
| 模型 manifestSha256 / filesSha256 | 下载后、安装前被掉包 | `GC/src/Security/ModelIntegrity.cs` |
| 加载前抽查 dll 哈希 | 本地模型文件被替换 | `GC/src/Services/ModelHost.cs` |
| `SafeArchive`(条目数/体积/压缩比/符号链接/穿越) | zip 炸弹、zip slip、链接攻击 | `GC/src/Security/SafeArchive.cs` |
| `GC-SAVEDOG` 独立进程 | 覆盖失败、断电、新版本起不来 | `GC-SAVEDOG/Applier.cs` |
| 健康标记 + 回滚 | 新版启动即崩 | `GC/src/Security/StartupHealth.cs` |
默认策略:**清单没签名或签名不符一律拒绝更新**。
自建私有构建可临时放开:`settings.json` 里 `requireSignedManifest: false`,
或环境变量 `GC_ALLOW_UNSIGNED_MANIFEST=1`(只建议调试用)。
### 签名密钥
- 私钥:`.signing/gc-signing.pem`(**已在 `.gitignore`,永不入库**;请自行备份)
- 公钥:硬编码在 `GC/src/Security/SignatureKeyring.cs`,指纹 `b41b1dd6259ea9ed`
- 生成新密钥:`dotnet run --project GC-SAVEDOG -- keygen`
- 轮换:把新公钥追加进 `SignatureKeyring.Keys`(保留旧公钥一个版本周期),再重新签名清单
- 部署前核对两边公钥一致:
`dotnet run --project GC-SAVEDOG -- verify --manifest version.json`
### zip 解压加固
更新包和模型源 zip 一律当成不可信输入:拒绝 `../`、绝对路径、盘符、UNC、符号链接;
条目数 ≤ 20000、解压后 ≤ 2 GiB、压缩比异常(>200:1 且体积较大)直接判为 zip 炸弹。
## 版本与指纹
- **启动器版本**:`Directory.Build.props` 的 `<Version>`;`./build.sh build -version=1.0.8` 可覆盖,
只影响启动器(程序集版本、关于页、`version.json` 的 `launcher.version`)。
- **模型版本**:模型清单里**作者手写**的 `version`(如 `1.6`),`./build.sh stamp` 不会改它。
客户端按字符串比较是否变化,所以改模型内容后必须手动升版本号,否则用户不会更新。
- **`build` 字段**:模型内容的构建指纹,只用于溯源;`updatedAt` / `build` 都不参与指纹计算,
保证「同一份内容重复构建得到同一个值」。
- **内容哈希算法**(构建端与客户端必须一致):
```
fileHash = SHA256(文件字节)
dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接 "<相对路径>\0<fileHash>\n" )
```
相对路径统一 `/` 分隔,跳过 `.` 开头的文件、`bin/`、`obj/`、`*.user`;
不含时间戳、权限位、文件顺序。实现见 `GC/src/Security/ContentHash.cs`,构建端由
`VersionStamp` 直接链接同一份源码,不会出现两套算法。
## 目录结构 ## 目录结构
``` ```
Repository/ EarthModelStudio/
├── GC.sln ├── EarthModelStudio.sln
├── Directory.Build.props # 公共构建属性(版本号在这里) ├── Directory.Build.props # 公共构建属性
├── version.json # ★ 自动生成并签名的版本清单(推送到仓库后才生效) ├── version.json # ★ 自动生成的版本清单(推送到仓库后才生效)
├── build.sh / build.ps1 # 构建脚本(实际实现在 buildsh/ 与 buildps1/) ├── build.sh / build.ps1 # 构建脚本
├── GC/ # 启动器 ├── src/ # ★ 启动器(没有渲染逻辑)
│ └── src/ │ └── main/dotnet/EarthModelStudio/
│ ├── GC.Core.csproj │ ├── Models/ Services/ # 清单/设置/目录探测/i18n/模型库/下载/自动更新
│ ├── Security/ # ★ 验签、哈希、安全解压、完整性、健康标记 │ │ # UpdateService · GitCodeRemote · DirectoryRemote · LauncherUpdate
│ ├── Models/ Services/ │ ├── ViewModels/ Views/ # 主页、下载、设置、模型窗口壳、启动更新状态条
│ ├── ViewModels/ Views/ │ └── Assets/i18n/ # 启动器界面语言包
│ ├── Assets/i18n/ # 界面语言包 ├── src/test/dotnet/…Tests/ # 离屏校验 + --update-test 离线更新链路验证
│ └── test/dotnet/GC.Tests/ # 离屏校验 + --update-test 离线更新链路验证
├── GC-BOOT/ # 轻量启动入口
├── GC-DOWNLOAD/ # 源仓库 / 模型 / 启动器下载更新
├── GC-DRAW/PlayerWindow.cs # 模型窗口宿主;绘制由模型提供
├── GC-SAVEDOG/ # ★ 更新守护进程(apply / verify / keygen / sign / status)
├── model/ # ★ 模型的一切 ├── model/ # ★ 模型的一切
│ ├── version.json # 与根 version.json 完全相同(同一份签名) │ ├── version.json # 与根 version.json 相同(便于按 model/ 地址读取)
│ ├── _sdk/GC.ModelSdk/ │ ├── _sdk/EarthModelStudio.ModelSdk/
│ ├── _engine/{src,PreviewGen,VersionStamp}/ │ ├── _engine/
│ ├── earth-rotation/{earth-rotation.json,src/,earth-rotation.model/} │ │ ├── src/ # CelestialView / PlanetTexture / EarthModelView …
│ │ ├── PreviewGen/ # 用模型渲染器生成封面
│ │ └── VersionStamp/ # 按内容指纹自动打版本、生成 version.json
│ ├── earth-rotation/
│ │ ├── earth-rotation.json
│ │ ├── src/ # 本模型源码
│ │ └── earth-rotation.model/ # dll + scene.json/land.json + preview.png + i18n
│ └── earth-revolution/ │ └── earth-revolution/
├── dist/ # 发布产物(.gitignore,只通过 Release 分发) └── dist/ # 发布产物(只有启动器 + .GC 骨架)
└── .signing/ # 签名私钥(.gitignore,绝不入库)
``` ```
模型库位置:`EMS_MODELS` 覆盖 → 开发态仓库根 `model/` → **发布态 `<可执行文件>/.GC/model/`**。 模型库位置:`EMS_MODELS` 覆盖 → 开发态仓库根 `model/` → **发布态 `<可执行文件>/.GC/model/`**。
`dist/` 不进仓库:二进制放 Git 会让 clone 变慢,也会让「仓库被改」的爆炸半径变大。
发布有两种方式,`version.json` 里两条路都写清楚了:
| 方式 | 清单字段 | 说明 |
| --- | --- | --- |
| Release 附件(推荐) | `url` | `.../releases/download/v<版本>/GC-<版本>-<系统>-<架构>.zip` |
| 仓库编译产物 | `path` / `dir` / `name` | `dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip` |
下载端按 `url` → `path` → `dist/<系统>-<架构>/` 目录扫描的顺序尝试,
**每个候选都必须与清单里的 `sha256` 一致**(`sha256` 由签名保护),
所以「多发一个地方」不会放宽校验,只是让「只提交产物、不发 Release」也能更新。
清单缺 `sha256` 的平台会被直接跳过,不再退化成「只校验非空」。
## 构建与运行 ## 构建与运行
```bash ```bash
./build.sh build # 三平台完整发布:启动器 + SAVEDOG + 运行骨架 + 更新包 ZIP ./build.sh build # 编译整个解决方案
./build.sh check # 编译、自检、离屏渲染及发布 ZIP 完整性检查 ./build.sh models # 编译模型 dll + 生成封面 + 自动打版本
./build.sh models # 编译模型 dll、生成封面、更新并签名版本清单 ./build.sh stamp # 只重新生成 version.json 与模型版本
./build.sh stamp # 只重新生成 + 签名 version.json ./build.sh run # 运行
./build.sh run # Debug 运行启动器 ./build.sh test # 离屏校验:页面 + 真实加载模型窗口截图
./build.sh test # 离屏校验,截图写入 build/screenshots/ ./build.sh update-test # 离线验证自动更新链路(不联网、不替换程序)
./build.sh update-test # 离线验证自动更新链路(验签 / 立即生效 / 篡改拒绝 / 断网兜底) ./build.sh publish # 三平台发布(不内置模型)+ 建 .GC 骨架 + 生成更新包
./build.sh pack-models # 编译模型并打包 dist/models-<版本>.zip ./build.sh pack-models # 单独打包模型 -> dist/models-<version>.zip
./build.sh pack-launcher # 把已有平台发布目录打成启动器更新 ZIP ./build.sh pack-launcher # 生成三个平台的启动器更新包 zip
./build.sh doctor # dotnet 环境信息 ./build.sh clean
./build.sh dist # 列出 dist/ 产物
./build.sh clean # 清理 build/ 与 dist/
``` ```
Windows 用 `.\build.ps1`(参数相同)。
| 产物 | 平台 | | 产物 | 平台 |
| --- | --- | | --- | --- |
| `dist/mac-arm64/GC-<版本>-mac-arm64.zip` | macOS Apple Silicon 应用包(含 GC-SAVEDOG) | | `dist/mac-arm64/EarthModelStudio.app` | macOS Apple Silicon |
| `dist/win-amd64/GC-<版本>-win-amd64.zip` | Windows x64 单文件启动器 + `GC-SAVEDOG.exe` | | `dist/win-x64/EarthModelStudio.exe` | Windows x64 |
| `dist/win-arm64/GC-<版本>-win-arm64.zip` | Windows on ARM 同上 | | `dist/win-arm64/EarthModelStudio.exe` | Windows on ARM |
平台目录就是「该平台的编译产物目录」:打包完成后只留最终 zip(原始 `.app` / `.exe` 均为自包含单文件启动器,**发布包内不含模型**。改完模型:
会被挪到 `build/trash/`,下次构建时移出,不做递归删除)。 `./build.sh models` → 把 `version.json` 和 `model/` 推送到 gitcode → 客户端下次启动自动更新。
发新版:`./build.sh build -version=1.0.8` → 把 `dist/<平台>/GC-1.0.8-<平台>.zip`
上传到 gitcode Release(tag `v1.0.8`),**或者**直接提交/上传到仓库的
`dist/<平台>/` 目录 → 提交并推送 `version.json` / `model/version.json`。
两种都能被客户端识别,客户端下次启动就会看到更新。
## 模型契约 ## 模型契约
@@ -240,25 +134,8 @@ public interface IModelContext
} }
``` ```
**线程约定** 启动器先弹进度窗,在后台调用 `Prepare`(模型用 `ReportProgress` 汇报真实进度),
再在 UI 线程调用 `CreateView`,把返回的控件直接铺满窗口 —— 除此之外什么都不做。
| 成员 | 允许的线程 | 说明 |
| --- | --- | --- |
| `Prepare` | 后台线程(调用一次) | 可耗时;用 `ReportProgress` 汇报真实进度;此时**不要**创建控件 |
| `CreateView` | UI 线程(`Prepare` 之后调用一次) | 只在这里创建/操作 Avalonia 控件 |
| `ReportProgress` / `Log` | 任意线程 | 线程安全,内部自行封送到 UI |
| `RequestClose` | 任意线程 | 线程安全,等价于点窗口关闭按钮 |
| `Dispose` | UI 线程 | 释放后不要再调用 `Log` / `ReportProgress` |
**契约版本协商**
- `IModelFactory.ApiVersion` 与启动器支持的版本(当前 `1`)必须相等,否则拒绝加载并提示更新启动器。
- 模型清单可写 `minAppVersion`(如 `"1.0.8"`):启动器版本更低时直接拒绝,并给出明确提示。
- 提升契约版本时必须保留旧接口的适配层,或在启动器里明确「最低启动器版本」,避免老客户端加载新模型后崩溃。
**卸载注意**:关窗即 `Unload()` 收集式 AssemblyLoadContext。只要有静态字段、未解绑的事件、
或缓存里还拿着模型内的类型/控件,程序集就回收不掉(内存持续增长)。
模型作者应避免静态持有 `Control` / `IModelContext`,并在 `Dispose` 里解绑事件。
详细清单字段、数据格式、封面生成见 [`model/README.md`](model/README.md)。 详细清单字段、数据格式、封面生成见 [`model/README.md`](model/README.md)。
@@ -266,7 +143,7 @@ public interface IModelContext
- 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口 - 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口
- 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集 - 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集
- 所有由启动器打开的窗口(模型窗、加载窗、确认框、更新窗)都是 16px 圆角 - 启动器快捷键 `Esc` 关闭、`F11` 全屏;模型窗口内的快捷键由模型自己定义
## 地球模型(model/_engine + model/<id>/src) ## 地球模型(model/_engine + model/<id>/src)
@@ -278,12 +155,20 @@ public interface IModelContext
**没有节气定位**(节气属于公转) **没有节气定位**(节气属于公转)
- **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定格、HUD(角度 / 直射纬度 / 日期) - **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定格、HUD(角度 / 直射纬度 / 日期)
- **触控一体机**:双指捏合缩放(跟手)、滚轮缩放、画布左下角大号 + / − / 复位按钮; - **触控一体机**:双指捏合缩放(跟手)、滚轮缩放、画布左下角大号 + / − / 复位按钮;
所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变** 所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**,
俯视角只由「俯视」按钮显式切换
- **课堂演示**:点二分二至自动暂停定格并显示节气、教材日期、直射纬度与现象说明; - **课堂演示**:点二分二至自动暂停定格并显示节气、教材日期、直射纬度与现象说明;
右侧课堂卡含可放大观察到的「地球特写」;`◀ ▶` 步进 5°、教学要点点击自动定格定位; 右侧课堂卡含可放大观察到的「地球特写」;`◀ ▶` 步进 5°、教学要点点击自动定格定位;
快捷键 `空格` 播放/暂停、`← →` 步进、`1–4` 二分二至、`F` 全屏、`+ -` 缩放、`0` 复位视角 快捷键 `空格` 播放/暂停、`← →` 步进、`1–4` 二分二至、`F` 全屏、`+ -` 缩放、`0` 复位视角
- 节气日期、直射纬度、现象说明、教学要点全部写在 `scene.json` 里;夸张倾角只改示意图形,不改教学读数
## 模型源(手动导入)
除了启动时自动更新,「下载」页还支持手动导入普通 git 仓库:
**仓库根目录下的 `model/` 文件夹即模型列表**。支持 GitHub / GitLab / Gitee(zip 归档,
失败回退 `git clone --depth 1`)、zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/<id>`。
## 启动时运行内存分配 ## 启动时运行内存分配
设置页的「启动时运行内存分配」类似启动器的 `-Xmx`:启动器把这份预算通过 `IModelContext.MemoryBudgetMb` 设置页的「启动时运行内存分配」类似启动器的 -Xmx:启动器把这份预算通过 `IModelContext.MemoryBudgetMb`
交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。 交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。
-78
View File
@@ -1,78 +0,0 @@
# GC v1.0.6
## 新模型:等高线地形图
依据人教版七年级上册「地形图的判读」制作,把课本最难讲清的一件事——**立体地形如何转成平面等高线图**——变成可交互的双图联动。
- **左右双图联动**:左边是三维地形块(斜视图),右边是等比例的分层设色等高线图。鼠标移到任一侧,两侧同步标出该点位置、海拔、相对高度和地形部位。
- **五种地形部位判读**:山峰、山脊、山谷、鞍部、陡崖。鼠标停在哪里,底部就实时显示该处属于哪种部位,并给出对应颜色。
- **等高线自动生成**:Marching Squares 算法从 192×192 高度场实时提取,等高距 100 m,共 14 条;每 5 条加粗为计曲线并标注海拔。
- **分层设色**:绿 → 黄绿 → 土黄 → 棕 → 雪白,与课本配色一致。
- **判读要点面板**:右侧列出五种部位的特征(如「山脊:等高线凸向低处,脊线是分水线」)和四条核心规则(等高距、疏密与坡度、计曲线、海拔与相对高度)。
- 地形本身包含主峰、次峰(之间形成鞍部)、两条山脊、一条河谷、一侧陡坡、一侧缓坡和一处陡崖,海拔 0~1322 m。
## 更新系统:双源支持
启动器现在同时对接 **Xhmcl** 和 **GitCode** 两个仓库(同一份内容的镜像)。
- **自动测速选源**:检查更新与下载前并发探测两边的 `version.json` 响应时间,自动选用更快的那一个。结果缓存 3 分钟,不会每次都测。
- **Release 交叉检查**:两个源的 Release 都会查询,取版本号最高且包含当前平台发布包的那个。某个源没发 Release 时自动跳到另一个,不影响使用。
- **版本号优先于发布时间**:Release 列表按版本号数值比较(`1.0.10 > 1.0.9`),不受发布时间顺序影响。草稿状态(draft)的 Release 不计入。
- **模型与启动器分开取**:模型清单始终读仓库里的 `version.json`(模型不需要发 Release),启动器版本只认 Release。这样即使某个源没发 Release,模型仍能正常更新。
- **同版本比对指纹**:远端版本与本地相同时,下载对应平台的发布包比对 sha256。一致则视为最新;不一致说明是自行编译的构建,不打扰用户。
- **修复版本读取**:此前 `Assembly.GetEntryAssembly()` 在某些宿主下会返回 `1.0.0`,导致明明是最新版却一直提示更新;现在改为读取本程序集版本。
## 下载页面
- **取消自定义模型源**:不再接受任意仓库地址,只保留 Xhmcl 与 GitCode 两个内置源,避免来源不明的模型。
- **一键测速切换**:原来的「导入模型源」输入框改为「测速并切换到最快源」按钮,点击后自动比对并切到更快的那个源。
- **下载与更新统一**:下载页面和启动更新现在共用同一个源选择器,不再出现两处下载速度不一致的情况。
## 窗口标题栏
- **去掉彩色圆圈**:最小化 / 最大化 / 关闭三个按钮改回纯矢量图标,不再有黄、绿、红圆底。
- **主窗口补齐最大化**:此前主窗口只有最小化和关闭,现在补上最大化,并支持双击标题栏切换。
- **图标随状态切换**:最大化后图标变为两个重叠小方框(还原),还原后变回单方框。
- **圆角始终保留**:任何窗口状态下都保持 16px 圆角,不再最大化后变成直角贴边。
- **尺寸自适应**:标题栏文字、按钮、图标随窗口宽度同比缩放(0.85–1.9 倍),全屏时不会小得点不中。
## 缩放动画
- **地理模型**:此前滚轮缩放直接跳变,现在改为指数逼近的平滑动画(60Hz),差值小于阈值自动停下,不空转耗 CPU。
- **地球模型**:本就带平滑缩放,保持原样。
## 关于页面
- 新增「**感谢**」卡片,样式与「开发者」卡片一致:**地理洪老师 — 地理学科内容指导**。
## 开发者工具
新增 `git.sh` / `git.bat` 与 `gitshell/` 目录,把仓库操作从手动命令变成可交互流程:
- **`./git.sh autogit`**:交互式提交。依次询问①选哪个仓库(支持多选、可选全部、可连续输入多个新地址)②确认仓库地址③确认提交分支④输入提交信息⑤最终确认,然后逐个推送并汇总结果。
- **自动排除构建产物**:`dist/` `build/` `bin/` `obj/` `.GC/` 无论是否被跟踪都不会提交,历史上被跟踪的会先从索引移出(本地文件保留)。
- **`./git.sh status`**:一眼看清当前分支、改动数量、最近提交,以及每个远程仓库的领先/落后情况。
## 模型版本
| 模型 | 版本 |
| --- | --- |
| 等高线地形图 contour-map | **1.0**(新) |
| 地球地理 earth-geography | 1.8 |
| 地球自转 earth-rotation | 1.6 |
| 地球公转 earth-revolution | 1.6 |
| 比例尺计算器 scale-calculator | 1.5 |
---
**安装包**
| 平台 | 文件 |
| --- | --- |
| Windows x64 | `GC-win-x64.zip` |
| Windows ARM64 | `GC-win-arm64.zip` |
| macOS Apple Silicon | `GC-osx-arm64.zip` |
| macOS Intel | `GC-osx-x64.zip` |
| Linux x64 | `GC-linux-x64.zip` |
下载后解压即可运行。模型会在首次启动时自动下载到程序目录旁的 `.GC/model/`。
+226 -6
View File
@@ -1,8 +1,228 @@
try { # ---------------------------------------------------------------------------
& (Join-Path $PSScriptRoot 'buildps1/build.ps1') @args # Earth Model Studio 构建脚本(Windows PowerShell)
exit 0 #
# .\build.ps1 编译
# .\build.ps1 run 运行
# .\build.ps1 test 离屏渲染校验
# .\build.ps1 models 编译模型 dll + 生成封面 + 自动打版本
# .\build.ps1 stamp 只重新生成 version.json 与模型版本
# .\build.ps1 publish 编译三个平台启动器(不内置模型)+ 建立 .GC 运行目录
# .\build.ps1 pack-models 单独打包模型数据(含 version.json)
# .\build.ps1 pack-launcher 生成三个平台的启动器更新包 zip
# .\build.ps1 update-test 离线验证自动更新链路
# .\build.ps1 clean 清理
#
# 分层:src\ 只是启动器;模型全部在 model\;**发布包不内置模型**。
#
# 运行目录(发布包里就长这样):
# <安装目录>\
# EarthModelStudio.exe
# .GC\settings.json
# .GC\model\ 启动时从 gitcode 下载的模型
# .GC\cache\ 下载暂存
# .GC\update\ 待下次启动应用的启动器更新
# ---------------------------------------------------------------------------
param(
[Parameter(Position = 0)]
[ValidateSet('build', 'run', 'test', 'publish', 'models', 'stamp', 'pack-models',
'pack-launcher', 'update-test', 'bundle', 'clean', 'doctor')]
[string]$Task = 'build'
)
$ErrorActionPreference = 'Stop'
$Root = $PSScriptRoot
Set-Location $Root
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。
# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
$AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj'
$TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj'
$PreviewProj = 'model/_engine/PreviewGen/PreviewGen.csproj'
$StampProj = 'model/_engine/VersionStamp/VersionStamp.csproj'
$Sln = 'EarthModelStudio.sln'
$Version = '1.0.1'
function Stamp-Versions {
Write-Host '==> 自动计算模型版本并生成 version.json'
dotnet run --project $StampProj -c Release -- $Root $Version
} }
catch {
[Console]::Error.WriteLine($_) function Build-Models {
exit 1 Write-Host '==> 编译模型功能程序集(源码就在各模型目录的 src\ 里)'
Get-ChildItem "$Root/model" -Directory | ForEach-Object {
$id = $_.Name
$src = Join-Path $_.FullName 'src'
if (-not (Test-Path $src)) { return }
$proj = Get-ChildItem $src -Filter *.csproj | Select-Object -First 1
if ($null -eq $proj) { return }
dotnet build $proj.FullName -c Release
$data = Join-Path $_.FullName "$id.model"
if (Test-Path $data) {
Get-ChildItem (Join-Path $src 'bin/Release/net8.0') -Filter *.dll | ForEach-Object {
if ($_.Name -eq 'EarthModelStudio.ModelSdk.dll') { return }
Copy-Item -Force $_.FullName $data
Write-Host " -> model/$id/$id.model/$($_.Name)"
}
}
}
Write-Host '==> 用模型自己的渲染器生成封面'
dotnet run --project $PreviewProj -c Release -- $Root
Stamp-Versions
}
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
function Prepare-RuntimeLayout([string]$RelDir) {
$dest = "$Root/$RelDir"
if (-not (Test-Path $dest)) { return }
foreach ($old in @("$dest/model", "$dest/examples")) {
if (Test-Path $old) { Remove-Item -Recurse -Force $old }
}
foreach ($dir in @("$dest/.GC/model", "$dest/.GC/cache", "$dest/.GC/update")) {
New-Item -ItemType Directory -Force -Path $dir | Out-Null
}
$readme = @'
模型库目录(.GC/model/)
启动时程序会读取 gitcode 仓库的 version.json,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
.GC/settings.json
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
'@
Set-Content -Path "$dest/.GC/model/README.txt" -Value $readme -Encoding UTF8
$settingsPath = "$dest/.GC/settings.json"
if (-not (Test-Path $settingsPath)) {
$json = @'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"updateRepository": "https://gitcode.com/2509_92447106/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
}
'@
Set-Content -Path $settingsPath -Value $json -Encoding UTF8
}
Write-Host " 运行目录 -> $RelDir/.GC (settings.json + model/ + cache/ + update/)"
}
function Publish-Rid([string]$Rid, [string]$OutDir) {
Write-Host "==> 编译 $Rid -> $OutDir"
# 先删旧产物目录,避免残留文件混进新包
if (Test-Path "$Root/$OutDir") { Remove-Item -Recurse -Force "$Root/$OutDir" }
dotnet publish $AppProj -c Release -r $Rid --self-contained true `
-p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true `
-p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false -o "$Root/$OutDir"
foreach ($old in @("$Root/$OutDir/model", "$Root/$OutDir/examples")) {
if (Test-Path $old) { Remove-Item -Recurse -Force $old }
}
}
function Pack-Models {
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
$zip = "$Root/dist/models-$Version.zip"
if (Test-Path $zip) { Remove-Item -Force $zip }
Write-Host "==> 打包模型数据 -> dist/models-$Version.zip"
$stage = Join-Path $env:TEMP "ems-models-stage"
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
New-Item -ItemType Directory -Force -Path $stage | Out-Null
Get-ChildItem "$Root/model" -Recurse -File | Where-Object {
$_.FullName -notmatch '\\(bin|obj)\\' -and $_.Extension -ne '.user'
} | ForEach-Object {
$rel = $_.FullName.Substring("$Root/model".Length + 1)
$dest = Join-Path $stage $rel
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
Copy-Item -Force $_.FullName $dest
}
Compress-Archive -Path "$stage/*" -DestinationPath $zip -Force
Remove-Item -Recurse -Force $stage
}
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户模型与设置)
function Pack-Launcher {
Write-Host '==> 生成启动器更新包(不含 .GC)'
$targets = @{
'GC-win-x64.zip' = "$Root/dist/win-x64"
'GC-win-arm64.zip' = "$Root/dist/win-arm64"
'GC-osx-arm64.zip' = "$Root/dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
}
if (-not (Test-Path $targets['GC-osx-arm64.zip'])) {
$targets['GC-osx-arm64.zip'] = "$Root/dist/mac-arm64"
}
foreach ($name in $targets.Keys) {
$src = $targets[$name]
if (-not (Test-Path $src)) { continue }
$stage = Join-Path $env:TEMP ("ems-launcher-" + [IO.Path]::GetFileNameWithoutExtension($name))
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
New-Item -ItemType Directory -Force -Path $stage | Out-Null
Get-ChildItem $src -Recurse -File | Where-Object {
$_.FullName -notmatch '\\\.GC\\' -and $_.Name -ne '.DS_Store'
} | ForEach-Object {
$rel = $_.FullName.Substring($src.Length).TrimStart('\', '/')
$dest = Join-Path $stage $rel
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
Copy-Item -Force $_.FullName $dest
}
$zip = "$Root/dist/$name"
if (Test-Path $zip) { Remove-Item -Force $zip }
Compress-Archive -Path "$stage/*" -DestinationPath $zip -Force
Remove-Item -Recurse -Force $stage
}
Stamp-Versions
Get-ChildItem "$Root/dist/GC-*.zip" | Select-Object Name, Length
}
switch ($Task) {
'build' {
Get-ChildItem "$Root/dist/GC-*.zip","$Root/dist/models-*.zip" -ErrorAction SilentlyContinue |
Remove-Item -Force
dotnet build $Sln -c Debug
}
'run' { dotnet run --project $AppProj -c Debug }
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
'publish' {
# 先清理 dist 旧产物,再重新生成
if (Test-Path "$Root/dist") { Remove-Item -Recurse -Force "$Root/dist" }
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
Stamp-Versions
Publish-Rid 'osx-arm64' 'dist/mac-arm64'
Publish-Rid 'win-x64' 'dist/win-x64'
Publish-Rid 'win-arm64' 'dist/win-arm64'
Prepare-RuntimeLayout 'dist/win-x64'
Prepare-RuntimeLayout 'dist/win-arm64'
Prepare-RuntimeLayout 'dist/mac-arm64'
Pack-Launcher
Write-Host '==> 三个平台编译完成(发布包不含模型,首次启动自动下载),见 dist\' -ForegroundColor Green
Write-Host ' 把 version.json / model/ 推送到 gitcode,启动器就会自动检查更新'
}
'models' { Build-Models }
'stamp' { Stamp-Versions }
'bundle' { Write-Host '已弃用:发布包不再内置模型。请改用 .\build.ps1 stamp 与 gitcode 自动更新。' }
'pack-models' {
Build-Models
Pack-Models
}
'pack-launcher' { Pack-Launcher }
'update-test' { dotnet run --project $TestProj -c Debug -- '--update-test' $Root }
'clean' {
Remove-Item -Recurse -Force "$Root/build", "$Root/dist" -ErrorAction SilentlyContinue
Get-ChildItem "$Root/src" -Recurse -Directory -Include bin, obj |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
'doctor' { dotnet --info }
} }
+237 -44
View File
@@ -1,65 +1,258 @@
#!/bin/sh #!/bin/sh
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# GC 构建入口(薄封装) # Earth Model Studio 构建脚本(macOS / Linux)
# #
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条 # ./build.sh build 编译(Debug)
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物 # ./build.sh run 本机运行
# ./build.sh models 编译模型 dll + 封面 + 版本戳 # ./build.sh test 离屏渲染校验,截图输出到 build/screenshots
# ./build.sh stamp 重新生成 version.json # ./build.sh models 编译模型 dll + 生成封面 + 自动打版本
# ./build.sh run / test / update-test / pack-models / pack-launcher # ./build.sh stamp 只重新生成 version.json 与模型版本
# ./build.sh clean 清理 # ./build.sh publish 编译三个平台启动器(不内置模型)+ 建立 .GC 运行目录
# ./build.sh doctor dotnet 信息 # ./build.sh pack-models 单独打包模型数据(含 version.json)
# ./build.sh dist 列出产物 # ./build.sh pack-launcher 生成三个平台的启动器更新包 zip
# ./build.sh update-test 离线验证自动更新链路
# ./build.sh clean 清理
# #
# 实际代码都在 buildsh/ 里,本文件只负责加载模块与分发。 # 分层:src/ 只是启动器;模型全部在 model/;**发布包不内置模型**。
#
# 运行目录(发布包里就长这样):
# <安装目录>/
# EarthModelStudio(.exe | .app/...)
# .GC/
# settings.json 设置与已安装版本
# model/ 启动时从 gitcode 下载的模型
# cache/ 下载暂存
# update/ 待下次启动应用的启动器更新
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
set -eu set -eu
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败中断编译(MSB4018) # Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。
# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。
export AVALONIA_TELEMETRY_OPTOUT=1 export AVALONIA_TELEMETRY_OPTOUT=1
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$ROOT_DIR" cd "$ROOT_DIR"
APP_PROJ="GC-BOOT/GC-BOOT.csproj" APP_PROJ="src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj"
SAVEDOG_PROJ="GC-SAVEDOG/GC-SAVEDOG.csproj"
PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj" PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj" STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
TEST_PROJ="GC/src/test/dotnet/GC.Tests/GC.Tests.csproj" TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj"
SLN="GC.sln" SLN="EarthModelStudio.sln"
VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props | head -1) VERSION="1.0.1"
[ -n "$VERSION" ] || VERSION="1.0.0"
TASK="${1:-build}" TASK="${1:-build}"
shift 2>/dev/null || true
# 解析 -version=<版本号>(也接受 --version=) # 按模型包内容指纹自动写回 <id>.json 的 version,并生成 version.json
CLI_VERSION="" stamp_versions() {
for arg in "$@"; do echo "==> 自动计算模型版本并生成 version.json"
case "$arg" in dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
-version=*|--version=*) CLI_VERSION="${arg#*=}" ;; }
esac
done # 编译模型自己的功能程序集,并把 dll / 封面直接写进模型包
if [ -n "$CLI_VERSION" ]; then build_models() {
VERSION="$CLI_VERSION" echo "==> 编译模型功能程序集(源码就在各模型目录的 src/ 里)"
# 写回 Directory.Build.props,让程序集版本与关于页显示一致 for DIR in "$ROOT_DIR"/model/*/; do
if [ -f Directory.Build.props ]; then ID=$(basename "$DIR")
sed -i.bak "s|<Version>[^<]*</Version>|<Version>${VERSION}</Version>|" Directory.Build.props [ -d "$DIR/src" ] || continue
rm -f Directory.Build.props.bak PROJ=$(ls "$DIR"src/*.csproj 2>/dev/null | head -1)
[ -n "$PROJ" ] || continue
dotnet build "$PROJ" -c Release
if [ -d "$DIR$ID.model" ]; then
for DLL in "$DIR"src/bin/Release/net8.0/*.dll; do
[ -f "$DLL" ] || continue
NAME=$(basename "$DLL")
[ "$NAME" = "EarthModelStudio.ModelSdk.dll" ] && continue
cp "$DLL" "$DIR$ID.model/"
echo " -> model/$ID/$ID.model/$NAME"
done
fi
done
echo "==> 用模型自己的渲染器生成封面"
dotnet run --project "$PREVIEW_PROJ" -c Release -- "$ROOT_DIR"
stamp_versions
}
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
prepare_runtime_layout() {
REL="$1"
DEST="$ROOT_DIR/$REL"
[ -d "$DEST" ] || return 0
rm -rf "$DEST/model" "$DEST/examples"
mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update"
cat > "$DEST/.GC/model/README.txt" <<'TXT'
模型库目录(.GC/model/)
启动时程序会读取 gitcode 仓库的 version.json,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
.GC/settings.json
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
TXT
if [ ! -f "$DEST/.GC/settings.json" ]; then
cat > "$DEST/.GC/settings.json" <<'JSON'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"updateRepository": "https://gitcode.com/2509_92447106/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
}
JSON
fi fi
echo "==> 版本号设为 ${VERSION}" echo " 运行目录 -> $REL/.GC (settings.json + model/ + cache/ + update/)"
fi }
mkdir -p "$ROOT_DIR/build/logs"
# 加载 buildsh 模块 publish_rid() {
. "$ROOT_DIR/buildsh/lib/progress.sh" RID="$1"; OUT="$2"
. "$ROOT_DIR/buildsh/lib/build_funcs.sh" echo ""
. "$ROOT_DIR/buildsh/build.sh" echo "==> 编译 ${RID} -> ${OUT}"
. "$ROOT_DIR/buildsh/check.sh" # 先删旧产物,避免上次 publish 的残留文件混进新包
. "$ROOT_DIR/buildsh/tools.sh" rm -rf "$ROOT_DIR/$OUT"
dotnet publish "$APP_PROJ" \
-c Release \
-r "$RID" \
--self-contained true \
-p:Version="$VERSION" \
-p:DebugType=none \
-p:PublishSingleFile=true \
-p:IncludeNativeLibrariesForSelfExtract=true \
-p:PublishTrimmed=false \
-o "$ROOT_DIR/$OUT"
rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples"
}
# 把 model/ 里的模型数据单独打包(与启动器分开分发)
pack_models() {
mkdir -p "$ROOT_DIR/dist"
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
rm -f "$ZIP"
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
( cd "$ROOT_DIR" && zip -qr "$ZIP" model \
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
du -sh "$ZIP"
}
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户已下载的模型与设置)
pack_launcher() {
echo "==> 生成启动器更新包(不含 .GC)"
WIN64="$ROOT_DIR/dist/win-x64"
WINARM="$ROOT_DIR/dist/win-arm64"
MACBIN="$ROOT_DIR/dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
[ -d "$MACBIN" ] || MACBIN="$ROOT_DIR/dist/mac-arm64"
[ -d "$WIN64" ] && ( cd "$WIN64" && zip -qr "$ROOT_DIR/dist/GC-win-x64.zip" . \
-x "./.GC" "./.GC/*" "*.DS_Store" )
[ -d "$WINARM" ] && ( cd "$WINARM" && zip -qr "$ROOT_DIR/dist/GC-win-arm64.zip" . \
-x "./.GC" "./.GC/*" "*.DS_Store" )
[ -d "$MACBIN" ] && ( cd "$MACBIN" && zip -qr "$ROOT_DIR/dist/GC-osx-arm64.zip" . \
-x "./.GC" "./.GC/*" "*.DS_Store" )
stamp_versions
ls -lh "$ROOT_DIR"/dist/GC-*.zip 2>/dev/null || true
}
package_mac_app() {
DIST="$ROOT_DIR/dist/mac-arm64"
APP="$DIST/EarthModelStudio.app"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cat > "$APP/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key><string>Earth Model Studio</string>
<key>CFBundleDisplayName</key><string>Earth Model Studio</string>
<key>CFBundleIdentifier</key><string>cn.neorf.earthmodelstudio</string>
<key>CFBundleVersion</key><string>${VERSION}</string>
<key>CFBundleShortVersionString</key><string>${VERSION}</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleExecutable</key><string>EarthModelStudio</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST
for f in "$DIST"/*; do
base=$(basename "$f")
[ "$base" = "EarthModelStudio.app" ] && continue
mv "$f" "$APP/Contents/MacOS/"
done
chmod +x "$APP/Contents/MacOS/EarthModelStudio"
echo "==> 已打包 $APP"
}
case "$TASK" in case "$TASK" in
build) bs_build "$ROOT_DIR" ;; build)
check) bs_check "$ROOT_DIR" ;; # 清理上次遗留的发布包 zip,避免误用旧产物
*) bs_tools "$ROOT_DIR" "$TASK" ;; rm -f "$ROOT_DIR"/dist/GC-*.zip "$ROOT_DIR"/dist/models-*.zip 2>/dev/null || true
dotnet build "$SLN" -c Debug
;;
run)
dotnet run --project "$APP_PROJ" -c Debug
;;
test)
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots"
;;
publish)
# 先清掉 dist 旧产物(含历史 zip / 目录),再重新生成
echo "==> 清理 dist 旧产物"
rm -rf "$ROOT_DIR/dist"
mkdir -p "$ROOT_DIR/dist"
stamp_versions
publish_rid "osx-arm64" "dist/mac-arm64"
publish_rid "win-x64" "dist/win-x64"
publish_rid "win-arm64" "dist/win-arm64"
package_mac_app
prepare_runtime_layout "dist/win-x64"
prepare_runtime_layout "dist/win-arm64"
prepare_runtime_layout "dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
pack_launcher
echo ""
echo "==> 三个平台编译完成(发布包不含模型,首次启动自动下载):"
du -sh "$ROOT_DIR/dist"/* 2>/dev/null || true
echo " 把 version.json / model/ 推送到 gitcode,启动器就会自动检查更新"
;;
models)
build_models
;;
stamp)
stamp_versions
;;
bundle)
echo "已弃用:发布包不再内置模型。请改用 ./build.sh stamp 与 gitcode 自动更新。"
;;
pack-models)
build_models
pack_models
;;
pack-launcher)
pack_launcher
;;
update-test)
dotnet run --project "$TEST_PROJ" -c Debug -- --update-test "$ROOT_DIR"
;;
clean)
rm -rf "$ROOT_DIR/build" "$ROOT_DIR/dist"
find "$ROOT_DIR/src" -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + 2>/dev/null || true
echo "==> 已清理"
;;
doctor)
dotnet --info | head -20
;;
*)
echo "未知任务: $TASK"
echo "可用: build | run | test | publish | models | stamp | pack-models | pack-launcher | update-test | clean | doctor"
exit 1
;;
esac esac
-45
View File
@@ -1,45 +0,0 @@
function Invoke-BuildCheck {
Initialize-BuildProgress @('编译检查', '模型自检', '离屏渲染', '产物检查')
$failures = [System.Collections.Generic.List[string]]::new()
try {
Start-BuildStep '编译检查'
try { Invoke-LoggedDotNet -Name 'check-build' -Arguments @('build', $script:Solution, '-c', 'Debug', '-v', 'quiet') }
catch { $failures.Add('编译失败,见 build/logs/check-build.log'); Write-Host "!! $($failures[-1])" }
Complete-BuildStep
Start-BuildStep '模型自检'
$previousSelfTest = $env:EMS_SELFTEST
try {
$env:EMS_SELFTEST = '1'
Invoke-LoggedDotNet -Name 'check-selftest' -Arguments @('run', '--project', $script:AppProject, '-c', 'Debug', '--no-build')
if (Select-String -Path 'build/logs/check-selftest.log' -Pattern 'FAIL' -Quiet) {
$failures.Add('模型自检有失败项')
Write-Host "!! $($failures[-1])"
}
}
catch { $failures.Add('模型自检异常'); Write-Host "!! $($failures[-1])" }
finally { $env:EMS_SELFTEST = $previousSelfTest }
Complete-BuildStep
Start-BuildStep '离屏渲染'
try {
New-Item -ItemType Directory -Force -Path 'build/screenshots' | Out-Null
Invoke-LoggedDotNet -Name 'check-render' -Arguments @('run', '--project', $script:TestProject, '-c', 'Debug', '--no-build', '--', (Join-Path $script:BuildRoot 'build/screenshots'))
}
catch { $failures.Add('离屏渲染失败,见 build/logs/check-render.log'); Write-Host "!! $($failures[-1])" }
Complete-BuildStep
Start-BuildStep '产物检查'
$packageCount = @(Get-ChildItem 'dist' -Filter "GC-$script:BuildVersion-*.zip" -ErrorAction SilentlyContinue).Count
if ($packageCount -lt 3) {
$failures.Add("产物不足 3 个(当前 $packageCount)")
Write-Host "!! $($failures[-1])"
}
Complete-BuildStep
}
finally { Complete-BuildProgress }
if ($failures.Count -eq 0) { Write-Host '==> 全部通过'; return }
Write-Host '==> 有失败项'
throw ($failures -join "`n")
}
-28
View File
@@ -1,28 +0,0 @@
function Invoke-BuildTool {
param([Parameter(Mandatory)][string]$Name)
switch ($Name) {
'models' { Build-Models }
'stamp' { Invoke-VersionStamp }
'pack-models' { Build-Models; Pack-Models }
'pack-launcher'{ Pack-Launcher }
'run' { & dotnet run --project $script:AppProject -c Debug; if ($LASTEXITCODE -ne 0) { throw "dotnet run 失败,退出码 $LASTEXITCODE" } }
'test' { & dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots'); if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" } }
'update-test' { & dotnet run --project $script:TestProject -c Debug -- --update-test $script:BuildRoot; if ($LASTEXITCODE -ne 0) { throw "更新测试失败,退出码 $LASTEXITCODE" } }
'clean' {
Remove-Item (Join-Path $script:BuildRoot 'build'), (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
foreach ($projectRoot in @('GC', 'GC-BOOT', 'GC-DRAW', 'model')) {
$path = Join-Path $script:BuildRoot $projectRoot
if (Test-Path $path) {
Get-ChildItem $path -Directory -Recurse -Force | Where-Object Name -in @('bin', 'obj') | Sort-Object FullName -Descending | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
}
Write-Host '==> 已清理'
}
'doctor' { & dotnet --info | Select-Object -First 20; if ($LASTEXITCODE -ne 0) { throw "dotnet --info 失败,退出码 $LASTEXITCODE" } }
'dist' {
Write-Host '==> dist 产物:'
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -ErrorAction SilentlyContinue | Select-Object Name, Length
}
default { throw "未知任务:$Name" }
}
}
-47
View File
@@ -1,47 +0,0 @@
param(
[Parameter(Position = 0)]
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
'run','test','update-test','clean','doctor','dist')]
[string]$Task = 'build',
[string]$Version = ''
)
$ErrorActionPreference = 'Stop'
$script:BuildRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
$script:AppProject = 'GC-BOOT/GC-BOOT.csproj'
$script:PreviewProject = 'model/_engine/PreviewGen/PreviewGen.csproj'
$script:StampProject = 'model/_engine/VersionStamp/VersionStamp.csproj'
$script:TestProject = 'GC/src/test/dotnet/GC.Tests/GC.Tests.csproj'
$script:Solution = 'GC.sln'
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
Push-Location $script:BuildRoot
try {
$props = [xml](Get-Content 'Directory.Build.props' -Raw)
$versionNode = $props.SelectSingleNode('/Project/PropertyGroup/Version')
if (-not $Version) { $Version = $versionNode.InnerText }
if (-not $Version) { $Version = '1.0.0' }
$script:BuildVersion = $Version
if ($PSBoundParameters.ContainsKey('Version')) {
if ($null -eq $versionNode) { throw 'Directory.Build.props 中找不到 Version 节点。' }
$versionNode.InnerText = $Version
$props.Save((Join-Path $script:BuildRoot 'Directory.Build.props'))
Write-Host "==> 版本号设为 $Version"
}
New-Item -ItemType Directory -Force -Path 'build/logs' | Out-Null
. (Join-Path $PSScriptRoot 'lib/Progress.ps1')
. (Join-Path $PSScriptRoot 'lib/Build-Funcs.ps1')
. (Join-Path $PSScriptRoot 'Build-Check.ps1')
. (Join-Path $PSScriptRoot 'Build-Tools.ps1')
switch ($Task) {
'build' { Invoke-FullBuild }
'check' { Invoke-BuildCheck }
default { Invoke-BuildTool $Task }
}
}
finally {
Pop-Location
}
-343
View File
@@ -1,343 +0,0 @@
function Invoke-LoggedDotNet {
param(
[Parameter(Mandatory)][string]$Name,
[Parameter(Mandatory)][string[]]$Arguments
)
$logPath = Join-Path $script:BuildRoot "build/logs/$Name.log"
& dotnet @Arguments *> $logPath
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
Get-Content $logPath | Write-Host
throw "dotnet $($Arguments -join ' ') 失败,退出码 $exitCode;日志:$logPath"
}
}
function Invoke-ManifestSign {
$key = Join-Path $script:BuildRoot '.signing/gc-signing.pem'
if (-not (Test-Path $key)) {
Write-Host '!! 未找到签名私钥 .signing/gc-signing.pem,version.json 未签名(客户端会拒绝更新)'
return
}
$keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-11' }
Write-Host "==> 签名 version.json ($keyId)"
Invoke-LoggedDotNet -Name 'sign' -Arguments @(
'run', '--project', (Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'),
'-c', 'Release', '--', 'sign',
'--manifest', (Join-Path $script:BuildRoot 'version.json'),
'--key', $key, '--key-id', $keyId
)
Copy-Item (Join-Path $script:BuildRoot 'version.json') (Join-Path $script:BuildRoot 'model/version.json') -Force
}
function Invoke-VersionStamp {
param([switch]$LauncherOnly)
if ($LauncherOnly) {
Write-Host '==> 刷新启动器包信息(sha256 / 体积 / dist 路径)'
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
'run', '--project', $script:StampProject, '-c', 'Release', '--',
$script:BuildRoot, $script:BuildVersion, '--launcher-only'
)
}
else {
Write-Host '==> 自动计算模型版本并生成 version.json'
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
'run', '--project', $script:StampProject, '-c', 'Release', '--',
$script:BuildRoot, $script:BuildVersion
)
}
Invoke-ManifestSign
}
function Build-Models {
Write-Host '==> 编译模型功能程序集(源码位于各模型目录的 src/)'
Get-ChildItem (Join-Path $script:BuildRoot 'model') -Directory | ForEach-Object {
$modelId = $_.Name
$sourceDir = Join-Path $_.FullName 'src'
if (-not (Test-Path $sourceDir)) { return }
$project = Get-ChildItem $sourceDir -Filter '*.csproj' | Select-Object -First 1
if ($null -eq $project) { return }
Invoke-LoggedDotNet -Name "model-$modelId" -Arguments @('build', $project.FullName, '-c', 'Release')
$packageDir = Join-Path $_.FullName "$modelId.model"
$outputDir = Join-Path $sourceDir 'bin/Release/net8.0'
if (Test-Path $packageDir) {
Get-ChildItem $outputDir -Filter '*.dll' -ErrorAction SilentlyContinue | Where-Object Name -ne 'GC.ModelSdk.dll' | ForEach-Object {
Copy-Item $_.FullName (Join-Path $packageDir $_.Name) -Force
Write-Host " -> model/$modelId/$modelId.model/$($_.Name)"
}
}
}
Write-Host '==> 用模型自己的渲染器生成封面'
Invoke-LoggedDotNet -Name 'preview' -Arguments @('run', '--project', $script:PreviewProject, '-c', 'Release', '--', $script:BuildRoot)
Invoke-VersionStamp
}
function Prepare-RuntimeLayout {
param([Parameter(Mandatory)][string]$RelativePath)
$destination = Join-Path $script:BuildRoot $RelativePath
if (-not (Test-Path $destination)) { return }
Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples') -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path (Join-Path $destination '.GC/model'), (Join-Path $destination '.GC/cache'), (Join-Path $destination '.GC/update'), (Join-Path $destination '.GC/config') | Out-Null
Set-Content -Path (Join-Path $destination '.GC/model/README.txt') -Encoding UTF8 -Value @'
模型库目录(.GC/model/)
启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚)
.GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置)
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
'@
$settingsPath = Join-Path $destination '.GC/config/settings.json'
if (-not (Test-Path $settingsPath)) {
Set-Content -Path $settingsPath -Encoding UTF8 -Value @'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"requireSignedManifest": true,
"updateRepository": "https://gitcode.com/Morris_1/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
}
'@
}
Write-Host " 运行目录 -> $RelativePath/.GC"
}
function Publish-Rid {
param(
[Parameter(Mandatory)][string]$Rid,
[Parameter(Mandatory)][string]$Output,
[bool]$SingleFile = $true
)
$outputPath = Join-Path $script:BuildRoot $Output
Remove-Item $outputPath -Recurse -Force -ErrorAction SilentlyContinue
$singleValue = $SingleFile.ToString().ToLowerInvariant()
Write-Host "==> 编译 $Rid (single-file=$singleValue) -> $Output"
Invoke-LoggedDotNet -Name "publish-$($Rid -replace '-', '')" -Arguments @(
'publish', $script:AppProject, '-c', 'Release', '-r', $Rid,
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
"-p:PublishSingleFile=$singleValue", "-p:IncludeNativeLibrariesForSelfExtract=$singleValue",
'-p:PublishTrimmed=false', '-o', $outputPath
)
# 更新守护进程:与主程序同目录(裁剪单文件,70MB -> 14MB)
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)
$savedogProj = Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'
if (Test-Path $savedogProj) {
Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪单文件)"
Invoke-LoggedDotNet -Name "savedog-$($Rid -replace '-', '')" -Arguments @(
'publish', $savedogProj, '-c', 'Release', '-r', $Rid,
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
'-p:PublishSingleFile=true', '-p:IncludeNativeLibrariesForSelfExtract=true',
'-p:PublishTrimmed=true', '-p:TrimMode=full',
'-p:JsonSerializerIsReflectionEnabledByDefault=false', '-o', $outputPath
)
}
Remove-Item (Join-Path $outputPath 'model'), (Join-Path $outputPath 'examples') -Recurse -Force -ErrorAction SilentlyContinue
}
function Pack-Models {
$zipPath = Join-Path $script:BuildRoot "dist/models-$script:BuildVersion.zip"
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
Write-Host "==> 打包模型数据 -> dist/models-$script:BuildVersion.zip"
Add-Type -AssemblyName System.IO.Compression.FileSystem
$modelRoot = Join-Path $script:BuildRoot 'model'
$archive = [System.IO.Compression.ZipFile]::Open($zipPath, [System.IO.Compression.ZipArchiveMode]::Create)
try {
Get-ChildItem $modelRoot -File -Recurse | Where-Object {
$relativePath = $_.FullName.Substring($modelRoot.Length).TrimStart([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar).Replace('\', '/')
$_.Name -ne '.DS_Store' -and
$_.Extension -ne '.user' -and
$relativePath -notmatch '(^|/)(bin|obj)/'
} | ForEach-Object {
$relativePath = $_.FullName.Substring($modelRoot.Length).TrimStart([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar).Replace('\', '/')
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile(
$archive, $_.FullName, "model/$relativePath", [System.IO.Compression.CompressionLevel]::Optimal
) | Out-Null
}
}
finally { $archive.Dispose() }
Get-Item $zipPath | Select-Object Name, Length
}
function Pack-Launcher {
$dist = Join-Path $script:BuildRoot 'dist'
Write-Host "==> 生成启动器产物(GC-$script:BuildVersion-<平台>)"
foreach ($platform in @(@{ Rid = 'win-x64'; Label = 'win-amd64' }, @{ Rid = 'win-arm64'; Label = 'win-arm64' })) {
# 产物落点 dist/<系统>-<架构>/,与 dist/mac-arm64 一致
$sourceDir = Join-Path $dist $platform.Label
if (-not (Test-Path $sourceDir)) { $sourceDir = Join-Path $dist $platform.Rid }
if (-not (Test-Path $sourceDir)) { continue }
# 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面
$executable = Get-ChildItem $sourceDir -Filter '*.exe' |
Where-Object { $_.Name -notlike 'GC-SAVEDOG*' } | Select-Object -First 1
if ($null -eq $executable) { continue }
$temp = Join-Path $dist ".winpkg-$($platform.Label)"
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $temp | Out-Null
Copy-Item $executable.FullName (Join-Path $temp "GC-$script:BuildVersion-$($platform.Label).exe") -Force
$savedogExe = Join-Path $sourceDir 'GC-SAVEDOG.exe'
if (Test-Path $savedogExe) { Copy-Item $savedogExe (Join-Path $temp 'GC-SAVEDOG.exe') -Force }
$zipPath = Join-Path $dist "$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
Compress-Archive -Path (Join-Path $temp '*') -DestinationPath $zipPath -CompressionLevel Optimal
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
Write-Host " -> dist/$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
}
$macApp = Join-Path $dist 'mac-arm64/GC.app'
if (Test-Path $macApp) {
$finalApp = Join-Path $dist "GC-$script:BuildVersion-mac-arm64.app"
Remove-Item $finalApp -Recurse -Force -ErrorAction SilentlyContinue
Move-Item $macApp $finalApp
$binary = Join-Path $finalApp 'Contents/MacOS/GC'
if ((Test-Path $binary) -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod +x $binary }
$plist = Join-Path $finalApp 'Contents/Info.plist'
if ((Test-Path $plist) -and (Test-Path '/usr/libexec/PlistBuddy')) {
& /usr/libexec/PlistBuddy -c 'Set :CFBundleName Morris GC' $plist 2>$null
& /usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Morris GC' $plist 2>$null
}
if (Get-Command xattr -ErrorAction SilentlyContinue) { & xattr -cr $finalApp 2>$null }
}
# Windows 的 zip 已在上面的循环里生成(含 GC-SAVEDOG.exe),这里只处理 .app
Get-ChildItem $dist | Where-Object { $_.Name -like "GC-$script:BuildVersion-*.app" } | ForEach-Object {
$label = $_.BaseName -replace "^GC-$([regex]::Escape($script:BuildVersion))-", ''
$targetDir = Join-Path $dist $label
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
$zipPath = Join-Path $targetDir ($_.BaseName + '.zip')
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
if ($_.PSIsContainer) {
Remove-Item (Join-Path $_.FullName 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
}
if ($_.PSIsContainer -and (Get-Command ditto -ErrorAction SilentlyContinue)) {
& ditto -c -k --sequesterRsrc --keepParent $_.FullName $zipPath
if ($LASTEXITCODE -ne 0) { throw "ditto 压缩失败:$($_.Name)" }
}
else {
Compress-Archive -Path $_.FullName -DestinationPath $zipPath -CompressionLevel Optimal
}
Write-Host " -> dist/$label/$($_.BaseName).zip"
}
# 原始产物(.exe / .app 目录)不再保留:只发布 zip
$trash = Join-Path $script:BuildRoot 'build/trash'
New-Item -ItemType Directory -Force -Path $trash | Out-Null
Get-ChildItem $dist -Force | Where-Object {
$_.Name -like "GC-$script:BuildVersion-*.exe" -or $_.Name -like "GC-$script:BuildVersion-*.app"
} | ForEach-Object {
Move-Item $_.FullName (Join-Path $trash "$($_.Name)-$([DateTime]::Now.Ticks)") -Force -ErrorAction SilentlyContinue
}
Remove-IntermediateDirectories
Invoke-VersionStamp -LauncherOnly
Write-Host '==> dist 可发布 zip:'
Get-ChildItem $dist -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
}
function Remove-IntermediateDirectories {
# 平台目录里只留最终 zip(其它都是 publish 中间产物)
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64')) {
$dir = Join-Path $script:BuildRoot "dist/$name"
if (-not (Test-Path $dir)) { continue }
Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GC-$script:BuildVersion-*.zip" } |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter '.DS_Store' -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force
}
function New-MacAppBundle {
$dist = Join-Path $script:BuildRoot 'dist/mac-arm64'
$app = Join-Path $dist 'GC.app'
Remove-Item $app -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path (Join-Path $app 'Contents/MacOS'), (Join-Path $app 'Contents/Resources') | Out-Null
$plist = @"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleName</key><string>GC</string>
<key>CFBundleDisplayName</key><string>GC</string>
<key>CFBundleIdentifier</key><string>cn.neorf.GC</string>
<key>CFBundleVersion</key><string>$script:BuildVersion</string>
<key>CFBundleShortVersionString</key><string>$script:BuildVersion</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleExecutable</key><string>GC</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
"@
Set-Content -Path (Join-Path $app 'Contents/Info.plist') -Encoding UTF8 -Value $plist
Get-ChildItem $dist -Force | Where-Object Name -notin @('GC.app', '.DS_Store') | Move-Item -Destination (Join-Path $app 'Contents/MacOS')
Remove-Item (Join-Path $app 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
$binary = Join-Path $app 'Contents/MacOS/GC'
if ((Test-Path $binary) -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod +x $binary }
$iconSource = Join-Path $script:BuildRoot 'GC/src/Assets/icon-1024.png'
if ((Test-Path $iconSource) -and (Get-Command iconutil -ErrorAction SilentlyContinue) -and (Get-Command sips -ErrorAction SilentlyContinue)) {
$iconset = Join-Path $dist 'AppIcon.iconset'
Remove-Item $iconset -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $iconset | Out-Null
foreach ($size in @(16, 32, 64, 128, 256, 512)) {
& sips -z $size $size $iconSource --out (Join-Path $iconset "icon_${size}x${size}.png") *> $null
$doubleSize = $size * 2
& sips -z $doubleSize $doubleSize $iconSource --out (Join-Path $iconset "icon_${size}x${size}@2x.png") *> $null
}
$iconFile = Join-Path $app 'Contents/Resources/AppIcon.icns'
& iconutil -c icns $iconset -o $iconFile
if ($LASTEXITCODE -eq 0) {
$infoPlist = Join-Path $app 'Contents/Info.plist'
if (Test-Path '/usr/libexec/PlistBuddy') {
& /usr/libexec/PlistBuddy -c 'Add :CFBundleIconFile string AppIcon' $infoPlist 2>$null
}
}
Remove-Item $iconset -Recurse -Force -ErrorAction SilentlyContinue
}
Write-Host "==> 已打包 $app"
}
function Invoke-FullBuild {
Initialize-BuildProgress @('清理旧产物', '版本戳', '编译 Mac', '编译 Win-x64', '编译 Win-arm64', '运行骨架', '打包 zip', '收尾')
try {
Start-BuildStep '清理旧产物'
Remove-Item (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path (Join-Path $script:BuildRoot 'dist') | Out-Null
Complete-BuildStep
Start-BuildStep '版本戳'; Invoke-VersionStamp; Complete-BuildStep
Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $false; Complete-BuildStep
Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $true; Complete-BuildStep
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $true; Complete-BuildStep
Start-BuildStep '运行骨架'
New-MacAppBundle
Prepare-RuntimeLayout 'dist/win-amd64'
Prepare-RuntimeLayout 'dist/win-arm64'
Prepare-RuntimeLayout 'dist/mac-arm64/GC.app/Contents/MacOS'
Complete-BuildStep
Start-BuildStep '打包 zip'; Pack-Launcher; Complete-BuildStep
Start-BuildStep '收尾'; Complete-BuildStep
Write-Host '==> 完成,产物:'
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
}
finally { Complete-BuildProgress }
}
-27
View File
@@ -1,27 +0,0 @@
$script:ProgressSteps = @()
$script:ProgressIndex = 0
$script:ProgressActivity = 'GC 构建'
function Initialize-BuildProgress {
param([string[]]$Steps)
$script:ProgressSteps = $Steps
$script:ProgressIndex = 0
Write-Progress -Activity $script:ProgressActivity -Status '准备' -PercentComplete 0
}
function Start-BuildStep {
param([string]$Name)
$script:ProgressIndex++
$percent = [math]::Min(99, [int](($script:ProgressIndex - 1) * 100 / [math]::Max(1, $script:ProgressSteps.Count)))
Write-Progress -Activity $script:ProgressActivity -Status $Name -PercentComplete $percent
Write-Host "==> $Name"
}
function Complete-BuildStep {
$percent = [int]($script:ProgressIndex * 100 / [math]::Max(1, $script:ProgressSteps.Count))
Write-Progress -Activity $script:ProgressActivity -Status '进行中' -PercentComplete $percent
}
function Complete-BuildProgress {
Write-Progress -Activity $script:ProgressActivity -Completed
}
-62
View File
@@ -1,62 +0,0 @@
#!/bin/sh
# buildsh/build.sh —— 完整发布(原 publish)
# 步骤及权重按实测耗时设定,供进度条估算总进度与剩余时间:
# 清理(2) 版本(3) Mac(35) WinX64(25) WinArm(25) 骨架(3) 打包(5) 收尾(2) = 100
bs_build() {
ROOT_DIR="$1"
: "${APP_PROJ:?}" "${SLN:?}" "${VERSION:?}"
progress_init 100 2 3 35 25 25 3 5 2
progress_step "清理旧产物"; progress_tick 100
rm -rf "$ROOT_DIR/dist"; mkdir -p "$ROOT_DIR/dist"
# 上次打包挪出来的中间产物(.app 目录,体积大、文件多)直接移出 build,
# 不做递归删除:避免动辄几百个文件的不可逆删除。
if [ -d "$ROOT_DIR/build/trash" ]; then
mv "$ROOT_DIR/build/trash" "${TMPDIR:-/tmp}/gc-trash-$(date +%s)" 2>/dev/null || true
fi
progress_step "版本戳"; progress_tick 100
stamp_versions
# 每个 publish 用后台任务包裹,边跑边按「已用时/预估用时」推进当前步骤进度
_run_publish() {
_label="$1"; _est="$2"; shift 2
( "$@" >"$ROOT_DIR/build/logs/publish-$_label.log" 2>&1 ) &
_pid=$!
_t0=$(date +%s)
while kill -0 "$_pid" 2>/dev/null; do
_elapsed=$(( $(date +%s) - _t0 ))
_p=$(( _elapsed * 100 / _est ))
[ "$_p" -gt 96 ] && _p=96
progress_tick "$_p"
sleep 1
done
wait "$_pid" || { echo; echo "!! $_label 编译失败,见 build/logs/publish-$_label.log"; return 1; }
progress_tick 100
}
progress_step "编译 Mac"
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" false || return 1
progress_step "编译 Win-x64"
_run_publish winx64 70 publish_rid "win-x64" "dist/win-amd64" true || return 1
progress_step "编译 Win-arm64"
_run_publish winarm 70 publish_rid "win-arm64" "dist/win-arm64" true || return 1
progress_step "运行骨架"; progress_tick 100
package_mac_app
prepare_runtime_layout "dist/win-amd64"
prepare_runtime_layout "dist/win-arm64"
prepare_runtime_layout "dist/mac-arm64/GC.app/Contents/MacOS"
progress_step "打包 zip"; progress_tick 100
pack_launcher
progress_step "收尾"; progress_tick 100
progress_done
echo "==> 完成,产物:"
ls -lh "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null || true
}
-46
View File
@@ -1,46 +0,0 @@
#!/bin/sh
# buildsh/check.sh —— 验证:编译 + 自检 + 离屏测试 + 产物完整性
# 步骤权重:编译(40) 自检(15) 离屏(25) 产物(20)
bs_check() {
ROOT_DIR="$1"
progress_init 100 40 15 25 20
_fail=0
progress_step "编译检查"
if dotnet build "$SLN" -c Debug -v quiet >"$ROOT_DIR/build/logs/check-build.log" 2>&1; then
progress_tick 100
else
progress_tick 100; _fail=1
echo; echo "!! 编译失败,见 build/logs/check-build.log"
fi
progress_step "模型自检"
if EMS_SELFTEST=1 dotnet run --project "$APP_PROJ" -c Debug --no-build \
>"$ROOT_DIR/build/logs/check-selftest.log" 2>&1; then
grep -q "FAIL" "$ROOT_DIR/build/logs/check-selftest.log" && { _fail=1; echo; echo "!! 自检有失败项"; }
else
_fail=1; echo; echo "!! 自检异常"
fi
progress_tick 100
progress_step "离屏渲染"
if dotnet run --project "$TEST_PROJ" -c Debug --no-build -- \
"$ROOT_DIR/build/screenshots" >"$ROOT_DIR/build/logs/check-render.log" 2>&1; then
progress_tick 100
else
_fail=1; progress_tick 100; echo; echo "!! 离屏渲染失败"
fi
progress_step "产物检查"
_n=$(ls "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null | wc -l | tr -d ' ')
if [ "$_n" -ge 3 ]; then
progress_tick 100
else
_fail=1; progress_tick 100; echo; echo "!! 产物不足 3 个(当前 $_n)"
fi
progress_done
[ "$_fail" -eq 0 ] && echo "==> 全部通过" || echo "==> 有失败项"
return "$_fail"
}
-329
View File
@@ -1,329 +0,0 @@
#!/bin/sh
# buildsh/lib/build_funcs.sh —— 构建函数库(由入口脚本 source)
# 依赖调用方提供:ROOT_DIR, APP_PROJ, PREVIEW_PROJ, STAMP_PROJ, TEST_PROJ, SLN, VERSION
# 以及任务进度上报函数 step / progress(由进度条引擎提供,未定义时降级为 echo)
if ! type step >/dev/null 2>&1; then step() { echo "==> $1"; }; fi
if ! type progress >/dev/null 2>&1; then progress() { :; }; fi
stamp_versions() {
echo "==> 自动计算模型版本并生成 version.json"
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
sign_manifest
}
# 打完 zip 之后刷新 launcher.packages(写入 path / dir / name / sha256 / size)。
# 只重写清单的启动器段:模型指纹可能涉及几百 MB 文件,没必要再算一遍。
stamp_launcher_only() {
echo "==> 刷新启动器包信息(sha256 / 体积 / dist 路径)"
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION" --launcher-only
sign_manifest
}
# 用 .signing/ 里的私钥给 version.json 签名(私钥不入库)。
# 没有私钥时只警告:清单不带 signature,客户端会按「未签名」处理。
sign_manifest() {
KEY="$ROOT_DIR/.signing/gc-signing.pem"
KEYID="${GC_SIGNING_KEY_ID:-gc-2026-11}"
if [ ! -f "$KEY" ]; then
echo "!! 未找到签名私钥 ${KEY},本次 version.json 未签名(客户端会拒绝更新)"
echo " 生成密钥:dotnet run --project GC-SAVEDOG -- keygen"
return 0
fi
echo "==> 签名 version.json(${KEYID})"
if dotnet run --project "$ROOT_DIR/GC-SAVEDOG/GC-SAVEDOG.csproj" -c Release -- \
sign --manifest "$ROOT_DIR/version.json" --key "$KEY" --key-id "$KEYID"; then
# model/version.json 必须与根清单完全一致(同一个签名),否则走 model 地址的源会验签失败
cp "$ROOT_DIR/version.json" "$ROOT_DIR/model/version.json"
else
echo "!! 签名失败,version.json 保持未签名状态"
return 1
fi
}
# 编译模型自己的功能程序集,并把 dll / 封面直接写进模型包
build_models() {
echo "==> 编译模型功能程序集(源码就在各模型目录的 src/ 里)"
for DIR in "$ROOT_DIR"/model/*/; do
ID=$(basename "$DIR")
[ -d "$DIR/src" ] || continue
PROJ=$(ls "$DIR"src/*.csproj 2>/dev/null | head -1)
[ -n "$PROJ" ] || continue
dotnet build "$PROJ" -c Release
if [ -d "$DIR$ID.model" ]; then
for DLL in "$DIR"src/bin/Release/net8.0/*.dll; do
[ -f "$DLL" ] || continue
NAME=$(basename "$DLL")
[ "$NAME" = "GC.ModelSdk.dll" ] && continue
cp "$DLL" "$DIR$ID.model/"
echo " -> model/$ID/$ID.model/$NAME"
done
fi
done
echo "==> 用模型自己的渲染器生成封面"
dotnet run --project "$PREVIEW_PROJ" -c Release -- "$ROOT_DIR"
stamp_versions
}
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
prepare_runtime_layout() {
REL="$1"
DEST="$ROOT_DIR/$REL"
[ -d "$DEST" ] || return 0
rm -rf "$DEST/model" "$DEST/examples"
mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update" "$DEST/.GC/config"
cat > "$DEST/.GC/model/README.txt" <<'TXT'
模型库目录(.GC/model/)
启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚)
.GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置)
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
TXT
if [ ! -f "$DEST/.GC/config/settings.json" ]; then
cat > "$DEST/.GC/config/settings.json" <<'JSON'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"requireSignedManifest": true,
"updateRepository": "https://gitcode.com/Morris_1/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
}
JSON
fi
echo " 运行目录 -> $REL/.GC (config/settings.json + model/ + cache/ + update/)"
}
# $1=RID $2=输出目录 $3=singlefile(true/false)
publish_rid() {
RID="$1"; OUT="$2"; SINGLE="${3:-true}"
echo ""
echo "==> 编译 ${RID} (single-file=${SINGLE}) -> ${OUT}"
# 先删旧产物,避免上次 publish 的残留文件混进新包
rm -rf "$ROOT_DIR/$OUT"
dotnet publish "$APP_PROJ" \
-c Release \
-r "$RID" \
--self-contained true \
-p:Version="$VERSION" \
-p:DebugType=none \
-p:PublishSingleFile="$SINGLE" \
-p:IncludeNativeLibrariesForSelfExtract="$SINGLE" \
-p:PublishTrimmed=false \
-o "$ROOT_DIR/$OUT"
# 更新守护进程:与主程序同目录(macOS 打包时会被一起移入 Contents/MacOS)
if [ -n "${SAVEDOG_PROJ:-}" ] && [ -f "$ROOT_DIR/$SAVEDOG_PROJ" ]; then
echo "==> 编译 GC-SAVEDOG (${RID}) -> ${OUT}(裁剪单文件)"
# 守护进程不引用 Avalonia,可以安全裁剪:70MB -> 14MB。
# 前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs),新增 JSON 类型
# 忘了注册只会在发布产物里炸,所以 update-test 会跑一次真实 apply 兜底。
dotnet publish "$SAVEDOG_PROJ" \
-c Release \
-r "$RID" \
--self-contained true \
-p:Version="$VERSION" \
-p:DebugType=none \
-p:PublishSingleFile=true \
-p:IncludeNativeLibrariesForSelfExtract=true \
-p:PublishTrimmed=true \
-p:TrimMode=full \
-p:JsonSerializerIsReflectionEnabledByDefault=false \
-o "$ROOT_DIR/$OUT"
fi
rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples"
}
# 把 model/ 里的模型数据单独打包(与启动器分开分发)
pack_models() {
mkdir -p "$ROOT_DIR/dist"
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
rm -f "$ZIP"
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
( cd "$ROOT_DIR" && zip -qr "$ZIP" model \
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
du -sh "$ZIP"
}
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户已下载的模型与设置)
#
# 产物落点遵循「仓库 dist/<系统>-<架构>/」布局:
# dist/mac-arm64/GC-<版本>-mac-arm64.zip
# dist/win-amd64/GC-<版本>-win-amd64.zip
# dist/win-arm64/GC-<版本>-win-arm64.zip
# 启动器更新时既可以从 Release 附件下载,也会到这些目录里找编译产物
# (见 GC-DOWNLOAD/LauncherArtifacts.cs),所以两种发布方式都能用。
#
# Windows: 单文件 exe 直接改名(本身就是可执行产物)
# macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip,
# 这样 macOS 双击会用归档工具解压出可运行的 .app。
# 若直接命名 .app,系统会把 zip 当成应用包解析 => 报「已损坏/打不开」。
pack_launcher() {
echo "==> 生成启动器产物(GC-<版本>-<系统>-<架构>)"
# --- Windows:exe 单文件(连同 GC-SAVEDOG.exe 一起打进 zip)---
for pair in "win-x64:win-amd64" "win-arm64:win-arm64"; do
RID="${pair%%:*}"; LABEL="${pair##*:}"
SRC="$ROOT_DIR/dist/$LABEL"
[ -d "$SRC" ] || SRC="$ROOT_DIR/dist/$RID" # 兼容旧布局
[ -d "$SRC" ] || continue
# 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面
EXE=$(ls "$SRC"/*.exe 2>/dev/null | grep -v 'GC-SAVEDOG' | head -1)
[ -n "$EXE" ] || continue
TMP="$ROOT_DIR/dist/.winpkg-$LABEL"
rm -rf "$TMP"; mkdir -p "$TMP"
cp "$EXE" "$TMP/GC-${VERSION}-${LABEL}.exe"
chmod +x "$TMP/GC-${VERSION}-${LABEL}.exe" 2>/dev/null || true
if [ -f "$SRC/GC-SAVEDOG.exe" ]; then
cp "$SRC/GC-SAVEDOG.exe" "$TMP/GC-SAVEDOG.exe"
else
echo " !! 缺少 GC-SAVEDOG.exe,该平台将退回旧脚本更新"
fi
ZIP="$ROOT_DIR/dist/$LABEL/GC-${VERSION}-${LABEL}.zip"
rm -f "$ZIP"
( cd "$TMP" && zip -q "$ZIP" ./* )
rm -rf "$TMP"
echo " -> dist/$LABEL/GC-${VERSION}-${LABEL}.zip"
done
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist)---
MACAPP="$ROOT_DIR/dist/mac-arm64/GC.app"
if [ -d "$MACAPP" ]; then
FINAL="$ROOT_DIR/dist/GC-${VERSION}-mac-arm64.app"
rm -rf "$FINAL"
mv "$MACAPP" "$FINAL"
chmod +x "$FINAL/Contents/MacOS/GC" 2>/dev/null || true
PLIST="$FINAL/Contents/Info.plist"
if [ -f "$PLIST" ]; then
/usr/libexec/PlistBuddy -c "Set :CFBundleName Morris GC" "$PLIST" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName Morris GC" "$PLIST" 2>/dev/null || true
fi
xattr -cr "$FINAL" 2>/dev/null || true
echo " -> $(basename "$FINAL")/"
fi
# --- 统一压缩:每个产物都打成同名 .zip,放进自己的平台目录 ---
# GC-1.0.3-mac-arm64.app -> dist/mac-arm64/GC-1.0.3-mac-arm64.zip
# 客户端下载时按「原名去掉扩展名 + .zip」取包,再解压回原名。
echo "==> 压缩为 zip"
for art in "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe "$ROOT_DIR"/dist/GC-"$VERSION"-*.app; do
[ -e "$art" ] || continue
base=$(basename "$art")
name="${base%.*}" # 去掉 .exe / .app
label="${name#GC-${VERSION}-}" # mac-arm64 / win-amd64
ZIP="$ROOT_DIR/dist/${label}/${name}.zip"
mkdir -p "$ROOT_DIR/dist/${label}"
rm -f "$ZIP"
if [ -d "$art" ]; then
# 目录(.app):保留权限与符号链接
if command -v ditto >/dev/null 2>&1; then
ditto -c -k --sequesterRsrc --keepParent "$art" "$ZIP"
else
( cd "$(dirname "$art")" && zip -qry "$ZIP" "$base" -x "*.DS_Store" )
fi
else
( cd "$(dirname "$art")" && zip -q "$ZIP" "$base" )
fi
echo " -> dist/${label}/${name}.zip"
done
# 原始产物(.exe / .app 目录)不再保留:只发布 zip。
# 用「移入暂存区」而不是 rm -rf:.app 里有两百多个文件,
# 一次性删除又慢又不可逆,先挪走更安全(暂存区在下次构建开始时挪出 dist)。
TRASH="$ROOT_DIR/build/trash"
mkdir -p "$TRASH"
for leftover in "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe "$ROOT_DIR"/dist/GC-"$VERSION"-*.app; do
[ -e "$leftover" ] || continue
mv "$leftover" "$TRASH/$(basename "$leftover")-$(date +%s)" 2>/dev/null || true
done
strip_intermediate_dirs
stamp_launcher_only
echo ""
echo "==> dist 里可发布的 zip:"
ls -lh "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null || true
}
# 删除 publish 过程中的中间目录:平台目录里只留最终 zip
strip_intermediate_dirs() {
for d in win-amd64 win-x64 win-arm64 mac-arm64; do
[ -d "$ROOT_DIR/dist/$d" ] || continue
find "$ROOT_DIR/dist/$d" -mindepth 1 -maxdepth 1 \
! -name "GC-${VERSION}-*.zip" -exec rm -rf {} + 2>/dev/null || true
done
find "$ROOT_DIR/dist" -name ".DS_Store" -delete 2>/dev/null || true
}
package_mac_app() {
DIST="$ROOT_DIR/dist/mac-arm64"
APP="$DIST/GC.app"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cat > "$APP/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key><string>GC</string>
<key>CFBundleDisplayName</key><string>GC</string>
<key>CFBundleIdentifier</key><string>cn.neorf.GC</string>
<key>CFBundleVersion</key><string>${VERSION}</string>
<key>CFBundleShortVersionString</key><string>${VERSION}</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleExecutable</key><string>GC</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST
for f in "$DIST"/*; do
base=$(basename "$f")
[ "$base" = "GC.app" ] && continue
[ "$base" = ".DS_Store" ] && continue
mv "$f" "$APP/Contents/MacOS/"
done
# 应用图标:由 Assets/icon-1024.png 生成 .icns
ICONSRC="$ROOT_DIR/GC/src/Assets/icon-1024.png"
if [ -f "$ICONSRC" ] && command -v iconutil >/dev/null 2>&1; then
ICONSET="$DIST/AppIcon.iconset"
rm -rf "$ICONSET"; mkdir -p "$ICONSET"
for sz in 16 32 64 128 256 512; do
sips -z $sz $sz "$ICONSRC" --out "$ICONSET/icon_${sz}x${sz}.png" >/dev/null 2>&1
d=$((sz * 2))
sips -z $d $d "$ICONSRC" --out "$ICONSET/icon_${sz}x${sz}@2x.png" >/dev/null 2>&1
done
iconutil -c icns "$ICONSET" -o "$APP/Contents/Resources/AppIcon.icns" 2>/dev/null && \
echo " + AppIcon.icns"
rm -rf "$ICONSET"
# Info.plist 增加图标项
if [ -f "$APP/Contents/Info.plist" ]; then
/usr/libexec/PlistBuddy -c "Delete :CFBundleIconFile" "$APP/Contents/Info.plist" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Add :CFBundleIconFile string AppIcon" "$APP/Contents/Info.plist" 2>/dev/null || true
fi
fi
# 发布包不带 .GC 运行骨架(用户首次启动自行创建),避免覆盖用户数据
rm -rf "$APP/Contents/MacOS/.GC"
chmod +x "$APP/Contents/MacOS/GC"
echo "==> 已打包 $APP"
}
-100
View File
@@ -1,100 +0,0 @@
#!/bin/sh
# buildsh/lib/progress.sh —— apt 风格底部实时进度条
#
# 底部一行:任务 当前任务进度 总进度 剩余时间
# 编译MacOS 95% 30% 10s
#
# 用法:
# progress_init <总步骤数> <每步权重...>
# progress_step <步骤名> # 开始某步骤
# progress_tick <0-100> # 更新当前步骤完成度
# progress_done # 结束
PROGRESS_TOTAL=1
PROGRESS_WEIGHTS=""
PROGRESS_IDX=0
PROGRESS_CUR=0
PROGRESS_STARTED=0
PROGRESS_LAST=0
PROGRESS_HISTORY=""
_now() { date +%s; }
# 加权总进度:前序步骤权重之和 + 当前步骤权重*完成度
_progress_overall() {
_sum=0; _i=1
for _w in $PROGRESS_WEIGHTS; do
if [ "$_i" -lt "$PROGRESS_IDX" ]; then
_sum=$((_sum + _w)) # 已完成的步骤:全额
elif [ "$_i" -eq "$PROGRESS_IDX" ]; then
_sum=$((_sum + _w * PROGRESS_CUR / 100)) # 当前步骤:按完成度
fi
_i=$((_i + 1))
done
_p=$((_sum * 100 / PROGRESS_TOTAL))
[ "$_p" -gt 100 ] && _p=100
echo "$_p"
}
# 剩余时间:基于「已完成总进度 / 已用时间」线性外推
_progress_eta() {
_p=$(_progress_overall)
_t=$(( $(_now) - PROGRESS_STARTED ))
# 前期用「预估总时长」估算(按各步骤经验权重),后期用实测速率外推,更稳
if [ "$_p" -le 3 ] || [ "$_t" -le 0 ]; then
_eta=$(( PROGRESS_TOTAL * 8 / 100 )) # 粗估:每 1% 约 8 秒 -> 总约 800s? 见下
_eta=$(( 240 )) # 默认预估 4 分钟
else
_eta=$(( _t * (100 - _p) / _p ))
fi
if [ "$_eta" -ge 60 ]; then echo "$(( _eta / 60 ))m$((_eta % 60))s"; else echo "${_eta}s"; fi
}
progress_draw() {
_task="$PROGRESS_TASK"
_cur=$PROGRESS_CUR
_overall=$(_progress_overall)
_eta=$(_progress_eta)
# 进度条(20 格)
_filled=$((_overall * 20 / 100))
_bar=""
_i=0
while [ "$_i" -lt 20 ]; do
if [ "$_i" -lt "$_filled" ]; then _bar="${_bar}#"; else _bar="${_bar}."; fi
_i=$((_i + 1))
done
# 底部一行:任务 当前任务进度 总进度 剩余时间
printf '\r\033[K[%s] %-14s %3d%% %3d%% %s' \
"$_bar" "$_task" "$_cur" "$_overall" "$_eta"
}
progress_init() {
PROGRESS_TOTAL=$1
shift
PROGRESS_WEIGHTS="$*"
PROGRESS_IDX=0
PROGRESS_CUR=0
PROGRESS_STARTED=$(_now)
PROGRESS_TASK="准备"
progress_draw
}
progress_step() {
PROGRESS_TASK="$1"
PROGRESS_CUR=0
PROGRESS_IDX=$((PROGRESS_IDX + 1))
progress_draw
}
progress_tick() {
PROGRESS_CUR=$1
progress_draw
}
progress_done() {
PROGRESS_CUR=100
progress_tick 100
printf '\n'
}
-33
View File
@@ -1,33 +0,0 @@
#!/bin/sh
# buildsh/tools.sh —— 实用工具:模型、版本戳、清理、运行、医生、打开目录
bs_tools() {
ROOT_DIR="$1"; TASK="$2"
case "$TASK" in
models)
build_models ;;
stamp)
stamp_versions ;;
pack-models)
build_models; pack_models ;;
pack-launcher)
pack_launcher ;;
run)
dotnet run --project "$APP_PROJ" -c Debug ;;
test)
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots" ;;
update-test)
dotnet run --project "$TEST_PROJ" -c Debug -- --update-test "$ROOT_DIR" ;;
clean)
rm -rf "$ROOT_DIR/build" "$ROOT_DIR/dist"
find "$ROOT_DIR/src" -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + 2>/dev/null || true
echo "==> 已清理" ;;
doctor)
dotnet --info | head -20 ;;
dist)
echo "==> dist 产物:"
ls -lh "$ROOT_DIR"/dist/*/GC-*.zip 2>/dev/null || ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;;
*)
echo "未知工具: $TASK"; return 1 ;;
esac
}
+21 -58
View File
@@ -5,7 +5,7 @@
> 模型相关的一切都在 `model/` 里:共享引擎源码 `model/_engine/`、契约源码 `model/_sdk/`、 > 模型相关的一切都在 `model/` 里:共享引擎源码 `model/_engine/`、契约源码 `model/_sdk/`、
> 每个模型自己的源码 `model/<id>/src/`,编译产物与数据 `model/<id>/<id>.model/`。 > 每个模型自己的源码 `model/<id>/src/`,编译产物与数据 `model/<id>/<id>.model/`。
> 仓库根还包含 `GC-DOWNLOAD/` 下载更新项目;这里的 `model/` 仍独立保存模型源码与可分发内容。 > 仓库根目录只有 `src/`(启动器)和 `model/`,没有任何旁路目录。
- 发布态模型库在 **`<可执行文件>/.GC/model/`**;开发态直接用仓库根 `model/` - 发布态模型库在 **`<可执行文件>/.GC/model/`**;开发态直接用仓库根 `model/`
- 优先级:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 发布态 `.GC/model/` - 优先级:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 发布态 `.GC/model/`
@@ -17,11 +17,11 @@
``` ```
model/ model/
version.json # 版本清单(与仓库根 version.json 相同,自动生成) version.json # 版本清单(与仓库根 version.json 相同,自动生成)
_sdk/GC.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码) _sdk/EarthModelStudio.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码)
_engine/ # 共享引擎源码 _engine/ # 共享引擎源码
src/ # CelestialView / PlanetTexture / EarthModelView / SphereRaster… src/ # CelestialView / PlanetTexture / EarthModelView / SphereRaster…
PreviewGen/ # 用模型渲染器生成封面的小工具 PreviewGen/ # 用模型渲染器生成封面的小工具
VersionStamp/ # 生成 version.json(手写版本 + 完整性哈希) VersionStamp/ # 按内容指纹自动打版本、生成 version.json
<模型 id>/ <模型 id>/
<模型 id>.json # 清单:名称、i18n、版本、程序集入口、封面 <模型 id>.json # 清单:名称、i18n、版本、程序集入口、封面
src/ # 模型自己的源码(csproj + IModelFactory 实现) src/ # 模型自己的源码(csproj + IModelFactory 实现)
@@ -34,34 +34,22 @@ model/
i18n/en.json i18n/en.json
``` ```
## 版本、指纹与完整性 ## 版本是自动改的
`./build.sh models`(或 `./build.sh stamp`)会调用 `model/_engine/VersionStamp`: `./build.sh models`(或 `./build.sh stamp`)会调用 `model/_engine/VersionStamp`:
1. 读每个模型的 `<id>.json`,**保留作者手写的 `version`**(如 `1.6`)—— 1. 对每个模型,把 `<id>.json`(去掉 `version` / `updatedAt`)与 `<id>.model/` 下所有文件
版本号是对用户可见的语义版本,不由指纹自动覆盖; 按路径排序做 SHA-256 指纹,得到版本号 `1.0-<10位指纹>`;
2. 计算 `build`:`<id>.json`(去掉 `build` / `updatedAt`)与 `<id>.model/` 下所有文件 2. 把这个版本写回 `<id>.json` 的 `version` 与 `updatedAt`;
按路径排序后的 SHA-256 指纹前 10 位,**仅用于构建溯源**; 3. 生成仓库根 `version.json` 和 `model/version.json`(内容相同),里面记录
3. 计算完整性哈希(客户端下载后会复算,不一致就丢弃): 启动器版本、各平台更新包地址、每个模型的 id / 版本 / 仓库目录。
- `manifestSha256` = 清单文件本身的 sha256
- `filesSha256` = `<id>.model` 目录指纹
4. 生成仓库根 `version.json` 与 `model/version.json`(内容相同),再用
`.signing/gc-signing.pem` 签名(ECDSA P-256),两份文件写的是**同一份签名**。
**改了模型内容必须手动升 `version`**,否则客户端认为版本没变,不会下载。 **所以只要改了模型文件,版本号就自动变**,不需要手工维护;内容没变时重复构建版本号保持不变。
(`build` 会变,但它不参与版本比较。) 客户端启动时读 `version.json`,和 `.GC/settings.json` 里记录的版本一比对就知道要不要下载。
哈希算法(构建端与客户端共用 `GC/src/Security/ContentHash.cs`,不会出现两套实现): > 改了 `scene.json` 或引擎源码后,跑 `./build.sh models`,再把 `version.json` 和 `model/`
> 推送到 gitcode;客户端下次启动会下载新模型并**本次启动立即生效**。
``` > 启动器自身更新包由 `./build.sh publish` 生成(`dist/GC-<rid>.zip`),下载后**下次启动才应用**。
fileHash = SHA256(文件字节)
dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接 "<相对路径>\0<fileHash>\n" )
```
相对路径统一 `/`,跳过 `.` 开头文件、`bin/`、`obj/`、`*.user`;不含时间戳/权限位。
安装成功后客户端会在模型目录写 `<id>.integrity.json`,每次加载 dll 前抽查
dll / json 的哈希 —— 本地文件被替换会直接拒绝加载。
## `<id>.json`(模型清单,启动器只读它) ## `<id>.json`(模型清单,启动器只读它)
@@ -72,49 +60,28 @@ dll / json 的哈希 —— 本地文件被替换会直接拒绝加载。
"nameI18n": { "zh-CN": "地球自转", "en": "Earth Rotation" }, "nameI18n": { "zh-CN": "地球自转", "en": "Earth Rotation" },
"description": "……", "description": "……",
"descriptionI18n": { "zh-CN": "……", "en": "……" }, "descriptionI18n": { "zh-CN": "……", "en": "……" },
"version": "1.6", "version": "1.0-3f9a2c1b7d",
"updatedAt": "2026-11-14T08:00:00Z", "updatedAt": "2026-11-07T08:00:00Z",
"author": "NeoRF", "author": "NeoRF",
"tags": ["astronomy", "geography"], "tags": ["astronomy", "geography"],
"assembly": "EarthRotationModel.dll", "assembly": "EarthRotationModel.dll",
"type": "NeoRF.EarthModels.RotationModelFactory", "type": "NeoRF.EarthModels.RotationModelFactory",
"preview": "preview.png", "preview": "preview.png",
"apiVersion": 1, "apiVersion": 1
"minAppVersion": "1.0.7"
} }
``` ```
| 字段 | 作用 | | 字段 | 作用 |
| --- | --- | | --- | --- |
| `version` | **作者手写**的语义版本;客户端靠它判断是否需要更新 | | `version` | **自动生成**,模型包内容指纹;客户端靠它判断是否需要更新 |
| `assembly` | 功能程序集文件名,相对 `<id>.model`;留空按 `<id>.dll` 找 | | `assembly` | 功能程序集文件名,相对 `<id>.model`;留空按 `<id>.dll` 找 |
| `type` | 实现 `IModelFactory` 的完整类型名;留空则自动找第一个实现 | | `type` | 实现 `IModelFactory` 的完整类型名;留空则自动找第一个实现 |
| `preview` | 封面图,默认 `preview.png` | | `preview` | 封面图,默认 `preview.png` |
| `apiVersion` | 模型契约版本,目前为 1;高于启动器支持版本会拒绝加载并提示升级 | | `apiVersion` | 模型契约版本,目前为 1 |
| `minAppVersion` | 可选,要求的最低启动器版本(如 `1.0.7`) |
`build` / `manifestSha256` / `filesSha256`(只出现在 `version.json` 里)由构建自动写入,
**不要手改**。
## 最小可分发结构
一个能跑的最小模型只需要三个文件:
```
model/hello/
hello.json # 清单(id / version / assembly / type / apiVersion)
hello.model/
HelloModel.dll # 实现 IModelFactory,返回任意 Avalonia 控件
```
其余(`preview.png`、`i18n/`、`scene.json`、`land.json`)都是可选的:
没有封面用默认灰图,没有语言包用清单里的 `name` / `description`。
源码放在同目录的 `src/` 里,`./build.sh models` 会自动编译并把 dll 复制进 `hello.model/`。
## 模型契约(model/_sdk) ## 模型契约(model/_sdk)
模型只依赖一个极小的契约程序集 `GC.ModelSdk`(源码在 `model/_sdk/`): 模型只依赖一个极小的契约程序集 `EarthModelStudio.ModelSdk`(源码在 `model/_sdk/`):
```csharp ```csharp
public interface IModelFactory public interface IModelFactory
@@ -185,9 +152,5 @@ public interface IModelContext
- **自动更新(推荐)**:把 `version.json` 和 `model/` 推到 gitcode 仓库,启动器开机自检并下载到 `.GC/model/` - **自动更新(推荐)**:把 `version.json` 和 `model/` 推到 gitcode 仓库,启动器开机自检并下载到 `.GC/model/`
- **离线源**:把整个仓库目录(含 `version.json` + `model/`)拷到 U 盘 / 共享盘, - **离线源**:把整个仓库目录(含 `version.json` + `model/`)拷到 U 盘 / 共享盘,
在 `.GC/config/settings.json` 填 `updateLocalRoot` 指向它 在 `.GC/settings.json` 填 `updateLocalRoot` 指向它
- **手动导入**:在「下载」页粘贴任意 git 仓库 / zip / 本地目录,读取其中的 `model/` 文件夹 - **手动导入**:在「下载」页粘贴任意 git 仓库 / zip / 本地目录,读取其中的 `model/` 文件夹
> 三种方式都会**验签**:`version.json` 必须由受信任私钥签名,否则客户端拒绝安装。
> 自己维护分支时,用 `dotnet run --project GC-SAVEDOG -- keygen` 生成密钥,
> 把公钥加进 `GC/src/Security/SignatureKeyring.cs`,再用 `--sign`/`build.sh stamp` 签名。
+1 -3
View File
@@ -18,12 +18,10 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
<!-- 通用封面路径会渲染模型自带的 UserControl,headless 下需要主题样式才会出内容 -->
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\_sdk\GC.ModelSdk\GC.ModelSdk.csproj" /> <ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+48 -227
View File
@@ -1,44 +1,24 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Headless; using Avalonia.Headless;
using Avalonia.Media.Imaging; using Avalonia.Media.Imaging;
using Avalonia.Platform;
using GC.ModelSdk;
using NeoRF.EarthModels; using NeoRF.EarthModels;
namespace NeoRF.EarthModels.Preview; namespace NeoRF.EarthModels.Preview;
/// <summary> /// <summary>
/// 封面生成工具:给每个模型画一张 preview.png。 /// 封面生成工具:用模型自己的渲染器给每个模型画一张封面 preview.png。
/// /// 封面在模型包里,启动器只负责显示 —— 所以公转模型的封面一定就是公转场景。
/// 两条路径: /// 用法:dotnet run --project model-src/tools/PreviewGen -- &lt;仓库根&gt;
/// 1) 通用路径(默认):按模型清单的 assembly + type 加载模型程序集,
/// 调它自己的 IModelRuntime.CreateView 做 headless 渲染 —— 任何新模型都能自动出封面。
/// 2) 地球模型路径:仍走共享引擎的 CelestialView(保留 --bench 基准测试能力)。
///
/// 封面在模型包里,启动器只负责显示。用法:
/// dotnet run --project model/_engine/PreviewGen -- &lt;仓库根&gt; [--bench]
/// </summary> /// </summary>
internal static class Program internal static class Program
{ {
private const int Width = 768; private const int Width = 768;
private const int Height = 316; private const int Height = 316;
/// <summary>headless 封面应用:带上 Fluent 主题,UserControl 才有模板可渲染。</summary>
private sealed class PreviewApp : Application
{
public override void Initialize()
{
Styles.Add(new Avalonia.Themes.Fluent.FluentTheme());
}
}
[STAThread] [STAThread]
public static int Main(string[] args) public static int Main(string[] args)
{ {
@@ -52,53 +32,23 @@ internal static class Program
var bench = args.Contains("--bench"); var bench = args.Contains("--bench");
AppBuilder.Configure<PreviewApp>() AppBuilder.Configure<Application>()
.UseSkia() .UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }) .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting(); .SetupWithoutStarting();
foreach (var modelDir in Directory.GetDirectories(modelRoot).OrderBy(p => p, StringComparer.Ordinal)) foreach (var modelDir in Directory.GetDirectories(modelRoot))
{ {
var id = Path.GetFileName(modelDir); var id = Path.GetFileName(modelDir);
if (id.StartsWith('.') || id.StartsWith('_')) continue; if (id.StartsWith(".")) continue;
var dataDir = Path.Combine(modelDir, id + ".model"); var dataDir = Path.Combine(modelDir, id + ".model");
if (!Directory.Exists(dataDir)) continue; var sceneFile = Path.Combine(dataDir, "scene.json");
if (!File.Exists(sceneFile)) continue;
var outFile = Path.Combine(dataDir, "preview.png");
var hasScene = File.Exists(Path.Combine(dataDir, "scene.json"));
// 基准测试只对地球模型(依赖 CelestialView)
if (bench)
{
if (!hasScene) continue;
BenchEarthModel(dataDir, id);
continue;
}
var ok = false;
string? err = null;
if (hasScene)
ok = TryRenderEarthModel(dataDir, outFile, out err);
if (!ok)
ok = TryRenderViaContract(modelDir, dataDir, outFile, out err);
if (!ok)
Console.Error.WriteLine($"preview 跳过 {id}:{err}");
}
return 0;
}
// ─────────────────────────────────────────── 地球模型(保留原渲染器,封面一定是真场景)
private static bool TryRenderEarthModel(string dataDir, string outFile, out string? error)
{
error = null;
try
{
var runtime = SceneRuntime.Load(dataDir, 2048); var runtime = SceneRuntime.Load(dataDir, 2048);
var texts = ModelStrings.Load(dataDir, "zh-CN"); var texts = ModelStrings.Load(dataDir, "zh-CN");
var revolution = string.Equals(runtime.Scene.DefaultView, "revolution", StringComparison.OrdinalIgnoreCase); var revolution = string.Equals(runtime.Scene.DefaultView, "revolution", StringComparison.OrdinalIgnoreCase);
var view = new CelestialView var view = new CelestialView
{ {
Scene = runtime, Scene = runtime,
@@ -112,181 +62,52 @@ internal static class Program
Width = Width, Width = Width,
Height = Height Height = Height
}; };
PrepareView(view, Width, Height); view.Measure(new Size(Width, Height));
view.Arrange(new Rect(0, 0, Width, Height));
view.JumpToOrbit(revolution ? 45 : 0); view.JumpToOrbit(revolution ? 45 : 0);
view.JumpToSpin(20); view.JumpToSpin(20);
Save(view, outFile);
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
private static void BenchEarthModel(string dataDir, string id) if (bench)
{
var runtime = SceneRuntime.Load(dataDir, 2048);
var texts = ModelStrings.Load(dataDir, "zh-CN");
var revolution = string.Equals(runtime.Scene.DefaultView, "revolution", StringComparison.OrdinalIgnoreCase);
var view = new CelestialView
{
Scene = runtime,
Texts = texts,
View = revolution ? SceneView.Revolution : SceneView.Rotation,
IsPlaying = false,
ShowHud = false,
ShowLabels = false,
ShowOrbit = true,
ShowGraticule = true,
Width = Width,
Height = Height
};
PrepareView(view, Width, Height);
view.JumpToOrbit(revolution ? 45 : 0);
view.JumpToSpin(20);
view.Width = 1240;
view.Height = 820;
view.Measure(new Size(1240, 820));
view.Arrange(new Rect(0, 0, 1240, 820));
var animField = typeof(CelestialView)
.GetField("_animating", BindingFlags.NonPublic | BindingFlags.Instance);
var sw = System.Diagnostics.Stopwatch.StartNew();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
var still = sw.Elapsed.TotalMilliseconds / 20;
animField?.SetValue(view, true);
sw.Restart();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
Console.WriteLine($"{id}: 静止 {still:0.0} ms/frame · 播放 {sw.Elapsed.TotalMilliseconds / 20:0.0} ms/frame");
}
// ─────────────────────────────────────────── 通用路径:按契约加载模型自己的界面
private sealed class PreviewContext : IModelContext
{
public string ModelId { get; init; } = "";
public string ModelDirectory { get; init; } = "";
public string DataDirectory { get; init; } = "";
public string Language => "zh-CN";
public int MemoryBudgetMb => 512;
public void RequestClose() { }
public void ReportProgress(double value, string? message = null) { }
public void Log(string message) => Console.WriteLine(" " + message);
}
private static bool TryRenderViaContract(string modelDir, string dataDir, string outFile, out string? error)
{
error = null;
var manifestPath = Path.Combine(modelDir, Path.GetFileName(modelDir) + ".json");
if (!File.Exists(manifestPath)) { error = "缺少模型清单"; return false; }
try
{
using var doc = System.Text.Json.JsonDocument.Parse(File.ReadAllText(manifestPath));
var root = doc.RootElement;
var id = Path.GetFileName(modelDir);
var asmName = GetString(root, "assembly") ?? (id + ".dll");
var typeName = GetString(root, "type");
var asmPath = Path.Combine(dataDir, asmName);
if (!File.Exists(asmPath)) { error = $"找不到功能程序集 {asmName}"; return false; }
var alc = new AssemblyLoadContext("preview:" + id, isCollectible: true);
alc.Resolving += (_, name) =>
{ {
// 契约与 Avalonia 一律回到默认上下文,与启动器 ModelLoadContext 一致 // 真实窗口尺寸下的帧耗时
if (name.Name is null) return null; view.Width = 1240;
if (name.Name.StartsWith("System", StringComparison.OrdinalIgnoreCase)) return null; view.Height = 820;
var shared = new[] { "GC.ModelSdk", "Avalonia", "Avalonia.Base", view.Measure(new Size(1240, 820));
"Avalonia.Controls", "Avalonia.Skia", "Avalonia.Themes.Fluent", "SkiaSharp", "HarfBuzzSharp" }; view.Arrange(new Rect(0, 0, 1240, 820));
if (shared.Contains(name.Name, StringComparer.OrdinalIgnoreCase)) return null; // 模拟播放态(运动时降分辨率),分别测静止高清帧与运动帧
var candidate = Path.Combine(dataDir, name.Name + ".dll"); var animField = typeof(NeoRF.EarthModels.CelestialView)
return File.Exists(candidate) ? alc.LoadFromAssemblyPath(candidate) : null; .GetField("_animating", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
}; var sw = System.Diagnostics.Stopwatch.StartNew();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
var still = sw.Elapsed.TotalMilliseconds / 20;
animField?.SetValue(view, true);
sw.Restart();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
Console.WriteLine($"{id}: 静止 {still:0.0} ms/frame · 播放 {sw.Elapsed.TotalMilliseconds / 20:0.0} ms/frame");
continue;
}
var asm = alc.LoadFromAssemblyPath(asmPath); var outFile = Path.Combine(dataDir, "preview.png");
Type? factoryType = null; using (var bitmap = new RenderTargetBitmap(new PixelSize(Width, Height), new Vector(96, 96)))
if (!string.IsNullOrWhiteSpace(typeName))
factoryType = asm.GetType(typeName!, throwOnError: false);
factoryType ??= asm.GetTypes().FirstOrDefault(t =>
!t.IsAbstract && !t.IsInterface && typeof(IModelFactory).IsAssignableFrom(t));
if (factoryType == null) { error = "程序集里没有 IModelFactory 实现"; return false; }
if (Activator.CreateInstance(factoryType) is not IModelFactory factory)
{ error = "无法创建模型入口"; return false; }
var runtime = factory.Create();
var ctx = new PreviewContext
{ {
ModelId = id, bitmap.Render(view);
ModelDirectory = modelDir, bitmap.Save(outFile);
DataDirectory = dataDir }
}; Console.WriteLine($"preview -> {outFile}");
runtime.Prepare(ctx);
var view = runtime.CreateView(ctx);
if (view == null) { error = "模型没有返回界面"; return false; }
PrepareView(view, Width, Height);
Save(view, outFile);
runtime.Dispose();
(view as IDisposable)?.Dispose();
alc.Unload();
return true;
} }
catch (Exception ex)
{
error = ex.ToString();
return false;
}
}
private static string? GetString(System.Text.Json.JsonElement e, string name) return 0;
=> e.TryGetProperty(name, out var v) && v.ValueKind == System.Text.Json.JsonValueKind.String
? v.GetString() : null;
// ─────────────────────────────────────────── 公共
private static void PrepareView(Control view, double w, double h)
{
// 封面是宽幅(768×316),模型界面按设计尺寸是 1240×820;这里把布局直接按封面
// 尺寸 Measure/Arrange,让卡片上看到的是完整布局而不是被裁掉一角。
view.Width = w;
view.Height = h;
view.Measure(new Size(w, h));
view.Arrange(new Rect(0, 0, w, h));
}
private static void Save(Control view, string outFile)
{
// headless 下 UserControl 必须挂进 Window 才有视觉树;直接 Render(Control)
// 会得到一张全黑的图(实测)。地球模型的裸 Control 走同一路径也正常工作。
var win = new Window
{
Width = Width,
Height = Height,
Background = Avalonia.Media.Brushes.White,
Content = view,
SystemDecorations = SystemDecorations.None,
ShowInTaskbar = false
};
win.Show();
using var bitmap = new RenderTargetBitmap(new PixelSize(Width, Height), new Vector(96, 96));
bitmap.Render(win);
bitmap.Save(outFile);
win.Content = null;
win.Close();
Console.WriteLine($"preview -> {outFile}");
} }
} }
+17 -94
View File
@@ -3,25 +3,14 @@ using System.Text;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using GC.Services;
// VersionStamp:构建时自动给模型打版本。 // VersionStamp:构建时自动给模型打版本。
// 用法:dotnet run --project model/_engine/VersionStamp -- <仓库根> <启动器版本> // 用法:dotnet run --project model/_engine/VersionStamp -- <仓库根> <启动器版本>
// 输出:更新 model/<id>/<id>.json 的 version / updatedAt,并生成 // 输出:更新 model/<id>/<id>.json 的 version / updatedAt,并生成
// 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。 // 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。
// 仓库地址(编译产物的 Release 也发在这里):与启动器默认 updateRepository 保持一致。 var root = args.Length > 0 ? Path.GetFullPath(args[0]) : Directory.GetCurrentDirectory();
const string Repository = "https://gitcode.com/Morris_1/GC"; var launcherVersion = args.Length > 1 && !string.IsNullOrWhiteSpace(args[1]) ? args[1] : "1.0.0";
// 位置参数:<仓库根> <启动器版本>;开关:--launcher-only
// --launcher-only 只刷新 launcher.packages(构建脚本在打完 zip 之后再调一次),
// 不重算模型指纹 —— 模型文件可能有几百 MB,重复哈希纯属浪费。
var positional = args.Where(a => !a.StartsWith("--", StringComparison.Ordinal)).ToArray();
var launcherOnly = args.Any(a => a.Equals("--launcher-only", StringComparison.OrdinalIgnoreCase));
var root = positional.Length > 0 ? Path.GetFullPath(positional[0]) : Directory.GetCurrentDirectory();
var launcherVersion = positional.Length > 1 && !string.IsNullOrWhiteSpace(positional[1])
? positional[1] : "1.0.0";
var modelRoot = Path.Combine(root, "model"); var modelRoot = Path.Combine(root, "model");
if (!Directory.Exists(modelRoot)) if (!Directory.Exists(modelRoot))
@@ -57,11 +46,8 @@ static string Fingerprint(IEnumerable<byte[]> chunks)
return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
} }
var models = new List<Dictionary<string, object>>();
if (!launcherOnly)
{
Console.WriteLine("==> 自动计算模型版本(按模型包内容指纹)"); Console.WriteLine("==> 自动计算模型版本(按模型包内容指纹)");
var models = new List<Dictionary<string, string>>();
foreach (var dir in Directory.GetDirectories(modelRoot) foreach (var dir in Directory.GetDirectories(modelRoot)
.OrderBy(p => Path.GetFileName(p), StringComparer.Ordinal)) .OrderBy(p => Path.GetFileName(p), StringComparer.Ordinal))
@@ -76,17 +62,11 @@ foreach (var dir in Directory.GetDirectories(modelRoot)
var manifest = JsonNode.Parse(File.ReadAllText(manifestPath))?.AsObject(); var manifest = JsonNode.Parse(File.ReadAllText(manifestPath))?.AsObject();
if (manifest == null) continue; if (manifest == null) continue;
// 版本号由模型清单里手写的 version 决定(作者手动升到 1.0 / 1.1 …), // 版本号只由「清单内容 + 模型包数据」决定,重复构建结果稳定
// 不再用内容指纹覆盖:指纹形式(1.0-393cb2b7d4)对用户不可读、也没有语义。 manifest.Remove("version");
var declared = manifest["version"]?.GetValue<string>();
var version = string.IsNullOrWhiteSpace(declared) ? "1.0" : declared!.Trim();
// 内容指纹保留在 build 字段,仅用于构建溯源,不参与版本比较。
// 注意:updatedAt / build 都是构建元数据,必须从指纹里剔除,
// 否则「同一份内容」每次构建都会算出不同指纹(等于每次都触发更新)。
manifest.Remove("build");
manifest.Remove("updatedAt"); manifest.Remove("updatedAt");
var canonical = manifest.ToJsonString(new JsonSerializerOptions { WriteIndented = false }); var canonical = manifest.ToJsonString(new JsonSerializerOptions { WriteIndented = false });
var chunks = new List<byte[]> { Encoding.UTF8.GetBytes(canonical) }; var chunks = new List<byte[]> { Encoding.UTF8.GetBytes(canonical) };
foreach (var file in Directory.GetFiles(dataDir, "*", SearchOption.AllDirectories) foreach (var file in Directory.GetFiles(dataDir, "*", SearchOption.AllDirectories)
.Where(Distributable) .Where(Distributable)
@@ -95,34 +75,20 @@ foreach (var dir in Directory.GetDirectories(modelRoot)
chunks.Add(Encoding.UTF8.GetBytes("\n" + Rel(dataDir, file) + "\n")); chunks.Add(Encoding.UTF8.GetBytes("\n" + Rel(dataDir, file) + "\n"));
chunks.Add(File.ReadAllBytes(file)); chunks.Add(File.ReadAllBytes(file));
} }
var fingerprint = Fingerprint(chunks)[..10];
var version = "1.0-" + Fingerprint(chunks)[..10];
manifest["version"] = version; manifest["version"] = version;
manifest["build"] = fingerprint;
manifest["updatedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); manifest["updatedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
var manifestText = manifest.ToJsonString(relaxed) + "\n"; File.WriteAllText(manifestPath, manifest.ToJsonString(relaxed) + "\n");
File.WriteAllText(manifestPath, manifestText);
// 完整性哈希:客户端下载后按同一算法复算,不一致就丢弃。 models.Add(new Dictionary<string, string>
// manifestSha256 = 清单文件本身的 sha256
// filesSha256 = <id>.model 目录指纹(算法见 GC/src/Security/ContentHash.cs)
var manifestSha = ContentHash.Sha256Hex(manifestText);
var filesMap = ContentHash.MapFiles(dataDir);
var filesSha = ContentHash.DirectoryHash(filesMap);
models.Add(new Dictionary<string, object>
{ {
["id"] = id, ["id"] = id,
["version"] = version, ["version"] = version,
["build"] = fingerprint,
["manifestSha256"] = manifestSha,
["filesSha256"] = filesSha,
["files"] = filesMap.Count,
["dir"] = "model/" + id ["dir"] = "model/" + id
}); });
Console.WriteLine($" {id,-20} {version,-8} (build {fingerprint}, {filesMap.Count} files)"); Console.WriteLine($" {id,-20} {version}");
} }
} // !launcherOnly
// 启动器源码指纹(只展示,不触发升级;升级看 launcher.version) // 启动器源码指纹(只展示,不触发升级;升级看 launcher.version)
var srcRoot = Path.Combine(root, "src"); var srcRoot = Path.Combine(root, "src");
@@ -145,45 +111,20 @@ if (Directory.Exists(srcRoot))
var launcherRevision = srcChunks.Count > 0 ? Fingerprint(srcChunks)[..10] : ""; var launcherRevision = srcChunks.Count > 0 ? Fingerprint(srcChunks)[..10] : "";
var packages = new Dictionary<string, Dictionary<string, object>>(); var packages = new Dictionary<string, Dictionary<string, object>>();
// 启动器更新包的两种落点,清单里都写清楚,下载端按顺序尝试:
// 1) Release 附件(url)—— 常规发布方式;
// 2) 仓库里的编译产物 dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip ——
// 不发 Release、只提交产物也能更新(用户明确要求支持这种布局)。
// 两种都写:url 只是「去哪儿找」,真正的完整性凭据是下面的 sha256(受签名保护)。
var releaseBase = $"{Repository}/releases/download/v{launcherVersion}";
foreach (var rid in new[] { "win-x64", "win-arm64", "osx-arm64", "osx-x64", "linux-x64" }) foreach (var rid in new[] { "win-x64", "win-arm64", "osx-arm64", "osx-x64", "linux-x64" })
{ {
var label = LauncherArtifacts.LabelOf(rid);
var fileName = LauncherArtifacts.PackageFileName(launcherVersion, rid);
var dir = $"dist/{label}";
var entry = new Dictionary<string, object> var entry = new Dictionary<string, object>
{ {
["path"] = $"{dir}/{fileName}", ["path"] = $"dist/GC-{rid}.zip",
["dir"] = dir, ["url"] = "" // 大文件建议填 Release 直链;留空则用仓库内 path
["name"] = fileName,
["url"] = $"{releaseBase}/{fileName}"
}; };
// 已生成的启动器更新包:把校验值和体积写进清单,供下载端校验
// 优先认平台产物目录,其次认 dist 根目录(历史构建把 zip 直接放在 dist/) var zipPath = Path.Combine(root, "dist", $"GC-{rid}.zip");
var zipPath = new[] if (File.Exists(zipPath))
{
Path.Combine(root, dir.Replace('/', Path.DirectorySeparatorChar), fileName),
Path.Combine(root, "dist", fileName),
Path.Combine(root, "dist", $"GC-{rid}.zip")
}.FirstOrDefault(File.Exists);
if (zipPath != null)
{ {
var bytes = File.ReadAllBytes(zipPath); var bytes = File.ReadAllBytes(zipPath);
entry["path"] = Rel(root, zipPath);
entry["sha256"] = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); entry["sha256"] = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
entry["size"] = bytes.LongLength; entry["size"] = bytes.LongLength;
Console.WriteLine($" 包 {label,-12} {entry["path"]}({bytes.LongLength / 1024 / 1024} MB)");
}
else
{
Console.WriteLine($" 包 {label,-12} 未找到产物(清单里不会有 sha256,下载端会跳过该平台)");
} }
packages[rid] = entry; packages[rid] = entry;
} }
@@ -192,7 +133,7 @@ var versionDoc = new Dictionary<string, object>
{ {
["schema"] = 1, ["schema"] = 1,
["generated"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), ["generated"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
["repository"] = Repository, ["repository"] = "https://gitcode.com/2509_92447106/GC",
["branch"] = "main", ["branch"] = "main",
["modelDir"] = "model", ["modelDir"] = "model",
["launcher"] = new Dictionary<string, object> ["launcher"] = new Dictionary<string, object>
@@ -204,26 +145,8 @@ var versionDoc = new Dictionary<string, object>
["models"] = models ["models"] = models
}; };
// --launcher-only:模型段沿用现有清单,只换启动器包,避免重复哈希几百 MB 模型文件
if (launcherOnly)
{
var manifestPath = Path.Combine(root, "version.json");
if (File.Exists(manifestPath))
{
var existing = JsonNode.Parse(File.ReadAllText(manifestPath))?.AsObject();
if (existing?["models"] is JsonNode existingModels)
versionDoc["models"] = existingModels.DeepClone();
if (existing?["generated"] is JsonNode generated)
versionDoc["generated"] = generated.DeepClone();
}
else
{
Console.Error.WriteLine("!! --launcher-only 需要已存在的 version.json,退回完整模式");
}
}
var json = JsonSerializer.Serialize(versionDoc, relaxed) + "\n"; var json = JsonSerializer.Serialize(versionDoc, relaxed) + "\n";
File.WriteAllText(Path.Combine(root, "version.json"), json); File.WriteAllText(Path.Combine(root, "version.json"), json);
File.WriteAllText(Path.Combine(modelRoot, "version.json"), json); File.WriteAllText(Path.Combine(modelRoot, "version.json"), json);
Console.WriteLine($"==> version.json 已更新(启动器 {launcherVersion},模型 {models.Count} 个)"); Console.WriteLine($"==> version.json 已生成(启动器 {launcherVersion},模型 {models.Count} 个)");
return 0; return 0;
@@ -8,11 +8,5 @@
<AssemblyName>VersionStamp</AssemblyName> <AssemblyName>VersionStamp</AssemblyName>
<RootNamespace>VersionStamp</RootNamespace> <RootNamespace>VersionStamp</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<!-- 与启动器 / SAVEDOG 共用同一份哈希实现,保证"构建端算的"和"客户端验的"完全一致 -->
<Compile Include="..\..\..\GC\src\Security\ContentHash.cs" Link="Shared\ContentHash.cs" />
<!-- 平台标签与 dist 目录推导也共用:构建端写进清单的路径,必须和下载端找的路径一致 -->
<Compile Include="..\..\..\GC-DOWNLOAD\LauncherArtifacts.cs" Link="Shared\LauncherArtifacts.cs" />
</ItemGroup>
</Project> </Project>
+20 -30
View File
@@ -403,7 +403,7 @@ public class CelestialView : Control, IDisposable
_sphere?.Dispose(); _sphere?.Dispose();
_sphere = null; _sphere = null;
_sphereSize = 0; _sphereSize = 0;
System.GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
private void OnTick(object? sender, EventArgs e) private void OnTick(object? sender, EventArgs e)
@@ -726,43 +726,34 @@ public class CelestialView : Control, IDisposable
if (!labels) return; if (!labels) return;
// 标签位置必须「稳定」:不能每帧搜索最佳可见点(那会随旋转跳动), // 收集每个标签的锚点,按屏幕 Y 排序后做垂直去重叠
// 也不能按可见性整块跳显/跳隐(那是抖动的来源)。 var placed = new List<(double Y, double X, string Text, IBrush Brush)>();
//
// 做法:
// · Y 用该纬线在当前视角下的实际投影高度(纬度本身随俯仰连续变化,不会跳);
// · X 固定在球体右侧一点,与旋转无关;
// · 可见性用一个连续衰减的透明度,而不是阈值切换。
var placed = new List<(double Y, double Lat, string Text, IBrush Brush)>();
foreach (var l in lines) foreach (var l in lines)
{ {
if (l.Label == null) continue; if (l.Label == null) continue;
Vector3 best = default;
// 该纬度圈在相机空间的最高点高度:取整圈采样里 Y 的最大值, var bestScore = double.NegativeInfinity;
// 只依赖俯仰角(连续量),不随自转变化。 for (var lon = -180; lon < 180; lon += 6)
var maxY = double.NegativeInfinity;
for (var lon = 0; lon < 360; lon += 10)
{ {
var world = Vector3.Transform(LatLonToUnit(l.Lat, lon), planet); var world = Vector3.Transform(LatLonToUnit(l.Lat, lon), planet);
var c = Vector3.Transform(world, cam); var c = Vector3.Transform(world, cam);
if (c.Y > maxY) maxY = c.Y; if (c.Z < 0.10f) continue;
var score = c.X * 2.0 + c.Z;
if (score > bestScore) { bestScore = score; best = c; }
} }
if (double.IsNegativeInfinity(maxY)) continue; if (double.IsNegativeInfinity(bestScore)) continue;
placed.Add((center.Y - best.Y * radius, center.X + best.X * radius, l.Label, l.Brush));
placed.Add((center.Y - maxY * radius, l.Lat, l.Label, l.Brush));
} }
// 按纬度从北到南排,保证顺序恒定;再用「期望间距」平滑排布, placed.Sort((a, b) => a.Y.CompareTo(b.Y));
// 间距不足时按固定比例压缩(而不是 +16 硬推,硬推会让整串标签滑动)。 const double minGap = 16.0;
placed.Sort((a, b) => b.Lat.CompareTo(a.Lat)); var lastY = double.NegativeInfinity;
if (placed.Count == 0) return; foreach (var p in placed)
var labelX = center.X + radius * 1.02; // 固定在球右侧外部
for (var i = 0; i < placed.Count; i++)
{ {
var p = placed[i]; var y = p.Y;
DrawLabelChip(ctx, p.Text, new Point(labelX, p.Y), if (y - lastY < minGap) y = lastY + minGap;
InsetMode ? 9.0 : 10.5, p.Brush, toRight: true); lastY = y;
DrawLabelChip(ctx, p.Text, new Point(p.X, y), InsetMode ? 9.0 : 10.5, p.Brush, toRight: false);
} }
} }
@@ -776,9 +767,8 @@ public class CelestialView : Control, IDisposable
TextAlignment = TextAlignment.Left, TextAlignment = TextAlignment.Left,
Trimming = TextTrimming.None Trimming = TextTrimming.None
}; };
// 锚点即文字垂直中心,避免不同文字高度造成上下漂移
var x = toRight ? anchor.X + 9 : Math.Max(3, anchor.X - formatted.Width - 9); var x = toRight ? anchor.X + 9 : Math.Max(3, anchor.X - formatted.Width - 9);
var y = anchor.Y - formatted.Height * 0.5; var y = anchor.Y - formatted.Height - 4;
ctx.DrawRectangle(ChipBg, null, ctx.DrawRectangle(ChipBg, null,
new Rect(x - 5, y - 2, formatted.Width + 10, formatted.Height + 5), 4, 4); new Rect(x - 5, y - 2, formatted.Width + 10, formatted.Height + 5), 4, 4);
ctx.DrawText(formatted, new Point(x, y)); ctx.DrawText(formatted, new Point(x, y));
+9 -3
View File
@@ -9,7 +9,7 @@ using Avalonia.Input;
using Avalonia.Layout; using Avalonia.Layout;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Threading; using Avalonia.Threading;
using GC.ModelSdk; using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels; namespace NeoRF.EarthModels;
@@ -48,6 +48,7 @@ public sealed class EarthModelView : UserControl, IDisposable
private TextBlock? _closeupLabel; private TextBlock? _closeupLabel;
private ModelButton? _playButton; private ModelButton? _playButton;
private ModelButton? _overheadButton; private ModelButton? _overheadButton;
private ModelButton? _closeupButton;
private TextBlock? _zoomText; private TextBlock? _zoomText;
private TextBlock? _cardState; private TextBlock? _cardState;
private TextBlock? _cardTitle; private TextBlock? _cardTitle;
@@ -187,7 +188,7 @@ public sealed class EarthModelView : UserControl, IDisposable
} }
_canvas.Dispose(); _canvas.Dispose();
_closeup.Dispose(); _closeup.Dispose();
System.GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
private string CurrentView { get; set; } = "rotation"; private string CurrentView { get; set; } = "rotation";
@@ -291,7 +292,12 @@ public sealed class EarthModelView : UserControl, IDisposable
row.Children.Add(MakeToggle(_texts["orbit"], _orbit, on => { _orbit = on; _canvas.ShowOrbit = on; })); row.Children.Add(MakeToggle(_texts["orbit"], _orbit, on => { _orbit = on; _canvas.ShowOrbit = on; }));
row.Children.Add(MakeToggle(_texts["grid"], _grid, on => { _grid = on; _canvas.ShowGraticule = on; })); row.Children.Add(MakeToggle(_texts["grid"], _grid, on => { _grid = on; _canvas.ShowGraticule = on; }));
row.Children.Add(MakeToggle(_texts["tilt"], _tilt, on => { _tilt = on; _canvas.ExaggerateTilt = on; })); row.Children.Add(MakeToggle(_texts["tilt"], _tilt, on => { _tilt = on; _canvas.ExaggerateTilt = on; }));
// 「放大」切换按钮已按需求移除;特写视图本身仍随公转显示 _closeupButton = MakeToggle(_texts["closeup"], _showCloseup, on =>
{
_showCloseup = on;
ApplyVisibility();
});
row.Children.Add(_closeupButton);
_overheadButton = MakeToggle(_texts["overhead"], _overhead, on => _overheadButton = MakeToggle(_texts["overhead"], _overhead, on =>
{ {
_overhead = on; _overhead = on;
+2 -2
View File
@@ -1,6 +1,6 @@
using System; using System;
using Avalonia.Controls; using Avalonia.Controls;
using GC.ModelSdk; using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels; namespace NeoRF.EarthModels;
@@ -40,6 +40,6 @@ public sealed class EarthModelRuntime : IModelRuntime
public void Dispose() public void Dispose()
{ {
_scene = null; _scene = null;
System.GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }
-132
View File
@@ -1,132 +0,0 @@
using System;
using System.Collections.Generic;
using System.Numerics;
namespace NeoRF.EarthModels;
/// <summary>
/// 地理模型的球面几何工具:经纬度 ↔ 单位球坐标、正交投影到屏幕、
/// 以及把一条经纬度折线投影成「可见弧段」(背面自动裁掉)。
/// 纯 CPU、无依赖,供 GeographyView 画线稿用。
/// </summary>
public static class Geometry
{
public const float DegToRad = (float)(Math.PI / 180.0);
public const float RadToDeg = (float)(180.0 / Math.PI);
/// <summary>经纬度 → 单位球坐标(y 轴为地轴,lon 向东为正)。</summary>
public static Vector3 LatLonToUnit(double latDeg, double lonDeg)
{
var lat = (float)(latDeg * Math.PI / 180.0);
var lon = (float)(lonDeg * Math.PI / 180.0);
var cosLat = (float)Math.Cos(lat);
return new Vector3(cosLat * (float)Math.Sin(lon), (float)Math.Sin(lat), cosLat * (float)Math.Cos(lon));
}
/// <summary>把世界坐标旋转到相机空间(先用 planet 旋转地球,再用 cam 转到屏幕)。</summary>
public static Vector3 ToCamera(Vector3 world, Matrix4x4 planet, Matrix4x4 cam)
=> Vector3.Transform(Vector3.Transform(world, planet), cam);
/// <summary>相机空间的正交投影:球心在原点,半径 radius。</summary>
public static Vector2 Project(Vector3 camPos, float radius, float centerX, float centerY)
=> new(centerX + camPos.X * radius, centerY - camPos.Y * radius);
/// <summary>相机空间里该点是否朝向观察者(z>0 为正面)。</summary>
public static bool IsVisible(Vector3 camPos, float threshold = 0f) => camPos.Z > threshold;
/// <summary>
/// 把一条经纬度折线拆成若干段「可见」的屏幕折线。
/// 跨越地平线的相邻两点用线性插值求出交点作为端点,保证线不会穿过球体背面。
/// </summary>
public static List<List<Vector2>> ProjectPolyline(
IReadOnlyList<double[]> latLonPoints,
Matrix4x4 planet, Matrix4x4 cam,
float radius, float centerX, float centerY,
bool closed = false)
{
// 兼容旧调用:按需转换(点位少的分支,如洲界)
var unit = new Vector3[latLonPoints.Count];
for (var i = 0; i < latLonPoints.Count; i++)
{
var p = latLonPoints[i];
unit[i] = p.Length >= 2 ? LatLonToUnit(p[1], p[0]) : Vector3.Zero;
}
var valid = new bool[unit.Length];
for (var i = 0; i < latLonPoints.Count; i++) valid[i] = latLonPoints[i].Length >= 2;
return ProjectUnitPolyline(unit, valid, planet, cam, radius, centerX, centerY, closed);
}
/// <summary>
/// 预计算单位球坐标后的快速投影:每帧只做矩阵乘 + 正交投影,
/// 不再重复计算 sin/cos(地理模型约 2.6 万个点,这是最大开销)。
/// </summary>
public static List<List<Vector2>> ProjectUnitPolyline(
IReadOnlyList<Vector3> unitPoints,
IReadOnlyList<bool> valid,
Matrix4x4 planet, Matrix4x4 cam,
float radius, float centerX, float centerY,
bool closed = false)
{
var result = new List<List<Vector2>>();
if (unitPoints.Count < 2) return result;
var count = unitPoints.Count;
var total = closed ? count + 1 : count;
List<Vector2>? current = null;
Vector3 prevCam = default;
var havePrev = false;
for (var i = 0; i < total; i++)
{
var k = i % count;
if (!valid[k]) { havePrev = false; continue; }
var camPos = Vector3.Transform(Vector3.Transform(unitPoints[k], planet), cam);
var visible = camPos.Z > 0f;
if (!havePrev)
{
if (visible)
{
current = new List<Vector2> { Project(camPos, radius, centerX, centerY) };
}
prevCam = camPos;
havePrev = true;
continue;
}
var prevVisible = prevCam.Z > 0f;
if (visible && prevVisible)
{
current ??= new List<Vector2>();
current.Add(Project(camPos, radius, centerX, centerY));
}
else if (visible != prevVisible)
{
// 求出与地平线(z=0)的交点
var t = prevCam.Z / (prevCam.Z - camPos.Z);
var hit = Vector3.Lerp(prevCam, camPos, t);
hit.Z = 0f;
var hitScreen = Project(hit, radius, centerX, centerY);
if (visible)
{
current = new List<Vector2> { hitScreen };
current.Add(Project(camPos, radius, centerX, centerY));
}
else
{
current?.Add(hitScreen);
if (current is { Count: > 1 }) result.Add(current);
current = null;
}
}
prevCam = camPos;
}
if (current is { Count: > 1 }) result.Add(current);
return result;
}
}
@@ -4,8 +4,8 @@
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>GC.ModelSdk</RootNamespace> <RootNamespace>EarthModelStudio.ModelSdk</RootNamespace>
<AssemblyName>GC.ModelSdk</AssemblyName> <AssemblyName>EarthModelStudio.ModelSdk</AssemblyName>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<Description>Earth Model 模型契约:启动器与模型之间唯一的编译期依赖。</Description> <Description>Earth Model 模型契约:启动器与模型之间唯一的编译期依赖。</Description>
</PropertyGroup> </PropertyGroup>
@@ -1,7 +1,7 @@
using System; using System;
using Avalonia.Controls; using Avalonia.Controls;
namespace GC.ModelSdk; namespace EarthModelStudio.ModelSdk;
/// <summary> /// <summary>
/// 模型入口契约。模型程序集里必须有一个公开、无参构造的 <see cref="IModelFactory"/> 实现, /// 模型入口契约。模型程序集里必须有一个公开、无参构造的 <see cref="IModelFactory"/> 实现,
@@ -9,12 +9,7 @@ namespace GC.ModelSdk;
/// </summary> /// </summary>
public interface IModelFactory public interface IModelFactory
{ {
/// <summary> /// <summary>契约版本。启动器目前支持 1。</summary>
/// 契约版本。启动器目前支持 <b>1</b>。
/// 协商规则:必须与启动器支持的版本**相等**,否则启动器拒绝加载并提示用户更新;
/// 模型清单里还可以写 <c>minAppVersion</c> 要求更高的启动器版本。
/// 提升版本时必须保留旧接口的适配层,避免老客户端加载新模型后崩溃。
/// </summary>
int ApiVersion { get; } int ApiVersion { get; }
/// <summary>创建一个模型运行时实例(每个窗口一个实例)。</summary> /// <summary>创建一个模型运行时实例(每个窗口一个实例)。</summary>
@@ -24,10 +19,6 @@ public interface IModelFactory
/// <summary> /// <summary>
/// 模型运行时:负责把模型自己的界面交给启动器。 /// 模型运行时:负责把模型自己的界面交给启动器。
/// 启动器只负责开窗口,**不参与任何渲染**。 /// 启动器只负责开窗口,**不参与任何渲染**。
///
/// 生命周期:<c>Create()</c> → <c>Prepare()</c>(后台线程,一次)→ <c>CreateView()</c>(UI 线程,一次)
/// → 用户关窗 → <c>Dispose()</c>(UI 线程)。<c>Dispose</c> 之后不要再调用任何
/// <see cref="IModelContext"/> 成员。
/// </summary> /// </summary>
public interface IModelRuntime : IDisposable public interface IModelRuntime : IDisposable
{ {
@@ -63,15 +54,15 @@ public interface IModelContext
/// <summary>用户在设置里分配的运行内存预算(MB),模型可据此控制缓存规模。</summary> /// <summary>用户在设置里分配的运行内存预算(MB),模型可据此控制缓存规模。</summary>
int MemoryBudgetMb { get; } int MemoryBudgetMb { get; }
/// <summary>请求关闭承载此模型的窗口。**线程安全**,任意线程可调用。</summary> /// <summary>请求关闭承载此模型的窗口。</summary>
void RequestClose(); void RequestClose();
/// <summary> /// <summary>
/// 汇报加载进度(0–1)与当前阶段文案。启动器的加载进度条会实时显示, /// 汇报加载进度(0–1)与当前阶段文案。启动器的加载进度条会实时显示,
/// 也可以在任何时候调用(例如切换数据集时)。**线程安全**,任意线程可调用。 /// 也可以在任何时候调用(例如切换数据集时)。
/// </summary> /// </summary>
void ReportProgress(double value, string? message = null); void ReportProgress(double value, string? message = null);
/// <summary>输出日志(启动器会写到控制台)。**线程安全**,任意线程可调用。</summary> /// <summary>输出日志(启动器会写到控制台)。</summary>
void Log(string message); void Log(string message);
} }
-30
View File
@@ -1,30 +0,0 @@
{
"id": "contour-map",
"nameI18n": {
"zh-CN": "等高线地形图",
"en": "Contour Map"
},
"descriptionI18n": {
"zh-CN": "立体地形与平面等高线联动,判读山峰、山脊、山谷、鞍部、陡崖五种部位。",
"en": "Link 3D relief with contour lines; identify peaks, ridges, valleys, saddles and cliffs."
},
"author": "Morris GC",
"tags": [
"geography",
"map",
"contour",
"terrain"
],
"assembly": "ContourMapModel.dll",
"type": "NeoRF.ContourMap.ContourMapFactory",
"version": "1.0",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "e4b3f2b87e",
"updatedAt": "2026-11-14T11:34:35Z"
}
@@ -1,132 +0,0 @@
{
"zh-CN": {
"title": "如何使用 · 等高线地形图",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:顶部选一种地形(山地 / 盆地 / 丘陵 / 高原 / 平原),画面会换成对应的等高线图。",
"第 2 步:把鼠标移到图上任意位置,底部会显示该点的海拔、相对高度和地形部位。",
"第 3 步:观察左边的立体地形与右边的等高线图,找出同一个山峰,看它在两张图上分别长什么样。",
"第 4 步:点右下角「取消上色」,只留等高线;再点一次恢复分层设色,对比哪种更便于判读。",
"第 5 步:对着右侧的判读要点,依次在图上找出一个山峰、一条山脊、一条山谷、一处鞍部和一处陡崖。"
]
},
{
"h": "等高线是什么",
"lines": [
"在地图上,把海拔相同的点用线连起来,这条线就叫等高线。",
"相邻两条等高线之间的高差叫等高距:本图山地、高原、盆地用 100 米,丘陵用 10 米,平原用 5 米。",
"等高线的闭合圈,数值由中心向四周递减的是山峰;四周高中间低的是盆地。",
"等高线向海拔低处凸出的是山脊(分水线);向海拔高处凸出的是山谷(集水线)。",
"两个山峰之间低下去的地方叫鞍部;等高线重叠或挤成一团的地方是陡崖。",
"等高线越密,坡度越陡;越疏,坡度越缓。",
"每 5 条等高线加粗一条叫计曲线,上面标着海拔,方便读数。"
]
},
{
"h": "海拔与相对高度",
"lines": [
"海拔:地面某一点高出海平面的垂直距离。",
"相对高度:两个地点海拔的差值,也就是图上两点的落差。",
"底部读数里的「相对高度」是本图最低点到该点的高差。"
]
},
{
"h": "五种地体的等高线特征",
"lines": [
"山地:海拔高、起伏大,等高线密集且数值跨度大。",
"盆地:四周高、中间低,等高线由外向内数值递减,常有河流发育。",
"丘陵:海拔不高、坡度和缓,等高线稀疏弯曲。",
"高原:海拔高而顶面平坦,等高线中部稀疏、边缘密集。",
"平原:海拔低、地面平坦,等高线很少甚至没有。"
]
},
{
"h": "地图上的教科书符号",
"lines": [
"分层设色:按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白),同一档内颜色完全相同。",
"山峰用 ▲ 加高程数字标注。",
"河流用蓝色线表示,沿谷底(等高线凸向高处的一侧)流。",
"陡崖用红色锯齿线表示。",
"指北针在图幅右上角,比例尺在左下角,分层设色图例在右下角。",
"地形剖面图在图幅底部:沿南北中线剖开地面,标出各点海拔,看清起伏。"
]
},
{
"h": "容易出错的地方",
"lines": [
"把「等高线密集 = 陡」记反:密集是陡,稀疏是缓。",
"把山脊和山谷看反:看凸出的方向 —— 凸向低处是山脊,凸向高处是山谷。",
"忽视等高距:等高距变了,同样的等高线密度代表的坡度就不同。",
"把计曲线当成普通等高线:计曲线加粗并标了数值,读高程要看它。"
]
}
]
},
"en": {
"title": "How to use · Contour Map",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: pick a terrain type at the top (mountains / basin / hills / plateau / plain) — the map switches to its contour map.",
"Step 2: move the pointer anywhere on the map; the footer shows elevation, relative height and the terrain feature.",
"Step 3: compare the 3D block on the left with the contour map on the right — find the same peak in both.",
"Step 4: click “No colour” at the bottom right to keep only the contour lines; click again to restore the colour fill.",
"Step 5: using the panel on the right, find one peak, one ridge, one valley, one saddle and one cliff."
]
},
{
"h": "What contour lines are",
"lines": [
"Connect points of equal elevation on a map and you get a contour line.",
"The height gap between neighbouring contours is the contour interval: 100 m for mountains, plateau and basin; 10 m for hills; 5 m for plain.",
"A closed loop whose values decrease outward is a peak; high ground around a low centre is a basin.",
"Contours bulging toward lower ground form a ridge (watershed); bulging toward higher ground form a valley (drainage).",
"The low ground between two peaks is a saddle; overlapping or tightly crowded contours mark a cliff.",
"The closer the contours, the steeper the slope; the wider apart, the gentler.",
"Every 5th contour is bolded as an index contour and labelled with its elevation."
]
},
{
"h": "Elevation and relative height",
"lines": [
"Elevation is the vertical height of a point above sea level.",
"Relative height is the difference between two elevations — the drop between two points on the map.",
"The relative height in the footer is measured from the lowest point of this map."
]
},
{
"h": "Contour patterns of the five terrains",
"lines": [
"Mountains: high elevation, large relief, dense contours over a wide value range.",
"Basin: high rim, low centre; values decrease inward, often with a river.",
"Hills: low elevation, gentle slopes, sparse winding contours.",
"Plateau: high but flat on top — contours sparse in the middle and crowded at the edges.",
"Plain: low and flat — few or no contour lines at all."
]
},
{
"h": "Textbook map symbols",
"lines": [
"Hypsometric tint: fixed colour bands by elevation (dark green → light green → green → pale yellow → yellow → light brown → brown → white); each band is a flat colour.",
"Peaks are marked with a ▲ and their elevation.",
"Rivers are drawn in blue along the valley floor (where contours bulge uphill).",
"Cliffs are marked with a red saw-tooth line.",
"A north arrow sits top-right, a scale bar bottom-left, and the tint legend bottom-right.",
"The terrain profile along the bottom cuts the ground open and labels elevations, showing the relief at a glance."
]
},
{
"h": "Common mistakes",
"lines": [
"Reversing dense and sparse: dense means steep, sparse means gentle.",
"Mixing up ridge and valley — look which way the bulge points: toward lower ground is a ridge, toward higher ground is a valley.",
"Ignoring the contour interval: change it and the same spacing means a different slope.",
"Treating index contours as ordinary ones — they are bold and labelled, so read elevations off them."
]
}
]
}
}
@@ -1,4 +0,0 @@
{
"app.title": "Contour Map",
"app.subtitle": "Grade 7 · Reading terrain maps: from 3D relief to contour lines"
}
@@ -1,4 +0,0 @@
{
"app.title": "等高线地形图",
"app.subtitle": "七年级上册 · 地形图的判读:从立体地形到平面等高线"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

@@ -1,23 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>NeoRF.ContourMap</RootNamespace>
<AssemblyName>ContourMapModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\GC.ModelSdk\GC.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
@@ -1,62 +0,0 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using GC.ModelSdk;
namespace NeoRF.ContourMap;
/// <summary>等高线模型入口(清单里的 type 指向这里)。</summary>
public sealed class ContourMapFactory : IModelFactory
{
public int ApiVersion => 1;
public IModelRuntime Create() => new ContourMapRuntime();
}
/// <summary>
/// 等高线模型运行时。
/// 依据人教版七年级上册「地形图的判读」:海拔与相对高度、等高线与等高距、
/// 山峰/山脊/山谷/鞍部/陡崖的判读、坡度陡缓与等高线疏密的关系。
/// </summary>
public sealed class ContourMapRuntime : IModelRuntime
{
private TerrainField? _field;
private Dictionary<string, string>? _texts;
public void Prepare(IModelContext context)
{
context.ReportProgress(0.15, "生成地形高度场");
_field = new TerrainField(TerrainKind.Mountain, 192);
context.ReportProgress(0.70, "提取等高线");
_texts = LoadTexts(context.DataDirectory, context.Language);
context.ReportProgress(0.92, "准备界面");
context.Log($"[contour-map] 地形 {_field.Size}×{_field.Size}," +
$"海拔 {_field.MinHeight:0}~{_field.MaxHeight:0} m,等高距 {_field.EffectiveInterval:0} m");
}
public Control CreateView(IModelContext context)
{
_texts ??= LoadTexts(context.DataDirectory, context.Language);
// 五种地体都在界面里现场生成(切换很快,不必预先生成全部)
return new ContourPage(_texts).Build();
}
public void Dispose()
{
_field = null;
_texts = null;
System.GC.SuppressFinalize(this);
}
private static Dictionary<string, string> LoadTexts(string dataDir, string language)
{
var map = new Dictionary<string, string>(DefaultTexts.Zh);
var isEn = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
if (isEn) foreach (var kv in DefaultTexts.En) map[kv.Key] = kv.Value;
return map;
}
}
-369
View File
@@ -1,369 +0,0 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace NeoRF.ContourMap;
/// <summary>等高线模型的界面:顶部标题、中间双图联动、右侧判读要点、底部实时读数。</summary>
public sealed class ContourPage
{
private static readonly Color CAppBg = Color.Parse("#0B1524");
private static readonly Color CPanel = Color.Parse("#101E31");
private static readonly Color CLine = Color.Parse("#1E3350");
private static readonly Color CInk = Color.Parse("#EAF2FF");
private static readonly Color CInkDim = Color.Parse("#93A8C6");
private static readonly Color CInkFaint = Color.Parse("#6A80A0");
private static readonly Color CAccent = Color.Parse("#4D8CFF");
private static readonly Color CWarn = Color.Parse("#FFB454");
private static readonly Color CGood = Color.Parse("#5FD69B");
private TerrainField _field;
private readonly Dictionary<string, string> _texts;
private readonly Dictionary<TerrainKind, TerrainField> _cache = new();
private Border? _colorBtn;
private TextBlock? _colorBtnText;
private TerrainKind _kind = TerrainKind.Mountain;
private ContourView? _view;
private TextBlock? _readout;
private TextBlock? _featureText;
public ContourPage(Dictionary<string, string> texts)
{
_texts = texts;
_field = GetField(TerrainKind.Mountain);
}
/// <summary>取(并缓存)某类地体的高度场,切换时不重复计算。</summary>
private TerrainField GetField(TerrainKind kind)
{
if (!_cache.TryGetValue(kind, out var f))
{
f = new TerrainField(kind, 192);
_cache[kind] = f;
}
return f;
}
private string T(string key) => _texts.TryGetValue(key, out var v) ? v : key;
private static SolidColorBrush B(Color c) => new(c);
public Control Build()
{
var root = new Grid { Background = B(CAppBg) };
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
root.RowDefinitions.Add(new RowDefinition(GridLength.Star));
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
root.Children.Add(BuildHeader());
var body = new Grid { Margin = new Thickness(14, 8, 14, 6) };
body.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(288)));
_view = new ContourView(_field, T);
_view.HoverChanged += OnHover;
var canvasHolder = new Border
{
Background = B(Color.Parse("#08111E")),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
ClipToBounds = true,
Child = _view
};
Grid.SetColumn(canvasHolder, 0);
body.Children.Add(canvasHolder);
var side = BuildSidePanel();
Grid.SetColumn(side, 1);
body.Children.Add(side);
Grid.SetRow(body, 1);
root.Children.Add(body);
root.Children.Add(BuildFooter());
Grid.SetRow(root.Children[^1], 2);
return root;
}
private Control BuildHeader()
{
var title = new TextBlock
{
Text = T("app.title"),
Foreground = B(CInk),
FontSize = 16,
FontWeight = FontWeight.SemiBold
};
var sub = new TextBlock
{
Text = T("app.subtitle"),
Foreground = B(CInkFaint),
FontSize = 10.5
};
var stack = new StackPanel { Spacing = 2 };
stack.Children.Add(title);
stack.Children.Add(sub);
// 地体类型选择:教科书里的五种基本地形
var kinds = new (TerrainKind Kind, string Key)[]
{
(TerrainKind.Mountain, "kind.mountain"),
(TerrainKind.Basin, "kind.basin"),
(TerrainKind.Hill, "kind.hill"),
(TerrainKind.Plateau, "kind.plateau"),
(TerrainKind.Plain, "kind.plain"),
};
var tabs = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 6,
Margin = new Thickness(0, 9, 0, 0)
};
foreach (var (kind, key) in kinds)
{
var btn = MakeKindTab(kind, T(key));
tabs.Children.Add(btn);
}
var header = new StackPanel();
header.Children.Add(stack);
header.Children.Add(tabs);
return new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 0, 0, 1),
Padding = new Thickness(18, 11, 18, 12),
Child = header
};
}
/// <summary>地体类型按钮:选中高亮。</summary>
private Button MakeKindTab(TerrainKind kind, string label)
{
var b = new Button
{
Content = label,
FontSize = 11.5,
Padding = new Thickness(13, 5),
CornerRadius = new CornerRadius(8),
BorderThickness = new Thickness(1),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Tag = kind
};
void Style()
{
var on = _kind == kind;
b.Background = B(on ? CAccent : Color.Parse("#16263C"));
b.BorderBrush = B(on ? CAccent : Color.Parse("#263A56"));
b.Foreground = B(on ? Colors.White : CInkDim);
}
Style();
b.Click += (_, _) =>
{
_kind = kind;
_field = GetField(kind);
_view?.SetField(_field);
// 重新刷新所有 tab 的选中态
if (b.Parent is StackPanel sp)
foreach (var c in sp.Children)
if (c is Button sib && sib.Tag is TerrainKind)
{
var on = (TerrainKind)sib.Tag == _kind;
sib.Background = B(on ? CAccent : Color.Parse("#16263C"));
sib.BorderBrush = B(on ? CAccent : Color.Parse("#263A56"));
sib.Foreground = B(on ? Colors.White : CInkDim);
}
};
return b;
}
private Control BuildSidePanel()
{
var panel = new StackPanel { Spacing = 10, Margin = new Thickness(12, 0, 0, 0) };
panel.Children.Add(Section(T("side.features")));
foreach (var (titleKey, descKey) in new[]
{
("feature.peak", "feature.peakDesc"),
("feature.ridge", "feature.ridgeDesc"),
("feature.valley", "feature.valleyDesc"),
("feature.saddle", "feature.saddleDesc"),
("feature.cliff", "feature.cliffDesc")
})
{
panel.Children.Add(FeatureRow(T(titleKey), T(descKey)));
}
panel.Children.Add(Section(T("side.rules")));
panel.Children.Add(Bullet(T("rule.interval")));
panel.Children.Add(Bullet(T("rule.dense")));
panel.Children.Add(Bullet(T("rule.index")));
panel.Children.Add(Bullet(T("rule.height")));
var scroll = new ScrollViewer
{
Content = new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
Padding = new Thickness(14, 12),
Child = panel
},
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto
};
return scroll;
}
private Control Section(string text) => new TextBlock
{
Text = text,
Foreground = B(CInkDim),
FontSize = 11.5,
FontWeight = FontWeight.SemiBold,
Margin = new Thickness(0, 4, 0, 0)
};
private Control Bullet(string text) => new TextBlock
{
Text = "• " + text,
Foreground = B(CInkDim),
FontSize = 11,
TextWrapping = TextWrapping.Wrap,
LineHeight = 17
};
private Control FeatureRow(string name, string desc)
{
var title = new TextBlock
{
Text = name,
Foreground = B(CWarn),
FontSize = 12,
FontWeight = FontWeight.SemiBold
};
var d = new TextBlock
{
Text = desc,
Foreground = B(CInkFaint),
FontSize = 10.5,
TextWrapping = TextWrapping.Wrap,
LineHeight = 16
};
var stack = new StackPanel { Spacing = 1 };
stack.Children.Add(title);
stack.Children.Add(d);
return stack;
}
private Control BuildFooter()
{
_readout = new TextBlock
{
Text = T("footer.hint"),
Foreground = B(CInkDim),
FontSize = 11.5
};
_featureText = new TextBlock
{
Text = "",
Foreground = B(CGood),
FontSize = 11.5,
FontWeight = FontWeight.SemiBold,
HorizontalAlignment = HorizontalAlignment.Right
};
// 右下角「上色」开关:点击一次去掉分层设色,只显示线稿,再点恢复
_colorBtnText = new TextBlock
{
Text = T("btn.color"),
FontSize = 11.5,
Foreground = B(Colors.White)
};
_colorBtn = new Border
{
Background = B(CAccent),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(13, 6),
Margin = new Thickness(0, 0, 12, 0),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = _colorBtnText
};
_colorBtn.PointerPressed += (_, _) => ToggleColor();
var left = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
left.Children.Add(_readout);
Grid.SetColumn(_colorBtn, 1);
left.Children.Add(_colorBtn);
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
row.Children.Add(left);
Grid.SetColumn(_featureText, 1);
row.Children.Add(_featureText);
return new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 1, 0, 0),
Padding = new Thickness(18, 9),
Child = row
};
}
/// <summary>切换分层设色。</summary>
private void ToggleColor()
{
if (_view == null) return;
_view.Colored = !_view.Colored;
if (_colorBtn != null)
_colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55"));
if (_colorBtnText != null)
_colorBtnText.Text = _view.Colored ? T("btn.colorOn") : T("btn.color");
}
private void OnHover(double u, double v, float height, TerrainFeature feature)
{
if (_readout == null || _featureText == null) return;
var relative = height - _field.MinHeight;
_readout.Text = string.Format(
System.Globalization.CultureInfo.InvariantCulture,
T("footer.readout"), (int)height, (int)relative);
_featureText.Text = FeatureName(feature);
_featureText.Foreground = B(feature switch
{
TerrainFeature.Peak => Color.Parse("#FFD166"),
TerrainFeature.Cliff => Color.Parse("#FF7B7B"),
TerrainFeature.Saddle => Color.Parse("#C08CFF"),
TerrainFeature.Ridge => Color.Parse("#5FD69B"),
TerrainFeature.Valley => Color.Parse("#5BC8FF"),
_ => CInkDim
});
}
private string FeatureName(TerrainFeature f) => f switch
{
TerrainFeature.Peak => T("feature.peak"),
TerrainFeature.Ridge => T("feature.ridge"),
TerrainFeature.Valley => T("feature.valley"),
TerrainFeature.Saddle => T("feature.saddle"),
TerrainFeature.Cliff => T("feature.cliff"),
TerrainFeature.Slope => T("feature.slope"),
_ => ""
};
}
-585
View File
@@ -1,585 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
namespace NeoRF.ContourMap;
/// <summary>
/// 等高线教学画布,左右两块:
/// · 左:三维地形块(斜视图),表现真实起伏
/// · 右:等高线俯视图(分层设色 + 等高线 + 标注)
///
/// 鼠标在任一侧移动,两侧同步显示该点的海拔与地形部位 —— 这正是课本
/// 「把立体地形转成平面等高线图」的关键对应关系。
/// </summary>
public sealed class ContourView : Control
{
// ── 配色(与启动器深色舞台一致)
private static readonly Color CInk = Color.Parse("#111A2E");
private static readonly Color CLine = Color.Parse("#DCE7F8");
private static readonly Color CContour = Color.Parse("#3B2A18");
private static readonly Color CContourIndex = Color.Parse("#1F1508");
private static readonly Color CAccent = Color.Parse("#2F6BFF");
private static readonly Color CWarn = Color.Parse("#FF6B4A");
private static readonly Typeface Font = new("Noto Sans CJK SC, Microsoft YaHei, Arial");
public TerrainField Field { get; private set; }
/// <summary>切换到另一块地形(重新提取等高线)。</summary>
public void SetField(TerrainField field)
{
Field = field;
_levels = Field.ContourLevels();
_contours.Clear();
foreach (var lv in _levels)
_contours.Add((lv, Field.ExtractContour(lv)));
InvalidateVisual();
}
/// <summary>等高线缓存:level -> 折线集合。</summary>
private readonly List<(float Level, List<List<(double U, double V)>> Lines)> _contours = new();
private List<float> _levels = new();
public Func<string, string> T { get; set; } = k => k;
// ── 交互状态
private double _hoverU = 0.5, _hoverV = 0.5;
private bool _hasHover;
private Point _pointerPosition;
private HoverRegion _hoverRegion;
private enum HoverRegion
{
None,
Terrain,
ContourMap
}
private bool _showContours = true;
private bool _showLabels = true;
private bool _showSlope = true;
private bool _colored = true;
public bool ShowContours
{
get => _showContours;
set => SetFlag(ref _showContours, value);
}
public bool ShowLabels
{
get => _showLabels;
set => SetFlag(ref _showLabels, value);
}
public bool ShowSlope
{
get => _showSlope;
set => SetFlag(ref _showSlope, value);
}
/// <summary>是否分层设色(关闭后只看线稿,便于观察等高线本身)。</summary>
public bool Colored
{
get => _colored;
set => SetFlag(ref _colored, value);
}
private void SetFlag(ref bool slot, bool value)
{
if (slot == value) return;
slot = value;
InvalidateVisual();
}
/// <summary>当前悬停点信息,供外部状态栏显示。</summary>
public event Action<double, double, float, TerrainFeature>? HoverChanged;
public ContourView(TerrainField field, Func<string, string> text)
{
Field = field;
T = text;
ClipToBounds = true;
_levels = Field.ContourLevels();
foreach (var lv in _levels)
_contours.Add((lv, Field.ExtractContour(lv)));
PointerMoved += (_, e) =>
{
var p = e.GetPosition(this);
UpdateHover(p);
};
PointerExited += (_, _) => ClearHover();
}
private void UpdateHover(Point p)
{
var size = Bounds.Size;
if (size.Width < 40 || size.Height < 40) return;
var (left, right) = SplitRects(size);
var map = ContourMapRect(right);
double u = -1, v = -1;
var region = HoverRegion.None;
if (map.Contains(p))
{
u = (p.X - map.X) / map.Width;
v = (p.Y - map.Y) / map.Height;
region = HoverRegion.ContourMap;
}
else if (left.Contains(p))
{
// 左图是斜视图,做逆变换近似:把点击位置反投到 u/v
(u, v) = UnprojectIso(left, p);
region = HoverRegion.Terrain;
}
if (region == HoverRegion.None || u < 0 || u > 1 || v < 0 || v > 1)
{
ClearHover();
return;
}
_hoverU = u; _hoverV = v; _hasHover = true;
_pointerPosition = p;
_hoverRegion = region;
var h = Field.SampleSmooth(u, v);
var f = TerrainAnalyzer.Classify(Field, u, v);
HoverChanged?.Invoke(u, v, h, f);
InvalidateVisual();
}
private void ClearHover()
{
if (!_hasHover) return;
_hasHover = false;
_hoverRegion = HoverRegion.None;
InvalidateVisual();
}
private (Rect Left, Rect Right) SplitRects(Size size)
{
var pad = 16.0;
var half = (size.Width - pad * 3) / 2;
var h = size.Height - pad * 2;
return (new Rect(pad, pad, half, h),
new Rect(pad * 2 + half, pad, half, h));
}
private static Rect ContourMapRect(Rect panel)
{
var profileHeight = Math.Min(132, panel.Height * 0.30);
return profileHeight > 50
? new Rect(panel.X, panel.Y, panel.Width, panel.Height - profileHeight)
: panel;
}
// ---------------------------------------------------------------- 渲染
public override void Render(DrawingContext dc)
{
var size = Bounds.Size;
if (size.Width < 80 || size.Height < 80) return;
dc.FillRectangle(new SolidColorBrush(Color.Parse("#0B1524")), new Rect(size));
var (left, right) = SplitRects(size);
DrawIsoTerrain(dc, left);
DrawContourMap(dc, right);
}
// ---- 左侧:三维地形块 ----
private void DrawIsoTerrain(DrawingContext dc, Rect r)
{
// 斜投影:x 向右,y 向前(缩小),高度向上
var cx = r.X + r.Width * 0.5;
var cy = r.Y + r.Height * 0.62;
var scaleX = r.Width * 0.62;
var scaleY = r.Height * 0.30;
var heightScale = r.Height * 0.00011; // 高度压缩系数
Point Project(double u, double v, double h) => new(
cx + (u - 0.5) * scaleX,
cy + (v - 0.5) * scaleY - h * heightScale);
// 逐格绘制(远到近,保证遮挡顺序正确)
const int N = 54;
for (var j = 0; j < N; j++)
{
for (var i = 0; i < N; i++)
{
var u0 = (double)i / N; var u1 = (double)(i + 1) / N;
var v0 = (double)j / N; var v1 = (double)(j + 1) / N;
var h00 = Field.SampleSmooth(u0, v0);
var h10 = Field.SampleSmooth(u1, v0);
var h11 = Field.SampleSmooth(u1, v1);
var h01 = Field.SampleSmooth(u0, v1);
var hAvg = (h00 + h10 + h11 + h01) / 4f;
var (cr, cg, cb) = TerrainAnalyzer.ColorForHeight(hAvg, Field.MinHeight, Field.MaxHeight);
// 简易光照:面向西北的坡面更亮
var shade = 0.78 + 0.42 * ((h00 - h11) / Math.Max(1f, Field.MaxHeight - Field.MinHeight) * -1 + 0.5);
shade = Math.Clamp(shade, 0.55, 1.25);
var brush = new SolidColorBrush(Color.FromRgb(
(byte)Math.Clamp(cr * shade, 0, 255),
(byte)Math.Clamp(cg * shade, 0, 255),
(byte)Math.Clamp(cb * shade, 0, 255)));
var p00 = Project(u0, v0, h00);
var p10 = Project(u1, v0, h10);
var p11 = Project(u1, v1, h11);
var p01 = Project(u0, v1, h01);
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(p00, true);
g.LineTo(p10);
g.LineTo(p11);
g.LineTo(p01);
g.EndFigure(true);
}
dc.DrawGeometry(brush, null, geo);
}
}
// 悬停指示
if (_hasHover)
{
var h = Field.SampleSmooth(_hoverU, _hoverV);
var p = _hoverRegion == HoverRegion.Terrain
? _pointerPosition
: Project(_hoverU, _hoverV, h);
dc.DrawEllipse(new SolidColorBrush(Colors.White), new Pen(new SolidColorBrush(CAccent), 2),
p, 5, 5);
var stem = new Point(p.X, p.Y + 30);
dc.DrawLine(new Pen(new SolidColorBrush(CAccent), 1.5), p, stem);
Text(dc, $"{(int)h} m", stem.X, stem.Y + 3, 11.5, Colors.White, true, TextAlignment.Center);
}
}
/// <summary>斜视图反投影(近似):把屏幕点还原成 u/v。</summary>
private (double U, double V) UnprojectIso(Rect r, Point p)
{
var cx = r.X + r.Width * 0.5;
var cy = r.Y + r.Height * 0.62;
var scaleX = r.Width * 0.62;
var scaleY = r.Height * 0.30;
var u = (p.X - cx) / scaleX + 0.5;
var v = (p.Y - cy) / scaleY + 0.5;
return (u, v);
}
// ---- 右侧:等高线俯视图 ----
private void DrawContourMap(DrawingContext dc, Rect r)
{
var panel = r;
var mapRect = ContourMapRect(panel);
var profileRect = new Rect(panel.X, mapRect.Bottom, panel.Width, panel.Bottom - mapRect.Bottom);
r = mapRect;
// 分层设色底图
const int N = 96;
for (var j = 0; j < N; j++)
{
for (var i = 0; i < N; i++)
{
var u = (i + 0.5) / N; var v = (j + 0.5) / N;
var h = Field.SampleSmooth(u, v);
var (cr, cg, cb) = TerrainAnalyzer.ColorForHeight(h, Field.MinHeight, Field.MaxHeight);
var brush = _colored
? new SolidColorBrush(Color.FromRgb(cr, cg, cb))
: new SolidColorBrush(Color.Parse("#F3F0E6"));
dc.FillRectangle(brush, new Rect(
r.X + r.Width * i / N,
r.Y + r.Height * j / N,
r.Width / N + 1,
r.Height / N + 1));
}
}
Point P(double u, double v) => new(r.X + u * r.Width, r.Y + v * r.Height);
// 等高线
if (_showContours)
{
foreach (var (level, lines) in _contours)
{
var isIndex = Math.Abs(level % 500) < 0.5; // 每 5 条一条计曲线
var pen = new Pen(new SolidColorBrush(isIndex ? CContourIndex : CContour),
isIndex ? 2.0 : 1.0);
foreach (var line in lines)
{
if (line.Count < 2) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(P(line[0].U, line[0].V), false);
for (var i = 1; i < line.Count; i++)
g.LineTo(P(line[i].U, line[i].V));
g.EndFigure(false);
}
dc.DrawGeometry(null, pen, geo);
}
}
}
// 等高线高程标注(计曲线)
if (_showLabels)
{
foreach (var (level, lines) in _contours)
{
if (Math.Abs(level % 500) > 0.5) continue;
foreach (var line in lines)
{
if (line.Count < 12) continue;
var mid = line[line.Count / 2];
var at = P(mid.U, mid.V);
if (at.X < r.X + 16 || at.X > r.Right - 16) continue;
Text(dc, $"{(int)level}", at.X, at.Y - 7, 9.5, CContourIndex, true, TextAlignment.Center);
}
}
}
// ── 教科书地形符号 ──
// 河流:蓝色线(沿谷底流)
if (Field.River.Count > 1)
{
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(P(Field.River[0].U, Field.River[0].V), false);
for (var i = 1; i < Field.River.Count; i++)
g.LineTo(P(Field.River[i].U, Field.River[i].V));
g.EndFigure(false);
}
var riverPen = new Pen(new SolidColorBrush(Color.Parse("#2F7FD0")), 2.2);
riverPen.LineJoin = PenLineJoin.Round;
riverPen.LineCap = PenLineCap.Round;
dc.DrawGeometry(null, riverPen, geo);
}
// 山峰:▲ + 高程数字(教科书标注法)
foreach (var (pu, pv, ph) in Field.Peaks.Take(4))
{
var at = P(pu, pv);
var tri = new StreamGeometry();
using (var g = tri.Open())
{
g.BeginFigure(new Point(at.X, at.Y - 6), true);
g.LineTo(new Point(at.X - 5.5, at.Y + 4));
g.LineTo(new Point(at.X + 5.5, at.Y + 4));
g.EndFigure(true);
}
dc.DrawGeometry(new SolidColorBrush(Color.Parse("#3A2A18")), null, tri);
Text(dc, ((int)ph).ToString(), at.X + 8, at.Y - 8, 10, Color.Parse("#3A2A18"), true);
}
// 陡崖:锯齿符号(教科书用锯齿线表示陡崖)
foreach (var (cu, cv) in Field.Cliffs.Take(40))
{
var at = P(cu, cv);
var saw = new StreamGeometry();
using (var g = saw.Open())
{
g.BeginFigure(new Point(at.X - 3, at.Y + 3), false);
for (var i = 0; i < 3; i++)
{
var x0 = at.X - 3 + i * 3;
g.LineTo(new Point(x0 + 1.5, at.Y - 2));
g.LineTo(new Point(x0 + 3, at.Y + 3));
}
g.EndFigure(false);
}
dc.DrawGeometry(null, new Pen(new SolidColorBrush(Color.Parse("#8B2E2E")), 1.4), saw);
}
// 悬停十字
if (_hasHover)
{
var at = P(_hoverU, _hoverV);
var pen = new Pen(new SolidColorBrush(CAccent), 1.6);
dc.DrawLine(pen, new Point(r.X, at.Y), new Point(r.Right, at.Y));
dc.DrawLine(pen, new Point(at.X, r.Y), new Point(at.X, r.Bottom));
dc.DrawEllipse(new SolidColorBrush(Colors.White), new Pen(new SolidColorBrush(CAccent), 2), at, 5, 5);
}
DrawNorthArrow(dc, r);
DrawScaleBar(dc, r);
DrawLegend(dc, r);
if (profileRect.Height > 50) DrawProfile(dc, profileRect, mapRect);
// 边框
dc.DrawRectangle(null, new Pen(new SolidColorBrush(CLine), 1.2), r);
}
/// <summary>
/// 地形剖面图(教科书等高线图必配):沿图幅中部的一条南北剖面线,
/// 画出地面起伏并标注各点海拔。这是最能体现「等高线图 ↔ 立体地形」关系的图。
/// </summary>
private void DrawProfile(DrawingContext dc, Rect r, Rect mapRect)
{
if (r.Height < 50) return;
// 背景
dc.FillRectangle(new SolidColorBrush(Color.FromArgb(235, 252, 250, 244)), r);
dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 1.0), r);
// 纵轴比例:0 → 最大高程
var maxH = Math.Max(1f, Field.MaxHeight);
var baseY = r.Bottom - 18;
var topY = r.Y + 16;
// 水平网格(每 200 m 一条)
for (var hh = 200f; hh < maxH; hh += 200)
{
var gy = baseY - (hh / maxH) * (baseY - topY);
dc.DrawLine(new Pen(new SolidColorBrush(Color.FromArgb(70, 42, 52, 70)), 0.8),
new Point(r.X, gy), new Point(r.Right, gy));
Text(dc, $"{hh:0}", r.X + 2, gy - 8, 7.5, Color.Parse("#5A6B80"));
}
// 基准线
dc.DrawLine(new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 1.2),
new Point(r.X, baseY), new Point(r.Right, baseY));
// 剖面线:沿图幅中部(v = 0.5)自西向东
const int N = 160;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
for (var i = 0; i <= N; i++)
{
var u = (double)i / N;
var hv = Field.SampleSmooth(u, 0.5);
var y = baseY - (hv / maxH) * (baseY - topY);
var x = r.X + u * r.Width;
if (i == 0) g.BeginFigure(new Point(x, y), false);
else g.LineTo(new Point(x, y));
}
g.EndFigure(false);
}
dc.DrawGeometry(null, new Pen(new SolidColorBrush(Color.Parse("#B03A2E")), 2.0), geo);
// 剖面线上的几个关键点(与等高线图上的位置对应)
var marks = new[] { 0.0, 0.25, 0.5, 0.75, 1.0 };
foreach (var u in marks)
{
var hv = Field.SampleSmooth(u, 0.5);
var y = baseY - (hv / maxH) * (baseY - topY);
var x = r.X + u * r.Width;
dc.DrawEllipse(new SolidColorBrush(Color.Parse("#B03A2E")), null, new Point(x, y), 3, 3);
Text(dc, $"{hv:0}", x, y - 13, 8, Color.Parse("#8B2E24"), true, TextAlignment.Center);
}
// 标注:剖面线在图上的位置
Text(dc, T("profile.title"), r.X + 6, r.Y + 3, 9, Color.Parse("#2A3446"), true);
dc.DrawLine(new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 1.2, dashStyle: DashStyle.Dash),
new Point(r.X + r.Width / 2, mapRect.Y), new Point(r.X + r.Width / 2, r.Y));
}
/// <summary>指北针(教科书地图必备,位于图幅右上角)。</summary>
private void DrawNorthArrow(DrawingContext dc, Rect r)
{
var x = r.Right - 26;
var y = r.Y + 20;
var tri = new StreamGeometry();
using (var g = tri.Open())
{
g.BeginFigure(new Point(x, y - 12), true);
g.LineTo(new Point(x - 5, y + 6));
g.LineTo(new Point(x, y + 2));
g.EndFigure(true);
}
dc.DrawGeometry(new SolidColorBrush(Color.Parse("#2A3446")), null, tri);
var tri2 = new StreamGeometry();
using (var g2 = tri2.Open())
{
g2.BeginFigure(new Point(x, y - 12), true);
g2.LineTo(new Point(x + 5, y + 6));
g2.LineTo(new Point(x, y + 2));
g2.EndFigure(true);
}
dc.DrawGeometry(new SolidColorBrush(Color.Parse("#8FA0B8")), null, tri2);
Text(dc, "N", x, y + 8, 9.5, Color.Parse("#2A3446"), true, TextAlignment.Center);
}
/// <summary>比例尺(教科书地图必备,左下角)。</summary>
private void DrawScaleBar(DrawingContext dc, Rect r)
{
var x = r.X + 14;
var y = r.Bottom - 22;
var w = 90.0;
var h = 5.0;
// 分黑白相间的格(教科书比例尺画法)
for (var i = 0; i < 4; i++)
{
var seg = new Rect(x + i * w / 4, y, w / 4, h);
dc.FillRectangle(new SolidColorBrush(i % 2 == 0
? Color.Parse("#2A3446") : Color.Parse("#FFFFFF")), seg);
dc.DrawRectangle(new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 0.8), seg);
}
Text(dc, "0", x, y - 11, 8.5, Color.Parse("#2A3446"), align: TextAlignment.Center);
Text(dc, "1 km", x + w, y - 11, 8.5, Color.Parse("#2A3446"), align: TextAlignment.Center);
}
/// <summary>分层设色图例(教科书右下角的色阶表)。</summary>
private void DrawLegend(DrawingContext dc, Rect r)
{
var bands = new (float From, float To)[]
{
(0, 200), (200, 400), (400, 600), (600, 800),
(800, 1000), (1000, 1200), (1200, 1400), (1400, 1600), (1600, 2000)
};
var w = 62.0;
var rowH = 11.0;
var h = bands.Length * rowH + 16;
var x = r.Right - w - 12;
var y = r.Bottom - h - 12;
dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(210, 255, 255, 255)), null,
new Rect(x, y, w, h));
dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 0.9),
new Rect(x, y, w, h));
Text(dc, T("legend.title"), x + 5, y + 3, 8.5, Color.Parse("#2A3446"), true);
for (var i = 0; i < bands.Length; i++)
{
var (from, to) = bands[i];
var mid = (from + to) / 2;
var (cr, cg, cb) = TerrainAnalyzer.ColorForHeight(mid, 0, 2000);
var cy = y + 14 + i * rowH;
dc.FillRectangle(new SolidColorBrush(Color.FromRgb(cr, cg, cb)),
new Rect(x + 5, cy, 14, rowH - 2));
dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 0.6),
new Rect(x + 5, cy, 14, rowH - 2));
var label = to >= 2000 ? ">1600 m" : $"{from:0}–{to:0} m";
Text(dc, label, x + 23, cy, 8, Color.Parse("#2A3446"));
}
}
// ---------------------------------------------------------------- 文字
private void Text(DrawingContext dc, string s, double x, double y, double size, Color color,
bool bold = false, TextAlignment align = TextAlignment.Left)
{
var ft = new FormattedText(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
new Typeface(Font.FontFamily, FontStyle.Normal, bold ? FontWeight.Bold : FontWeight.Normal),
size, new SolidColorBrush(color));
ft.TextAlignment = align;
dc.DrawText(ft, new Point(align == TextAlignment.Center ? x - ft.Width / 2 : x, y));
}
}
-83
View File
@@ -1,83 +0,0 @@
using System.Collections.Generic;
namespace NeoRF.ContourMap;
/// <summary>内置全量文案兜底:没有语言包也能完整显示。</summary>
internal static class DefaultTexts
{
public static readonly Dictionary<string, string> Zh = new()
{
["app.title"] = "等高线地形图",
["app.subtitle"] = "七年级上册 · 地形图的判读:从立体地形到平面等高线",
["kind.mountain"] = "山地",
["kind.basin"] = "盆地",
["kind.hill"] = "丘陵",
["kind.plateau"] = "高原",
["kind.plain"] = "平原",
["legend.title"] = "分层设色",
["profile.title"] = "地形剖面图",
["btn.color"] = "上色",
["btn.colorOn"] = "取消上色",
["side.features"] = "五种地形部位",
["feature.peak"] = "山峰",
["feature.peakDesc"] = "等高线闭合,数值由中心向四周递减。",
["feature.ridge"] = "山脊",
["feature.ridgeDesc"] = "等高线凸向低处,脊线是分水线。",
["feature.valley"] = "山谷",
["feature.valleyDesc"] = "等高线凸向高处,谷线是集水线,常发育河流。",
["feature.saddle"] = "鞍部",
["feature.saddleDesc"] = "两个山峰之间的低地,形如马鞍。",
["feature.cliff"] = "陡崖",
["feature.cliffDesc"] = "等高线重叠或非常密集,近乎垂直。",
["feature.slope"] = "坡面",
["side.rules"] = "判读要点",
["rule.interval"] = "等高距:相邻两条等高线的高度差,本图 100 米。",
["rule.dense"] = "等高线越密坡越陡,越疏坡越缓。",
["rule.index"] = "每 5 条加粗一条计曲线,标注海拔便于读数。",
["rule.height"] = "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。",
["footer.hint"] = "把鼠标移到任意一侧,可查看该点的海拔与地形部位",
["footer.readout"] = "海拔 {0} m 相对高度 {1} m"
};
public static readonly Dictionary<string, string> En = new()
{
["app.title"] = "Contour Map",
["app.subtitle"] = "Grade 7 · Reading terrain maps: from 3D relief to contour lines",
["kind.mountain"] = "Mountains",
["kind.basin"] = "Basin",
["kind.hill"] = "Hills",
["kind.plateau"] = "Plateau",
["kind.plain"] = "Plain",
["legend.title"] = "Hypsometric tint",
["profile.title"] = "Terrain profile",
["btn.color"] = "Colour",
["btn.colorOn"] = "No colour",
["side.features"] = "Five terrain features",
["feature.peak"] = "Peak",
["feature.peakDesc"] = "Closed contours; values decrease outward from the centre.",
["feature.ridge"] = "Ridge",
["feature.ridgeDesc"] = "Contours bulge toward lower ground; a watershed line.",
["feature.valley"] = "Valley",
["feature.valleyDesc"] = "Contours bulge toward higher ground; a drainage line, often a stream.",
["feature.saddle"] = "Saddle",
["feature.saddleDesc"] = "Low ground between two peaks, shaped like a saddle.",
["feature.cliff"] = "Cliff",
["feature.cliffDesc"] = "Contours overlap or crowd tightly — nearly vertical.",
["feature.slope"] = "Slope",
["side.rules"] = "Key rules",
["rule.interval"] = "Contour interval: height gap between neighbours (100 m here).",
["rule.dense"] = "Closer contours = steeper slope; wider spacing = gentler.",
["rule.index"] = "Every 5th contour is bolded and labelled as an index contour.",
["rule.height"] = "Elevation above sea level; relative height is the difference of two elevations.",
["footer.hint"] = "Move the pointer over either side to read elevation and terrain feature",
["footer.readout"] = "Elevation {0} m Relative height {1} m"
};
}
-155
View File
@@ -1,155 +0,0 @@
using System;
using System.Collections.Generic;
namespace NeoRF.ContourMap;
/// <summary>地形部位识别结果:课本要求学生能在等高线图上认出这五种部位。</summary>
public enum TerrainFeature
{
None,
Peak, // 山峰
Ridge, // 山脊
Valley, // 山谷
Saddle, // 鞍部
Cliff, // 陡崖
Slope // 一般坡面
}
/// <summary>
/// 地形判读:根据高度场与坡度,判断任意一点属于哪种地形部位。
/// 这是课本「等高线判读」的核心,直接从数据算出来,不靠预设标记。
/// </summary>
public static class TerrainAnalyzer
{
/// <summary>
/// 判断某点的地形部位。
///
/// 先查地形自带的**标注区**(教学用,位置由地形定义保证准确),
/// 未命中再按坡度/曲率自动推断。纯几何推断对「鞍部」「陡崖」这类
/// 特征容易误判,教学场景必须精确。
/// </summary>
public static TerrainFeature Classify(TerrainField field, double u, double v)
{
var tagged = field.TagAt(u, v);
if (tagged != TerrainFeature.None) return tagged;
var h = field.SampleSmooth(u, v);
var grad = Gradient(field, u, v);
var slope = Math.Sqrt(grad.dU * grad.dU + grad.dV * grad.dV); // 归一化坡度
// 陡崖:坡度极大(等高线挤成一团)。
// 阈值按本图实际坡度分布标定(中位≈2.5、p99≈6.8),
// 取 p99 以上一小段,否则大片坡面会被误判成陡崖。
if (slope > 8.5) return TerrainFeature.Cliff;
// 山峰:比四周都高
if (IsLocalMax(field, u, v)) return TerrainFeature.Peak;
// 鞍部:两个方向上高、另两个方向上低
if (IsSaddle(field, u, v)) return TerrainFeature.Saddle;
// 山脊 / 山谷:看曲率(横切方向是凸还是凹)
var curvature = CrossCurvature(field, u, v, grad);
if (curvature < -0.55) return TerrainFeature.Ridge; // 向外凸
if (curvature > 0.55) return TerrainFeature.Valley; // 向内凹
return TerrainFeature.Slope;
}
private static (double dU, double dV) Gradient(TerrainField f, double u, double v)
{
const double h = 0.004;
var du = (f.SampleSmooth(u + h, v) - f.SampleSmooth(u - h, v)) / (2 * h);
var dv = (f.SampleSmooth(u, v + h) - f.SampleSmooth(u, v - h)) / (2 * h);
return (du / 1000.0, dv / 1000.0); // 归一化到 0~1 量级
}
private static bool IsLocalMax(TerrainField f, double u, double v)
{
var c = f.SampleSmooth(u, v);
const double r = 0.035;
foreach (var (du, dv) in new[] { (r, 0.0), (-r, 0.0), (0.0, r), (0.0, -r) })
{
// 越近边界越不判为峰
if (u + du < 0 || u + du > 1 || v + dv < 0 || v + dv > 1) return false;
if (f.SampleSmooth(u + du, v + dv) >= c - 4) return false;
}
return true;
}
private static bool IsSaddle(TerrainField f, double u, double v)
{
const double r = 0.05;
if (u - r < 0 || u + r > 1 || v - r < 0 || v + r > 1) return false;
var c = f.SampleSmooth(u, v);
var l = f.SampleSmooth(u - r, v); var rt = f.SampleSmooth(u + r, v);
var t = f.SampleSmooth(u, v - r); var b = f.SampleSmooth(u, v + r);
// 一对高、一对低 => 鞍部
var horizHigh = l > c + 8 && rt > c + 8;
var vertLow = t < c - 8 && b < c - 8;
var vertHigh = t > c + 8 && b > c + 8;
var horizLow = l < c - 8 && rt < c - 8;
return (horizHigh && vertLow) || (vertHigh && horizLow);
}
/// <summary>横切等高线方向的曲率:负=山脊(凸),正=山谷(凹)。</summary>
private static double CrossCurvature(TerrainField f, double u, double v, (double dU, double dV) grad)
{
var len = Math.Sqrt(grad.dU * grad.dU + grad.dV * grad.dV);
if (len < 1e-6) return 0;
// 垂直于梯度方向(即沿等高线方向)的平均法向变化
var nU = -grad.dV / len;
var nV = grad.dU / len;
const double r = 0.045;
var c = f.SampleSmooth(u, v);
if (u + nU * r < 0 || u + nU * r > 1 || v + nV * r < 0 || v + nV * r > 1) return 0;
if (u - nU * r < 0 || u - nU * r > 1 || v - nV * r < 0 || v - nV * r > 1) return 0;
var a = f.SampleSmooth(u + nU * r, v + nV * r);
var b = f.SampleSmooth(u - nU * r, v - nV * r);
return (a + b - 2 * c) / 1000.0 * 6.0;
}
/// <summary>
/// 教科书规范的**分层设色**:按固定高程档位套用固定色阶,档内不渐变。
///
/// 人教版七年级上册的分层设色色阶(自低到高):
/// 深绿 → 浅绿 → 绿 → 浅黄 → 黄 → 浅褐 → 褐 → 浅棕 → 白
/// 关键点:**同一档内颜色完全相同**,这样一眼就能数出有几层,
/// 而不是课本上那种连续渐变。
/// </summary>
public static (byte R, byte G, byte B) ColorForHeight(float h, float min, float max)
{
// 按绝对高程分档(教科书就是这么画的:看的是海拔,不是相对高度)
const float band = 200f; // 每 200 米一档
if (h < 200) return (0x1E, 0x6B, 0x3A); // 深绿:< 200 m
if (h < 400) return (0x4E, 0x9E, 0x4E); // 浅绿:200–400
if (h < 600) return (0xA8, 0xC6, 0x66); // 绿:400–600
if (h < 800) return (0xE8, 0xE2, 0x9A); // 浅黄:600–800
if (h < 1000) return (0xE0, 0xC0, 0x5A); // 黄:800–1000
if (h < 1200) return (0xC8, 0x9A, 0x63); // 浅褐:1000–1200
if (h < 1400) return (0xA8, 0x74, 0x4C); // 褐:1200–1400
if (h < 1600) return (0xC8, 0xA8, 0x8C); // 浅棕:1400–1600
return (0xF5, 0xF5, 0xF0); // 白:> 1600(雪线以上)
}
/// <summary>该颜色属于哪一档(用于图例)。</summary>
public static string BandName(float h) => h switch
{
< 200 => "200 米以下",
< 400 => "200–400 米",
< 600 => "400–600 米",
< 800 => "600–800 米",
< 1000 => "800–1000 米",
< 1200 => "1000–1200 米",
< 1400 => "1200–1400 米",
< 1600 => "1400–1600 米",
_ => "1600 米以上"
};
private static byte Lerp(byte a, byte b, double k)
=> (byte)Math.Clamp(a + (b - a) * k, 0, 255);
}
-502
View File
@@ -1,502 +0,0 @@
using System;
using System.Collections.Generic;
namespace NeoRF.ContourMap;
/// <summary>五种基本地形类型(教科书分类)。</summary>
public enum TerrainKind
{
Mountain, // 山地:海拔高、起伏大
Basin, // 盆地:四周高、中间低
Hill, // 丘陵:海拔较低、坡度和缓
Plateau, // 高原:海拔高、地面平坦、边缘陡
Plain // 平原:海拔低、地面平坦
}
/// <summary>
/// 地形高度场(等高线模型的数据核心)。
///
/// 用叠加的高斯山包合成一块教学用地形:
/// · 主峰(山峰)
/// · 次峰(与主峰之间形成鞍部)
/// · 两条山脊、一条山谷
/// · 一侧陡坡(等高线密集)、一侧缓坡(等高线稀疏)
/// · 一处陡崖
///
/// 高度单位米,网格分辨率可配置;网格值一次性算好,等高线由它切线得出。
/// </summary>
public sealed class TerrainField
{
/// <summary>网格边长(正方形,便于俯视与等高线处理)。</summary>
public int Size { get; }
/// <summary>海拔网格,[y, x],单位米。</summary>
public float[,] Heights { get; }
public float MinHeight { get; private set; }
public float MaxHeight { get; private set; }
/// <summary>等高距(米):教学图常用 100 m。</summary>
public float Interval { get; init; } = 100f;
/// <summary>这块地形属于哪种类型(决定界面标题与说明)。</summary>
public TerrainKind Kind { get; }
public TerrainField(TerrainKind kind = TerrainKind.Mountain, int size = 192)
{
Size = size;
Kind = kind;
Heights = new float[size, size];
Build(kind);
}
/// <summary>该类型对应的等高距:平原/丘陵用 20m,山地/高原/盆地用 100m。</summary>
public float EffectiveInterval => Kind switch
{
TerrainKind.Plain => 5f, // 平原起伏小,等高距要小才画得出线
TerrainKind.Hill => 10f, // 丘陵相对高差约 150 m
_ => 100f
};
/// <summary>归一化坐标 (u,v) ∈ [0,1],u 向东、v 向南。</summary>
public float HeightAt(double u, double v)
{
var x = (int)Math.Round(u * (Size - 1));
var y = (int)Math.Round(v * (Size - 1));
x = Math.Clamp(x, 0, Size - 1);
y = Math.Clamp(y, 0, Size - 1);
return Heights[y, x];
}
/// <summary>双线性插值取值,画平滑曲线时用。</summary>
public float SampleSmooth(double u, double v)
{
var fx = Math.Clamp(u, 0, 1) * (Size - 1);
var fy = Math.Clamp(v, 0, 1) * (Size - 1);
var x0 = (int)Math.Floor(fx); var y0 = (int)Math.Floor(fy);
var x1 = Math.Min(x0 + 1, Size - 1); var y1 = Math.Min(y0 + 1, Size - 1);
var tx = fx - x0; var ty = fy - y0;
var h00 = Heights[y0, x0]; var h10 = Heights[y0, x1];
var h01 = Heights[y1, x0]; var h11 = Heights[y1, x1];
var a = h00 * (1 - tx) + h10 * tx;
var b = h01 * (1 - tx) + h11 * tx;
return (float)(a * (1 - ty) + b * ty);
}
private void Build(TerrainKind kind)
{
switch (kind)
{
case TerrainKind.Mountain: BuildMountain(); break;
case TerrainKind.Basin: BuildBasin(); break;
case TerrainKind.Hill: BuildHill(); break;
case TerrainKind.Plateau: BuildPlateau(); break;
case TerrainKind.Plain: BuildPlain(); break;
}
BuildFeatures();
}
private void BuildMountain()
{
// 各山体参数:中心(u,v)、高度、东西半径、南北半径
var peaks = new (double U, double V, double H, double RU, double RV)[]
{
(0.34, 0.34, 1180, 0.26, 0.24), // 主峰
(0.66, 0.52, 860, 0.20, 0.20), // 次峰(与主峰间成鞍部)
(0.22, 0.70, 520, 0.18, 0.16), // 西侧小山
(0.78, 0.22, 430, 0.16, 0.15), // 东北小山
};
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
double h = 120; // 基准面(平原 / 河谷)
foreach (var p in peaks)
{
var du = (u - p.U) / p.RU;
var dv = (v - p.V) / p.RV;
var d2 = du * du + dv * dv;
h += p.H * Math.Exp(-d2 * 1.15);
}
// 山谷:沿一条斜线切下去,形成 V 形谷地
var valley = Math.Abs((u - 0.5) * 0.8 + (v - 0.44) * 0.6);
h -= 210 * Math.Exp(-valley * valley / 0.0016);
// 陡崖:东侧一条近乎垂直的高差带(等高线会挤在一起)
if (u > 0.86 && v > 0.18 && v < 0.72)
h += 260 * SmoothStep(0.86, 0.895, u);
// 缓坡:西南角缓慢抬升
if (u < 0.3 && v > 0.6)
h += 90 * (1 - u / 0.3) * ((v - 0.6) / 0.4);
// 轻微起伏,避免地形过于几何化
h += 18 * Math.Sin(u * 9.1) * Math.Cos(v * 7.7);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min;
MaxHeight = max;
}
/// <summary>盆地:四周高、中间低,等高线由外向内递减。</summary>
private void BuildBasin()
{
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
var du = u - 0.5; var dv = v - 0.5;
var r = Math.Sqrt(du * du + dv * dv) * 2.0; // 0=中心 1=边缘
// 边缘抬升、中心下沉,形成碗状
double h = 160 + 900 * Math.Pow(Math.Clamp(r, 0, 1.15), 2.2);
// 一侧开个缺口(山口),让盆地向外开口
var gap = Math.Abs(Math.Atan2(dv, du) - 0.5);
if (gap < 0.35) h -= 320 * (1 - gap / 0.35) * (1 - Math.Clamp(r, 0, 1));
h += 14 * Math.Sin(u * 7.3) * Math.Cos(v * 6.1);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min; MaxHeight = max;
}
/// <summary>丘陵:起伏和缓、海拔不高,等高线稀疏而弯曲。</summary>
private void BuildHill()
{
var bumps = new (double U, double V, double H, double R)[]
{
(0.30, 0.32, 120, 0.20), (0.66, 0.28, 95, 0.17),
(0.52, 0.62, 140, 0.22), (0.22, 0.72, 88, 0.16),
(0.78, 0.70, 110, 0.18),
};
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
double h = 60;
foreach (var b in bumps)
{
var du = (u - b.U) / b.R; var dv = (v - b.V) / b.R;
h += b.H * Math.Exp(-(du * du + dv * dv) * 1.3);
}
h += 10 * Math.Sin(u * 11.0) * Math.Cos(v * 9.0);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min; MaxHeight = max;
}
/// <summary>高原:顶部平坦、边缘陡峭(等高线在中部稀疏、边缘密集)。</summary>
private void BuildPlateau()
{
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
// 到中心的距离,做平台 + 陡降
var du = (u - 0.5); var dv = (v - 0.5);
var r = Math.Sqrt(du * du + dv * dv) * 2.0;
double h;
if (r < 0.55) h = 1250; // 平坦顶面
else h = 1250 - 1000 * SmoothStep(0.55, 0.78, r); // 边缘陡降
// 顶面轻微起伏,避免完全平板
if (r < 0.55) h += 25 * Math.Sin(u * 6.0) * Math.Cos(v * 5.0);
h += 30 * (1 - Math.Clamp(r, 0, 1));
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min; MaxHeight = max;
}
/// <summary>平原:地面低平、起伏极小,等高线很少。</summary>
private void BuildPlain()
{
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
// 整体微倾 + 极缓的起伏
double h = 40 + 22 * u + 8 * Math.Sin(u * 4.2) * Math.Cos(v * 3.6);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min; MaxHeight = max;
}
private static double SmoothStep(double a, double b, double x)
{
var t = Math.Clamp((x - a) / (b - a), 0, 1);
return t * t * (3 - 2 * t);
}
/// <summary>
/// 教学标注区:把「典型部位」的位置固化成圆形区域,
/// 保证判读结果与地形设计一致(纯几何推断对鞍部/陡崖易误判)。
/// </summary>
public List<(double U, double V, double Radius, TerrainFeature Feature)> Tags { get; } = new()
{
(0.34, 0.34, 0.045, TerrainFeature.Peak), // 主峰
(0.66, 0.52, 0.042, TerrainFeature.Peak), // 次峰
(0.50, 0.44, 0.055, TerrainFeature.Saddle), // 两峰之间的鞍部
(0.90, 0.45, 0.035, TerrainFeature.Cliff), // 东侧陡崖
(0.22, 0.70, 0.045, TerrainFeature.Ridge), // 西南山脊
(0.50, 0.22, 0.040, TerrainFeature.Valley), // 河谷
};
/// <summary>查询标注区;未命中返回 None。</summary>
public TerrainFeature TagAt(double u, double v)
{
foreach (var (tu, tv, r, f) in Tags)
{
var du = u - tu; var dv = v - tv;
if (du * du + dv * dv <= r * r) return f;
}
return TerrainFeature.None;
}
/// <summary>
/// 河流:从最高点出发,沿最陡下降方向流到图边。
/// 教科书上的河流画蓝色线,且**只在河谷(等高线凸向高处的一侧)里流**。
/// </summary>
public List<(double U, double V)> River { get; } = new();
/// <summary>山峰位置(用于画 ▲ 与高程数字):局部最高点。</summary>
public List<(double U, double V, float Height)> Peaks { get; } = new();
/// <summary>陡崖位置(用于画锯齿线):坡度极大处。</summary>
public List<(double U, double V)> Cliffs { get; } = new();
/// <summary>找出山峰、陡崖,并生成河流线。</summary>
private void BuildFeatures()
{
// --- 山峰:局部最高且足够高 ---
const int step = 4;
for (var y = step; y < Size - step; y += step)
{
for (var x = step; x < Size - step; x += step)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
var h = Heights[y, x];
if (h < MaxHeight * 0.55) continue;
var isMax = true;
for (var dy = -step; dy <= step && isMax; dy += step)
for (var dx = -step; dx <= step; dx += step)
{
if (dx == 0 && dy == 0) continue;
if (Heights[y + dy, x + dx] > h) { isMax = false; break; }
}
if (isMax) Peaks.Add((u, v, h));
}
}
Peaks.Sort((a, b) => b.Height.CompareTo(a.Height));
// --- 陡崖:坡度极大 ---
const int cstep = 3;
for (var y = cstep; y < Size - cstep; y += cstep)
{
for (var x = cstep; x < Size - cstep; x += cstep)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
var h = 0.004;
var du = (Heights[y, x + 2] - Heights[y, x - 2]) / (2 * h * (Size - 1)) / 1000;
var dv = (Heights[y + 2, x] - Heights[y - 2, x]) / (2 * h * (Size - 1)) / 1000;
var slope = Math.Sqrt(du * du + dv * dv);
if (slope > 0.11) Cliffs.Add((u, v));
}
}
// --- 河流:从最高点沿最陡下降方向走 ---
if (Peaks.Count > 0)
{
var start = Peaks[0];
var cu = start.U; var cv = start.V;
River.Add((cu, cv));
const int maxSteps = 400;
for (var step2 = 0; step2 < maxSteps; step2++)
{
var h0 = SampleSmooth(cu, cv);
double bestU = 0, bestV = 0; var bestH = h0; var found = false;
for (var a = 0; a < 16; a++)
{
var ang = a * Math.PI * 2 / 16;
var nu = cu + Math.Cos(ang) * 0.012;
var nv = cv + Math.Sin(ang) * 0.012;
if (nu < 0 || nu > 1 || nv < 0 || nv > 1) continue;
var nh = SampleSmooth(nu, nv);
if (nh < bestH) { bestH = nh; bestU = nu; bestV = nv; found = true; }
}
if (!found) break;
cu = bestU; cv = bestV;
River.Add((cu, cv));
if (cu <= 0.001 || cu >= 0.999 || cv <= 0.001 || cv >= 0.999) break;
if (bestH < MinHeight + 20) break;
}
}
}
/// <summary>等高线高度列表:从 MaxHeight 往下按等高距取整。</summary>
public List<float> ContourLevels()
{
var levels = new List<float>();
var iv = EffectiveInterval;
var top = (float)(Math.Floor(MaxHeight / iv) * iv);
var bottom = (float)(Math.Ceiling(MinHeight / iv) * iv);
for (var h = bottom; h <= top + 0.01f; h += iv)
levels.Add(h);
levels.Sort();
return levels;
}
/// <summary>
/// 用 Marching Squares 提取某条等高线,返回若干条折线(归一化坐标)。
/// </summary>
public List<List<(double U, double V)>> ExtractContour(float level)
{
var result = new List<List<(double, double)>>();
var size = Size;
// 记录每条线段,再按端点连通性串成折线
var segments = new List<(double U1, double V1, double U2, double V2)>();
for (var y = 0; y < size - 1; y++)
{
for (var x = 0; x < size - 1; x++)
{
var h00 = Heights[y, x];
var h10 = Heights[y, x + 1];
var h11 = Heights[y + 1, x + 1];
var h01 = Heights[y + 1, x];
var idx = 0;
if (h00 >= level) idx |= 1;
if (h10 >= level) idx |= 2;
if (h11 >= level) idx |= 4;
if (h01 >= level) idx |= 8;
if (idx == 0 || idx == 15) continue;
double u0 = (double)x / (size - 1), u1 = (double)(x + 1) / (size - 1);
double v0 = (double)y / (size - 1), v1 = (double)(y + 1) / (size - 1);
// 四条边上的交点
(double, double) Top() => (Lerp(u0, u1, (level - h00) / (h10 - h00)), v0);
(double, double) Bottom() => (Lerp(u0, u1, (level - h01) / (h11 - h01)), v1);
(double, double) Left() => (u0, Lerp(v0, v1, (level - h00) / (h01 - h00)));
(double, double) Right() => (u1, Lerp(v0, v1, (level - h10) / (h11 - h10)));
void Add((double U, double V) a, (double U, double V) b)
=> segments.Add((a.Item1, a.Item2, b.Item1, b.Item2));
switch (idx)
{
case 1: case 14: Add(Left(), Top()); break;
case 2: case 13: Add(Top(), Right()); break;
case 3: case 12: Add(Left(), Right()); break;
case 4: case 11: Add(Right(), Bottom()); break;
case 6: case 9: Add(Top(), Bottom()); break;
case 7: case 8: Add(Left(), Bottom()); break;
case 5: Add(Left(), Top()); Add(Right(), Bottom()); break;
case 10: Add(Top(), Right()); Add(Left(), Bottom()); break;
}
}
}
return Chain(segments);
}
private static double Lerp(double a, double b, double t)
=> a + (b - a) * Math.Clamp(double.IsNaN(t) ? 0.5 : t, 0, 1);
/// <summary>把零散线段按端点邻近关系串成折线。</summary>
private static List<List<(double U, double V)>> Chain(
List<(double U1, double V1, double U2, double V2)> segments)
{
const double Eps = 0.004;
var result = new List<List<(double, double)>>();
var used = new bool[segments.Count];
for (var i = 0; i < segments.Count; i++)
{
if (used[i]) continue;
used[i] = true;
var line = new List<(double, double)>
{
(segments[i].U1, segments[i].V1),
(segments[i].U2, segments[i].V2)
};
// 向两端延伸
var grown = true;
while (grown)
{
grown = false;
var (tailU, tailV) = line[^1];
for (var j = 0; j < segments.Count; j++)
{
if (used[j]) continue;
var s = segments[j];
if (Near(tailU, tailV, s.U1, s.V1, Eps))
{
line.Add((s.U2, s.V2)); used[j] = true; grown = true; break;
}
if (Near(tailU, tailV, s.U2, s.V2, Eps))
{
line.Add((s.U1, s.V1)); used[j] = true; grown = true; break;
}
}
}
if (line.Count >= 4) result.Add(line);
}
return result;
}
private static bool Near(double u1, double v1, double u2, double v2, double eps)
=> Math.Abs(u1 - u2) < eps && Math.Abs(v1 - v2) < eps;
}
@@ -1,30 +0,0 @@
{
"id": "earth-geography",
"nameI18n": {
"zh-CN": "地球地理",
"en": "Earth Geography"
},
"descriptionI18n": {
"zh-CN": "五带划分、七大洲四大洋轮廓、六大板块与洲界,纯线稿教学图。",
"en": "Climate zones, continent/ocean outlines, plates and borders — clean line art."
},
"assembly": "EarthGeographyModel.dll",
"type": "NeoRF.EarthModels.GeographyModelFactory",
"author": "Morris GC",
"tags": [
"geography",
"earth",
"atlas"
],
"dataDir": "earth-geography.model",
"version": "1.8",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "3b645c45c2",
"updatedAt": "2026-11-14T11:34:35Z"
}
@@ -1 +0,0 @@
{"borders":[{"between":"亚洲-非洲","name":"苏伊士运河","lines":[[[32.6,31.3],[32.4,30.5],[32.3,29.9]]]},{"between":"亚洲-欧洲","name":"亚欧分界(乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡)","segments":[{"name":"乌拉尔山","nameI18n":{"zh-CN":"乌拉尔山","en":"Ural Mts."},"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0]]]},{"name":"乌拉尔河","nameI18n":{"zh-CN":"乌拉尔河","en":"Ural River"},"lines":[[[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5]]]},{"name":"里海","nameI18n":{"zh-CN":"里海","en":"Caspian Sea"},"lines":[[[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5]]]},{"name":"大高加索山","nameI18n":{"zh-CN":"大高加索山","en":"Greater Caucasus"},"lines":[[[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2]]]},{"name":"黑海","nameI18n":{"zh-CN":"黑海","en":"Black Sea"},"lines":[[[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5]]]},{"name":"土耳其海峡","nameI18n":{"zh-CN":"土耳其海峡","en":"Turkish Straits"},"lines":[[[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]}],"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0],[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5],[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5],[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2],[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5],[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]},{"between":"欧洲-非洲","name":"直布罗陀海峡","lines":[[[-5.6,36.0],[-4.0,36.2],[0.0,36.5]]]},{"between":"北美-南美","name":"巴拿马运河","lines":[[[-79.6,9.1],[-78.5,8.9],[-77.5,8.6]]]},{"between":"南美-南极","name":"德雷克海峡","nameI18n":{"zh-CN":"德雷克海峡","en":"Drake Passage"},"lines":[[[-68.0,-56.0],[-66.5,-57.5],[-65.0,-59.0],[-63.5,-60.5],[-62.0,-62.0]]]},{"between":"亚洲-北美","name":"白令海峡","lines":[[[-169.0,65.5],[-170.5,65.8],[-172.0,66.0]]]},{"between":"亚洲-大洋洲","name":"印尼群岛","lines":[[[120.0,-1.0],[125.0,-2.0],[130.0,-3.0]]]},{"between":"南极洲","name":"南极圈","lines":[[[-180.0,-66.5],[-170.0,-66.5],[-160.0,-66.5],[-150.0,-66.5],[-140.0,-66.5],[-130.0,-66.5],[-120.0,-66.5],[-110.0,-66.5],[-100.0,-66.5],[-90.0,-66.5],[-80.0,-66.5],[-70.0,-66.5],[-60.0,-66.5],[-50.0,-66.5],[-40.0,-66.5],[-30.0,-66.5],[-20.0,-66.5],[-10.0,-66.5],[0.0,-66.5],[10.0,-66.5],[20.0,-66.5],[30.0,-66.5],[40.0,-66.5],[50.0,-66.5],[60.0,-66.5],[70.0,-66.5],[80.0,-66.5],[90.0,-66.5],[100.0,-66.5],[110.0,-66.5],[120.0,-66.5],[130.0,-66.5],[140.0,-66.5],[150.0,-66.5],[160.0,-66.5],[170.0,-66.5],[180.0,-66.5]]]}]}
@@ -1 +0,0 @@
{"lines":[[[180.0,-16.17],[179.56,-16.64],[179.93,-16.52],[179.93,-16.74],[179.2,-16.71],[178.71,-16.98],[178.5,-16.79],[178.58,-16.62],[180.0,-16.17]],[[143.18,-11.95],[143.11,-12.3],[143.4,-12.64],[143.76,-14.35],[143.96,-14.46],[144.47,-14.23],[145.29,-14.94],[145.43,-16.41],[145.91,-16.91],[146.13,-17.64],[146.03,-18.27],[146.33,-18.55],[146.38,-18.98],[147.42,-19.38],[147.74,-19.77],[148.76,-20.29],[148.88,-20.48],[148.68,-20.58],[149.45,-21.58],[149.7,-22.44],[149.97,-22.55],[150.02,-22.17],[150.54,-22.56],[150.62,-22.37],[150.84,-23.46],[151.83,-24.12],[153.16,-25.96],[153.12,-27.19],[153.62,-28.67],[153.03,-30.56],[152.94,-31.43],[152.47,-32.44],[151.81,-32.9],[151.29,-33.58],[150.81,-35.01],[150.19,-35.83],[149.93,-37.53],[149.48,-37.77],[147.88,-37.93],[146.86,-38.66],[146.22,-38.73],[146.47,-38.84],[146.4,-39.15],[145.4,-38.53],[145.48,-38.24],[144.96,-38.5],[144.72,-38.34],[145.12,-38.09],[144.89,-37.9],[144.4,-38.14],[144.66,-38.21],[143.54,-38.82],[142.46,-38.39],[141.42,-38.36],[140.39,-37.9],[139.78,-37.25],[139.73,-36.37],[138.97,-35.58],[139.29,-35.61],[139.28,-35.38],[138.18,-35.61],[138.51,-35.02],[138.09,-34.17],[137.69,-35.14],[136.88,-35.24],[137.01,-34.92],[137.39,-34.91],[137.49,-34.16],[137.93,-33.58],[137.85,-33.2],[137.99,-33.09],[137.78,-32.58],[137.79,-32.82],[137.24,-33.63],[136.43,-34.03],[135.89,-34.66],[135.97,-34.98],[135.65,-34.94],[135.12,-34.59],[135.45,-34.58],[135.22,-33.96],[134.72,-33.26],[134.3,-33.16],[134.1,-32.75],[134.23,-32.55],[133.66,-32.21],[132.76,-31.96],[132.22,-32.01],[131.14,-31.5],[128.95,-31.7],[127.32,-32.26],[125.92,-32.3],[124.24,-33.02],[123.51,-33.92],[122.15,-33.99],[121.41,-33.83],[119.85,-33.98],[119.45,-34.37],[117.86,-35.05],[116.52,-34.99],[115.01,-34.26],[114.99,-33.52],[115.36,-33.64],[115.68,-33.19],[115.7,-31.7],[115.08,-30.56],[114.86,-29.14],[114.17,-28.08],[114.03,-27.35],[113.19,-26.18],[113.32,-26.24],[113.36,-26.08],[113.58,-26.56],[113.84,-26.5],[113.45,-25.6],[113.71,-25.83],[113.72,-26.13],[113.85,-26.01],[113.99,-26.32],[114.22,-26.29],[114.21,-25.85],[113.42,-24.44],[113.76,-23.42],[113.68,-22.64],[114.02,-21.88],[114.14,-22.48],[114.71,-21.82],[116.71,-20.65],[117.41,-20.72],[119.1,-20.0],[119.59,-20.04],[121.0,-19.6],[121.83,-18.48],[122.34,-18.11],[122.15,-17.55],[122.26,-17.14],[122.97,-16.44],[123.56,-17.52],[123.59,-17.03],[123.83,-17.12],[123.87,-16.92],[123.49,-16.49],[123.61,-16.22],[124.77,-16.4],[124.41,-16.3],[124.65,-15.87],[124.5,-15.97],[124.38,-15.76],[124.44,-15.49],[124.69,-15.27],[125.06,-15.44],[124.84,-15.16],[125.04,-15.0],[125.36,-15.12],[125.18,-14.71],[125.58,-14.48],[125.63,-14.26],[125.66,-14.53],[126.02,-14.49],[126.05,-13.98],[126.57,-14.16],[126.9,-13.74],[127.46,-14.03],[128.2,-14.75],[128.07,-15.33],[128.58,-14.78],[129.06,-14.88],[129.22,-15.16],[129.27,-14.87],[129.63,-15.14],[129.64,-14.85],[129.85,-14.83],[129.38,-14.39],[129.84,-13.57],[130.26,-13.3],[130.17,-12.96],[130.62,-12.65],[130.62,-12.43],[130.87,-12.56],[131.29,-12.07],[131.44,-12.28],[132.41,-12.29],[132.71,-12.12],[132.67,-11.65],[131.82,-11.3],[131.96,-11.18],[135.03,-12.19],[135.92,-11.83],[135.7,-12.21],[136.01,-12.19],[136.08,-12.42],[136.26,-12.43],[136.27,-12.13],[136.54,-11.96],[136.95,-12.35],[136.54,-12.78],[136.46,-13.22],[135.93,-13.3],[135.95,-13.94],[135.45,-14.92],[138.25,-16.72],[139.01,-16.9],[139.25,-17.33],[140.04,-17.7],[140.51,-17.62],[140.83,-17.41],[141.41,-16.07],[141.62,-15.06],[141.47,-13.8],[141.61,-12.94],[141.93,-12.74],[141.69,-12.35],[141.96,-12.05],[142.17,-10.95],[142.6,-10.75],[142.87,-11.82],[143.18,-11.95]],[[178.28,-17.37],[178.59,-17.65],[178.67,-18.08],[177.96,-18.26],[177.32,-18.08],[177.26,-17.86],[177.5,-17.54],[178.28,-17.37]],[[164.2,-20.25],[165.19,-20.77],[166.94,-22.09],[166.97,-22.32],[166.47,-22.26],[164.93,-21.29],[164.38,-20.74],[164.04,-20.17],[164.2,-20.25]],[[127.73,0.85],[127.88,0.83],[128.22,1.4],[128.69,1.57],[128.7,1.11],[128.26,0.73],[128.9,0.22],[127.98,0.47],[127.89,0.3],[127.98,-0.25],[128.43,-0.89],[127.69,-0.24],[127.61,0.85],[127.43,1.14],[127.63,1.84],[128.04,2.2],[127.89,1.83],[128.01,1.33],[127.65,1.01],[127.73,0.85]],[[69.19,-49.11],[69.59,-48.97],[69.64,-49.12],[69.41,-49.18],[69.54,-49.26],[70.32,-49.06],[70.56,-49.2],[70.39,-49.43],[69.76,-49.43],[70.31,-49.58],[70.12,-49.7],[69.15,-49.53],[68.81,-49.7],[68.77,-49.07],[69.0,-48.66],[69.19,-49.11]],[[63.37,80.7],[62.52,80.82],[64.1,81.0],[64.31,81.17],[65.17,81.14],[65.44,80.93],[63.37,80.7]],[[-25.43,70.92],[-25.4,70.65],[-26.22,70.45],[-28.04,70.49],[-27.62,70.91],[-25.82,71.04],[-25.43,70.92]],[[117.31,8.44],[117.35,8.71],[119.22,10.48],[119.55,11.31],[119.69,10.5],[118.78,9.92],[118.44,9.26],[117.31,8.44]],[[122.5,11.62],[122.89,11.44],[123.16,11.54],[123.12,11.29],[122.77,10.82],[121.95,10.44],[122.1,11.64],[121.92,11.85],[122.5,11.62]],[[123.13,9.06],[122.4,9.82],[122.86,10.09],[122.98,10.89],[123.26,10.99],[123.57,10.78],[123.16,9.86],[123.32,9.27],[123.13,9.06]],[[124.58,11.34],[124.93,11.37],[125.0Line truncated
@@ -1 +0,0 @@
{"continents":[{"id":"eurasia","nameI18n":{"zh-CN":"亚欧大陆","en":"Eurasia"},"label":[85,52],"lines":[[[127.7,0.8],[127.9,0.8],[128.2,1.4],[128.7,1.6],[128.7,1.1],[128.3,0.9],[128.3,0.7],[128.9,0.2],[128.0,0.5],[127.9,0.3]],[[127.7,0.3],[127.4,1.1],[127.6,1.8],[128.0,2.2],[128.0,1.3],[127.7,0.8]],[[63.4,80.7],[62.5,80.8],[63.1,81.0],[64.1,81.0],[64.3,81.2],[65.4,81.1],[65.4,80.9],[63.4,80.7]],[[117.3,8.4],[117.3,8.7],[119.2,10.5],[119.3,11.0],[119.6,11.3],[119.5,11.0],[119.7,10.5],[118.8,9.9],[118.4,9.3],[117.3,8.4]],[[122.5,11.6],[122.8,11.6],[122.9,11.4],[123.2,11.5],[122.8,10.8],[122.0,10.4],[122.1,11.6],[121.9,11.9],[122.5,11.6]],[[123.1,9.1],[122.4,9.8],[122.5,10.0],[122.9,10.1],[122.8,10.5],[123.0,10.9],[123.3,11.0],[123.6,10.8],[123.2,9.9],[123.3,9.3],[123.1,9.1]],[[124.6,11.3],[124.9,11.4],[125.3,10.3],[125.1,10.2],[125.0,10.4],[125.0,10.0],[124.8,10.2],[124.7,11.0],[124.4,10.9],[124.3,11.5],[124.6,11.3]],[[125.2,12.5],[125.5,12.2],[125.7,11.1],[125.2,11.1],[124.9,11.6],[125.0,11.8],[124.4,12.2],[124.3,12.6],[125.2,12.5]],[[120.7,13.5],[121.2,13.4],[121.5,13.1],[121.5,12.6],[121.2,12.2],[120.5,13.4],[120.3,13.4],[120.7,13.5]],[[22.6,58.6],[23.3,58.5],[22.0,57.9],[22.2,58.2],[21.9,58.3],[21.9,58.5],[22.6,58.6]],[[21.6,78.6],[22.0,78.6],[22.3,78.2],[23.0,78.3],[23.5,78.1],[23.1,78.0],[24.9,77.8],[22.8,77.3],[22.4,77.3],[22.7,77.6],[21.1,77.4],[20.9,77.6],[21.7,77.9],[20.2,78.5],[21.6,78.6]],[[47.4,80.9],[48.4,80.8],[48.7,80.6],[47.7,80.8],[46.1,80.4],[46.0,80.6],[44.9,80.6],[47.4,80.9]],[[50.3,80.9],[51.7,80.7],[51.0,80.5],[48.8,80.4],[48.7,80.3],[49.0,80.2],[48.4,80.1],[46.6,80.3],[49.1,80.5],[49.2,80.8],[50.3,80.9]],[[50.3,69.2],[50.2,69.0],[48.9,68.7],[48.4,68.8],[48.3,69.0],[48.4,69.3],[49.0,69.5],[50.3,69.2]],[[23.9,35.5],[24.2,35.6],[24.1,35.5],[24.4,35.4],[25.7,35.3],[25.8,35.1],[26.3,35.3],[26.2,35.0]],[[23.9,35.5],[24.2,35.6],[24.1,35.5],[24.4,35.4],[25.7,35.3],[25.8,35.1],[26.3,35.3],[26.2,35.0],[24.8,34.9],[24.5,35.2],[23.6,35.3],[23.7,35.7],[23.9,35.5]],[[23.4,39.0],[23.5,38.8],[24.1,38.6],[24.6,38.0],[22.9,38.9],[23.4,39.0]],[[34.5,35.6],[33.9,35.3],[34.0,35.0],[33.0,34.6],[32.4,34.7],[32.3,35.1],[32.9,35.2],[32.9,35.4],[34.5,35.6]],[[19.1,57.8],[18.8,57.7],[18.9,57.4],[18.1,56.9],[18.3,57.1],[18.1,57.6],[18.9,57.9],[19.1,57.8]],[[12.6,55.8],[12.2,55.5],[12.4,55.3],[12.1,55.2],[12.1,54.8],[11.9,54.8],[11.7,55.2],[11.3,55.2],[11.0,55.7],[11.6,56.0],[11.8,55.7],[11.9,56.0],[12.2,56.1],[12.6,56.1],[12.6,55.8]],[[96.5,81.1],[97.9,80.7],[97.1,80.6],[97.0,80.5],[97.4,80.3],[97.2,80.2],[93.9,80.0],[91.5,80.4],[92.8,80.6],[93.3,80.8],[92.6,80.8],[93.4,81.0],[95.8,81.3],[96.5,81.1]],[[97.7,80.2],[98.0,80.0],[97.6,79.8],[98.4,79.9],[98.6,80.1],[100.1,79.8],[99.7,79.3],[99.0,79.3],[99.9,79.0],[99.4,78.8],[94.8,79.1],[94.2,79.4],[93.1,79.5],[95.0,80.1],[97.7,80.2]],[[102.9,79.3],[102.4,78.8],[103.0,79.1],[103.8,79.1],[105.1,78.8],[105.3,78.5],[104.7,78.3],[99.3,78.0],[100.0,78.3],[100.4,78.8],[101.0,78.8],[100.9,78.9],[101.5,79.3],[102.9,79.3]],[[140.0,75.8],[140.8,75.6],[141.0,76.0],[141.5,76.1],[143.7,75.9],[145.4,75.5],[144.7,75.4],[144.9,75.3],[144.0,75.0],[142.8,75.3],[142.7,75.5],[143.0,75.6],[142.9,75.7],[142.1,75.7],[142.6,75.1],[143.1,75.0],[142.5,74.8],[142.0,75.0],[140.3,74.8],[139.7,75.0],[139.1,74.7],[138.1,74.8],[136.9,75.3],[137.3,75.3],[137.2,75.6],[137.7,75.8],[137.5,75.9],[137.6,76.0],[138.2,76.1],[138.9,76.2],[140.0,75.8]],[[142.2,73.9],[143.5,73.5],[143.5,73.2],[140.7,73.5],[139.7,73.4],[140.4,73.5],[141.1,73.9],[142.2,73.9]],[[146.8,75.4],[150.8,75.2],[150.6,74.9],[148.1,74.8],[146.1,75.2],[146.4,75.6],[146.8,75.4]],[[126.0,9.3],[126.2,9.3],[126.3,9.0],[126.1,8.6],[126.4,8.5],[126.6,7.2],[126.2,6.9],[126.2,6.3],[125.7,7.3],[125.4,6.7],[125.7,6.0],[125.3,5.6],[125.2,6.1],[124.9,5.9],[124.2,6.2],[124.0,7.0],[124.2,7.4],[124.0,7.7],[123.5,7.8],[123.4,7.4],[123.1,7.7],[122.8,7.5],[122.6,7.8],[122.0,7.0],[121.9,7.2],[122.2,7.9],[122.9,8.2],[123.4,8.7],[123.7,8.6],[123.8,8.0],[124.2,8.2],[124.4,8.6],[124.7,8.6],[124.9,9.0],[125.5,9.0],[125.5,9.8],[126.0,9.3]],[[121.1,18.6],[121.8,18.3],[122.3,18.5],[122.2,17.7],[122.5,17.1],[122.1,16.2],[121.6,15.9],[121.4,15.3],[121.7,14.8],[121.6,14.6],[121.9,14.0],[122.2,13.9],[122.2,14.1],[122.6,14.3],[122.9,14.2],[123.1,13.8],[123.3,13.8],[123.3,14.1],[123.8,13.8],[123.5,13.6],[123.8,13.1],[124.1,13.0],[124.1,12.6],[123.9,12.9],[123.3,13.0],[123.2,13.4],[122.6,13.9],[122.6,13.2],[121.8,13.9],[121.3,13.6],[120.8,13.9],[120.6,13.8],[120.6,14.2],[120.9,14.6],[120.6,14.9],[120.6,14.5],[120.4,14.5],[120.1,14.9],[119.8,16.3],[120.2,16.0],[120.4,16.1],[120.3,16.6],[120.6,18.5],[121.1,18.6]],[[124.9,1.0],[124.4,0.5],[123.8,0.3],[123.3,0.3],[123.0,0.5],[120.6,0.5],[120.2,0.3]],[[119.9,0.0],[119.8,0.2],[120.3,1.0],[120.4,0.8],[120.9,1.3],[122.8,0.8],[123.9,0.8],[125.1,1.7],[125.2,1.5],[124.9,1.0]],[[96.5,5.2],[97.5,5.2],[98.3,4.1],[99.7,3.2],[100.5,2.2],[100.9,1.9],[100.8,2.2],[101.0,2.3],[102.4,0.8],[103.0,0.6],[103.0,0.4],[102.5,0.2],[103.3,0.5],[10Line truncated
@@ -1,124 +0,0 @@
{
"zh-CN": {
"title": "如何使用 · 地球地理",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:点右上「平面」,先看完整的世界地图,确认七大洲四大洋的位置。",
"第 2 步:点「五带」,看回归线与极圈怎么把地球分成五个温度带。",
"第 3 步:关掉「五带」,打开「六大板块」,记住六块板块的名字和范围。",
"第 4 步:再打开「五大陆」,对比金色实线(大陆)与彩色虚线(板块)的差别。",
"第 5 步:切回「3D 球面」,拖动转动地球,看背面会自动隐藏。",
"看不清?滚轮放大;想重来点「复位」。每个图层都能单独开关,互不干扰。"
]
},
{
"h": "一、这个模型包含什么",
"lines": [
"五带:热带、南北温带、南北寒带(按回归线 23.5° 与极圈 66.5° 划分)。",
"七大洲四大洋轮廓,以及洲与洲之间的分界线(苏伊士运河、巴拿马运河、白令海峡等)。",
"六大板块:亚欧、非洲、美洲、太平洋、印度洋、南极洲板块。",
"五块大陆:亚欧大陆、非洲大陆、美洲大陆、澳大利亚大陆、南极大陆。"
]
},
{
"h": "二、两种视图",
"lines": [
"「3D 球面」:正交投影球体,拖动旋转、滚轮缩放,背面自动裁掉。",
"「平面」:等经纬矩形地图,课本地图样式,一次看全整幅。",
"「复位」回到初始视角与缩放。"
]
},
{
"h": "三、图层开关(各自独立)",
"lines": [
"「五带」:叠加五带分界线与回归线、极圈。",
"「大洲轮廓」:白色海岸线。",
"「六大板块」:彩色虚线,是板块边界(不是大陆边界)。",
"「五大陆」:金色实线,是大陆轮廓。",
"「洲界」:分界点与分界线标签(如德雷克海峡、乌拉尔山…)。"
]
},
{
"h": "四、颜色与图例",
"lines": [
"右侧图例说明三种线型:海岸线 / 板块边界 / 分界线。",
"底部色块对应五个温度带。",
"六大板块各一种颜色,标签放在板块中心附近。"
]
},
{
"h": "五、教学要点与易错点",
"lines": [
"「板块 ≠ 大陆」:美洲板块覆盖南北美大陆并向东到大西洋中脊;印度洋板块包含澳大利亚与印度次大陆。",
"六大板块是全球一级板块,纳斯卡、阿拉伯等属于次级小板块,教材不列入。",
"板块交界处多火山地震(环太平洋带、地中海—喜马拉雅带)。",
"洲界是人为约定:亚欧以乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡为界;亚非以苏伊士运河为界;南北美以巴拿马运河为界;南美与南极以德雷克海峡为界。",
"Esc 关闭窗口,F11 全屏。"
]
}
]
},
"en": {
"title": "How to use · Earth Geography",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: click Flat in the top right for the whole world map first.",
"Step 2: turn on Climate zones to see how the tropics and polar circles split five belts.",
"Step 3: switch zones off and turn on Six plates; learn the six names and extents.",
"Step 4: turn on Five mainlands and compare solid gold lines (mainlands) with dashed colored lines (plates).",
"Step 5: switch back to 3D globe, drag to rotate, and see back faces clip automatically.",
"Hard to read? Scroll to zoom; press Reset to start over. Each layer toggles independently."
]
},
{
"h": "1. What this model contains",
"lines": [
"Five climate zones split by the tropics (23.5°) and polar circles (66.5°).",
"Seven continents, four oceans, and continental borders (Suez, Panama, Bering, etc.).",
"Six major plates: Eurasian, African, American, Pacific, Indian Ocean, Antarctic.",
"Five mainlands: Eurasia, Africa, America, Australia, Antarctica."
]
},
{
"h": "2. Two views",
"lines": [
"3D globe: orthographic sphere; drag to rotate, scroll to zoom, back faces clipped.",
"Flat: equirectangular textbook map, whole world at once.",
"Reset restores the initial view and zoom."
]
},
{
"h": "3. Independent layer toggles",
"lines": [
"Climate zones: tropics, polar circles and zone edges.",
"Coastlines: white continental outlines.",
"Six plates: dashed colored lines — plate BOUNDARIES, not continental edges.",
"Five mainlands: solid gold lines — continental outlines.",
"Borders: boundary dots and labels (Drake Passage, Ural Mts., ...)."
]
},
{
"h": "4. Colors & legend",
"lines": [
"The right legend explains the three line styles.",
"The bottom strip maps the five climate zones.",
"Each of the six plates has its own color, labelled near its center."
]
},
{
"h": "5. Teaching notes & pitfalls",
"lines": [
"Plates are NOT mainlands: the American Plate spans both Americas to the Mid-Atlantic Ridge; the Indian Ocean Plate includes Australia and the Indian subcontinent.",
"These six are the first-order plates; Nazca, Arabian, etc. are secondary and are not listed in textbooks.",
"Volcanoes and earthquakes concentrate along plate boundaries (Pacific Ring, Mediterranean–Himalayan belt).",
"Borders are conventions: Asia/Europe along the Urals–Ural River–Caspian–Caucasus–Black Sea–Turkish Straits; Asia/Africa at Suez; N/S America at Panama; S. America/Antarctica at Drake Passage.",
"Esc closes, F11 toggles fullscreen."
]
}
]
}
}
@@ -1,7 +0,0 @@
{
"zones": "Zones",
"coast": "Continents",
"plates": "Plates",
"borders": "Borders",
"reset": "Reset"
}
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff. Show more