feat:修复部分问题

This commit is contained in:
2509_92447106 committed 2026-11-07 17:23:41 +08:00
1 parent 153ea88f4f
commit 5760fb77b0
38 files changed
+2273 -200

No files matched your search

+1
View File
@@ -2,6 +2,7 @@ bin/
obj/
dist/
build/
.GC/
*.user
.DS_Store
.vs/
+84 -36
View File
@@ -1,56 +1,97 @@
# Earth Model Studio
天文教学模型**启动器**:主页管理/启动模型、从链接导入模型源并下载、设置模型源与启动内存分配。
天文教学模型**启动器**:管理/启动模型、启动时自动检查并下载最新版模型与启动器、设置语言与内存。
> **分层约定(重要)**
> - `src/` = 启动器:扫描、下载、开窗口、显示启动进度。**不渲染、不含任何模型内容、不预置模型源**。
> - `src/` = 启动器:扫描、下载、开窗口、显示加载进度、自检更新。**不渲染、不含任何模型内容、发布包不内置模型**。
> - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。
>
> 结论:**模型相关代码全部直接存在模型目录里**,仓库根目录没有 `model-src/` / `model-sdk/` 这类旁路目录。
> 启动器只负责下载和启动;想加新内容 = 在 `model/<id>/` 里放模型,`src` 一行都不用改。
> - 模型相关代码全部直接存在模型目录里,仓库根没有 `model-src/` / `model-sdk/` 这类旁路目录。
> - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,`src` 一行都不用改,客户端启动自动更新。
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**,一条命令全部编译
- 更新仓库:<https://gitcode.com/2509_92447106/GC>,模型目录 <https://gitcode.com/2509_92447106/GC/tree/main/model>
## 运行目录(发布包里就长这样)
```
<安装目录>/
EarthModelStudio.exe | EarthModelStudio.app/
.GC/
settings.json 设置 + 已安装版本记录
model/ 启动时下载的模型
cache/ 下载暂存 / 原子替换
update/ 待下次启动应用的启动器更新
```
**发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示;
安装目录不可写时自动退回用户数据目录。`.GC/` 可以随程序一起搬迁,也可以整个删掉重新下载。
## 自动更新
| 检查项 | 不是最新版时 | 生效时机 |
| --- | --- | --- |
| 模型 | 从 gitcode 下载到 `cache/`,校验后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) |
| 启动器 | 下载对应平台 zip 到 `.GC/update/payload`,写 `pending.json` | **下次启动时应用**(独立脚本覆盖程序并重启) |
- 默认更新仓库写在 `.GC/settings.json` 的 `updateRepository`:
`https://gitcode.com/2509_92447106/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
- 版本来自仓库根 `version.json`(由 `./build.sh stamp` 生成):模型版本 = **模型包内容指纹**,
所以**改了模型文件,版本号自动变**;启动器版本 = 构建版本。
- `settings.json` 记录 `installedModelVersions` / `pendingLauncherVersion` / `lastUpdateCheck`。
- 断网、仓库还没推 `version.json`、下载失败:**一律保留本地模型,绝不把模型库清空**,底部状态条说明原因。
- 设置页可关闭自动更新;状态条可手动「检查更新」(忽略开关强制检查)。
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
`updateLocalRoot` 指向它,即可完全离线更新。
- 发新版:把 `dist/GC-<rid>.zip` 上传到 Release / 仓库 `dist/`,把直链填进 `version.json`
对应平台的 `url`(`./build.sh publish` 会生成 zip 并自动写入 `sha256` / `size`)。
更新包只含程序文件,**不会覆盖 `.GC/` 里的模型与设置**。
## 目录结构
```
EarthModelStudio/
├── EarthModelStudio.sln
├── Directory.Build.props # 公共构建属性(-p:TargetFramework=net10.0 可切 .NET 10)
├── build.sh / build.ps1 # 构建脚本(build/run/test/publish/models/pack-models)
├── Directory.Build.props # 公共构建属性
├── version.json # ★ 自动生成的版本清单(推送到仓库后才生效)
├── build.sh / build.ps1 # 构建脚本
├── src/ # ★ 启动器(没有渲染逻辑)
│ └── main/dotnet/EarthModelStudio/
│ ├── Models/ # 模型清单、设置(只有启动器需要的元数据)
│ ├── Services/ # 目录探测/设置/i18n/模型库/模型源/下载/内存预算/**ModelHost**
│ ├── ViewModels/ Views/ # 主页、下载、设置、模型窗口壳
│ ├── Models/ Services/ # 清单/设置/目录探测/i18n/模型库/下载/自动更新
│ │ # UpdateService · GitCodeRemote · DirectoryRemote · LauncherUpdate
│ ├── ViewModels/ Views/ # 主页、下载、设置、模型窗口壳、启动更新状态条
│ └── Assets/i18n/ # 启动器界面语言包
├── src/test/dotnet/…Tests/ # 离屏校验(启动器页面 + 真实加载模型窗口)
├── model/ # ★ 模型的一切(源码 + 数据 + dll + 封面 + 语言包)
│ ├── _sdk/EarthModelStudio.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码)
│ ├── _engine/ # 共享引擎源码(渲染、界面、交互)
├── src/test/dotnet/…Tests/ # 离屏校验 + --update-test 离线更新链路验证
├── model/ # ★ 模型的一切
│ ├── version.json # 与根 version.json 相同(便于按 model/ 地址读取)
│ ├── _sdk/EarthModelStudio.ModelSdk/
│ ├── _engine/
│ │ ├── src/ # CelestialView / PlanetTexture / EarthModelView …
│ │ └── PreviewGen/ # 用模型渲染器生成封面
│ │ ├── PreviewGen/ # 用模型渲染器生成封面
│ │ └── VersionStamp/ # 按内容指纹自动打版本、生成 version.json
│ ├── earth-rotation/
│ │ ├── earth-rotation.json # 清单
│ │ ├── src/ # 本模型源码(csproj + 入口工厂)
│ │ ├── earth-rotation.json
│ │ ├── src/ # 本模型源码
│ │ └── earth-rotation.model/ # dll + scene.json/land.json + preview.png + i18n
│ └── earth-revolution/ # 同上结构,封面是公转场景
└── dist/ # 发布产物(启动器 + 单独打包的模型)
│ └── earth-revolution/
└── dist/ # 发布产物(只有启动器 + .GC 骨架)
```
模型库查找顺序:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 可执行文件旁 `model/` → 用户数据目录。
模型库位置:`EMS_MODELS` 覆盖 → 开发态仓库根 `model/` → **发布态 `<可执行文件>/.GC/model/`**。
## 构建与运行
```bash
./build.sh build # 编译启动器
./build.sh models # 编译模型 dll + 生成封面(写进 model/)
./build.sh run # 运行
./build.sh test # 离屏校验:页面截图 + 真实加载模型窗口截图
./build.sh publish # 一次性编译三个平台(启动器,不含模型)
./build.sh pack-models # 编译模型后打包 -> dist/models-<version>.zip
./build.sh build # 编译整个解决方案
./build.sh models # 编译模型 dll + 生成封面 + 自动打版本
./build.sh stamp # 只重新生成 version.json 与模型版本
./build.sh run # 运行
./build.sh test # 离屏校验:页面 + 真实加载模型窗口截图
./build.sh update-test # 离线验证自动更新链路(不联网、不替换程序)
./build.sh publish # 三平台发布(不内置模型)+ 建 .GC 骨架 + 生成更新包
./build.sh pack-models # 单独打包模型 -> dist/models-<version>.zip
./build.sh pack-launcher # 生成三个平台的启动器更新包 zip
./build.sh clean
```
@@ -62,7 +103,8 @@ Windows 用 `.\build.ps1`(参数相同)。
| `dist/win-x64/EarthModelStudio.exe` | Windows x64 |
| `dist/win-arm64/EarthModelStudio.exe` | Windows on ARM |
均为自包含单文件启动器,`model/` 目录为空(只有 README)。模型用 `pack-models` 单独分发。
均为自包含单文件启动器,**发布包内不含模型**。改完模型:
`./build.sh models` → 把 `version.json` 和 `model/` 推送到 gitcode → 客户端下次启动自动更新。
## 模型契约
@@ -101,24 +143,30 @@ public interface IModelContext
- 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口
- 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集
- 快捷键 `Esc` 关闭、`F11` 全屏(其余快捷键由模型自己决定)
- 启动器快捷键 `Esc` 关闭、`F11` 全屏;模型窗口内的快捷键由模型自己定义
## 地球模型(model/_engine + model/<id>/src)
- **地表**:加载时烘焙 1024×512 等经纬度纹理 —— 海洋深度、沙漠/雨林/针叶林/苔原分带、极地冰盖、
山脉起伏(高度梯度参与光照)、云层、夜间城市辉光;每帧只做双线性采样 + 地形光照,60 FPS
- **教材数值**:黄赤交角 / 回归线统一为 **23.5°**,极圈 66.5°;夏至直射 **23.5°N**、冬至 **23.5°S**、
春分秋分 **0°(赤道)**。球面上画出赤道、南北回归线、南北极圈与真实日下点黄圈,读数不受「夸张倾角」影响
- **自转**:球面像素渲染、晨昏线、大气边缘光、经纬网、地轴、太阳直射点;只有自转视角,
**没有节气定位**(节气属于公转)
- **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定位、HUD
- **交互**:滚轮 / 工具栏 −+ 缩放(0.6×–6×,带缓动);暂停后拖动可旋转地球或沿轨道拖动公转位置;
松手有惯性;缩放、视角、面板都有过渡动画
- 两个模型共用 `model/_engine` 的代码,各自 `src/` 只提供入口工厂;界面、文案、封面都在模型包里
- **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定格、HUD(角度 / 直射纬度 / 日期)
- **触控一体机**:双指捏合缩放(跟手)、滚轮缩放、画布左下角大号 + / − / 复位按钮;
所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**,
俯视角只由「俯视」按钮显式切换
- **课堂演示**:点二分二至自动暂停定格并显示节气、教材日期、直射纬度与现象说明;
右侧课堂卡含可放大观察到的「地球特写」;`◀ ▶` 步进 5°、教学要点点击自动定格定位;
快捷键 `空格` 播放/暂停、`← →` 步进、`1–4` 二分二至、`F` 全屏、`+ -` 缩放、`0` 复位视角
- 节气日期、直射纬度、现象说明、教学要点全部写在 `scene.json` 里;夸张倾角只改示意图形,不改教学读数
## 模型源(git 仓库)
## 模型源(手动导入)
模型源就是普通 git 仓库,**仓库根目录下的 `model/` 文件夹即模型列表**。
支持 `https://github.com/<user>/<repo>.git`(GitLab / Gitee 同理,走 zip 归档,失败回退 `git clone --depth 1`)、
zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/<id>`,下载时把模型目录复制进本地 `model/`。
除了启动时自动更新,「下载」页还支持手动导入普通 git 仓库:
**仓库根目录下的 `model/` 文件夹即模型列表**。支持 GitHub / GitLab / Gitee(zip 归档,
失败回退 `git clone --depth 1`)、zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/<id>`。
## 启动时运行内存分配
+128 -22
View File
@@ -4,16 +4,28 @@
# .\build.ps1 编译
# .\build.ps1 run 运行
# .\build.ps1 test 离屏渲染校验
# .\build.ps1 publish 一次性编译三个平台 -> dist\
# .\build.ps1 models 编译模型功能程序集 + 生成封面
# .\build.ps1 pack-models 编译模型后整体打包 -> dist\models-x.y.z.zip
# .\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\(外置数据)。
# 分层:src\ 只是启动器;模型全部在 model\;**发布包不内置模型**。
#
# 运行目录(发布包里就长这样):
# <安装目录>\
# EarthModelStudio.exe
# .GC\settings.json
# .GC\model\ 启动时从 gitcode 下载的模型
# .GC\cache\ 下载暂存
# .GC\update\ 待下次启动应用的启动器更新
# ---------------------------------------------------------------------------
param(
[Parameter(Position = 0)]
[ValidateSet('build', 'run', 'test', 'publish', 'models', 'pack-models', 'clean', 'doctor')]
[ValidateSet('build', 'run', 'test', 'publish', 'models', 'stamp', 'pack-models',
'pack-launcher', 'update-test', 'bundle', 'clean', 'doctor')]
[string]$Task = 'build'
)
@@ -23,21 +35,14 @@ Set-Location $Root
$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.0'
function Publish-Rid([string]$Rid, [string]$OutDir) {
Write-Host "==> 编译 $Rid -> $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"
if (Test-Path "$Root/$OutDir/model") { Remove-Item -Recurse -Force "$Root/$OutDir/model" }
if (Test-Path "$Root/$OutDir/examples") { Remove-Item -Recurse -Force "$Root/$OutDir/examples" }
# 启动器不带模型:只建空的模型库目录,模型作为独立内容放置 / 下载
New-Item -ItemType Directory -Force -Path "$Root/$OutDir/model" | Out-Null
if (Test-Path "$Root/model/README.md") {
Copy-Item -Force "$Root/model/README.md" "$Root/$OutDir/model/README.md"
}
function Stamp-Versions {
Write-Host '==> 自动计算模型版本并生成 version.json'
dotnet run --project $StampProj -c Release -- $Root $Version
}
function Build-Models {
@@ -60,6 +65,66 @@ function Build-Models {
}
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"
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 {
@@ -82,25 +147,66 @@ function Pack-Models {
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' { dotnet build $Sln -c Debug }
'run' { dotnet run --project $AppProj -c Debug }
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
'publish' {
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'
Write-Host '==> 三个平台编译完成(启动器不含模型数据),见 dist\' -ForegroundColor Green
Write-Host ' 模型数据用 .\build.ps1 pack-models 单独打包,或放进 <安装目录>\model 后再启动'
}
'models' {
Build-Models
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 |
+121 -33
View File
@@ -2,20 +2,27 @@
# ---------------------------------------------------------------------------
# Earth Model Studio 构建脚本(macOS / Linux)
#
# ./build.sh build 编译(Debug)
# ./build.sh run 本机运行
# ./build.sh test 离屏渲染校验,截图输出到 build/screenshots
# ./build.sh publish 一次性编译三个平台 -> dist/
# ./build.sh models 编译模型功能程序集 + 生成模型封面(写进 model/<id>/<id>.model)
# ./build.sh pack-models 编译模型后把 model/ 整体打包 -> dist/models-x.y.z.zip
# ./build.sh clean 清理
# ./build.sh build 编译(Debug)
# ./build.sh run 本机运行
# ./build.sh test 离屏渲染校验,截图输出到 build/screenshots
# ./build.sh models 编译模型 dll + 生成封面 + 自动打版本
# ./build.sh stamp 只重新生成 version.json 与模型版本
# ./build.sh publish 编译三个平台启动器(不内置模型)+ 建立 .GC 运行目录
# ./build.sh pack-models 单独打包模型数据(含 version.json)
# ./build.sh pack-launcher 生成三个平台的启动器更新包 zip
# ./build.sh update-test 离线验证自动更新链路
# ./build.sh clean 清理
#
# 分层约定:src/ 只是启动器,不含任何模型数据;模型全部放在 model/(外置数据)。
# 分层:src/ 只是启动器;模型全部在 model/;**发布包不内置模型**。
#
# publish 产出(启动器,模型库目录为空):
# dist/mac-arm64/EarthModelStudio.app macOS Apple Silicon
# dist/win-x64/EarthModelStudio.exe Windows x86_64
# dist/win-arm64/EarthModelStudio.exe Windows on ARM
# 运行目录(发布包里就长这样):
# <安装目录>/
# EarthModelStudio(.exe | .app/...)
# .GC/
# settings.json 设置与已安装版本
# model/ 启动时从 gitcode 下载的模型
# cache/ 下载暂存
# update/ 待下次启动应用的启动器更新
# ---------------------------------------------------------------------------
set -e
@@ -24,29 +31,16 @@ cd "$ROOT_DIR"
APP_PROJ="src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj"
PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj"
SLN="EarthModelStudio.sln"
VERSION="1.0.0"
TASK="${1:-build}"
publish_rid() {
RID="$1"; OUT="$2"
echo ""
echo "==> 编译 ${RID} -> ${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"
mkdir -p "$ROOT_DIR/$OUT/model"
cp "$ROOT_DIR/model/README.md" "$ROOT_DIR/$OUT/model/README.md" 2>/dev/null || true
# 按模型包内容指纹自动写回 <id>.json 的 version,并生成 version.json
stamp_versions() {
echo "==> 自动计算模型版本并生成 version.json"
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
}
# 编译模型自己的功能程序集,并把 dll / 封面直接写进模型包
@@ -70,6 +64,66 @@ build_models() {
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
echo " 运行目录 -> $REL/.GC (settings.json + model/ + cache/ + update/)"
}
publish_rid() {
RID="$1"; OUT="$2"
echo ""
echo "==> 编译 ${RID} -> ${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/ 里的模型数据单独打包(与启动器分开分发)
@@ -83,6 +137,23 @@ pack_models() {
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"
@@ -127,22 +198,39 @@ case "$TASK" in
;;
publish)
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 "==> 三个平台编译完成(启动器不含模型数据):"
echo "==> 三个平台编译完成(发布包不含模型,首次启动自动下载):"
du -sh "$ROOT_DIR/dist"/* 2>/dev/null || true
echo " 模型数据用 ./build.sh pack-models 单独打包,或放进 <安装目录>/model 后再启动"
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
@@ -153,7 +241,7 @@ case "$TASK" in
;;
*)
echo "未知任务: $TASK"
echo "可用: build | run | test | publish | models | pack-models | clean | doctor"
echo "可用: build | run | test | publish | models | stamp | pack-models | pack-launcher | update-test | clean | doctor"
exit 1
;;
esac
+40 -9
View File
@@ -1,13 +1,14 @@
# 模型库(model/)
这个目录是**模型**,包含模型自己的**源码 + 数据 + 功能程序集 + 封面 + 语言包**。
`src/`(启动器)只做三件事:扫描模型、下载模型、开窗口加载模型。**启动器没有任何渲染逻辑**。
`src/`(启动器)只做四件事:扫描模型、下载模型、开窗口加载模型、检查更新。**启动器没有任何渲染逻辑,发布包也不内置模型**。
> 模型相关的一切都在 `model/` 里:共享引擎源码 `model/_engine/`、契约源码 `model/_sdk/`、
> 每个模型自己的源码 `model/<id>/src/`,编译产物与数据 `model/<id>/<id>.model/`。
> 仓库根目录只有 `src/`(启动器)和 `model/`,没有任何旁路目录。
- 启动器查找模型库的顺序:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 可执行文件旁边 `model/` → 用户数据目录
- 发布态模型库在 **`<可执行文件>/.GC/model/`**;开发态直接用仓库根 `model/`
- 优先级:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 发布态 `.GC/model/`
- 一个模型 = 一个文件夹,文件夹名即模型 id;`_sdk/`、`_engine/` 是下划线开头的共享目录,不会被当成模型
- 模型可以单独打包、单独分发,也可以放进 git 仓库当模型源
@@ -15,10 +16,12 @@
```
model/
_sdk/EarthModelStudio.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码)
_engine/ # 共享引擎源码(可选,只有地球模型用)
version.json # 版本清单(与仓库根 version.json 相同,自动生成)
_sdk/EarthModelStudio.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码)
_engine/ # 共享引擎源码
src/ # CelestialView / PlanetTexture / EarthModelView / SphereRaster…
PreviewGen/ # 用模型渲染器生成封面的小工具
VersionStamp/ # 按内容指纹自动打版本、生成 version.json
<模型 id>/
<模型 id>.json # 清单:名称、i18n、版本、程序集入口、封面
src/ # 模型自己的源码(csproj + IModelFactory 实现)
@@ -31,6 +34,23 @@ model/
i18n/en.json
```
## 版本是自动改的
`./build.sh models`(或 `./build.sh stamp`)会调用 `model/_engine/VersionStamp`:
1. 对每个模型,把 `<id>.json`(去掉 `version` / `updatedAt`)与 `<id>.model/` 下所有文件
按路径排序做 SHA-256 指纹,得到版本号 `1.0-<10位指纹>`;
2. 把这个版本写回 `<id>.json` 的 `version` 与 `updatedAt`;
3. 生成仓库根 `version.json` 和 `model/version.json`(内容相同),里面记录
启动器版本、各平台更新包地址、每个模型的 id / 版本 / 仓库目录。
**所以只要改了模型文件,版本号就自动变**,不需要手工维护;内容没变时重复构建版本号保持不变。
客户端启动时读 `version.json`,和 `.GC/settings.json` 里记录的版本一比对就知道要不要下载。
> 改了 `scene.json` 或引擎源码后,跑 `./build.sh models`,再把 `version.json` 和 `model/`
> 推送到 gitcode;客户端下次启动会下载新模型并**本次启动立即生效**。
> 启动器自身更新包由 `./build.sh publish` 生成(`dist/GC-<rid>.zip`),下载后**下次启动才应用**。
## `<id>.json`(模型清单,启动器只读它)
```json
@@ -40,7 +60,8 @@ model/
"nameI18n": { "zh-CN": "地球自转", "en": "Earth Rotation" },
"description": "……",
"descriptionI18n": { "zh-CN": "……", "en": "……" },
"version": "1.0.0",
"version": "1.0-3f9a2c1b7d",
"updatedAt": "2026-11-07T08:00:00Z",
"author": "NeoRF",
"tags": ["astronomy", "geography"],
"assembly": "EarthRotationModel.dll",
@@ -52,6 +73,7 @@ model/
| 字段 | 作用 |
| --- | --- |
| `version` | **自动生成**,模型包内容指纹;客户端靠它判断是否需要更新 |
| `assembly` | 功能程序集文件名,相对 `<id>.model`;留空按 `<id>.dll` 找 |
| `type` | 实现 `IModelFactory` 的完整类型名;留空则自动找第一个实现 |
| `preview` | 封面图,默认 `preview.png` |
@@ -95,6 +117,12 @@ public interface IModelContext
这两个文件的内容完全由模型自己定义(启动器不解析)。地球模型用的是:
- `scene.json`:`defaultView`、`views`、行星参数、颜色、轨道、`lessons` 教学要点
- `orbit.seasonLayout`:`springTopSummerLeft` = **上春分、左夏至**(下秋分、右冬至),季节角度与直射纬度读数不变
- `planet.axialTiltDeg` / `planet.tropicDeg`:教材值 **23.5°**(极圈自动算 90 − 23.5 = 66.5°)
- `orbit.seasons[].declinationDeg`:二分二至的太阳直射纬度(0 / +23.5 / 0 / −23.5),
定格时读数直接取这个值,不用近似公式
- `orbit.seasons[].teachingI18n`:该节气的课堂现象说明(中英双语,写在模型数据里)
- `orbit.seasons[].date`:教材日期(3/21、6/22、9/23、12/22),定格时 HUD 与课堂卡都用它
- `land.json`:大陆轮廓,`{ "polygons": [ { "name": "...", "points": [[lon,lat], ...] } ] }`
## 语言包
@@ -109,7 +137,7 @@ public interface IModelContext
封面是 `preview.png`,由 `model/_engine/PreviewGen` 用**模型自己的渲染器**生成:
```bash
./build.sh models # 编译模型 dll + 生成所有模型封面
./build.sh models # 编译模型 dll + 生成所有模型封面 + 自动打版本
```
## 做一个新模型
@@ -117,9 +145,12 @@ public interface IModelContext
1. 在 `model/<id>/src/` 里新建类库项目(可引用 `model/_engine/src` 的共享代码,也可完全自己写)
2. 写一个 `IModelFactory` 实现:`Prepare` 里读数据算纹理并 `ReportProgress`,`CreateView` 里返回控件
3. 在 `model/<id>/` 放清单和 `<id>.model/` 数据目录,用 `assembly` / `type` 指向你的 dll
4. `./build.sh models` 会自动编译每个模型、把 dll 复制进对应 `<id>.model/`,并生成封面
4. `./build.sh models` 会自动编译每个模型、把 dll 复制进对应 `<id>.model/`、生成封面、打版本并写进 `version.json`
5. 推送仓库,客户端下次启动自动下载 —— 不用改启动器、不用重新发布程序
## 作为模型源分发
把 `model/` 放到任意 git 仓库根目录并推送,用户在「下载」页粘贴仓库链接即可;
启动器读取仓库里的 `model/` 文件夹,一栏一个模型。
- **自动更新(推荐)**:把 `version.json` 和 `model/` 推到 gitcode 仓库,启动器开机自检并下载到 `.GC/model/`
- **离线源**:把整个仓库目录(含 `version.json` + `model/`)拷到 U 盘 / 共享盘,
在 `.GC/settings.json` 填 `updateLocalRoot` 指向它
- **手动导入**:在「下载」页粘贴任意 git 仓库 / zip / 本地目录,读取其中的 `model/` 文件夹
+152
View File
@@ -0,0 +1,152 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
// VersionStamp:构建时自动给模型打版本。
// 用法:dotnet run --project model/_engine/VersionStamp -- <仓库根> <启动器版本>
// 输出:更新 model/<id>/<id>.json 的 version / updatedAt,并生成
// 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。
var root = args.Length > 0 ? Path.GetFullPath(args[0]) : Directory.GetCurrentDirectory();
var launcherVersion = args.Length > 1 && !string.IsNullOrWhiteSpace(args[1]) ? args[1] : "1.0.0";
var modelRoot = Path.Combine(root, "model");
if (!Directory.Exists(modelRoot))
{
Console.Error.WriteLine($"找不到模型库: {modelRoot}");
return 1;
}
var relaxed = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
static string Rel(string baseDir, string file) =>
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
static bool Distributable(string file)
{
var name = Path.GetFileName(file);
if (name.StartsWith('.')) return false;
if (name.EndsWith(".user", StringComparison.OrdinalIgnoreCase)) return false;
var rel = file.Replace('\\', '/');
return !rel.Contains("/bin/", StringComparison.OrdinalIgnoreCase) &&
!rel.Contains("/obj/", StringComparison.OrdinalIgnoreCase) &&
!rel.EndsWith(".installing", StringComparison.OrdinalIgnoreCase);
}
static string Fingerprint(IEnumerable<byte[]> chunks)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
foreach (var chunk in chunks) hash.AppendData(chunk);
return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
}
Console.WriteLine("==> 自动计算模型版本(按模型包内容指纹)");
var models = new List<Dictionary<string, string>>();
foreach (var dir in Directory.GetDirectories(modelRoot)
.OrderBy(p => Path.GetFileName(p), StringComparer.Ordinal))
{
var id = Path.GetFileName(dir);
if (id.StartsWith('_')) continue; // _sdk / _engine 是共享源码,不是模型
var manifestPath = Path.Combine(dir, id + ".json");
var dataDir = Path.Combine(dir, id + ".model");
if (!File.Exists(manifestPath) || !Directory.Exists(dataDir)) continue;
var manifest = JsonNode.Parse(File.ReadAllText(manifestPath))?.AsObject();
if (manifest == null) continue;
// 版本号只由「清单内容 + 模型包数据」决定,重复构建结果稳定
manifest.Remove("version");
manifest.Remove("updatedAt");
var canonical = manifest.ToJsonString(new JsonSerializerOptions { WriteIndented = false });
var chunks = new List<byte[]> { Encoding.UTF8.GetBytes(canonical) };
foreach (var file in Directory.GetFiles(dataDir, "*", SearchOption.AllDirectories)
.Where(Distributable)
.OrderBy(f => Rel(dataDir, f), StringComparer.Ordinal))
{
chunks.Add(Encoding.UTF8.GetBytes("\n" + Rel(dataDir, file) + "\n"));
chunks.Add(File.ReadAllBytes(file));
}
var version = "1.0-" + Fingerprint(chunks)[..10];
manifest["version"] = version;
manifest["updatedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
File.WriteAllText(manifestPath, manifest.ToJsonString(relaxed) + "\n");
models.Add(new Dictionary<string, string>
{
["id"] = id,
["version"] = version,
["dir"] = "model/" + id
});
Console.WriteLine($" {id,-20} {version}");
}
// 启动器源码指纹(只展示,不触发升级;升级看 launcher.version)
var srcRoot = Path.Combine(root, "src");
var srcChunks = new List<byte[]>();
if (Directory.Exists(srcRoot))
{
foreach (var file in Directory.GetFiles(srcRoot, "*", SearchOption.AllDirectories)
.Where(Distributable)
.Where(f => f.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".axaml", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".props", StringComparison.OrdinalIgnoreCase))
.OrderBy(f => Rel(srcRoot, f), StringComparer.Ordinal))
{
srcChunks.Add(Encoding.UTF8.GetBytes(Rel(srcRoot, file) + "\n"));
srcChunks.Add(File.ReadAllBytes(file));
}
}
var launcherRevision = srcChunks.Count > 0 ? Fingerprint(srcChunks)[..10] : "";
var packages = new Dictionary<string, Dictionary<string, object>>();
foreach (var rid in new[] { "win-x64", "win-arm64", "osx-arm64", "osx-x64", "linux-x64" })
{
var entry = new Dictionary<string, object>
{
["path"] = $"dist/GC-{rid}.zip",
["url"] = "" // 大文件建议填 Release 直链;留空则用仓库内 path
};
// 已生成的启动器更新包:把校验值和体积写进清单,供下载端校验
var zipPath = Path.Combine(root, "dist", $"GC-{rid}.zip");
if (File.Exists(zipPath))
{
var bytes = File.ReadAllBytes(zipPath);
entry["sha256"] = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
entry["size"] = bytes.LongLength;
}
packages[rid] = entry;
}
var versionDoc = new Dictionary<string, object>
{
["schema"] = 1,
["generated"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
["repository"] = "https://gitcode.com/2509_92447106/GC",
["branch"] = "main",
["modelDir"] = "model",
["launcher"] = new Dictionary<string, object>
{
["version"] = launcherVersion,
["revision"] = launcherRevision,
["packages"] = packages
},
["models"] = models
};
var json = JsonSerializer.Serialize(versionDoc, relaxed) + "\n";
File.WriteAllText(Path.Combine(root, "version.json"), json);
File.WriteAllText(Path.Combine(modelRoot, "version.json"), json);
Console.WriteLine($"==> version.json 已生成(启动器 {launcherVersion},模型 {models.Count} 个)");
return 0;
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>VersionStamp</AssemblyName>
<RootNamespace>VersionStamp</RootNamespace>
</PropertyGroup>
</Project>
+72 -15
View File
@@ -152,7 +152,34 @@ public class CelestialView : Control
}
public string DeclinationLabel => DeclinationText(SubsolarLatitude);
public string CurrentDate => DateForAngle(_orbitDeg);
/// <summary>定格在二分二至时,日期直接取模型数据里的教材日期,避免近似公式差一两天。</summary>
public string CurrentDate
{
get
{
if (View == SceneView.Revolution)
{
var season = NearestSeason(2.5);
if (season?.Date != null) return FormatSeasonDate(season.Date);
}
return DateForAngle(_orbitDeg);
}
}
private string FormatSeasonDate(string monthDay)
{
var parts = monthDay.Split('/');
if (parts.Length == 2 && int.TryParse(parts[0], out var m) && int.TryParse(parts[1], out var d)
&& m is >= 1 and <= 12 && d is >= 1 and <= 31)
{
var date = new DateTime(2025, m, d);
var chinese = Texts.Language.StartsWith("zh", StringComparison.OrdinalIgnoreCase);
return date.ToString(chinese ? "M月d日" : "MMM d", CultureInfo.InvariantCulture);
}
return monthDay;
}
public event Action? AnglesChanged;
/// <summary>缩放目标变化(滚轮、按钮、捏合)。</summary>
public event Action<double>? ZoomChanged;
@@ -256,8 +283,9 @@ public class CelestialView : Control
if (!_dragging) return;
var dx = p.X - _dragLast.X;
var dy = p.Y - _dragLast.Y;
_dragLast = p;
DragBy(dx, p.Y - _dragLast.Y + (p.Y - _dragLast.Y));
DragBy(dx, dy);
e.Handled = true;
}
@@ -330,9 +358,13 @@ public class CelestialView : Control
if (!_pinching) { BeginPinch(); return; }
var pts = _pointers.Values.Take(2).ToArray();
var d = Math.Max(8.0, Distance(pts[0], pts[1]));
SetZoom(_pinchStartZoom * d / _pinchStartDistance, immediate: true);
SetZoom(PinchZoom(_pinchStartZoom, _pinchStartDistance, d), immediate: true);
}
/// <summary>捏合比例换算:两指间距放大多少倍,缩放就放大多少倍(限幅 0.6–6)。</summary>
public static double PinchZoom(double startZoom, double startDistance, double currentDistance)
=> Math.Clamp(startZoom * Math.Max(8.0, currentDistance) / Math.Max(8.0, startDistance), 0.6, 6.0);
private static double Distance(Point a, Point b)
{
var dx = a.X - b.X;
@@ -654,11 +686,34 @@ public class CelestialView : Control
t => LatLonToUnit(lat, t * 360.0), 144);
if (label == null) return;
var world = Vector3.Transform(LatLonToUnit(lat, 64), planet);
var c = Vector3.Transform(world, cam);
if (c.Z <= 0.05f) return;
var p = new Point(center.X + c.X * radius, center.Y - c.Y * radius);
DrawText(ctx, label, p.X + 5, p.Y - 13, 10.5, labelBrush, FontWeight.SemiBold);
// 找该纬线上「最靠右且可见」的点作为标签锚点:
// 地球自转时标签始终留在可见半球右侧,不会忽隐忽现
Vector3 best = default;
var bestScore = double.NegativeInfinity;
for (var lon = -180; lon < 180; lon += 6)
{
var world = Vector3.Transform(LatLonToUnit(lat, lon), planet);
var c = Vector3.Transform(world, cam);
if (c.Z < 0.10f) continue;
var score = c.X * 2.0 + c.Z;
if (score > bestScore) { bestScore = score; best = c; }
}
if (double.IsNegativeInfinity(bestScore)) return;
var p = new Point(center.X + best.X * radius, center.Y - best.Y * radius);
DrawLabelChip(ctx, label, p, InsetMode ? 9.0 : 10.5, labelBrush, toRight: false);
}
/// <summary>带深色底衬的标签:压在明亮的地球上也读得清,且不会被画布边缘裁掉。</summary>
private static void DrawLabelChip(DrawingContext ctx, string text, Point anchor,
double fontSize, IBrush brush, bool toRight)
{
var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
new Typeface(FontFamily.Default, FontStyle.Normal, FontWeight.SemiBold), fontSize, brush);
var x = toRight ? anchor.X + 9 : Math.Max(3, anchor.X - formatted.Width - 9);
var y = anchor.Y - formatted.Height - 4;
ctx.DrawRectangle(ChipBg, null,
new Rect(x - 5, y - 2, formatted.Width + 10, formatted.Height + 5), 4, 4);
ctx.DrawText(formatted, new Point(x, y));
}
private void DrawGraticule(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet, Point center, double radius)
@@ -732,11 +787,12 @@ public class CelestialView : Control
{
if (light.Z <= 0.02f) return;
var p = new Point(center.X + light.X * radius, center.Y - light.Y * radius);
ctx.DrawEllipse(SubsolarGlowBrush, null, p, 9, 9);
ctx.DrawEllipse(null, SubsolarPen, p, 5, 5);
var marker = InsetMode ? 6.5 : 5.0;
ctx.DrawEllipse(SubsolarGlowBrush, null, p, marker * 2.5, marker * 2.5);
ctx.DrawEllipse(null, SubsolarPen, p, marker, marker);
if (withLabel)
DrawText(ctx, Texts["directPoint"] + " " + DeclinationText(SubsolarLatitude),
p.X + 12, p.Y - 9, 11.5, SubsolarBrush, FontWeight.SemiBold);
DrawLabelChip(ctx, Texts["directPoint"] + " " + DeclinationText(SubsolarLatitude),
p, 11.5, SubsolarBrush, toRight: p.X < center.X);
}
private void DrawAxis(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet, Point center, double radius,
@@ -780,7 +836,7 @@ public class CelestialView : Control
var cam = CameraMatrix(0, _camElev);
var theta = Deg2Rad(_orbitDeg);
var earthPos = new Vector3((float)(-a * Math.Sin(theta)), 0, (float)(a * Math.Cos(theta)));
var earthPos = new Vector3((float)(-a * Math.Sin(theta)), 0, (float)(-a * Math.Cos(theta)));
var earthScreen = ToScreen(earthPos, cam, center);
var lightWorld = Vector3.Normalize(-earthPos);
var lightCam = Vector3.TransformNormal(lightWorld, cam);
@@ -864,7 +920,7 @@ public class CelestialView : Control
for (var i = 0; i <= 240; i++)
{
var t = i / 240.0 * Math.PI * 2;
var p = new Vector3((float)(-a * Math.Sin(t)), 0, (float)(a * Math.Cos(t)));
var p = new Vector3((float)(-a * Math.Sin(t)), 0, (float)(-a * Math.Cos(t)));
var c = Vector3.Transform(p, cam);
var sp = new Point(center.X + c.X, center.Y - c.Y);
if (c.Z < 0)
@@ -899,7 +955,7 @@ public class CelestialView : Control
foreach (var s in seasons)
{
var t = Deg2Rad(s.AngleDeg);
var pos = new Vector3((float)(-a * Math.Sin(t)), 0, (float)(a * Math.Cos(t)));
var pos = new Vector3((float)(-a * Math.Sin(t)), 0, (float)(-a * Math.Cos(t)));
var outer = pos * 1.19f;
var p = ToScreen(outer, cam, center);
ctx.DrawEllipse(SeasonDotBrush, null, ToScreen(pos, cam, center), 2.4, 2.4);
@@ -985,6 +1041,7 @@ public class CelestialView : Control
private static readonly IBrush AxisBrush = new SolidColorBrush(Color.FromArgb(220, 255, 214, 130));
private static readonly IBrush SubsolarBrush = new SolidColorBrush(Color.FromArgb(240, 255, 236, 170));
private static readonly IBrush SubsolarGlowBrush = new SolidColorBrush(Color.FromArgb(64, 255, 214, 110));
private static readonly IBrush ChipBg = new SolidColorBrush(Color.FromArgb(185, 8, 16, 34));
private static readonly IBrush TropicBrush = new SolidColorBrush(Color.FromArgb(240, 255, 196, 120));
private static readonly IBrush PolarBrush = new SolidColorBrush(Color.FromArgb(210, 164, 210, 255));
private static readonly Pen SubsolarPen = new Pen(new SolidColorBrush(Color.FromArgb(230, 255, 226, 150)), 1.4);
+13 -6
View File
@@ -45,6 +45,7 @@ public sealed class EarthModelView : UserControl
private StackPanel? _seasonPanel;
private Border? _lessons;
private Border? _closeupHost;
private TextBlock? _closeupLabel;
private ModelButton? _playButton;
private ModelButton? _overheadButton;
private ModelButton? _closeupButton;
@@ -71,6 +72,8 @@ public sealed class EarthModelView : UserControl
_runtime = runtime;
_texts = ModelStrings.Load(context.DataDirectory, context.Language);
_views = ResolveViews(runtime.Scene);
// 自转模型主画布本身就是放大的地球,不需要再来一份特写
_showCloseup = IsRevolution;
Background = new SolidColorBrush(Color.Parse("#05070F"));
@@ -535,13 +538,14 @@ public sealed class EarthModelView : UserControl
});
readouts.Children.Add(_cardDirect);
readouts.Children.Add(_cardNote);
readouts.Children.Add(new TextBlock
_closeupLabel = new TextBlock
{
Text = _texts["closeup"],
Foreground = MutedBrush,
FontSize = 11,
Margin = new Thickness(0, 6, 0, 0)
});
};
readouts.Children.Add(_closeupLabel);
readouts.Children.Add(_closeupHost);
var list = new StackPanel { Spacing = 2 };
@@ -675,13 +679,15 @@ public sealed class EarthModelView : UserControl
_cardTitle.Text = season != null
? _texts[season.Key]
: (IsRevolution ? _texts["seasons"] : _texts.Pick(_runtime.Scene.NameI18n, _texts["title"]));
_cardDate!.Text = _canvas.CurrentDate + (season?.Date != null ? " · " + season.Date : "");
_cardDate!.Text = IsRevolution ? _canvas.CurrentDate : _texts["dayNight"];
_cardDirect!.Text = season?.DeclinationDeg.HasValue == true
? FormatDeclination(season.DeclinationDeg.Value)
: _canvas.DeclinationLabel;
_cardNote!.Text = season != null
? _texts.Pick(season.TeachingI18n, _texts["orbitTeach"])
: _texts["orbitTeach"];
_cardNote!.Text = !IsRevolution
? _texts["rotationTeach"]
: season != null
? _texts.Pick(season.TeachingI18n, _texts["orbitTeach"])
: _texts["orbitTeach"];
if (_showCloseup && (double.IsNaN(_lastDeclination) || Math.Abs(_lastDeclination - decl) > 0.04))
{
@@ -811,6 +817,7 @@ public sealed class EarthModelView : UserControl
if (_lessons != null) _lessons.IsVisible = _showLessons;
if (_seasonPanel != null) _seasonPanel.IsVisible = IsRevolution;
if (_closeupHost != null) _closeupHost.IsVisible = _showCloseup;
if (_closeupLabel != null) _closeupLabel.IsVisible = _showCloseup;
}
/// <summary>带悬停过渡的按钮:本地基础色 + 悬停提亮。</summary>
+4
View File
@@ -106,6 +106,8 @@ internal static class DefaultTexts
["sideview"] = "侧视",
["zoom"] = "缩放",
["orbitTeach"] = "太阳直射点在南北回归线之间往返,形成四季更替。",
["rotationTeach"] = "晨昏线把地球分成昼半球与夜半球;自转产生昼夜交替与地方时差。",
["dayNight"] = "昼夜交替周期 24 小时",
["lat.equator"] = "赤道",
["lat.tropicN"] = "北回归线 23.5°N",
["lat.tropicS"] = "南回归线 23.5°S",
@@ -157,6 +159,8 @@ internal static class DefaultTexts
["sideview"] = "Side view",
["zoom"] = "Zoom",
["orbitTeach"] = "The subsolar point travels between the tropics, producing the seasons.",
["rotationTeach"] = "The terminator splits day and night; rotation drives the day–night cycle and local time.",
["dayNight"] = "Day–night cycle: 24 h",
["lat.equator"] = "Equator",
["lat.tropicN"] = "Tropic of Cancer 23.5°N",
["lat.tropicS"] = "Tropic of Capricorn 23.5°S",
+2
View File
@@ -50,6 +50,8 @@ public sealed class OrbitDefinition
public double SemiMajorAxis { get; set; } = 4.0;
public double Eccentricity { get; set; } = 0.0167;
public bool Show { get; set; } = true;
/// <summary>节气方位声明:springTopSummerLeft = 上春分 / 左夏至(引擎按此布局绘制轨道)。</summary>
public string SeasonLayout { get; set; } = "springTopSummerLeft";
public List<SeasonPoint> Seasons { get; set; } = new();
}
+3 -3
View File
@@ -6,7 +6,6 @@
"zh-CN": "地球公转",
"en": "Earth Revolution"
},
"version": "1.0.0",
"author": "NeoRF",
"description": "四季更替、黄赤交角与二分二至",
"descriptionI18n": {
@@ -20,9 +19,10 @@
],
"entry": "scene.json",
"license": "MIT",
"updatedAt": "2026-11-07",
"assembly": "EarthRevolutionModel.dll",
"type": "NeoRF.EarthModels.RevolutionModelFactory",
"preview": "preview.png",
"apiVersion": 1
"apiVersion": 1,
"version": "1.0-b8139bb568",
"updatedAt": "2026-11-07T09:23:04Z"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 67 KiB

@@ -42,6 +42,7 @@
"semiMajorAxis": 4.0,
"eccentricity": 0.0167,
"show": true,
"seasonLayout": "springTopSummerLeft",
"seasons": [
{
"angleDeg": 0,
+3 -3
View File
@@ -6,7 +6,6 @@
"zh-CN": "地球自转",
"en": "Earth Rotation"
},
"version": "1.0.0",
"author": "NeoRF",
"description": "昼夜交替、晨昏线与太阳直射点",
"descriptionI18n": {
@@ -20,9 +19,10 @@
],
"entry": "scene.json",
"license": "MIT",
"updatedAt": "2026-11-07",
"assembly": "EarthRotationModel.dll",
"type": "NeoRF.EarthModels.RotationModelFactory",
"preview": "preview.png",
"apiVersion": 1
"apiVersion": 1,
"version": "1.0-52ac06496e",
"updatedAt": "2026-11-07T09:23:04Z"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 175 KiB

After

Width:  |  Height:  |  Size: 178 KiB

+51
View File
@@ -0,0 +1,51 @@
{
"schema": 1,
"generated": "2026-11-07T09:23:04Z",
"repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main",
"modelDir": "model",
"launcher": {
"version": "1.0.0",
"revision": "eee4fbbfbc",
"packages": {
"win-x64": {
"path": "dist/GC-win-x64.zip",
"url": "",
"sha256": "dbd4997d111c4a60c5d06eadaf0962f41750bafa5b26946e216200ddf7d6c1cf",
"size": 39378935
},
"win-arm64": {
"path": "dist/GC-win-arm64.zip",
"url": "",
"sha256": "662589f9b315357702d855c46b12c1d088475bdf160c0c042793f2af404f8cb7",
"size": 37679907
},
"osx-arm64": {
"path": "dist/GC-osx-arm64.zip",
"url": "",
"sha256": "01dbf8b4787717aeb804a157ebaf0a75b8fffb1e9ab5e3fb0279fa9299ebee0a",
"size": 39853456
},
"osx-x64": {
"path": "dist/GC-osx-x64.zip",
"url": ""
},
"linux-x64": {
"path": "dist/GC-linux-x64.zip",
"url": ""
}
}
},
"models": [
{
"id": "earth-revolution",
"version": "1.0-b8139bb568",
"dir": "model/earth-revolution"
},
{
"id": "earth-rotation",
"version": "1.0-52ac06496e",
"dir": "model/earth-rotation"
}
]
}
@@ -40,6 +40,14 @@ public partial class App : Application
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
// 主窗口已建好,后台检查模型 / 启动器更新,不阻塞界面
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
{
Avalonia.Threading.Dispatcher.UIThread.Post(
() => _ = vm.RunStartupUpdateAsync(),
Avalonia.Threading.DispatcherPriority.Background);
}
}
base.OnFrameworkInitializationCompleted();
@@ -14,7 +14,7 @@
"home.installed": "Installed models",
"home.count": "{0} models",
"home.empty": "No models yet",
"home.emptyHint": "Import a model source on the Download page, or drop a model folder into model/.",
"home.emptyHint": "Models download from gitcode on startup; offline you can drop them into .GC/model/ or import a source on the Download page.",
"home.emptyAction": "Get models",
"home.open": "Open folder",
"home.delete": "Delete",
@@ -93,7 +93,32 @@
"set.license": "License",
"set.licenseValue": "MIT",
"set.checkUpdate": "Check for updates",
"set.checkUpdate.desc": "Offline build — update by replacing the app folder.",
"set.checkUpdate.desc": "Check on startup whether models and the launcher are up to date.",
"update.title": "Auto update",
"update.desc": "Models take effect immediately after download; launcher updates apply on the next start.",
"update.auto": "Check for updates on startup",
"update.checkNow": "Check now",
"update.source": "Update source",
"update.lastCheck": "Last check",
"update.pending": "Pending version",
"update.never": "Never",
"update.none": "None",
"update.checking": "Checking for updates…",
"update.disabled": "Auto update is off",
"update.offline": "Update server unavailable — continuing with local models",
"update.noManifest": "No remote version manifest — continuing with local models",
"update.noChange": "Models and launcher are up to date",
"update.modelsLatest": "Models are up to date",
"update.applied": "Updated {0} models, applied now",
"update.partial": " ({0} item(s) incomplete)",
"update.downloadingModel": "Downloading model {0}…",
"update.downloadingLauncher": "Downloading launcher {0}…",
"update.done": "Update check complete",
"update.pendingReady": "Launcher {0} is ready, applies on next start",
"update.pendingDownloaded": "Launcher {0} downloaded, applies on next start",
"update.noRidPackage": "Launcher {0} found (no package for {1})",
"update.noPackageUrl": "Launcher {0} found, but no download address",
"update.launcherFailed": "Launcher update failed: {0}",
"set.modelFormat": "Model format",
"set.modelFormat.desc": "model/<model-id>/<model-id>.json + <model-id>.model/ scene data",
"player.back": "Close window",
@@ -14,7 +14,7 @@
"home.installed": "已安装模型",
"home.count": "{0} 个模型",
"home.empty": "模型库还是空的",
"home.emptyHint": "在「下载」页从链接导入模型源,或把模型直接放进 model 目录。",
"home.emptyHint": "启动时会从 gitcode 自动下载模型;离线可把模型放进 .GC/model/,或在「下载」页导入模型源。",
"home.emptyAction": "去下载模型",
"home.open": "打开目录",
"home.delete": "删除",
@@ -93,7 +93,32 @@
"set.license": "许可",
"set.licenseValue": "MIT",
"set.checkUpdate": "检查更新",
"set.checkUpdate.desc": "当前为离线构建,更新请替换程序目录。",
"set.checkUpdate.desc": "启动时自动检查模型与启动器是否为最新版。",
"update.title": "自动更新",
"update.desc": "启动时检查模型与启动器是否为最新版;模型下载后立即生效,启动器在下次启动时应用。",
"update.auto": "启动时自动检查更新",
"update.checkNow": "检查更新",
"update.source": "更新源",
"update.lastCheck": "上次检查",
"update.pending": "待应用版本",
"update.never": "尚未检查",
"update.none": "无",
"update.checking": "正在检查更新…",
"update.disabled": "自动更新已关闭",
"update.offline": "暂时无法连接更新服务器,继续使用本地模型",
"update.noManifest": "远端还没有版本清单,继续使用本地模型",
"update.noChange": "模型与启动器均为最新版",
"update.modelsLatest": "模型已是最新版",
"update.applied": "已更新 {0} 个模型,立即生效",
"update.partial": "({0} 项未完成)",
"update.downloadingModel": "正在下载模型 {0}…",
"update.downloadingLauncher": "正在下载启动器新版 {0}…",
"update.done": "更新检查完成",
"update.pendingReady": "启动器新版 {0} 已就绪,下次启动生效",
"update.pendingDownloaded": "启动器新版 {0} 已下载,下次启动生效",
"update.noRidPackage": "发现启动器新版 {0}({1} 暂无安装包)",
"update.noPackageUrl": "发现启动器新版 {0},但下载地址不可用",
"update.launcherFailed": "启动器更新失败:{0}",
"set.modelFormat": "模型格式",
"set.modelFormat.desc": "model/<模型ID>/<模型ID>.json + <模型ID>.model/ 场景数据",
"player.back": "关闭窗口",
@@ -28,6 +28,32 @@ public sealed class AppSettings
public List<ModelSource> Sources { get; set; } = new();
public List<string> RecentModels { get; set; } = new();
// ---- 自动更新 ----------------------------------------------------------
/// <summary>启动时检查模型 / 启动器是否为最新版。</summary>
public bool AutoUpdateOnStartup { get; set; } = true;
/// <summary>默认更新仓库地址。</summary>
public string UpdateRepository { get; set; } = "https://gitcode.com/2509_92447106/GC";
/// <summary>版本清单地址覆盖(留空则按 UpdateRepository 拼接)。</summary>
public string? UpdateManifestUrl { get; set; }
/// <summary>本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。</summary>
public string? UpdateLocalRoot { get; set; }
/// <summary>已安装的模型版本:id -> version.json 里的版本。</summary>
public Dictionary<string, string> InstalledModelVersions { get; set; } = new();
/// <summary>当前已经应用过的启动器版本。</summary>
public string? LauncherVersion { get; set; }
/// <summary>已下载、等待下次启动应用的启动器版本。</summary>
public string? PendingLauncherVersion { get; set; }
/// <summary>最近一次更新检查时间(ISO 8601)。</summary>
public string? LastUpdateCheck { get; set; }
}
/// <summary>模型源:一个满足 Earth Model 规范的 git 仓库 / zip / 本地目录。</summary>
+12 -1
View File
@@ -1,12 +1,23 @@
using System;
using Avalonia;
using EarthModelStudio.Services;
namespace EarthModelStudio;
internal static class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
public static void Main(string[] args)
{
// 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/)
var paths = AppPaths.Discover();
paths.EnsureCreated();
// 上次下载的启动器新版,到这次启动才应用:交给独立脚本覆盖文件并重启
if (LauncherUpdate.TryApplyPending(paths)) return;
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
@@ -4,76 +4,102 @@ using System.IO;
namespace EarthModelStudio.Services;
/// <summary>
/// 目录探测。启动器本身不含任何模型数据,模型一律从外部模型库目录读取:
/// 1) 开发态:从 bin 目录向上找到 EarthModelStudio.sln,模型库用仓库根 model/
/// 2) 绿色态:可执行文件旁边有 model/ 目录(发布包默认只建空目录)
/// 3) 安装态:模型库放到用户数据目录
/// 也可用环境变量 EMS_HOME / EMS_MODELS 显式指定。
/// 运行目录约定(可执行文件旁边,不内置任何模型):
/// <code>
/// &lt;安装目录&gt;/
/// EarthModelStudio(.exe | .app/...)
/// .GC/
/// settings.json 设置与已安装版本记录
/// model/ 模型(启动时下载;model 目录也在 .GC 里)
/// cache/ 下载缓存 / 原子替换暂存
/// update/ 待下次启动应用的启动器更新包
/// </code>
/// 开发态同样使用 .GC/model,并自动把仓库 model/ 的可分发部分同步进去。
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
/// </summary>
public sealed class AppPaths
{
/// <summary>安装目录(开发态为仓库根)。</summary>
public string AppRoot { get; private init; } = "";
public string ModelRoot { get; private init; } = "";
public string DataRoot { get; private init; } = "";
public bool IsPortableModelRoot { get; private init; }
public string CacheRoot => Path.Combine(DataRoot, "cache");
public string SettingsFile => Path.Combine(DataRoot, "settings.json");
/// <summary>可执行文件真正所在目录:启动器自更新时要覆盖这里。</summary>
public string InstallDirectory { get; private init; } = "";
/// <summary>.GC 目录。</summary>
public string HomeRoot { get; private init; } = "";
/// <summary>模型库,恒为 &lt;HomeRoot&gt;/model。</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");
public string SettingsFile => Path.Combine(HomeRoot, "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);
var dataRoot = Environment.GetEnvironmentVariable("EMS_DATA")
?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EarthModelStudio");
// 显式指定模型库(模型是外置数据,可放在任意磁盘/网络盘)
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
if (!string.IsNullOrWhiteSpace(envModels))
{
return new AppPaths
{
AppRoot = baseDir,
ModelRoot = envModels!,
DataRoot = dataRoot,
IsPortableModelRoot = false
};
}
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
repoRoot = FindRepoRoot(baseDir);
var isDev = !string.IsNullOrEmpty(repoRoot) &&
File.Exists(Path.Combine(repoRoot!, "EarthModelStudio.sln"));
var appRoot = isDev ? repoRoot! : baseDir;
var exeModelDir = Path.Combine(baseDir, "model");
string appRoot, modelRoot;
bool portable = false;
if (!string.IsNullOrEmpty(repoRoot) && Directory.Exists(Path.Combine(repoRoot!, "model")))
// 只读安装位置(如 Program Files / /Applications)自动退回用户数据目录
var explicitData = Environment.GetEnvironmentVariable("EMS_DATA");
string home;
if (!string.IsNullOrWhiteSpace(explicitData))
{
appRoot = repoRoot!;
modelRoot = Path.Combine(appRoot, "model");
}
else if (Directory.Exists(exeModelDir))
{
appRoot = baseDir;
modelRoot = exeModelDir;
portable = true;
home = explicitData!;
}
else
{
appRoot = baseDir;
modelRoot = Path.Combine(dataRoot, "model");
var portableHome = Path.Combine(appRoot, ".GC");
home = CanWrite(portableHome)
? portableHome
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EarthModelStudio", ".GC");
}
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
? envModels!
: Path.Combine(home, "model"); // 统一:model 目录在 .GC 里
return new AppPaths
{
AppRoot = appRoot,
InstallDirectory = baseDir,
HomeRoot = home,
ModelRoot = modelRoot,
DataRoot = dataRoot,
IsPortableModelRoot = portable
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");
File.Delete(probe);
return true;
}
catch
{
return false;
}
}
private static string? FindRepoRoot(string start)
{
var dir = new DirectoryInfo(start);
@@ -86,8 +112,51 @@ public sealed class AppPaths
public void EnsureCreated()
{
Directory.CreateDirectory(DataRoot);
Directory.CreateDirectory(HomeRoot);
Directory.CreateDirectory(CacheRoot);
Directory.CreateDirectory(ModelRoot);
Directory.CreateDirectory(UpdateRoot);
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
SyncDevelopmentModels();
}
private void SyncDevelopmentModels()
{
try
{
var source = Path.Combine(AppRoot, "model");
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);
}
}
}
@@ -15,16 +15,20 @@ public sealed class AppServices
public ModelSourceClient Sources { get; }
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
public ModelHost ModelHost { get; }
/// <summary>启动时检查模型 / 启动器更新。</summary>
public UpdateService Updates { get; }
private AppServices(AppPaths paths)
{
Paths = paths;
Settings = new SettingsService(paths);
Settings.Load(); // 先读设置,才知道用在线源还是本地离线源
Models = new ModelRepository(paths);
Sources = new ModelSourceClient(paths);
Downloads = new DownloadCenter(paths, Models);
Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory);
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
}
public static AppServices Create()
@@ -33,7 +37,6 @@ public sealed class AppServices
paths.EnsureCreated();
var services = new AppServices(paths);
services.Settings.Load();
L.I.Initialize(services.Settings.Current.Language);
services.Memory.Apply(services.Settings.Current.MemoryMb);
@@ -41,9 +44,5 @@ public sealed class AppServices
return services;
}
public static AppServices Ensure()
{
if (Current == null) Create();
return Current;
}
public static AppServices Ensure() => Current ?? Create();
}
@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
/// 目录结构与远端仓库一致:version.json + model/&lt;id&gt;/...
/// </summary>
public sealed class DirectoryRemote : IModelRemote
{
private readonly string _root;
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
public string DisplayName => _root;
public Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
var primary = SafePath("version.json");
var fallback = SafePath(Path.Combine("model", "version.json"));
var file = File.Exists(primary) ? primary : fallback;
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
return Task.FromResult(Json.Read<RepoVersion>(file));
}
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var baseDir = SafePath(rootPath ?? "model");
var result = new List<RepoEntry>();
if (!Directory.Exists(baseDir)) return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
Walk(baseDir, baseDir, 0, result);
return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
}
private void Walk(string dir, string baseDir, int depth, List<RepoEntry> result)
{
if (depth > 8) return;
foreach (var sub in Directory.GetDirectories(dir))
{
var name = Path.GetFileName(sub);
if (name.StartsWith('.')) continue;
var rel = Relative(baseDir, sub);
result.Add(new RepoEntry
{
Name = name,
Path = Relative(_root, sub),
RelativePath = rel,
IsDirectory = true
});
Walk(sub, baseDir, depth + 1, result);
}
foreach (var file in Directory.GetFiles(dir))
{
var name = Path.GetFileName(file);
if (name.StartsWith('.')) continue;
result.Add(new RepoEntry
{
Name = name,
Path = Relative(_root, file),
RelativePath = Relative(baseDir, file),
IsDirectory = false,
Size = new FileInfo(file).Length
});
}
}
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
=> await File.ReadAllBytesAsync(SafePath(entry.Path), ct);
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{
if (!string.IsNullOrWhiteSpace(package.Path))
{
var local = SafePath(package.Path!);
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
}
var url = package.Url;
if (string.IsNullOrWhiteSpace(url)) return null;
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
if (Path.IsPathRooted(url) && File.Exists(url))
return await File.ReadAllBytesAsync(url, ct);
if (Uri.TryCreate(url, UriKind.Absolute, out _))
return await Http.GetByteArrayAsync(url, ct);
return null;
}
private string SafePath(string relative)
{
var full = Path.GetFullPath(Path.Combine(_root, relative));
var prefix = _root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"路径越界: {relative}");
return full;
}
private static string Relative(string baseDir, string file) =>
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
}
@@ -0,0 +1,211 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
/// (https://gitcode.com/2509_92447106/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/2509_92447106/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";
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("EarthModelStudio-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 ("2509_92447106", "GC", "main");
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) return ("2509_92447106", "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('/');
return version;
}
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 = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
payload, EarthModelStudio.Services.Json.Options);
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null;
}
catch (Exception ex)
{
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
return null;
}
}
/// <summary>递归列出目录树(含目录项与文件项)。</summary>
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var result = new List<RepoEntry>();
var repoPath = (rootPath ?? _modelDir).Trim('/');
await WalkAsync(repoPath, "", 0, result, ct);
return result;
}
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);
}
}
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)
{
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim();
if (url == null && !string.IsNullOrWhiteSpace(package.Path))
{
try
{
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch;
var text = await _http.GetStringAsync(apiUrl, ct);
using var doc = JsonDocument.Parse(text);
if (doc.RootElement.TryGetProperty("download_url", out var dl))
url = dl.GetString();
}
catch (Exception ex)
{
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
return null;
}
}
if (string.IsNullOrWhiteSpace(url)) return null;
return await _http.GetByteArrayAsync(url!, ct);
}
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;
}
@@ -0,0 +1,176 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
/// <summary>.GC/update/pending.json:已下载、等待下次启动应用的启动器版本。</summary>
public sealed class PendingUpdate
{
public string Version { get; set; } = "";
public string Rid { get; set; } = "";
public string InstallDirectory { get; set; } = "";
public string Executable { get; set; } = "";
public string Payload { get; set; } = "payload";
public string? DownloadedAt { get; set; }
}
/// <summary>
/// 「下次启动时应用」:主进程刚进 Main、还没建窗口时,交给一个独立脚本进程,
/// 脚本等主进程退出后覆盖可执行文件并重启。这样 Windows 上也不会碰到文件占用。
/// </summary>
public static class LauncherUpdate
{
public static bool TryApplyPending(AppPaths paths) => TryApplyPending(paths, launch: true);
/// <summary>launch=false 只生成脚本、不启动进程,供离线自动更新测试使用。</summary>
public static bool TryApplyPending(AppPaths paths, bool launch)
{
// 开发态、自检、显式关闭时一律不替换正在运行的程序
if (paths.IsDevelopment) return false;
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
var pendingFile = Path.Combine(paths.UpdateRoot, "pending.json");
if (!File.Exists(pendingFile))
{
ClearPendingSetting(paths);
return false;
}
PendingUpdate? pending;
try { pending = Json.Read<PendingUpdate>(pendingFile); }
catch { pending = null; }
var payload = Path.Combine(paths.UpdateRoot,
string.IsNullOrWhiteSpace(pending?.Payload) ? "payload" : pending!.Payload!);
var installDir = string.IsNullOrWhiteSpace(pending?.InstallDirectory)
? paths.InstallDirectory : pending!.InstallDirectory!;
// 版本已经生效,或包不完整:清掉标记后正常启动
if (pending == null || string.IsNullOrWhiteSpace(pending.Version) ||
string.Equals(pending.Version, UpdateService.CurrentLauncherVersion,
StringComparison.OrdinalIgnoreCase) || !Directory.Exists(payload))
{
TryDelete(pendingFile);
ClearPendingSetting(paths);
return false;
}
var exeName = string.IsNullOrWhiteSpace(pending.Executable)
? (OperatingSystem.IsWindows() ? "EarthModelStudio.exe" : "EarthModelStudio")
: pending.Executable!;
var exePath = Path.Combine(installDir, exeName);
var isWindows = OperatingSystem.IsWindows();
var script = Path.Combine(paths.UpdateRoot, isWindows ? "apply-update.bat" : "apply-update.sh");
var content = isWindows
? WindowsScript(payload, installDir, exePath, pendingFile, script)
: UnixScript(payload, installDir, exePath, pendingFile, script);
try
{
File.WriteAllText(script, content, new UTF8Encoding(false));
if (!launch)
{
Console.WriteLine($"(dry-run) 更新脚本已生成: {script}");
return true;
}
ProcessStartInfo psi;
if (isWindows)
{
psi = new ProcessStartInfo("cmd.exe")
{
UseShellExecute = false,
CreateNoWindow = true
};
psi.ArgumentList.Add("/c");
psi.ArgumentList.Add(script);
}
else
{
try
{
File.SetUnixFileMode(script,
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
catch { /* 某些文件系统不支持 */ }
psi = new ProcessStartInfo("/bin/sh")
{
UseShellExecute = false,
CreateNoWindow = true
};
psi.ArgumentList.Add(script);
}
Process.Start(psi);
Console.WriteLine($"启动器更新 {pending.Version} 已安排,重启后生效");
return true; // Main 直接返回,进程退出后由脚本接管
}
catch (Exception ex)
{
Console.Error.WriteLine($"应用启动器更新失败(保留待更新包,下次再试): {ex.Message}");
return false;
}
}
private static string WindowsScript(string payload, string installDir,
string exePath, string pendingFile, string script)
{
var text = new StringBuilder();
text.AppendLine("@echo off");
text.AppendLine("chcp 65001 >nul 2>&1");
text.AppendLine($"set \"SRC={payload}\"");
text.AppendLine($"set \"DST={installDir}\"");
text.AppendLine($"set \"EXE={exePath}\"");
text.AppendLine($"set \"PENDING={pendingFile}\"");
text.AppendLine("timeout /t 2 /nobreak >nul");
text.AppendLine("xcopy /E /Y /I /Q \"%SRC%\\*\" \"%DST%\\\" >nul 2>&1");
text.AppendLine("if exist \"%PENDING%\" del /Q \"%PENDING%\" >nul 2>&1");
text.AppendLine("if exist \"%EXE%\" start \"\" \"%EXE%\"");
text.AppendLine($"del /Q \"{script}\" >nul 2>&1");
return text.ToString();
}
private static string UnixScript(string payload, string installDir,
string exePath, string pendingFile, string script)
{
static string Q(string value) => "\"" + value
.Replace("\\", "\\\\")
.Replace("\"", "\\\"")
.Replace("$", "\\$")
.Replace("`", "\\`") + "\"";
var text = new StringBuilder();
text.AppendLine("#!/bin/sh");
text.AppendLine("sleep 2");
text.AppendLine($"cp -R {Q(payload + "/.")} {Q(installDir + "/")}");
text.AppendLine($"chmod +x {Q(exePath)} 2>/dev/null");
text.AppendLine($"rm -f {Q(pendingFile)}");
text.AppendLine($"{Q(exePath)} >/dev/null 2>&1 &");
text.AppendLine($"rm -f {Q(script)}");
return text.ToString();
}
private static void ClearPendingSetting(AppPaths paths)
{
try
{
var settings = Json.Read<AppSettings>(paths.SettingsFile);
if (settings == null || string.IsNullOrEmpty(settings.PendingLauncherVersion)) return;
settings.PendingLauncherVersion = null;
settings.LauncherVersion = UpdateService.CurrentLauncherVersion;
Json.Write(paths.SettingsFile, settings);
}
catch { /* 设置文件不可写时忽略 */ }
}
private static void TryDelete(string file)
{
try { if (File.Exists(file)) File.Delete(file); } catch { }
}
}
@@ -22,8 +22,8 @@ public sealed class SettingsService
}
/// <summary>
/// 首次启动不预置任何模型源:启动器只做适配,模型内容由用户从链接导入。
/// 这里只给一条空的自定义源占位。
/// 自动更新由 UpdateService 负责(版本清单 version.json),这里不预置任何在线源;
/// 只给「下载」页留一条空的自定义源占位。
/// </summary>
private void SeedSources()
{
@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary>
public sealed class RepoVersion
{
public int Schema { get; set; } = 1;
public string Generated { get; set; } = "";
public string Repository { get; set; } = "";
public string Branch { get; set; } = "main";
public string ModelDir { get; set; } = "model";
public RepoLauncher Launcher { get; set; } = new();
public List<RepoModel> Models { get; set; } = new();
}
public sealed class RepoLauncher
{
public string Version { get; set; } = "1.0.0";
/// <summary>启动器源码指纹(自动算,仅展示,不触发升级)。</summary>
public string Revision { get; set; } = "";
public Dictionary<string, RepoPackage> Packages { get; set; } = new();
}
/// <summary>某个平台的启动器发布包;url 优先,否则用 path 去仓库里解析下载地址。</summary>
public sealed class RepoPackage
{
public string? Url { get; set; }
public string? Path { get; set; }
public string? Sha256 { get; set; }
public long Size { get; set; }
}
public sealed class RepoModel
{
public string Id { get; set; } = "";
public string Version { get; set; } = "";
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
public string Dir { get; set; } = "";
}
/// <summary>远端目录树里的一个条目。</summary>
public sealed class RepoEntry
{
public string Name { get; init; } = "";
/// <summary>仓库内完整路径。</summary>
public string Path { get; init; } = "";
/// <summary>相对所请求根目录的路径,统一用 / 分隔。</summary>
public string RelativePath { get; init; } = "";
public bool IsDirectory { get; init; }
public string? DownloadUrl { get; init; }
public long Size { get; init; }
public string? Sha { get; init; }
}
/// <summary>
/// 远端源抽象:gitcode 是默认实现,本地目录实现用于离线教学与自动化测试。
/// </summary>
public interface IModelRemote
{
string DisplayName { get; }
Task<RepoVersion?> GetVersionAsync(CancellationToken ct);
Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct);
Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct);
Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct);
}
public sealed class UpdateProgress
{
public double Value { get; init; }
public string Message { get; init; } = "";
public string? Detail { get; init; }
}
public enum UpdateOutcome
{
NoChange,
Applied,
Partial,
Unavailable,
Disabled
}
public sealed class UpdateResult
{
public UpdateOutcome Outcome { get; init; }
public string Message { get; init; } = "";
public int UpdatedModels { get; init; }
public List<string> ModelNames { get; init; } = new();
public string? LauncherMessage { get; init; }
public string? Error { get; init; }
}
@@ -0,0 +1,356 @@
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 EarthModelStudio.Models;
namespace EarthModelStudio.Services;
/// <summary>
/// 启动时的自动更新:
/// · 读远端 version.json,和 .GC/settings.json 里记录的版本比较;
/// · 模型:下载到 cache 后原子替换 .GC/model/&lt;id&gt;,结果立刻刷新列表(本次启动生效);
/// · 启动器:下载到 .GC/update/payload 并写 pending.json,下次启动才应用;
/// · 任何失败都保留本地已装模型,绝不把模型库清空。
/// </summary>
public sealed class UpdateService
{
private readonly AppPaths _paths;
private readonly SettingsService _settings;
private readonly IModelRemote _remote;
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
{
_paths = paths;
_settings = settings;
_remote = remote;
}
public IModelRemote Remote => _remote;
public static string CurrentLauncherVersion
{
get
{
var v = Assembly.GetEntryAssembly()?.GetName().Version;
if (v == null) return "0.0.0";
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
}
}
public static string CurrentRid
{
get
{
var arch = RuntimeInformation.OSArchitecture switch
{
Architecture.Arm64 => "arm64",
Architecture.X86 => "x86",
_ => "x64"
};
if (OperatingSystem.IsWindows()) return "win-" + arch;
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
if (OperatingSystem.IsLinux()) return "linux-" + arch;
return RuntimeInformation.RuntimeIdentifier;
}
}
public static IModelRemote CreateRemote(AppSettings settings)
{
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
Directory.Exists(settings.UpdateLocalRoot!))
return new DirectoryRemote(settings.UpdateLocalRoot!);
return new GitCodeRemote(settings.UpdateManifestUrl, settings.UpdateRepository);
}
public async Task<UpdateResult> RunAsync(bool force,
IProgress<UpdateProgress>? progress, CancellationToken ct = default)
{
// 开发态的 model/ 里有源码与工程文件,自动更新一律跳过,避免把源码目录整体替换掉。
// 需要验证更新链路请用 ./build.sh update-test(它使用临时目录,不碰仓库)。
if (_paths.IsDevelopment && Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1")
return new UpdateResult
{
Outcome = UpdateOutcome.Disabled,
Message = "开发态跳过自动更新(保护仓库内模型源码)"
};
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"]
};
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
_settings.Save();
var needed = 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}");
}
}
string? launcherMessage = null;
try
{
launcherMessage = await StageLauncherAsync(remote.Launcher, progress, ct);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
launcherMessage = L.I.F("update.launcherFailed", ex.Message);
errors.Add("launcher: " + 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"] : 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('\\', '/');
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));
long done = 0;
foreach (var entry in files)
{
ct.ThrowIfCancellationRequested();
var bytes = await _remote.DownloadAsync(entry, ct);
var dest = Path.Combine(staging, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar));
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await File.WriteAllBytesAsync(dest, bytes, ct);
done += bytes.Length;
progress?.Report(new UpdateProgress
{
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)done / Math.Max(1, total))) / Math.Max(1, count),
Message = L.I.F("update.downloadingModel", model.Id),
Detail = entry.RelativePath
});
}
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
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 { /* 占用时留到下次 */ }
}
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
throw;
}
}
private async Task<string?> StageLauncherAsync(RepoLauncher launcher,
IProgress<UpdateProgress>? progress, CancellationToken ct)
{
var current = CurrentLauncherVersion;
var pending = _settings.Current.PendingLauncherVersion;
if (!string.IsNullOrWhiteSpace(pending) &&
string.Equals(pending, launcher.Version, StringComparison.OrdinalIgnoreCase))
return L.I.F("update.pendingReady", launcher.Version);
if (!IsNewer(launcher.Version, current)) return null;
var rid = CurrentRid;
if (!launcher.Packages.TryGetValue(rid, out var package) &&
!launcher.Packages.TryGetValue("default", out package))
return L.I.F("update.noRidPackage", launcher.Version, rid);
progress?.Report(new UpdateProgress
{
Value = 0.85,
Message = L.I.F("update.downloadingLauncher", launcher.Version)
});
var bytes = await _remote.DownloadPackageAsync(package!, ct);
if (bytes == null || bytes.Length == 0)
return L.I.F("update.noPackageUrl", launcher.Version);
if (!string.IsNullOrWhiteSpace(package!.Sha256))
{
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, package.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("启动器包校验失败(sha256 不符)");
}
Directory.CreateDirectory(_paths.UpdateRoot);
var payload = Path.Combine(_paths.UpdateRoot, "payload");
if (Directory.Exists(payload)) Directory.Delete(payload, true);
var zip = Path.Combine(_paths.CacheRoot, "launcher-" + Safe(launcher.Version) + ".zip");
await File.WriteAllBytesAsync(zip, bytes, ct);
try
{
ZipFile.ExtractToDirectory(zip, payload, true);
}
finally
{
try { File.Delete(zip); } catch { }
}
FlattenPayload(payload);
Json.Write(Path.Combine(_paths.UpdateRoot, "pending.json"), new PendingUpdate
{
Version = launcher.Version,
Rid = rid,
InstallDirectory = _paths.InstallDirectory,
Executable = Path.GetFileName(Environment.ProcessPath ?? ""),
Payload = "payload",
DownloadedAt = DateTime.UtcNow.ToString("O")
});
_settings.Current.PendingLauncherVersion = launcher.Version;
_settings.Save();
return L.I.F("update.pendingDownloaded", launcher.Version);
}
private static void FlattenPayload(string dir)
{
var entries = Directory.GetFileSystemEntries(dir);
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
var inner = entries[0];
var flat = dir + "-flat";
if (Directory.Exists(flat)) Directory.Delete(flat, true);
Directory.Move(inner, flat);
Directory.Delete(dir, true);
Directory.Move(flat, dir);
}
private static bool IsNewer(string remote, string local)
{
if (Version.TryParse(remote, out var r) && Version.TryParse(local, out var l)) return r > l;
return !string.Equals(remote, local, StringComparison.OrdinalIgnoreCase);
}
private static string Safe(string value)
{
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
return value.Replace('/', '-').Replace(' ', '-');
}
}
@@ -1,17 +1,16 @@
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models;
using EarthModelStudio.Services;
using EarthModelStudio.ViewModels;
namespace EarthModelStudio.ViewModels;
public partial class MainViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _updateRunning;
public HomeViewModel Home { get; }
public DownloadViewModel Download { get; }
@@ -25,17 +24,21 @@ public partial class MainViewModel : ObservableObject
[ObservableProperty] private bool _isDownloadActive;
[ObservableProperty] private bool _isSettingsActive;
// 启动更新状态条
[ObservableProperty] private bool _updateBarVisible;
[ObservableProperty] private bool _updateBusy;
[ObservableProperty] private double _updateProgress;
[ObservableProperty] private string _updateStatus = "";
[ObservableProperty] private string _updateDetail = "";
[ObservableProperty] private string _launcherNotice = "";
/// <summary>由主窗口注入的确认对话框。</summary>
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
/// <summary>
/// 请求为新模型开一个独立窗口。真正创建窗口的是主窗口,
/// 因此同一个模型可以同时开多份,主界面也不会被替换。
/// </summary>
public event Action<ModelPackage>? PlayerRequested;
public string VersionText => "v1.0.0";
public string PlatformText => RuntimeInformation.RuntimeIdentifier;
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
public string PlatformText => UpdateService.CurrentRid;
public MainViewModel(AppServices services)
{
@@ -84,4 +87,69 @@ public partial class MainViewModel : ObservableObject
public async Task<bool> ConfirmAsync(string message)
=> ConfirmHandler == null || await ConfirmHandler(message);
// ---- 自动更新 ----------------------------------------------------------
/// <summary>启动后由 App 调用:后台检查更新,不阻塞主界面。</summary>
public Task RunStartupUpdateAsync() => RunUpdateAsync(false);
/// <summary>状态条 / 设置页的「检查更新」,忽略自动开关强制检查。</summary>
[RelayCommand]
private Task CheckUpdate() => RunUpdateAsync(true);
private async Task RunUpdateAsync(bool force)
{
if (_updateRunning) return;
_updateRunning = true;
try
{
UpdateBarVisible = true;
UpdateBusy = true;
UpdateProgress = 0;
UpdateStatus = L.I["update.checking"];
UpdateDetail = "";
LauncherNotice = "";
// 在 UI 线程构造,进度回调自动回到 UI 线程
var progress = new Progress<UpdateProgress>(p =>
{
UpdateProgress = Math.Clamp(p.Value, 0, 1);
UpdateStatus = p.Message;
UpdateDetail = p.Detail ?? "";
});
var result = await _services.Updates.RunAsync(force, progress);
UpdateStatus = result.Message;
UpdateDetail = result.Error ?? "";
LauncherNotice = result.LauncherMessage ?? "";
// 模型下载完成后本次启动就刷新列表,立刻可用
if (result.UpdatedModels > 0) Home.Refresh();
if ((result.Outcome == UpdateOutcome.NoChange || result.Outcome == UpdateOutcome.Applied) &&
string.IsNullOrEmpty(LauncherNotice))
_ = AutoHideAsync();
}
catch (Exception ex)
{
UpdateStatus = L.I["update.offline"];
UpdateDetail = ex.Message;
}
finally
{
UpdateBusy = false;
_updateRunning = false;
}
}
private async Task AutoHideAsync()
{
try
{
await Task.Delay(6000);
if (!_updateRunning && string.IsNullOrEmpty(LauncherNotice)) UpdateBarVisible = false;
}
catch { /* 忽略 */ }
}
}
@@ -30,6 +30,21 @@ public partial class SettingsViewModel : ObservableObject
[ObservableProperty] private int _selectedFps = 30;
[ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _autoUpdate = true;
public string UpdateSourceText => _services.Updates.Remote.DisplayName;
public string LastCheckText
{
get
{
var value = _services.Settings.Current.LastUpdateCheck;
if (string.IsNullOrWhiteSpace(value)) return L.I["update.never"];
return DateTimeOffset.TryParse(value, out var time)
? time.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : value!;
}
}
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
public string MemoryValueText => $"{(int)Math.Round(MemoryValue)} MB";
public string UsageText => _services.Memory.UsageText;
@@ -54,6 +69,7 @@ public partial class SettingsViewModel : ObservableObject
var settings = _services.Settings.Current;
SelectedFps = settings.RenderFps;
MemoryValue = settings.MemoryMb;
AutoUpdate = settings.AutoUpdateOnStartup;
Sources.Clear();
foreach (var source in settings.Sources)
@@ -65,6 +81,15 @@ public partial class SettingsViewModel : ObservableObject
OnPropertyChanged(nameof(MemoryHint));
OnPropertyChanged(nameof(ModelRoot));
OnPropertyChanged(nameof(DataRoot));
OnPropertyChanged(nameof(UpdateSourceText));
OnPropertyChanged(nameof(LastCheckText));
OnPropertyChanged(nameof(PendingText));
}
partial void OnAutoUpdateChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.AutoUpdateOnStartup = value);
}
private void BuildLanguages()
@@ -8,10 +8,10 @@
Background="{DynamicResource AppBg}"
WindowStartupLocation="CenterScreen">
<Grid ColumnDefinitions="236,*">
<Grid ColumnDefinitions="236,*" RowDefinitions="*,Auto">
<!-- 侧栏 -->
<Border Grid.Column="0" Background="{DynamicResource SideBg}">
<Border Grid.Column="0" Grid.RowSpan="2" Background="{DynamicResource SideBg}">
<Grid RowDefinitions="Auto,*,Auto" Margin="16,22,16,18">
<StackPanel Orientation="Horizontal" Spacing="11">
@@ -45,6 +45,30 @@
</Border>
<!-- 内容:页面切换由 MainWindow 做淡入过渡,避免硬切 -->
<ContentControl x:Name="PageHost" Grid.Column="1" Content="{Binding Current}" />
<ContentControl x:Name="PageHost" Grid.Column="1" Grid.Row="0" Content="{Binding Current}" />
<!-- 启动更新状态条:模型立即生效,启动器下次启动生效 -->
<Border Grid.Column="1" Grid.Row="1"
Background="{DynamicResource Surface}"
BorderBrush="{DynamicResource Line}" BorderThickness="0,1,0,0"
Padding="20,9" IsVisible="{Binding UpdateBarVisible}">
<Grid ColumnDefinitions="Auto,*,Auto,Auto">
<TextBlock Grid.Column="0" Text="⟳" FontSize="16" Foreground="{DynamicResource Accent}"
VerticalAlignment="Center" Margin="0,0,12,0" />
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
<TextBlock Text="{Binding UpdateStatus}" FontSize="12.5" FontWeight="SemiBold"
Foreground="{DynamicResource Ink}" TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding UpdateDetail}" Classes="faint" TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding LauncherNotice}" FontSize="11" Foreground="{DynamicResource Warn}"
TextWrapping="Wrap" />
</StackPanel>
<ProgressBar Grid.Column="2" Width="130" Minimum="0" Maximum="1"
Value="{Binding UpdateProgress}" IsVisible="{Binding UpdateBusy}"
VerticalAlignment="Center" Margin="14,0" />
<Button Grid.Column="3" Classes="ghost small" Content="{loc:Loc update.checkNow}"
Command="{Binding CheckUpdateCommand}" IsEnabled="{Binding !UpdateBusy}"
VerticalAlignment="Center" />
</Grid>
</Border>
</Grid>
</Window>
@@ -84,6 +84,28 @@
</StackPanel>
</Border>
<!-- 自动更新 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="12">
<TextBlock Classes="h2" Text="{loc:Loc update.title}" />
<TextBlock Classes="muted" Text="{loc:Loc update.desc}" TextWrapping="Wrap" />
<CheckBox IsChecked="{Binding AutoUpdate}" Content="{loc:Loc update.auto}" />
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.source}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding UpdateSourceText}"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.lastCheck}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding LastCheckText}" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.pending}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding PendingText}" />
</Grid>
</StackPanel>
</Border>
<!-- 存储 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="14">
@@ -3,7 +3,9 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.IO.Compression;
using System.Linq;
using EarthModelStudio.Models;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
@@ -27,6 +29,9 @@ internal static class Program
[STAThread]
public static int Main(string[] args)
{
if (args.Length > 0 && args[0] == "--update-test")
return RunUpdateTest(args.Length > 1 ? args[1] : FindRepoRoot());
_outDir = args.Length > 0 ? args[0] : "screenshots";
Directory.CreateDirectory(_outDir);
Environment.SetEnvironmentVariable("EMS_HOME", FindRepoRoot());
@@ -44,6 +49,164 @@ internal static class Program
return 0;
}
/// <summary>
/// 离线验证自动更新完整链路:用本地目录冒充 gitcode 仓库,不访问网络、不替换真实程序。
/// </summary>
private static int RunUpdateTest(string repoRoot)
{
Console.WriteLine("=== 离线自动更新链路验证 ===");
AppBuilder.Configure<App>()
.UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting();
L.I.Initialize("zh-CN");
var versionFile = Path.Combine(repoRoot, "version.json");
if (!File.Exists(versionFile))
{
Console.WriteLine("FAIL: 缺少 version.json,请先执行 ./build.sh stamp");
return 1;
}
var tmp = Path.Combine(Path.GetTempPath(), "ems-update-" + Guid.NewGuid().ToString("N")[..8]);
var remote = Path.Combine(tmp, "remote");
var home = Path.Combine(tmp, ".GC");
var modelRoot = Path.Combine(home, "model");
Directory.CreateDirectory(modelRoot);
// 模拟远端仓库:version.json + 每个模型的 <id>.json / <id>.model/
Directory.CreateDirectory(Path.Combine(remote, "model"));
File.Copy(versionFile, Path.Combine(remote, "version.json"), true);
foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model")))
{
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(remote, "model", id);
Directory.CreateDirectory(dest);
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
CopyTree(data, Path.Combine(dest, id + ".model"));
}
// EMS_HOME 指向不含 .sln 的临时目录 -> 非开发态,走真实 .GC 布局
Environment.SetEnvironmentVariable("EMS_HOME", tmp);
Environment.SetEnvironmentVariable("EMS_DATA", home);
Environment.SetEnvironmentVariable("EMS_MODELS", modelRoot);
Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "1");
var paths = AppPaths.Discover();
paths.EnsureCreated();
var settings = new SettingsService(paths);
settings.Load();
var updater = new UpdateService(paths, settings, new DirectoryRemote(remote));
var failures = 0;
void Check(bool ok, string label)
{
Console.WriteLine($" {(ok ? "OK " : "FAIL")} {label}");
if (!ok) failures++;
}
Console.WriteLine($"运行目录: {paths.HomeRoot}");
Console.WriteLine($"模型库: {paths.ModelRoot}");
Check(paths.ModelRoot == modelRoot, ".GC/model 是下载目标");
Check(File.Exists(paths.SettingsFile), ".GC/settings.json 已创建");
// 1) 首次启动:模型全部下载并立即落地
var r1 = updater.RunAsync(true, null).GetAwaiter().GetResult();
Console.WriteLine($"首次启动: {r1.Message} 更新数={r1.UpdatedModels}");
Check(r1.UpdatedModels == 2, "首次启动下载 2 个模型");
foreach (var id in new[] { "earth-rotation", "earth-revolution" })
{
var dir = Path.Combine(modelRoot, id);
Check(File.Exists(Path.Combine(dir, id + ".json")), id + " 清单已落地");
Check(File.Exists(Path.Combine(dir, id + ".model", "scene.json")), id + " 场景数据已落地");
Check(!Directory.Exists(Path.Combine(dir, "src")), id + " 源码没有下到运行目录");
Check(settings.Current.InstalledModelVersions.ContainsKey(id), id + " 版本已记录到 settings");
}
// 2) 版本没变:不重复下载
var r2 = updater.RunAsync(true, null).GetAwaiter().GetResult();
Console.WriteLine($"二次检查: {r2.Message} 更新数={r2.UpdatedModels}");
Check(r2.UpdatedModels == 0, "版本未变时不重复下载");
// 3) 远端模型改版:只更新这一个,并且本次启动立即生效
var rv = Json.Read<RepoVersion>(Path.Combine(remote, "version.json"))!;
Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version),
"version.json 里模型版本由构建自动生成");
var changed = rv.Models[0];
changed.Version += "-changed";
var stampName = "_version-stamp.txt";
File.WriteAllText(Path.Combine(remote, "model", changed.Id,
changed.Id + ".model", stampName), "new content");
Json.Write(Path.Combine(remote, "version.json"), rv);
var r3 = updater.RunAsync(true, null).GetAwaiter().GetResult();
Console.WriteLine($"模型改版: {r3.Message} 更新数={r3.UpdatedModels}");
Check(r3.UpdatedModels == 1, "模型版本变化只更新 1 个模型");
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".model", stampName)),
"新版本本次启动立即生效");
// 4) 启动器新版:下载到 update/ 并写 pending,不立刻替换程序
var rid = UpdateService.CurrentRid;
Console.WriteLine($"当前平台: {rid},启动器版本: {UpdateService.CurrentLauncherVersion}");
var stage = Path.Combine(tmp, "launcher-stage");
Directory.CreateDirectory(stage);
File.WriteAllText(Path.Combine(stage, "EarthModelStudio.fake"), "new launcher");
var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
ZipFile.CreateFromDirectory(stage, zip);
rv.Launcher.Version = "9.9.9";
rv.Launcher.Packages[rid] = new RepoPackage { Url = zip, Path = "dist/GC-" + rid + ".zip" };
Json.Write(Path.Combine(remote, "version.json"), rv);
var r4 = updater.RunAsync(true, null).GetAwaiter().GetResult();
Console.WriteLine($"启动器新版: {r4.LauncherMessage}");
Check(File.Exists(Path.Combine(paths.UpdateRoot, "pending.json")), "启动器更新写入 pending.json");
Check(File.Exists(Path.Combine(paths.UpdateRoot, "payload", "EarthModelStudio.fake")),
"更新包已解压到 update/payload");
Check(settings.Current.PendingLauncherVersion == "9.9.9", "settings 记录待应用版本");
Check((r4.LauncherMessage ?? "").Contains("下次启动"), "提示下次启动才生效");
// 5) dry-run:验证下次启动的替换脚本能正确生成(不真的启动进程)
Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "");
var scripted = LauncherUpdate.TryApplyPending(paths, launch: false);
var scriptPath = Path.Combine(paths.UpdateRoot,
OperatingSystem.IsWindows() ? "apply-update.bat" : "apply-update.sh");
Check(scripted && File.Exists(scriptPath), "下次启动的替换脚本可生成");
if (File.Exists(scriptPath))
{
var script = File.ReadAllText(scriptPath);
Check(script.Contains(paths.InstallDirectory), "脚本包含正确的安装目录");
}
// 6) 断网兜底:保留本地模型,不清空
var offline = new UpdateService(paths, settings, new GitCodeRemote("http://127.0.0.1:1/nope"));
var beforeCount = settings.Current.InstalledModelVersions.Count;
var r5 = offline.RunAsync(true, null).GetAwaiter().GetResult();
Check(r5.Outcome == UpdateOutcome.Unavailable &&
settings.Current.InstalledModelVersions.Count == beforeCount &&
Directory.Exists(Path.Combine(modelRoot, "earth-rotation")),
"断网时保留本地模型、不清空模型库");
try { Directory.Delete(tmp, true); } catch { }
Console.WriteLine(failures == 0
? "=== 自动更新链路全部通过 ==="
: $"=== 有 {failures} 项失败 ===");
return failures == 0 ? 0 : 1;
}
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 dest = Path.Combine(dst, Path.GetRelativePath(src, file));
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
File.Copy(file, dest, true);
}
}
private static string FindRepoRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
@@ -111,8 +274,12 @@ internal static class Program
.Any(b => b.Tag is string tag && (tag == "rotation" || tag == "revolution") && ShownInTree(b));
Console.WriteLine($" {packages[i].Id}: 节气定位={hasSeasons} 视图切换={hasViewSwitch}");
// 缩放 / 拖动能力:模型画布由模型程序集提供,这里用反射验证接口存在且可用
var canvas = Descendants(player).FirstOrDefault(c => c.GetType().Name == "CelestialView");
// 缩放 / 触控 / 教学能力:模型画布由模型程序集提供,这里用反射逐项校验
var canvases = Descendants(player).Where(c => c.GetType().Name == "CelestialView").ToList();
var canvas = canvases.FirstOrDefault(c => Prop(c, "InsetMode") is bool inset && !inset)
?? canvases.FirstOrDefault();
var isRevolution = packages[i].Id.Contains("revolution", StringComparison.OrdinalIgnoreCase);
Console.WriteLine($" {packages[i].Id}: 画布数={canvases.Count}(含课堂特写)");
if (canvas != null)
{
var type = canvas.GetType();
@@ -126,13 +293,54 @@ internal static class Program
var resetZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
var hasPointerOverride = type.GetMethod("OnPointerMoved",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) != null;
Console.WriteLine($" {packages[i].Id}: 缩放={beforeZoom:0.00}→{afterZoom:0.00}→{resetZoom:0.00} 暂停拖动={hasPointerOverride}");
var hasMultiTouch = type.GetField("_pointers",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) != null;
Console.WriteLine($" {packages[i].Id}: 缩放={beforeZoom:0.00}→{afterZoom:0.00}→{resetZoom:0.00} 拖动={hasPointerOverride} 多指跟踪={hasMultiTouch}");
// 双指捏合:两指间距 100→150,缩放应当 1.00→1.50
var pinch = type.GetMethod("PinchZoom",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var pinchZoom = (double)(pinch?.Invoke(null, new object[] { 1.0, 100.0, 150.0 }) ?? 0d);
Console.WriteLine($" {packages[i].Id}: 捏合 100→150px = {pinchZoom:0.00}×");
// 手动转动:竖直拖动 300px 也不能改变视角平面
var elevBefore = Field(canvas, "_camElevTarget");
var angleBefore = (double)(Prop(canvas, isRevolution ? "OrbitAngle" : "SpinAngle") ?? 0d);
type.GetMethod("DragBy")?.Invoke(canvas, new object[] { 40.0, 300.0 });
var elevAfter = Field(canvas, "_camElevTarget");
var angleAfter = (double)(Prop(canvas, isRevolution ? "OrbitAngle" : "SpinAngle") ?? 0d);
Console.WriteLine($" {packages[i].Id}: 拖动 视角={elevBefore}→{elevAfter} 地球角度={angleBefore:0.0}→{angleAfter:0.0} 平面不变={Equals(elevBefore, elevAfter)}");
if (isRevolution)
{
// 两至日的直射点必须是教材值 23.5°
foreach (var (angle, expect) in new[] { (0d, 0d), (90d, 23.5d), (180d, 0d), (270d, -23.5d) })
{
type.GetMethod("JumpToOrbit")?.Invoke(canvas, new object[] { angle });
var decl = (double)(Prop(canvas, "SubsolarLatitude") ?? double.NaN);
Console.WriteLine($" 直射点 {angle:0}° => {decl:0.00}° (应 {expect:0.0}°,误差 {Math.Abs(decl - expect):0.000})");
}
// 点「夏至」应自动定格,并显示 23.5°N 的课堂读数
var summer = Descendants(player).OfType<Button>()
.FirstOrDefault(b => (b.Content as TextBlock)?.Text == "夏至" && ShownInTree(b));
summer?.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
Dispatcher.UIThread.RunJobs();
var frozen = Prop(canvas, "IsPlaying") is bool play && !play;
var frozenAngle = (double)(Prop(canvas, "OrbitAngle") ?? -1d);
var cardReadout = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "") == "23.5°N" && ShownInTree(t));
Console.WriteLine($" 夏至按钮: 已定格={frozen} 角度={frozenAngle:0} 课堂卡显示 23.5°N={cardReadout}");
Capture(player, "page-player-solstice.png");
}
}
// 底部提示:滚轮缩放 / 暂停后可拖动
// 课堂演示卡 / 底部触控提示
var hasCard = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("课堂演示", StringComparison.Ordinal) && ShownInTree(t));
var hasHint = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("拖动", StringComparison.Ordinal) && ShownInTree(t));
Console.WriteLine($" {packages[i].Id}: 交互提示={hasHint}");
Console.WriteLine($" {packages[i].Id}: 课堂演示卡={hasCard} 交互提示={hasHint}");
}
// 关掉第二个窗口,只留一个继续验证主窗口
@@ -150,6 +358,13 @@ internal static class Program
window.Close();
}
private static object? Prop(Control control, string name)
=> control.GetType().GetProperty(name)?.GetValue(control);
private static object? Field(Control control, string name)
=> control.GetType().GetField(name,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.GetValue(control);
private static bool WaitFor(Func<bool> condition, int timeoutMs = 20000)
{
var watch = Stopwatch.StartNew();
+51
View File
@@ -0,0 +1,51 @@
{
"schema": 1,
"generated": "2026-11-07T09:23:04Z",
"repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main",
"modelDir": "model",
"launcher": {
"version": "1.0.0",
"revision": "eee4fbbfbc",
"packages": {
"win-x64": {
"path": "dist/GC-win-x64.zip",
"url": "",
"sha256": "dbd4997d111c4a60c5d06eadaf0962f41750bafa5b26946e216200ddf7d6c1cf",
"size": 39378935
},
"win-arm64": {
"path": "dist/GC-win-arm64.zip",
"url": "",
"sha256": "662589f9b315357702d855c46b12c1d088475bdf160c0c042793f2af404f8cb7",
"size": 37679907
},
"osx-arm64": {
"path": "dist/GC-osx-arm64.zip",
"url": "",
"sha256": "01dbf8b4787717aeb804a157ebaf0a75b8fffb1e9ab5e3fb0279fa9299ebee0a",
"size": 39853456
},
"osx-x64": {
"path": "dist/GC-osx-x64.zip",
"url": ""
},
"linux-x64": {
"path": "dist/GC-linux-x64.zip",
"url": ""
}
}
},
"models": [
{
"id": "earth-revolution",
"version": "1.0-b8139bb568",
"dir": "model/earth-revolution"
},
{
"id": "earth-rotation",
"version": "1.0-52ac06496e",
"dir": "model/earth-rotation"
}
]
}