Compare commits

..
17 Commits
Author SHA1 Message Date
2509_92447106 1cca045f08 添加部分功能,以及等高线模型 2026-11-14 09:28:38 +08:00
2509_92447106 4f5beb5109 添加部分功能,以及等高线模型 2026-11-14 09:23:41 +08:00
2509_92447106 6d4d098681 添加部分功能 2026-11-14 06:40:54 +08:00
2509_92447106 9293fee3bf 修复一些文件 2026-11-13 22:09:17 +08:00
2509_92447106 f1787dff9d 更新 Directory.Build.props git.bat git.sh (2026-11-13 22:01) 2026-11-13 22:01:57 +08:00
2509_92447106 b6dc5649d6 修复 2026-11-12 20:37:20 +08:00
2509_92447106 4b5aa7799f x修复 2026-11-12 19:42:05 +08:00
2509_92447106 0f19921dd4 修复 2026-11-12 19:35:07 +08:00
2509_92447106 0e86c17056 修复 2026-11-12 19:30:45 +08:00
2509_92447106 7de92a25f5 修复 2026-11-08 20:43:56 +08:00
2509_92447106 874c97ee27 同步 2026-11-08 20:19:31 +08:00
2509_92447106 936aec8185 修复: .GC 不应入库(曾覆盖远程仓库)+ 模型读取优化 2026-11-08 18:25:00 +08:00
2509_92447106 f69a8fbb7f 修复model读取 2026-11-08 18:19:28 +08:00
2509_92447106 5e0b46b3f3 构建系统重构: buildsh 模块化 + apt 风格进度条 2026-11-08 17:36:15 +08:00
2509_92447106 22e1b8fbb9 修复 2026-11-08 17:30:09 +08:00
2509_92447106 e9c8952481 修复更新,更改build 2026-11-08 17:29:48 +08:00
2509_92447106 1ee49b8966 y 2026-11-08 17:29:32 +08:00
118 changed files with 9249 additions and 1292 deletions

No files matched your search

+8 -6
View File
@@ -1,20 +1,22 @@
# 运行数据目录(settings/model/cache/update),绝不入库
.GC/
# .NET 构建中间产物(已跟踪的历史文件不动,只防新增)
bin/
obj/
build/
.GC/
*.user
.DS_Store
.vs/
.venv/
venv/
env/
.idea/
.vscode/
.DS_Store
__pycache__/
*.pyc
*.pyo
*.log
node_modules/
dist/
build/
.pytest_cache/
.mypy_cache/
dist/
-40
View File
@@ -1,40 +0,0 @@
# 2026-11-07
## Earth Model Studio(新建项目)
- 用户要求:C#/.NET8(可切10),多目录结构(曾要求 gradle 命名,后明确改为标准 .NET 命名,勿再用 gradle 字样)
- 结构:src/main/dotnet + src/test/dotnet + src/main/resources + model/ + examples/ + dist/ + Directory.Build.props + build.sh/build.ps1
- 三平台一次性编译:`./build.sh publish` → dist/{mac-arm64(.app),win-x64,win-arm64},自包含单文件 + 内置 model/ + examples/
- 技术栈:Avalonia 11.3.9 + CommunityToolkit.Mvvm 8.2.2(本地 NuGet 已缓存);纯 CPU 球面像素渲染(SphereRaster + CelestialView)
- 模型格式:model/<id>/<id>.json + <id>.model/scene.json + land.json;模型源=git 仓库根的 model/ 目录(支持 github/gitlab/gitee zip 归档、git clone、本地目录)
- 内置模型:earth-rotation(自转)、earth-revolution(公转),land.json 手绘大陆轮廓已校验
- 校验:src/test/dotnet 用 Avalonia.Headless 渲染截图到 build/screenshots(页面+场景全通过,HUD 重叠已修)
- 已知小问题:RadialGradientBrush.Radius 过时警告;发布后 mac 单文件在沙箱内需 DOTNET_BUNDLE_EXTRACT_BASE_DIR 可写
## 修改(14:10 之后)
- 模型启动改为独立窗口:新增 Views/PlayerWindow.axaml(.cs),MainViewModel 只抛 PlayerRequested 事件,MainWindow 负责 Show(owner) 并维护 PlayerWindows 列表;PlayerViewModel 去掉 MainViewModel 依赖,改 CloseRequested + IDisposable;Esc/空格/F11 快捷键
- 分层:src=启动器(无模型数据、无预置模型源),model/=模型数据。移除 examples/,SettingsService 不再种内置源,AppPaths 去掉 ExamplesRoot 并新增 EMS_MODELS
- build.sh/build.ps1:publish 只建空 model/(仅 README),新增 pack-models → dist/models-1.0.0.zip
- model/README.md 写清模型格式规范
- 验证:离屏截图 page-player.png / page-main-while-playing.png,双窗口计数 2→关一个→1→0;三平台重新发布 + 模型 zip
## 架构重构(14:30 之后):启动器不再渲染,模型自带功能代码
- 新分层:src=启动器(扫描/下载/开窗,零渲染);model-sdk=契约;model-src=模型源码+封面工具;model=模型包(数据+dll+preview.png+i18n)
- 契约:IModelFactory(ApiVersion/Create) / IModelRuntime.CreateView(IModelContext) / IModelContext(ModelId/ModelDirectory/DataDirectory/Language/MemoryBudgetMb/RequestClose/Log)
- 加载:ModelHost + 可收集 AssemblyLoadContext,Sdk/Avalonia 走默认上下文,关窗 Unload
- 迁移:CelestialView/SphereRaster/LandMask/SceneDefinition/SceneRuntime → model-src/EarthModels(命名空间 NeoRF.EarthModels);PlayerView+PlayerViewModel 换成模型内 EarthModelView(C# 构建 UI)
- 模型包新增清单字段 assembly/type/preview/apiVersion;封面由 model-src/tools/PreviewGen 用模型渲染器生成
- 自转模型 views=["rotation"] → 无节气定位/无视图切换;公转 views=["revolution"] → 有节气、封面是公转场景
- 构建:./build.sh models 编译模型 dll + 生成封面;pack-models 先编译再打包
- 验证:EMS_SELFTEST=1 自检(dev + 发布包 /tmp 部署)两个模型均 OK;离屏截图含插件加载真实窗口
## 六项改动(15:00–15:35):真实贴图 / 缩放 / 拖动 / 动画 / 代码归位 / 进度条
- 目录:删除 model-src,根目录 model-sdk -> model/_sdk;现在根目录只有 src/ 与 model/。模型源码在 model/<id>/src/,共享引擎在 model/_engine/,契约在 model/_sdk/
- 清单 assembly 改为各模型自己的 dll:EarthRotationModel.dll / EarthRevolutionModel.dll(工厂仍是 NeoRF.EarthModels.*ModelFactory)
- 贴图:PlanetTexture 烘焙 1024×512 等经纬度纹理(海洋深度、沙漠/雨林/针叶林/苔原、极地冰盖、云层模糊、夜间辉光);反照率打包 uint[] Albedo
- 性能:地形梯度 SlopeEast/SlopeNorth 预烘焙(去掉每像素 4 次 SampleHeight + 6 次三角函数);海面高光 Pow 改乘法;运动时降分辨率 460 + 按帧耗时自适应 320–460,静止补 820 高清帧。实测公转播放 6ms、自转播放 ~18ms
- 交互:滚轮/工具栏 −100%+/⟲ 缩放 0.6–6×(缓动),暂停后拖动旋转地球或沿轨道移动、松手惯性;云层播放/暂停都缓慢漂移
- 动画:模型窗口淡入、按钮悬停 BrushTransition、教学面板滑入淡出;启动器页面切换淡入、按钮/卡片悬停过渡、进度条 DoubleTransition 平滑
- 进度条:契约新增 IModelRuntime.Prepare(后台)+ IModelContext.ReportProgress;ModelHost.LoadAsync 两阶段;LoadingWindow 显示真实阶段(读场景→烘焙纹理→构建界面)
- 打包:pack-models 排除 */bin/* */obj/*,避免把 107MB SkiaSharp native 打进包;模型包 356KB(含源码+dll+封面+i18n)
- 验证:离屏截图全部正常;反射校验缩放 1.00→1.25→1.00、暂停拖动=True、交互提示=True;自转无节气;发布包复制到 /tmp 自检两个模型 OK
- 产物:dist/mac-arm64 97M、win-x64 88M、win-arm64 94M(model/ 仅 README),dist/models-1.0.0.zip 356K
+1 -1
View File
@@ -21,7 +21,7 @@
-->
<AvaloniaVersion>11.3.9</AvaloniaVersion>
<MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.2</Version>
<Version>1.0.6</Version>
<Company>NeoRF</Company>
<Product>Earth Model Studio</Product>
<NeutralLanguage>zh-Hans</NeutralLanguage>
+78
View File
@@ -0,0 +1,78 @@
# GC v1.0.6
## 新模型:等高线地形图
依据人教版七年级上册「地形图的判读」制作,把课本最难讲清的一件事——**立体地形如何转成平面等高线图**——变成可交互的双图联动。
- **左右双图联动**:左边是三维地形块(斜视图),右边是等比例的分层设色等高线图。鼠标移到任一侧,两侧同步标出该点位置、海拔、相对高度和地形部位。
- **五种地形部位判读**:山峰、山脊、山谷、鞍部、陡崖。鼠标停在哪里,底部就实时显示该处属于哪种部位,并给出对应颜色。
- **等高线自动生成**:Marching Squares 算法从 192×192 高度场实时提取,等高距 100 m,共 14 条;每 5 条加粗为计曲线并标注海拔。
- **分层设色**:绿 → 黄绿 → 土黄 → 棕 → 雪白,与课本配色一致。
- **判读要点面板**:右侧列出五种部位的特征(如「山脊:等高线凸向低处,脊线是分水线」)和四条核心规则(等高距、疏密与坡度、计曲线、海拔与相对高度)。
- 地形本身包含主峰、次峰(之间形成鞍部)、两条山脊、一条河谷、一侧陡坡、一侧缓坡和一处陡崖,海拔 0~1322 m。
## 更新系统:双源支持
启动器现在同时对接 **Xhmcl** 和 **GitCode** 两个仓库(同一份内容的镜像)。
- **自动测速选源**:检查更新与下载前并发探测两边的 `version.json` 响应时间,自动选用更快的那一个。结果缓存 3 分钟,不会每次都测。
- **Release 交叉检查**:两个源的 Release 都会查询,取版本号最高且包含当前平台发布包的那个。某个源没发 Release 时自动跳到另一个,不影响使用。
- **版本号优先于发布时间**:Release 列表按版本号数值比较(`1.0.10 > 1.0.9`),不受发布时间顺序影响。草稿状态(draft)的 Release 不计入。
- **模型与启动器分开取**:模型清单始终读仓库里的 `version.json`(模型不需要发 Release),启动器版本只认 Release。这样即使某个源没发 Release,模型仍能正常更新。
- **同版本比对指纹**:远端版本与本地相同时,下载对应平台的发布包比对 sha256。一致则视为最新;不一致说明是自行编译的构建,不打扰用户。
- **修复版本读取**:此前 `Assembly.GetEntryAssembly()` 在某些宿主下会返回 `1.0.0`,导致明明是最新版却一直提示更新;现在改为读取本程序集版本。
## 下载页面
- **取消自定义模型源**:不再接受任意仓库地址,只保留 Xhmcl 与 GitCode 两个内置源,避免来源不明的模型。
- **一键测速切换**:原来的「导入模型源」输入框改为「测速并切换到最快源」按钮,点击后自动比对并切到更快的那个源。
- **下载与更新统一**:下载页面和启动更新现在共用同一个源选择器,不再出现两处下载速度不一致的情况。
## 窗口标题栏
- **去掉彩色圆圈**:最小化 / 最大化 / 关闭三个按钮改回纯矢量图标,不再有黄、绿、红圆底。
- **主窗口补齐最大化**:此前主窗口只有最小化和关闭,现在补上最大化,并支持双击标题栏切换。
- **图标随状态切换**:最大化后图标变为两个重叠小方框(还原),还原后变回单方框。
- **圆角始终保留**:任何窗口状态下都保持 16px 圆角,不再最大化后变成直角贴边。
- **尺寸自适应**:标题栏文字、按钮、图标随窗口宽度同比缩放(0.85–1.9 倍),全屏时不会小得点不中。
## 缩放动画
- **地理模型**:此前滚轮缩放直接跳变,现在改为指数逼近的平滑动画(60Hz),差值小于阈值自动停下,不空转耗 CPU。
- **地球模型**:本就带平滑缩放,保持原样。
## 关于页面
- 新增「**感谢**」卡片,样式与「开发者」卡片一致:**地理洪老师 — 地理学科内容指导**。
## 开发者工具
新增 `git.sh` / `git.bat` 与 `gitshell/` 目录,把仓库操作从手动命令变成可交互流程:
- **`./git.sh autogit`**:交互式提交。依次询问①选哪个仓库(支持多选、可选全部、可连续输入多个新地址)②确认仓库地址③确认提交分支④输入提交信息⑤最终确认,然后逐个推送并汇总结果。
- **自动排除构建产物**:`dist/` `build/` `bin/` `obj/` `.GC/` 无论是否被跟踪都不会提交,历史上被跟踪的会先从索引移出(本地文件保留)。
- **`./git.sh status`**:一眼看清当前分支、改动数量、最近提交,以及每个远程仓库的领先/落后情况。
## 模型版本
| 模型 | 版本 |
| --- | --- |
| 等高线地形图 contour-map | **1.0**(新) |
| 地球地理 earth-geography | 1.8 |
| 地球自转 earth-rotation | 1.6 |
| 地球公转 earth-revolution | 1.6 |
| 比例尺计算器 scale-calculator | 1.5 |
---
**安装包**
| 平台 | 文件 |
| --- | --- |
| Windows x64 | `GC-win-x64.zip` |
| Windows ARM64 | `GC-win-arm64.zip` |
| macOS Apple Silicon | `GC-osx-arm64.zip` |
| macOS Intel | `GC-osx-x64.zip` |
| Linux x64 | `GC-linux-x64.zip` |
下载后解压即可运行。模型会在首次启动时自动下载到程序目录旁的 `.GC/model/`。
+42 -195
View File
@@ -1,228 +1,75 @@
# ---------------------------------------------------------------------------
# Earth Model Studio 构建脚本(Windows PowerShell)
#
# .\build.ps1 编译
# .\build.ps1 run 运行
# .\build.ps1 test 离屏渲染校验
# .\build.ps1 models 编译模型 dll + 生成封面 + 自动打版本
# .\build.ps1 stamp 只重新生成 version.json 与模型版本
# .\build.ps1 publish 编译三个平台启动器(不内置模型)+ 建立 .GC 运行目录
# .\build.ps1 pack-models 单独打包模型数据(含 version.json)
# .\build.ps1 pack-launcher 生成三个平台的启动器更新包 zip
# .\build.ps1 update-test 离线验证自动更新链路
# .\build.ps1 clean 清理
#
# 分层:src\ 只是启动器;模型全部在 model\;**发布包不内置模型**。
#
# 运行目录(发布包里就长这样):
# <安装目录>\
# EarthModelStudio.exe
# .GC\settings.json
# .GC\model\ 启动时从 gitcode 下载的模型
# .GC\cache\ 下载暂存
# .GC\update\ 待下次启动应用的启动器更新
# Earth Model Studio 构建入口(Windows PowerShell,薄封装)
# 实际代码在 buildsh/ 里。Windows 上若无 sh,则走内置的最小实现。
# .\build.ps1 build | check | models | stamp | run | test | clean | doctor
# ---------------------------------------------------------------------------
param(
[Parameter(Position = 0)]
[ValidateSet('build', 'run', 'test', 'publish', 'models', 'stamp', 'pack-models',
'pack-launcher', 'update-test', 'bundle', 'clean', 'doctor')]
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
'run','test','update-test','clean','doctor','dist')]
[string]$Task = 'build'
)
$ErrorActionPreference = 'Stop'
$Root = $PSScriptRoot
Set-Location $Root
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。
# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
$AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj'
$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.2'
$StampProj= 'model/_engine/VersionStamp/VersionStamp.csproj'
$Sln = 'EarthModelStudio.sln'
$Version = ([regex]::Match((Get-Content Directory.Build.props -Raw), '<Version>(.*?)</Version>')).Groups[1].Value
if (-not $Version) { $Version = '1.0.0' }
New-Item -ItemType Directory -Force -Path "$Root/build/logs" | Out-Null
function Stamp-Versions {
Write-Host '==> 自动计算模型版本并生成 version.json'
dotnet run --project $StampProj -c Release -- $Root $Version
# 优先复用 buildsh 的 shell 实现(Git Bash / WSL / sh 可用时)
$sh = Get-Command sh -ErrorAction SilentlyContinue
if ($sh) {
& $sh.Source "$Root/build.sh" $Task
exit $LASTEXITCODE
}
function Stamp { dotnet run --project $StampProj -c Release -- $Root $Version }
function Build-Models {
Write-Host '==> 编译模型功能程序集(源码就在各模型目录的 src\ 里)'
Get-ChildItem "$Root/model" -Directory | ForEach-Object {
$id = $_.Name
$src = Join-Path $_.FullName 'src'
if (-not (Test-Path $src)) { return }
$proj = Get-ChildItem $src -Filter *.csproj | Select-Object -First 1
if ($null -eq $proj) { return }
if (-not $proj) { return }
dotnet build $proj.FullName -c Release
$data = Join-Path $_.FullName "$id.model"
if (Test-Path $data) {
Get-ChildItem (Join-Path $src 'bin/Release/net8.0') -Filter *.dll | ForEach-Object {
if ($_.Name -eq 'EarthModelStudio.ModelSdk.dll') { return }
Copy-Item -Force $_.FullName $data
Write-Host " -> model/$id/$id.model/$($_.Name)"
}
}
}
Write-Host '==> 用模型自己的渲染器生成封面'
dotnet run --project $PreviewProj -c Release -- $Root
Stamp-Versions
}
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
function Prepare-RuntimeLayout([string]$RelDir) {
$dest = "$Root/$RelDir"
if (-not (Test-Path $dest)) { return }
foreach ($old in @("$dest/model", "$dest/examples")) {
if (Test-Path $old) { Remove-Item -Recurse -Force $old }
}
foreach ($dir in @("$dest/.GC/model", "$dest/.GC/cache", "$dest/.GC/update")) {
New-Item -ItemType Directory -Force -Path $dir | Out-Null
}
$readme = @'
模型库目录(.GC/model/)
启动时程序会读取 gitcode 仓库的 version.json,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
.GC/settings.json
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
'@
Set-Content -Path "$dest/.GC/model/README.txt" -Value $readme -Encoding UTF8
$settingsPath = "$dest/.GC/settings.json"
if (-not (Test-Path $settingsPath)) {
$json = @'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"updateRepository": "https://gitcode.com/2509_92447106/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
}
'@
Set-Content -Path $settingsPath -Value $json -Encoding UTF8
}
Write-Host " 运行目录 -> $RelDir/.GC (settings.json + model/ + cache/ + update/)"
}
function Publish-Rid([string]$Rid, [string]$OutDir) {
Write-Host "==> 编译 $Rid -> $OutDir"
# 先删旧产物目录,避免残留文件混进新包
if (Test-Path "$Root/$OutDir") { Remove-Item -Recurse -Force "$Root/$OutDir" }
dotnet publish $AppProj -c Release -r $Rid --self-contained true `
-p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true `
-p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false -o "$Root/$OutDir"
foreach ($old in @("$Root/$OutDir/model", "$Root/$OutDir/examples")) {
if (Test-Path $old) { Remove-Item -Recurse -Force $old }
}
}
function Pack-Models {
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
$zip = "$Root/dist/models-$Version.zip"
if (Test-Path $zip) { Remove-Item -Force $zip }
Write-Host "==> 打包模型数据 -> dist/models-$Version.zip"
$stage = Join-Path $env:TEMP "ems-models-stage"
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
New-Item -ItemType Directory -Force -Path $stage | Out-Null
Get-ChildItem "$Root/model" -Recurse -File | Where-Object {
$_.FullName -notmatch '\\(bin|obj)\\' -and $_.Extension -ne '.user'
} | ForEach-Object {
$rel = $_.FullName.Substring("$Root/model".Length + 1)
$dest = Join-Path $stage $rel
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
Copy-Item -Force $_.FullName $dest
}
Compress-Archive -Path "$stage/*" -DestinationPath $zip -Force
Remove-Item -Recurse -Force $stage
}
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户模型与设置)
function Pack-Launcher {
Write-Host '==> 生成启动器更新包(不含 .GC)'
$targets = @{
'GC-win-x64.zip' = "$Root/dist/win-x64"
'GC-win-arm64.zip' = "$Root/dist/win-arm64"
'GC-osx-arm64.zip' = "$Root/dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
}
if (-not (Test-Path $targets['GC-osx-arm64.zip'])) {
$targets['GC-osx-arm64.zip'] = "$Root/dist/mac-arm64"
}
foreach ($name in $targets.Keys) {
$src = $targets[$name]
if (-not (Test-Path $src)) { continue }
$stage = Join-Path $env:TEMP ("ems-launcher-" + [IO.Path]::GetFileNameWithoutExtension($name))
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
New-Item -ItemType Directory -Force -Path $stage | Out-Null
Get-ChildItem $src -Recurse -File | Where-Object {
$_.FullName -notmatch '\\\.GC\\' -and $_.Name -ne '.DS_Store'
} | ForEach-Object {
$rel = $_.FullName.Substring($src.Length).TrimStart('\', '/')
$dest = Join-Path $stage $rel
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
Copy-Item -Force $_.FullName $dest
}
$zip = "$Root/dist/$name"
if (Test-Path $zip) { Remove-Item -Force $zip }
Compress-Archive -Path "$stage/*" -DestinationPath $zip -Force
Remove-Item -Recurse -Force $stage
}
Stamp-Versions
Get-ChildItem "$Root/dist/GC-*.zip" | Select-Object Name, Length
Stamp
}
switch ($Task) {
'build' {
Get-ChildItem "$Root/dist/GC-*.zip","$Root/dist/models-*.zip" -ErrorAction SilentlyContinue |
Remove-Item -Force
dotnet build $Sln -c Debug
}
'run' { dotnet run --project $AppProj -c Debug }
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
'publish' {
# 先清理 dist 旧产物,再重新生成
if (Test-Path "$Root/dist") { Remove-Item -Recurse -Force "$Root/dist" }
Write-Host '==> 编译三平台(进度见 buildsh/lib/progress.sh,建议用 Git Bash 运行 ./build.sh build)'
Remove-Item -Recurse -Force "$Root/dist" -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
Stamp-Versions
Publish-Rid 'osx-arm64' 'dist/mac-arm64'
Publish-Rid 'win-x64' 'dist/win-x64'
Publish-Rid 'win-arm64' 'dist/win-arm64'
Prepare-RuntimeLayout 'dist/win-x64'
Prepare-RuntimeLayout 'dist/win-arm64'
Prepare-RuntimeLayout 'dist/mac-arm64'
Pack-Launcher
Write-Host '==> 三个平台编译完成(发布包不含模型,首次启动自动下载),见 dist\' -ForegroundColor Green
Write-Host ' 把 version.json / model/ 推送到 gitcode,启动器就会自动检查更新'
Stamp
foreach ($rid in @('osx-arm64','win-x64','win-arm64')) {
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/dist/$rid"
}
Write-Host '==> 完成(详细打包请用 ./build.sh build)'
}
'models' { Build-Models }
'stamp' { Stamp-Versions }
'bundle' { Write-Host '已弃用:发布包不再内置模型。请改用 .\build.ps1 stamp 与 gitcode 自动更新。' }
'pack-models' {
Build-Models
Pack-Models
'check' {
dotnet build $Sln -c Debug
$env:EMS_SELFTEST = '1'; dotnet run --project $AppProj -c Debug --no-build; Remove-Item Env:\EMS_SELFTEST
dotnet run --project $TestProj -c Debug --no-build -- "$Root/build/screenshots"
}
'pack-launcher' { Pack-Launcher }
'models' { Build-Models }
'stamp' { Stamp }
'pack-models' { Build-Models }
'pack-launcher' { Write-Host '请用 ./build.sh pack-launcher' }
'run' { dotnet run --project $AppProj -c Debug }
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
'update-test' { dotnet run --project $TestProj -c Debug -- '--update-test' $Root }
'clean' {
Remove-Item -Recurse -Force "$Root/build", "$Root/dist" -ErrorAction SilentlyContinue
Get-ChildItem "$Root/src" -Recurse -Directory -Include bin, obj |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
'doctor' { dotnet --info }
'clean' { Remove-Item -Recurse -Force "$Root/build","$Root/dist" -ErrorAction SilentlyContinue; Write-Host '==> 已清理' }
'doctor' { dotnet --info | Select-Object -First 20 }
'dist' { Get-ChildItem "$Root/dist" -ErrorAction SilentlyContinue }
}
+40 -308
View File
@@ -1,33 +1,21 @@
#!/bin/sh
# ---------------------------------------------------------------------------
# Earth Model Studio 构建脚本(macOS / Linux)
# Earth Model Studio 构建入口(薄封装)
#
# ./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 清理
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物
# ./build.sh models 编译模型 dll + 封面 + 版本戳
# ./build.sh stamp 重新生成 version.json
# ./build.sh run / test / update-test / pack-models / pack-launcher
# ./build.sh clean 清理
# ./build.sh doctor dotnet 信息
# ./build.sh dist 列出产物
#
# 分层:src/ 只是启动器;模型全部在 model/;**发布包不内置模型**。
#
# 运行目录(发布包里就长这样):
# <安装目录>/
# EarthModelStudio(.exe | .app/...)
# .GC/
# settings.json 设置与已安装版本
# model/ 启动时从 gitcode 下载的模型
# cache/ 下载暂存
# update/ 待下次启动应用的启动器更新
# 实际代码都在 buildsh/ 里,本文件只负责加载模块与分发。
# ---------------------------------------------------------------------------
set -eu
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。
# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败中断编译(MSB4018)
export AVALONIA_TELEMETRY_OPTOUT=1
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
@@ -38,295 +26,39 @@ 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.2"
VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props | head -1)
[ -n "$VERSION" ] || VERSION="1.0.0"
TASK="${1:-build}"
shift 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 / 封面直接写进模型包
build_models() {
echo "==> 编译模型功能程序集(源码就在各模型目录的 src/ 里)"
for DIR in "$ROOT_DIR"/model/*/; do
ID=$(basename "$DIR")
[ -d "$DIR/src" ] || continue
PROJ=$(ls "$DIR"src/*.csproj 2>/dev/null | head -1)
[ -n "$PROJ" ] || continue
dotnet build "$PROJ" -c Release
if [ -d "$DIR$ID.model" ]; then
for DLL in "$DIR"src/bin/Release/net8.0/*.dll; do
[ -f "$DLL" ] || continue
NAME=$(basename "$DLL")
[ "$NAME" = "EarthModelStudio.ModelSdk.dll" ] && continue
cp "$DLL" "$DIR$ID.model/"
echo " -> model/$ID/$ID.model/$NAME"
done
fi
done
echo "==> 用模型自己的渲染器生成封面"
dotnet run --project "$PREVIEW_PROJ" -c Release -- "$ROOT_DIR"
stamp_versions
}
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
prepare_runtime_layout() {
REL="$1"
DEST="$ROOT_DIR/$REL"
[ -d "$DEST" ] || return 0
rm -rf "$DEST/model" "$DEST/examples"
mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update"
cat > "$DEST/.GC/model/README.txt" <<'TXT'
模型库目录(.GC/model/)
启动时程序会读取 gitcode 仓库的 version.json,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
.GC/settings.json
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
TXT
if [ ! -f "$DEST/.GC/settings.json" ]; then
cat > "$DEST/.GC/settings.json" <<'JSON'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"updateRepository": "https://gitcode.com/2509_92447106/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
}
JSON
# 解析 -version=<版本号>(也接受 --version=)
CLI_VERSION=""
for arg in "$@"; do
case "$arg" in
-version=*|--version=*) CLI_VERSION="${arg#*=}" ;;
esac
done
if [ -n "$CLI_VERSION" ]; then
VERSION="$CLI_VERSION"
# 写回 Directory.Build.props,让程序集版本与关于页显示一致
if [ -f Directory.Build.props ]; then
sed -i.bak "s|<Version>[^<]*</Version>|<Version>${VERSION}</Version>|" Directory.Build.props
rm -f Directory.Build.props.bak
fi
echo " 运行目录 -> $REL/.GC (settings.json + model/ + cache/ + update/)"
}
echo "==> 版本号设为 ${VERSION}"
fi
mkdir -p "$ROOT_DIR/build/logs"
# $1=RID $2=输出目录 $3=singlefile(true/false)
publish_rid() {
RID="$1"; OUT="$2"; SINGLE="${3:-true}"
echo ""
echo "==> 编译 ${RID} (single-file=${SINGLE}) -> ${OUT}"
# 先删旧产物,避免上次 publish 的残留文件混进新包
rm -rf "$ROOT_DIR/$OUT"
dotnet publish "$APP_PROJ" \
-c Release \
-r "$RID" \
--self-contained true \
-p:Version="$VERSION" \
-p:DebugType=none \
-p:PublishSingleFile="$SINGLE" \
-p:IncludeNativeLibrariesForSelfExtract="$SINGLE" \
-p:PublishTrimmed=false \
-o "$ROOT_DIR/$OUT"
rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples"
}
# 把 model/ 里的模型数据单独打包(与启动器分开分发)
pack_models() {
mkdir -p "$ROOT_DIR/dist"
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
rm -f "$ZIP"
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
( cd "$ROOT_DIR" && zip -qr "$ZIP" model \
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
du -sh "$ZIP"
}
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户已下载的模型与设置)
# 产物命名:GC-<版本>-<系统>-<架构>.exe / GC-<版本>-<系统>-<架构>.app.zip
# Windows: 单文件 exe 直接改名(本身就是可执行产物)
# macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip,
# 这样 macOS 双击会用归档工具解压出可运行的 .app。
# 若直接命名 .app,系统会把 zip 当成应用包解析 => 报「已损坏/打不开」。
pack_launcher() {
echo "==> 生成启动器产物(GC-<版本>-<系统>-<架构>)"
# --- Windows:exe 单文件 ---
for pair in "win-x64:win-amd64" "win-arm64:win-arm64"; do
RID="${pair%%:*}"; LABEL="${pair##*:}"
SRC="$ROOT_DIR/dist/$RID"
[ -d "$SRC" ] || continue
EXE=$(ls "$SRC"/*.exe 2>/dev/null | head -1)
[ -n "$EXE" ] || continue
DEST="$ROOT_DIR/dist/GC-${VERSION}-${LABEL}.exe"
cp "$EXE" "$DEST"
chmod +x "$DEST"
echo " -> $(basename "$DEST")"
done
# --- macOS:打包成 zip -> 解压回来 -> 改名 -> 删除 zip ---
# 这样 dist 里得到的是一个可直接双击运行的真实 .app 目录,
# 而 zip 只是保证权限/符号链接不丢的中间载体,用完即删。
MACAPP="$ROOT_DIR/dist/mac-arm64/EarthModelStudio.app"
if [ -d "$MACAPP" ]; then
FINAL="$ROOT_DIR/dist/GC-${VERSION}-mac-arm64.app"
TMPZIP="$ROOT_DIR/dist/.gc-mac-tmp.zip"
WORK="$ROOT_DIR/dist/.gc-mac-work"
rm -rf "$FINAL" "$WORK" "$TMPZIP"
mkdir -p "$WORK"
# 1) 打包(ditto 保留可执行权限与符号链接,比 zip -y 可靠)
if command -v ditto >/dev/null 2>&1; then
ditto -c -k --sequesterRsrc --keepParent "$MACAPP" "$TMPZIP"
else
( cd "$(dirname "$MACAPP")" && zip -qry "$TMPZIP" "$(basename "$MACAPP")" -x "*.DS_Store" )
fi
# 2) 解压到工作目录
if command -v ditto >/dev/null 2>&1; then
ditto -x -k "$TMPZIP" "$WORK"
else
( cd "$WORK" && unzip -q "$TMPZIP" )
fi
# 3) 改名为发布名(保持 .app 是目录)
SRCAPP="$WORK/EarthModelStudio.app"
if [ -d "$SRCAPP" ]; then
mv "$SRCAPP" "$FINAL"
chmod +x "$FINAL/Contents/MacOS/EarthModelStudio" 2>/dev/null || true
# 同步 Info.plist 的显示名,避免 Finder 里显示旧名
PLIST="$FINAL/Contents/Info.plist"
if [ -f "$PLIST" ]; then
/usr/libexec/PlistBuddy -c "Set :CFBundleName Morris GC" "$PLIST" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName Morris GC" "$PLIST" 2>/dev/null || true
fi
# 去掉隔离属性,避免 Gatekeeper 误拦(本地构建产物)
xattr -cr "$FINAL" 2>/dev/null || true
echo " -> $(basename "$FINAL")/ (目录)"
else
echo " !! macOS 打包失败:解压后未找到 EarthModelStudio.app" >&2
fi
# 4) 删除 zip 与工作目录
rm -rf "$WORK" "$TMPZIP"
fi
strip_intermediate_dirs
stamp_versions
echo ""
echo "==> dist 只保留可发布的附件:"
ls -lh "$ROOT_DIR"/dist/GC-"$VERSION"-* 2>/dev/null || true
}
# 删除 publish 过程中的中间目录,dist 里只留最终附件
strip_intermediate_dirs() {
for d in win-x64 win-arm64 mac-arm64; do
[ -d "$ROOT_DIR/dist/$d" ] && rm -rf "$ROOT_DIR/dist/$d"
done
find "$ROOT_DIR/dist" -name ".DS_Store" -delete 2>/dev/null || true
}
package_mac_app() {
DIST="$ROOT_DIR/dist/mac-arm64"
APP="$DIST/EarthModelStudio.app"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cat > "$APP/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key><string>Earth Model Studio</string>
<key>CFBundleDisplayName</key><string>Earth Model Studio</string>
<key>CFBundleIdentifier</key><string>cn.neorf.earthmodelstudio</string>
<key>CFBundleVersion</key><string>${VERSION}</string>
<key>CFBundleShortVersionString</key><string>${VERSION}</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleExecutable</key><string>EarthModelStudio</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST
for f in "$DIST"/*; do
base=$(basename "$f")
[ "$base" = "EarthModelStudio.app" ] && continue
[ "$base" = ".DS_Store" ] && continue
mv "$f" "$APP/Contents/MacOS/"
done
# 发布包不带 .GC 运行骨架(用户首次启动自行创建),避免覆盖用户数据
rm -rf "$APP/Contents/MacOS/.GC"
chmod +x "$APP/Contents/MacOS/EarthModelStudio"
echo "==> 已打包 $APP"
}
# 加载 buildsh 模块
. "$ROOT_DIR/buildsh/lib/progress.sh"
. "$ROOT_DIR/buildsh/lib/build_funcs.sh"
. "$ROOT_DIR/buildsh/build.sh"
. "$ROOT_DIR/buildsh/check.sh"
. "$ROOT_DIR/buildsh/tools.sh"
case "$TASK" in
build)
# 清理上次遗留的发布包 zip,避免误用旧产物
rm -f "$ROOT_DIR"/dist/GC-*.zip "$ROOT_DIR"/dist/models-*.zip 2>/dev/null || true
dotnet build "$SLN" -c Debug
;;
run)
dotnet run --project "$APP_PROJ" -c Debug
;;
test)
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots"
;;
publish)
# 先清掉 dist 旧产物(含历史 zip / 目录),再重新生成
echo "==> 清理 dist 旧产物"
rm -rf "$ROOT_DIR/dist"
mkdir -p "$ROOT_DIR/dist"
stamp_versions
# macOS 用目录形式(非单文件):单文件包启动时需要解压缓存目录,
# 在受限/沙箱环境下创建失败会直接报「打不开」。目录形式无此依赖。
publish_rid "osx-arm64" "dist/mac-arm64" false
publish_rid "win-x64" "dist/win-x64" true
publish_rid "win-arm64" "dist/win-arm64" true
package_mac_app
prepare_runtime_layout "dist/win-x64"
prepare_runtime_layout "dist/win-arm64"
prepare_runtime_layout "dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
pack_launcher
echo ""
echo "==> 三个平台编译完成(发布包不含模型,首次启动自动下载):"
du -sh "$ROOT_DIR/dist"/* 2>/dev/null || true
echo " 把 version.json / model/ 推送到 gitcode,启动器就会自动检查更新"
;;
models)
build_models
;;
stamp)
stamp_versions
;;
bundle)
echo "已弃用:发布包不再内置模型。请改用 ./build.sh stamp 与 gitcode 自动更新。"
;;
pack-models)
build_models
pack_models
;;
pack-launcher)
pack_launcher
;;
update-test)
dotnet run --project "$TEST_PROJ" -c Debug -- --update-test "$ROOT_DIR"
;;
clean)
rm -rf "$ROOT_DIR/build" "$ROOT_DIR/dist"
find "$ROOT_DIR/src" -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + 2>/dev/null || true
echo "==> 已清理"
;;
doctor)
dotnet --info | head -20
;;
*)
echo "未知任务: $TASK"
echo "可用: build | run | test | publish | models | stamp | pack-models | pack-launcher | update-test | clean | doctor"
exit 1
;;
build) bs_build "$ROOT_DIR" ;;
check) bs_check "$ROOT_DIR" ;;
*) bs_tools "$ROOT_DIR" "$TASK" ;;
esac
+57
View File
@@ -0,0 +1,57 @@
#!/bin/sh
# buildsh/build.sh —— 完整发布(原 publish)
# 步骤及权重按实测耗时设定,供进度条估算总进度与剩余时间:
# 清理(2) 版本(3) Mac(35) WinX64(25) WinArm(25) 骨架(3) 打包(5) 收尾(2) = 100
bs_build() {
ROOT_DIR="$1"
: "${APP_PROJ:?}" "${SLN:?}" "${VERSION:?}"
progress_init 100 2 3 35 25 25 3 5 2
progress_step "清理旧产物"; progress_tick 100
rm -rf "$ROOT_DIR/dist"; mkdir -p "$ROOT_DIR/dist"
progress_step "版本戳"; progress_tick 100
stamp_versions
# 每个 publish 用后台任务包裹,边跑边按「已用时/预估用时」推进当前步骤进度
_run_publish() {
_label="$1"; _est="$2"; shift 2
( "$@" >"$ROOT_DIR/build/logs/publish-$_label.log" 2>&1 ) &
_pid=$!
_t0=$(date +%s)
while kill -0 "$_pid" 2>/dev/null; do
_elapsed=$(( $(date +%s) - _t0 ))
_p=$(( _elapsed * 100 / _est ))
[ "$_p" -gt 96 ] && _p=96
progress_tick "$_p"
sleep 1
done
wait "$_pid" || { echo; echo "!! $_label 编译失败,见 build/logs/publish-$_label.log"; return 1; }
progress_tick 100
}
progress_step "编译 Mac"
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" false || return 1
progress_step "编译 Win-x64"
_run_publish winx64 70 publish_rid "win-x64" "dist/win-x64" true || return 1
progress_step "编译 Win-arm64"
_run_publish winarm 70 publish_rid "win-arm64" "dist/win-arm64" true || return 1
progress_step "运行骨架"; progress_tick 100
package_mac_app
prepare_runtime_layout "dist/win-x64"
prepare_runtime_layout "dist/win-arm64"
prepare_runtime_layout "dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
progress_step "打包 zip"; progress_tick 100
pack_launcher
progress_step "收尾"; progress_tick 100
progress_done
echo "==> 完成,产物:"
ls -lh "$ROOT_DIR"/dist/GC-"$VERSION"-*.zip 2>/dev/null || true
}
+46
View File
@@ -0,0 +1,46 @@
#!/bin/sh
# buildsh/check.sh —— 验证:编译 + 自检 + 离屏测试 + 产物完整性
# 步骤权重:编译(40) 自检(15) 离屏(25) 产物(20)
bs_check() {
ROOT_DIR="$1"
progress_init 100 40 15 25 20
_fail=0
progress_step "编译检查"
if dotnet build "$SLN" -c Debug -v quiet >"$ROOT_DIR/build/logs/check-build.log" 2>&1; then
progress_tick 100
else
progress_tick 100; _fail=1
echo; echo "!! 编译失败,见 build/logs/check-build.log"
fi
progress_step "模型自检"
if EMS_SELFTEST=1 dotnet run --project "$APP_PROJ" -c Debug --no-build \
>"$ROOT_DIR/build/logs/check-selftest.log" 2>&1; then
grep -q "FAIL" "$ROOT_DIR/build/logs/check-selftest.log" && { _fail=1; echo; echo "!! 自检有失败项"; }
else
_fail=1; echo; echo "!! 自检异常"
fi
progress_tick 100
progress_step "离屏渲染"
if dotnet run --project "$TEST_PROJ" -c Debug --no-build -- \
"$ROOT_DIR/build/screenshots" >"$ROOT_DIR/build/logs/check-render.log" 2>&1; then
progress_tick 100
else
_fail=1; progress_tick 100; echo; echo "!! 离屏渲染失败"
fi
progress_step "产物检查"
_n=$(ls "$ROOT_DIR"/dist/GC-"$VERSION"-*.zip 2>/dev/null | wc -l | tr -d ' ')
if [ "$_n" -ge 3 ]; then
progress_tick 100
else
_fail=1; progress_tick 100; echo; echo "!! 产物不足 3 个(当前 $_n)"
fi
progress_done
[ "$_fail" -eq 0 ] && echo "==> 全部通过" || echo "==> 有失败项"
return "$_fail"
}
+247
View File
@@ -0,0 +1,247 @@
#!/bin/sh
# buildsh/lib/build_funcs.sh —— 构建函数库(由入口脚本 source)
# 依赖调用方提供:ROOT_DIR, APP_PROJ, PREVIEW_PROJ, STAMP_PROJ, TEST_PROJ, SLN, VERSION
# 以及任务进度上报函数 step / progress(由进度条引擎提供,未定义时降级为 echo)
if ! type step >/dev/null 2>&1; then step() { echo "==> $1"; }; fi
if ! type progress >/dev/null 2>&1; then progress() { :; }; fi
stamp_versions() {
echo "==> 自动计算模型版本并生成 version.json"
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
}
# 编译模型自己的功能程序集,并把 dll / 封面直接写进模型包
build_models() {
echo "==> 编译模型功能程序集(源码就在各模型目录的 src/ 里)"
for DIR in "$ROOT_DIR"/model/*/; do
ID=$(basename "$DIR")
[ -d "$DIR/src" ] || continue
PROJ=$(ls "$DIR"src/*.csproj 2>/dev/null | head -1)
[ -n "$PROJ" ] || continue
dotnet build "$PROJ" -c Release
if [ -d "$DIR$ID.model" ]; then
for DLL in "$DIR"src/bin/Release/net8.0/*.dll; do
[ -f "$DLL" ] || continue
NAME=$(basename "$DLL")
[ "$NAME" = "EarthModelStudio.ModelSdk.dll" ] && continue
cp "$DLL" "$DIR$ID.model/"
echo " -> model/$ID/$ID.model/$NAME"
done
fi
done
echo "==> 用模型自己的渲染器生成封面"
dotnet run --project "$PREVIEW_PROJ" -c Release -- "$ROOT_DIR"
stamp_versions
}
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
prepare_runtime_layout() {
REL="$1"
DEST="$ROOT_DIR/$REL"
[ -d "$DEST" ] || return 0
rm -rf "$DEST/model" "$DEST/examples"
mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update"
cat > "$DEST/.GC/model/README.txt" <<'TXT'
模型库目录(.GC/model/)
启动时程序会读取 gitcode 仓库的 version.json,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
.GC/settings.json
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
TXT
if [ ! -f "$DEST/.GC/settings.json" ]; then
cat > "$DEST/.GC/settings.json" <<'JSON'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"updateRepository": "https://gitcode.com/2509_92447106/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
}
JSON
fi
echo " 运行目录 -> $REL/.GC (settings.json + model/ + cache/ + update/)"
}
# $1=RID $2=输出目录 $3=singlefile(true/false)
publish_rid() {
RID="$1"; OUT="$2"; SINGLE="${3:-true}"
echo ""
echo "==> 编译 ${RID} (single-file=${SINGLE}) -> ${OUT}"
# 先删旧产物,避免上次 publish 的残留文件混进新包
rm -rf "$ROOT_DIR/$OUT"
dotnet publish "$APP_PROJ" \
-c Release \
-r "$RID" \
--self-contained true \
-p:Version="$VERSION" \
-p:DebugType=none \
-p:PublishSingleFile="$SINGLE" \
-p:IncludeNativeLibrariesForSelfExtract="$SINGLE" \
-p:PublishTrimmed=false \
-o "$ROOT_DIR/$OUT"
rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples"
}
# 把 model/ 里的模型数据单独打包(与启动器分开分发)
pack_models() {
mkdir -p "$ROOT_DIR/dist"
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
rm -f "$ZIP"
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
( cd "$ROOT_DIR" && zip -qr "$ZIP" model \
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
du -sh "$ZIP"
}
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户已下载的模型与设置)
# 产物命名:GC-<版本>-<系统>-<架构>.exe / GC-<版本>-<系统>-<架构>.app.zip
# Windows: 单文件 exe 直接改名(本身就是可执行产物)
# macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip,
# 这样 macOS 双击会用归档工具解压出可运行的 .app。
# 若直接命名 .app,系统会把 zip 当成应用包解析 => 报「已损坏/打不开」。
pack_launcher() {
echo "==> 生成启动器产物(GC-<版本>-<系统>-<架构>)"
# --- Windows:exe 单文件 ---
for pair in "win-x64:win-amd64" "win-arm64:win-arm64"; do
RID="${pair%%:*}"; LABEL="${pair##*:}"
SRC="$ROOT_DIR/dist/$RID"
[ -d "$SRC" ] || continue
EXE=$(ls "$SRC"/*.exe 2>/dev/null | head -1)
[ -n "$EXE" ] || continue
DEST="$ROOT_DIR/dist/GC-${VERSION}-${LABEL}.exe"
cp "$EXE" "$DEST"
chmod +x "$DEST"
echo " -> $(basename "$DEST")"
done
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist)---
MACAPP="$ROOT_DIR/dist/mac-arm64/EarthModelStudio.app"
if [ -d "$MACAPP" ]; then
FINAL="$ROOT_DIR/dist/GC-${VERSION}-mac-arm64.app"
rm -rf "$FINAL"
mv "$MACAPP" "$FINAL"
chmod +x "$FINAL/Contents/MacOS/EarthModelStudio" 2>/dev/null || true
PLIST="$FINAL/Contents/Info.plist"
if [ -f "$PLIST" ]; then
/usr/libexec/PlistBuddy -c "Set :CFBundleName Morris GC" "$PLIST" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName Morris GC" "$PLIST" 2>/dev/null || true
fi
xattr -cr "$FINAL" 2>/dev/null || true
echo " -> $(basename "$FINAL")/"
fi
# --- 统一压缩:每个产物都打成同名 .zip ---
# GC-1.0.3-win-amd64.exe -> GC-1.0.3-win-amd64.zip
# GC-1.0.3-win-arm64.exe -> GC-1.0.3-win-arm64.zip
# GC-1.0.3-mac-arm64.app -> GC-1.0.3-mac-arm64.zip
# 客户端下载时按「原名去掉扩展名 + .zip」取包,再解压回原名。
echo "==> 压缩为 zip"
for art in "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe "$ROOT_DIR"/dist/GC-"$VERSION"-*.app; do
[ -e "$art" ] || continue
base=$(basename "$art")
name="${base%.*}" # 去掉 .exe / .app
ZIP="$ROOT_DIR/dist/${name}.zip"
rm -f "$ZIP"
if [ -d "$art" ]; then
# 目录(.app):保留权限与符号链接
if command -v ditto >/dev/null 2>&1; then
ditto -c -k --sequesterRsrc --keepParent "$art" "$ZIP"
else
( cd "$(dirname "$art")" && zip -qry "$ZIP" "$base" -x "*.DS_Store" )
fi
else
( cd "$(dirname "$art")" && zip -q "$ZIP" "$base" )
fi
echo " -> ${name}.zip"
done
# 原始产物(.exe / .app 目录)不再保留:只发布 zip
rm -f "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe
rm -rf "$ROOT_DIR"/dist/GC-"$VERSION"-*.app
strip_intermediate_dirs
stamp_versions
echo ""
echo "==> dist 只保留可发布的 zip:"
ls -lh "$ROOT_DIR"/dist/GC-"$VERSION"-*.zip 2>/dev/null || true
}
# 删除 publish 过程中的中间目录,dist 里只留最终附件
strip_intermediate_dirs() {
for d in win-x64 win-arm64 mac-arm64; do
[ -d "$ROOT_DIR/dist/$d" ] && rm -rf "$ROOT_DIR/dist/$d"
done
find "$ROOT_DIR/dist" -name ".DS_Store" -delete 2>/dev/null || true
}
package_mac_app() {
DIST="$ROOT_DIR/dist/mac-arm64"
APP="$DIST/EarthModelStudio.app"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cat > "$APP/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key><string>Earth Model Studio</string>
<key>CFBundleDisplayName</key><string>Earth Model Studio</string>
<key>CFBundleIdentifier</key><string>cn.neorf.earthmodelstudio</string>
<key>CFBundleVersion</key><string>${VERSION}</string>
<key>CFBundleShortVersionString</key><string>${VERSION}</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleExecutable</key><string>EarthModelStudio</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST
for f in "$DIST"/*; do
base=$(basename "$f")
[ "$base" = "EarthModelStudio.app" ] && continue
[ "$base" = ".DS_Store" ] && continue
mv "$f" "$APP/Contents/MacOS/"
done
# 应用图标:由 Assets/icon-1024.png 生成 .icns
ICONSRC="$ROOT_DIR/src/main/dotnet/EarthModelStudio/Assets/icon-1024.png"
if [ -f "$ICONSRC" ] && command -v iconutil >/dev/null 2>&1; then
ICONSET="$DIST/AppIcon.iconset"
rm -rf "$ICONSET"; mkdir -p "$ICONSET"
for sz in 16 32 64 128 256 512; do
sips -z $sz $sz "$ICONSRC" --out "$ICONSET/icon_${sz}x${sz}.png" >/dev/null 2>&1
d=$((sz * 2))
sips -z $d $d "$ICONSRC" --out "$ICONSET/icon_${sz}x${sz}@2x.png" >/dev/null 2>&1
done
iconutil -c icns "$ICONSET" -o "$APP/Contents/Resources/AppIcon.icns" 2>/dev/null && \
echo " + AppIcon.icns"
rm -rf "$ICONSET"
# Info.plist 增加图标项
if [ -f "$APP/Contents/Info.plist" ]; then
/usr/libexec/PlistBuddy -c "Delete :CFBundleIconFile" "$APP/Contents/Info.plist" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Add :CFBundleIconFile string AppIcon" "$APP/Contents/Info.plist" 2>/dev/null || true
fi
fi
# 发布包不带 .GC 运行骨架(用户首次启动自行创建),避免覆盖用户数据
rm -rf "$APP/Contents/MacOS/.GC"
chmod +x "$APP/Contents/MacOS/EarthModelStudio"
echo "==> 已打包 $APP"
}
+100
View File
@@ -0,0 +1,100 @@
#!/bin/sh
# buildsh/lib/progress.sh —— apt 风格底部实时进度条
#
# 底部一行:任务 当前任务进度 总进度 剩余时间
# 编译MacOS 95% 30% 10s
#
# 用法:
# progress_init <总步骤数> <每步权重...>
# progress_step <步骤名> # 开始某步骤
# progress_tick <0-100> # 更新当前步骤完成度
# progress_done # 结束
PROGRESS_TOTAL=1
PROGRESS_WEIGHTS=""
PROGRESS_IDX=0
PROGRESS_CUR=0
PROGRESS_STARTED=0
PROGRESS_LAST=0
PROGRESS_HISTORY=""
_now() { date +%s; }
# 加权总进度:前序步骤权重之和 + 当前步骤权重*完成度
_progress_overall() {
_sum=0; _i=1
for _w in $PROGRESS_WEIGHTS; do
if [ "$_i" -lt "$PROGRESS_IDX" ]; then
_sum=$((_sum + _w)) # 已完成的步骤:全额
elif [ "$_i" -eq "$PROGRESS_IDX" ]; then
_sum=$((_sum + _w * PROGRESS_CUR / 100)) # 当前步骤:按完成度
fi
_i=$((_i + 1))
done
_p=$((_sum * 100 / PROGRESS_TOTAL))
[ "$_p" -gt 100 ] && _p=100
echo "$_p"
}
# 剩余时间:基于「已完成总进度 / 已用时间」线性外推
_progress_eta() {
_p=$(_progress_overall)
_t=$(( $(_now) - PROGRESS_STARTED ))
# 前期用「预估总时长」估算(按各步骤经验权重),后期用实测速率外推,更稳
if [ "$_p" -le 3 ] || [ "$_t" -le 0 ]; then
_eta=$(( PROGRESS_TOTAL * 8 / 100 )) # 粗估:每 1% 约 8 秒 -> 总约 800s? 见下
_eta=$(( 240 )) # 默认预估 4 分钟
else
_eta=$(( _t * (100 - _p) / _p ))
fi
if [ "$_eta" -ge 60 ]; then echo "$(( _eta / 60 ))m$((_eta % 60))s"; else echo "${_eta}s"; fi
}
progress_draw() {
_task="$PROGRESS_TASK"
_cur=$PROGRESS_CUR
_overall=$(_progress_overall)
_eta=$(_progress_eta)
# 进度条(20 格)
_filled=$((_overall * 20 / 100))
_bar=""
_i=0
while [ "$_i" -lt 20 ]; do
if [ "$_i" -lt "$_filled" ]; then _bar="${_bar}#"; else _bar="${_bar}."; fi
_i=$((_i + 1))
done
# 底部一行:任务 当前任务进度 总进度 剩余时间
printf '\r\033[K[%s] %-14s %3d%% %3d%% %s' \
"$_bar" "$_task" "$_cur" "$_overall" "$_eta"
}
progress_init() {
PROGRESS_TOTAL=$1
shift
PROGRESS_WEIGHTS="$*"
PROGRESS_IDX=0
PROGRESS_CUR=0
PROGRESS_STARTED=$(_now)
PROGRESS_TASK="准备"
progress_draw
}
progress_step() {
PROGRESS_TASK="$1"
PROGRESS_CUR=0
PROGRESS_IDX=$((PROGRESS_IDX + 1))
progress_draw
}
progress_tick() {
PROGRESS_CUR=$1
progress_draw
}
progress_done() {
PROGRESS_CUR=100
progress_tick 100
printf '\n'
}
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
# buildsh/tools.sh —— 实用工具:模型、版本戳、清理、运行、医生、打开目录
bs_tools() {
ROOT_DIR="$1"; TASK="$2"
case "$TASK" in
models)
build_models ;;
stamp)
stamp_versions ;;
pack-models)
build_models; pack_models ;;
pack-launcher)
pack_launcher ;;
run)
dotnet run --project "$APP_PROJ" -c Debug ;;
test)
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots" ;;
update-test)
dotnet run --project "$TEST_PROJ" -c Debug -- --update-test "$ROOT_DIR" ;;
clean)
rm -rf "$ROOT_DIR/build" "$ROOT_DIR/dist"
find "$ROOT_DIR/src" -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + 2>/dev/null || true
echo "==> 已清理" ;;
doctor)
dotnet --info | head -20 ;;
dist)
echo "==> dist 产物:"
ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;;
*)
echo "未知工具: $TASK"; return 1 ;;
esac
}
+53
View File
@@ -0,0 +1,53 @@
@echo off
REM ---------------------------------------------------------------------------
REM git.bat —— GC 仓库的 git 导航入口(Windows)
REM
REM git.bat 显示帮助(列出 gitshell\ 里所有可用命令)
REM git.bat <命令> [参数] 调用 gitshell\<命令>.bat
REM
REM 例:
REM git.bat autogit 提交并推送到所有已配置的仓库
REM git.bat autogit -m "修复" 指定提交信息
REM
REM 实际脚本都在 gitshell\ 里,本文件只负责查找与分发(与 build.ps1 同样的设计)。
REM ---------------------------------------------------------------------------
setlocal
chcp 65001 >nul 2>&1
set "ROOT_DIR=%~dp0"
if "%ROOT_DIR:~-1%"=="\" set "ROOT_DIR=%ROOT_DIR:~0,-1%"
set "SHELL_DIR=%ROOT_DIR%\gitshell"
cd /d "%ROOT_DIR%"
if "%~1"=="" goto help
if /i "%~1"=="-h" goto help
if /i "%~1"=="--help" goto help
if /i "%~1"=="help" goto help
set "CMD=%~1"
shift
set "SCRIPT=%SHELL_DIR%\%CMD%.bat"
if not exist "%SCRIPT%" (
echo !! 没有这个命令:%CMD%
echo.
goto help
exit /b 1
)
call "%SCRIPT%" "%ROOT_DIR%" %*
exit /b %errorlevel%
:help
echo GC git 工具(gitshell\)
echo.
if exist "%SHELL_DIR%" (
for %%f in ("%SHELL_DIR%\*.bat") do (
echo %%~nf
)
) else (
echo (gitshell\ 目录不存在)
)
echo.
echo 用法:git.bat ^<命令^> [参数]
exit /b 0
Executable
+54
View File
@@ -0,0 +1,54 @@
#!/bin/sh
# ---------------------------------------------------------------------------
# git.sh —— GC 仓库的 git 导航入口
#
# ./git.sh 显示帮助(列出 gitshell/ 里所有可用命令)
# ./git.sh <命令> [参数] 调用 gitshell/<命令>.sh
#
# 例:
# ./git.sh autogit 提交并推送到所有已配置的仓库
# ./git.sh autogit -m "修复" 指定提交信息
#
# 实际脚本都在 gitshell/ 里,本文件只负责查找与分发(与 build.sh 同样的设计)。
# ---------------------------------------------------------------------------
set -eu
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$ROOT_DIR"
SHELL_DIR="$ROOT_DIR/gitshell"
list_commands() {
echo "GC git 工具(gitshell/)"
echo
if [ -d "$SHELL_DIR" ]; then
for f in "$SHELL_DIR"/*.sh; do
[ -f "$f" ] || continue
name=$(basename "$f" .sh)
# 取文件头第一条「# 描述」行(跳过 shebang 与空注释)
desc=$(sed -n '2,6p' "$f" | sed -n 's/^# *\(.\)/\1/p' | grep -v '^$' | head -1)
printf ' %-14s %s\n' "$name" "${desc:-}"
done
else
echo " (gitshell/ 目录不存在)"
fi
echo
echo "用法:./git.sh <命令> [参数]"
}
CMD="${1:-}"
[ -n "$CMD" ] || { list_commands; exit 0; }
case "$CMD" in
-h|--help|help) list_commands; exit 0 ;;
esac
shift 2>/dev/null || true
SCRIPT="$SHELL_DIR/$CMD.sh"
if [ ! -f "$SCRIPT" ]; then
echo "!! 没有这个命令:$CMD"
echo
list_commands
exit 1
fi
exec sh "$SCRIPT" "$ROOT_DIR" "$@"
+162
View File
@@ -0,0 +1,162 @@
# git 工具(gitshell/)
仓库的 git 操作入口。与 `build.sh` / `build.ps1` 同样的设计:根目录只放一个薄入口,
实际脚本都在 `gitshell/` 里。
## 入口
| 平台 | 文件 |
| --- | --- |
| macOS / Linux | `./git.sh` |
| Windows | `git.bat` |
不带参数运行会列出所有可用命令。
```bash
./git.sh # 显示帮助
./git.sh status # 查看状态
./git.sh autogit # 提交并推送
```
## autogit —— 交互式提交(支持多仓库)
```bash
./git.sh autogit
```
交互顺序:
**① 选择仓库(可多选)**
```
已配置的仓库:
1) origin git@gitcode.com:2509_92447106/GC.git
2) gitee git@github.com:user/GC.git
a) 全部
n) 添加新仓库地址
请选择(可多选,用空格或逗号分隔,如 1 3 或 a 或 n;默认 1):
```
支持的输入:
| 输入 | 含义 |
| --- | --- |
| `1` | 第 1 个仓库 |
| `1 3` / `1,3` / `1、3` | 同时选第 1 和第 3 个 |
| `a` | 全部仓库 |
| `n` | 添加新地址(**可连续输入多个,空行结束**) |
选 `n` 时可以一次加好几个:
```
可以连续输入多个地址,每行一个,输入空行结束:
地址: git@gitcode.com:user/GC.git
给这个仓库起个名字(回车自动命名): origin
已添加 origin -> git@gitcode.com:user/GC.git
地址: git@github.com:user/GC-mirror.git
给这个仓库起个名字(回车自动命名): mirror
已添加 mirror -> git@github.com:user/GC-mirror.git
地址: ← 空行结束
```
**② 确认仓库地址**
```
目标仓库(共 2 个):
origin git@gitcode.com:2509_92447106/GC.git
mirror git@github.com:user/GC-mirror.git
----------------------------------------------
以上地址都正确吗?(Y/n)
```
答 `n` 会逐个询问新地址,直接回车表示不改。
**③ 确认分支**
```
提交分支(当前 main,直接回车沿用,或输入其它分支名):
----------------------------------------------
提交分支:main
----------------------------------------------
分支正确吗?(Y/n)
```
输入其它名字时,不存在会自动创建并切换。
**④ 输入提交信息**
```
请输入提交信息:修复渲染卡顿
```
留空则自动生成 `更新(日期 时间)`。
**⑤ 最终确认**
```
==============================================
分支: main
信息: 修复渲染卡顿
推送到:
- origin git@gitcode.com:2509_92447106/GC.git
- mirror git@github.com:user/GC-mirror.git
==============================================
确认提交并推送?(y/N)
```
确认后逐个推送,最后汇总:
```
==> [1] 推送到 origin
OK
==> [2] 推送到 mirror
OK
==> 完成:2 个仓库已同步
```
参数:
```bash
./git.sh autogit -m "修复渲染卡顿" # 跳过信息输入
./git.sh autogit --dry-run # 只看不动
./git.sh autogit -y -m "信息" # 全自动
```
## status —— 状态速览
```bash
./git.sh status
```
显示当前分支、改动数量、最近提交,以及每个远程的领先/落后情况。
## 常见情况
**提交了但忘了排除构建产物**
```bash
git rm -r --cached -- '*bin/*' '*obj/*'
git commit -m "移除构建产物"
```
**远程有别人的提交,推不上去**
```bash
git pull --rebase origin main
./git.sh autogit
```
若确认以本地为准(会覆盖远程历史,慎用):
```bash
git push --force-with-lease origin main
```
**想确认没有把不该提交的东西加进去**
```bash
./git.sh autogit --dry-run
```
+187
View File
@@ -0,0 +1,187 @@
@echo off
REM autogit.bat —— 交互式提交(Windows)
REM
REM 用法:
REM git.bat autogit 交互模式(推荐)
REM git.bat autogit -m "信息" 跳过信息输入,其余仍交互
REM git.bat autogit --dry-run 只看会提交什么,不动仓库
REM git.bat autogit -y 全部确认跳过(配合 -m 可全自动)
REM
REM 交互流程:显示改动 → 逐个选仓库 → 输入提交信息 → 确认 → 执行
REM 自动跳过:dist\ build\ bin\ obj\ .GC\(任意层级)
setlocal enabledelayedexpansion
chcp 65001 >nul 2>&1
set "ROOT_DIR=%~1"
if "%ROOT_DIR%"=="" set "ROOT_DIR=%CD%"
cd /d "%ROOT_DIR%" 2>nul || (echo !! 目录不存在 & exit /b 1)
shift
set "MSG="
set "DRY=0"
set "ASSUME_YES=0"
:parse
if "%~1"=="" goto parsed
if /i "%~1"=="-m" ( set "MSG=%~2" & shift & shift & goto parse )
if /i "%~1"=="--message" ( set "MSG=%~2" & shift & shift & goto parse )
if /i "%~1"=="--dry-run" ( set "DRY=1" & shift & goto parse )
if /i "%~1"=="-y" ( set "ASSUME_YES=1" & shift & goto parse )
if /i "%~1"=="--yes" ( set "ASSUME_YES=1" & shift & goto parse )
echo 未知参数:%~1
exit /b 1
:parsed
REM ---------- 0. 前置检查 ----------
git rev-parse --git-dir >nul 2>&1
if errorlevel 1 ( echo !! 这里不是 git 仓库:%CD% & exit /b 1 )
for /f "delims=" %%b in ('git rev-parse --abbrev-ref HEAD 2^>nul') do set "BRANCH=%%b"
if "%BRANCH%"=="" ( echo !! 当前不在任何分支上 & exit /b 1 )
set "REMOTES="
for /f "delims=" %%r in ('git remote') do set "REMOTES=!REMOTES! %%r"
if "!REMOTES!"=="" ( echo !! 没有配置任何远程仓库 & exit /b 1 )
echo ==============================================
echo 仓库:%CD%
echo 分支:%BRANCH%
echo ==============================================
echo.
echo ==^> 会被排除的构建产物:
for %%d in (dist build bin obj .GC) do (
for /f %%c in ('git ls-files -- "*%%d/*" 2^>nul ^| find /c /v ""') do (
if not "%%c"=="0" echo %%d\ %%c 个文件
)
)
echo.
echo ==^> 待提交的改动:
git status --short | findstr /v /r "\\dist\\ \\build\\ \\bin\\ \\obj\\ \\.GC\\" | more +0
echo.
if "%DRY%"=="1" (
echo ==^> --dry-run:未做任何修改
exit /b 0
)
REM ---------- 2. 选择仓库 ----------
echo ==^> 选择要推送的仓库(y=推送 / n=跳过 / a=全部 / q=退出)
echo.
for %%r in (!REMOTES!) do (
for /f "delims=" %%u in ('git remote get-url %%r 2^>nul') do echo %%r %%u
)
echo.
set "SELECTED="
for %%r in (!REMOTES!) do (
if "!ASSUME_YES!"=="1" (
set "SELECTED=!SELECTED! %%r"
echo [自动] %%r
) else (
set "ANS="
set /p "ANS= 推送到 %%r (y/n/a/q) "
if /i "!ANS!"=="a" (
set "SELECTED=!REMOTES!"
goto selected_done
) else if /i "!ANS!"=="q" (
echo 已取消
exit /b 0
) else if /i "!ANS!"=="y" (
set "SELECTED=!SELECTED! %%r"
echo -^> 推送
) else (
echo -^> 跳过
)
)
)
:selected_done
set "PUSH=1"
if "!SELECTED!"=="" (
echo.
echo !! 没有选择任何仓库,只提交到本地不推送
set "PUSH=0"
)
REM ---------- 3. 提交信息 ----------
echo.
if "%MSG%"=="" (
echo ==^> 请输入提交信息(留空自动生成)
set "MSG="
set /p "MSG= ^> "
)
if "%MSG%"=="" (
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do set "D=%%a-%%b-%%c"
set "MSG=更新项目(!D!)"
echo (自动生成:!MSG!)
)
REM ---------- 4. 确认 ----------
echo.
echo ==============================================
echo 提交信息:%MSG%
if "%PUSH%"=="1" (
echo 推送到: !SELECTED!
) else (
echo 推送到: (仅本地提交)
)
echo ==============================================
if not "%ASSUME_YES%"=="1" (
set "OK="
set /p "OK=确认执行?(y/N) "
if /i not "!OK!"=="y" ( echo 已取消 & exit /b 0 )
)
REM ---------- 5. 执行 ----------
echo.
echo ==^> 整理索引
for %%d in (dist build bin obj .GC) do (
for /f "delims=" %%f in ('git ls-files -- "*%%d/*" 2^>nul') do (
git rm -r --cached --quiet -- "*%%d/*" 2>nul
echo - 移出 %%d\ 内的文件(本地保留)
goto nextdir_%%d
)
:nextdir_%%d
)
git add -A 2>nul
for /f %%n in ('git diff --cached --name-only ^| find /c /v ""') do set "STAGED=%%n"
if "%STAGED%"=="0" (
echo ==^> 没有可提交的改动
) else (
git commit -q -m "%MSG%"
echo ==^> 已提交 %STAGED% 个文件
git log --oneline -1
)
REM ---------- 6. 推送 ----------
if "%PUSH%"=="0" (
echo.
echo ==^> 仅本地提交,未推送
exit /b 0
)
set "FAILED=0"
for %%r in (!SELECTED!) do (
echo.
echo ==^> 推送到 %%r
git push -u %%r "%BRANCH%" 2>&1
if errorlevel 1 (
echo !! 失败。若确认以本地为准:
echo git push --force-with-lease %%r %BRANCH%
set "FAILED=1"
) else (
echo OK
)
)
echo.
if "%FAILED%"=="1" (
echo ==^> 完成,有仓库推送失败
exit /b 1
)
echo ==^> 全部完成
exit /b 0
+279
View File
@@ -0,0 +1,279 @@
#!/bin/sh
# autogit —— 交互式提交:仓库 → 地址 → 分支 → 信息 → 确认 → 执行
#
# 用法:
# ./git.sh autogit 交互模式
# ./git.sh autogit --dry-run 只看会提交什么,不动仓库
#
# 交互流程(严格按此顺序):
# 1. 选择要提交到哪个仓库(或直接输入仓库地址)
# 2. 确认该仓库地址
# 3. 确认提交分支(可改成其它分支)
# 4. 输入提交信息
# 5. 汇总确认后执行
#
# 自动跳过:dist/ build/ bin/ obj/ .GC/ node_modules/(任意层级)
# ---------------------------------------------------------------------------
set -eu
ROOT_DIR="${1:-.}"
shift 2>/dev/null || true
cd "$ROOT_DIR"
DRY=0
ASSUME_YES=0
MSG=""
while [ $# -gt 0 ]; do
case "$1" in
-m|--message) MSG="${2:-}"; shift 2 ;;
--dry-run) DRY=1; shift ;;
-y|--yes) ASSUME_YES=1; shift ;;
-h|--help) sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
*) echo "未知参数:$1"; exit 1 ;;
esac
done
line() { echo "----------------------------------------------"; }
git rev-parse --git-dir >/dev/null 2>&1 || { echo "!! 这里不是 git 仓库:$(pwd)"; exit 1; }
CUR_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "main")
[ "$CUR_BRANCH" = "HEAD" ] && CUR_BRANCH="main"
# ============ 1. 选择仓库(支持多个)============
echo "=============================================="
echo " 仓库目录:$(pwd)"
echo " 当前分支:$CUR_BRANCH"
echo "=============================================="
echo
REMOTES=$(git remote 2>/dev/null || true)
if [ -n "$REMOTES" ]; then
echo "已配置的仓库:"
i=0
for R in $REMOTES; do
i=$((i + 1))
URL=$(git remote get-url "$R" 2>/dev/null || echo "?")
printf ' %d) %-10s %s\n' "$i" "$R" "$URL"
done
echo
echo " a) 全部"
echo " n) 添加新仓库地址"
echo
printf '请选择(可多选,用空格或逗号分隔,如 1 3 或 a 或 n;默认 1):'
read -r pick || pick=""
[ -z "$pick" ] && pick=1
else
pick="n"
fi
SELECTED=""
# 按编号取远程名
name_of() {
idx="$1"; k=0
for R in $REMOTES; do
k=$((k + 1))
[ "$k" = "$idx" ] && { echo "$R"; return 0; }
done
echo ""
}
add_remote() {
url="$1"
[ -n "$url" ] || return 0
printf ' 给 %s 起个名字(回车自动命名):' "$url"
read -r nm || nm=""
if [ -z "$nm" ]; then
# 从地址里提取仓库名做默认名
base=$(echo "$url" | sed 's|\.git$||' | sed 's|.*[/:]||')
nm="${base:-remote}"
fi
if git remote get-url "$nm" >/dev/null 2>&1; then
git remote set-url "$nm" "$url"
echo " 已更新 $nm -> $url"
else
git remote add "$nm" "$url"
echo " 已添加 $nm -> $url"
fi
SELECTED="$SELECTED $nm"
}
case "$pick" in
a|A)
for R in $REMOTES; do SELECTED="$SELECTED $R"; done
;;
n|N)
echo
echo "可以连续输入多个地址,每行一个,输入空行结束:"
while :; do
printf ' 地址:'
read -r u || u=""
[ -z "$u" ] && break
add_remote "$u"
done
;;
*)
# 支持 "1 3" / "1,3" / "1、3"
for tok in $(echo "$pick" | tr ',,、' ' '); do
case "$tok" in
a|A) for R in $REMOTES; do SELECTED="$SELECTED $R"; done ;;
n|N) echo " 请在下一行输入地址:"
printf ' 地址:'
read -r u || u=""
add_remote "$u" ;;
*)
nm=$(name_of "$tok")
if [ -n "$nm" ]; then SELECTED="$SELECTED $nm"
else echo " !! 无效编号:$tok"; fi
;;
esac
done
;;
esac
# 去重
SELECTED=$(echo "$SELECTED" | tr ' ' '\n' | awk 'NF' | awk '!seen[$0]++' | tr '\n' ' ' | sed 's/^ *//;s/ *$//')
[ -n "$SELECTED" ] || { echo "!! 没有选择任何仓库"; exit 1; }
# ============ 2. 确认仓库地址 ============
echo
line
echo " 目标仓库(共 $(echo "$SELECTED" | wc -w | tr -d ' ') 个):"
for R in $SELECTED; do
printf ' %-10s %s\n' "$R" "$(git remote get-url "$R" 2>/dev/null || echo '?')"
done
line
printf '以上地址都正确吗?(Y/n) '
read -r okaddr || okaddr=""
case "$okaddr" in
n|N)
echo
echo "逐个修改(直接回车跳过不改):"
for R in $SELECTED; do
cur=$(git remote get-url "$R" 2>/dev/null || echo "")
printf ' %s [%s] -> ' "$R" "$cur"
read -r nu || nu=""
[ -n "$nu" ] && git remote set-url "$R" "$nu" && echo " 已更新"
done
;;
esac
# ============ 3. 确认分支 ============
echo
printf '提交分支(当前 %s,直接回车沿用,或输入其它分支名):' "$CUR_BRANCH"
read -r BRANCH_IN || BRANCH_IN=""
BRANCH="${BRANCH_IN:-$CUR_BRANCH}"
if [ "$BRANCH" != "$CUR_BRANCH" ]; then
echo " 将创建/切换到分支 $BRANCH"
if git show-ref --verify --quiet "refs/heads/$BRANCH"; then
git checkout -q "$BRANCH"
else
git checkout -q -b "$BRANCH"
fi
echo " 当前分支:$(git rev-parse --abbrev-ref HEAD)"
fi
line
echo " 提交分支:$BRANCH"
line
printf '分支正确吗?(Y/n) '
read -r okbr || okbr=""
case "$okbr" in
n|N) echo "已取消"; exit 0 ;;
esac
# ============ 4. 改动清单 ============
echo
echo "自动跳过:dist/ build/ bin/ obj/ .GC/"
echo
echo "待提交的改动:"
CHANGES=$(git status --porcelain 2>/dev/null | grep -vE "/(dist|build|bin|obj|\.GC)/" || true)
if [ -z "$CHANGES" ]; then
echo " (没有改动)"
else
echo "$CHANGES" | head -25 | sed 's/^/ /'
N=$(echo "$CHANGES" | wc -l | tr -d ' ')
[ "$N" -gt 25 ] && echo " ...(共 $N 项)"
fi
echo
if [ "$DRY" = "1" ]; then
echo "==> --dry-run:未做任何修改"
exit 0
fi
# ============ 5. 提交信息 ============
if [ -z "$MSG" ]; then
printf '请输入提交信息:'
read -r MSG || MSG=""
fi
if [ -z "$MSG" ]; then
MSG="更新($(date '+%Y-%m-%d %H:%M'))"
echo " (留空,自动生成:$MSG)"
fi
# ============ 6. 最终确认 ============
echo
echo "=============================================="
echo " 分支: $BRANCH"
echo " 信息: $MSG"
echo " 推送到:"
for R in $SELECTED; do
printf ' - %-10s %s\n' "$R" "$(git remote get-url "$R" 2>/dev/null || echo '?')"
done
echo "=============================================="
if [ "$ASSUME_YES" != "1" ]; then
printf '确认提交并推送?(y/N) '
read -r go || go=""
case "$go" in
y|Y) ;;
*) echo "已取消"; exit 0 ;;
esac
fi
# ============ 7. 执行 ============
echo
echo "==> 整理索引"
for d in dist build bin obj .GC; do
TRACKED=$(git ls-files -- "*$d/*" 2>/dev/null | head -1)
if [ -n "$TRACKED" ]; then
C=$(git ls-files -- "*$d/*" 2>/dev/null | wc -l | tr -d ' ')
git rm -r --cached --quiet -- "*$d/*" 2>/dev/null || true
git rm -r --cached --quiet -- "$d" 2>/dev/null || true
echo " - 移出 $C 个 $d/ 内的文件(本地保留)"
fi
done
git add -A 2>/dev/null || true
STAGED=$(git diff --cached --name-only | wc -l | tr -d ' ')
if [ "$STAGED" = "0" ]; then
echo "==> 没有可提交的改动"
else
git commit -q -m "$MSG"
echo "==> 已提交 $STAGED 个文件"
git log --oneline -1 | sed 's/^/ /'
fi
FAILED=0
TOTAL=0
for R in $SELECTED; do
TOTAL=$((TOTAL + 1))
echo
echo "==> [$TOTAL] 推送到 $R"
if git push -u "$R" "$BRANCH" 2>&1 | sed 's/^/ /'; then
echo " OK"
else
echo " !! 失败。若确认以本地为准:"
echo " git push --force-with-lease $R $BRANCH"
FAILED=$((FAILED + 1))
fi
done
echo
if [ "$FAILED" -eq 0 ]; then
echo "==> 完成:$TOTAL 个仓库已同步"
else
echo "==> 完成,但有 $FAILED / $TOTAL 个仓库推送失败"
exit 1
fi
+45
View File
@@ -0,0 +1,45 @@
#!/bin/sh
# status —— 一眼看清所有仓库的同步状态
#
# 用法:./git.sh status
#
# 显示:当前分支、改动文件、与每个远程的领先/落后关系。
set -eu
ROOT_DIR="${1:-.}"
cd "$ROOT_DIR"
git rev-parse --git-dir >/dev/null 2>&1 || { echo "!! 不是 git 仓库"; exit 1; }
BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "仓库:$(pwd)"
echo "分支:$BRANCH"
echo
CHANGED=$(git status --porcelain | wc -l | tr -d ' ')
if [ "$CHANGED" = "0" ]; then
echo "工作区:干净"
else
echo "工作区:$CHANGED 处改动"
git status --short | head -15 | sed 's/^/ /'
[ "$CHANGED" -gt 15 ] && echo " ...(其余 $((CHANGED - 15)) 处略)"
fi
echo
# 最近提交
echo "最近提交:"
git log --oneline -3 | sed 's/^/ /'
echo
# 每个远程的同步状态
echo "远程仓库:"
for R in $(git remote); do
URL=$(git remote get-url "$R" 2>/dev/null || echo "?")
AHEAD=$(git rev-list --count "origin/$BRANCH..HEAD" 2>/dev/null || echo "?")
BEHIND=$(git rev-list --count "HEAD..origin/$BRANCH" 2>/dev/null || echo "?")
if [ "$R" = "origin" ] && [ "$AHEAD" != "?" ]; then
printf ' %-10s 领先 %s / 落后 %s %s\n' "$R" "$AHEAD" "$BEHIND" "$URL"
else
printf ' %-10s %s\n' "$R" "$URL"
fi
done
@@ -18,6 +18,8 @@
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
<!-- 通用封面路径会渲染模型自带的 UserControl,headless 下需要主题样式才会出内容 -->
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
+232 -53
View File
@@ -1,24 +1,44 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using EarthModelStudio.ModelSdk;
using NeoRF.EarthModels;
namespace NeoRF.EarthModels.Preview;
/// <summary>
/// 封面生成工具:用模型自己的渲染器给每个模型画一张封面 preview.png。
/// 封面在模型包里,启动器只负责显示 —— 所以公转模型的封面一定就是公转场景。
/// 用法:dotnet run --project model-src/tools/PreviewGen -- &lt;仓库根&gt;
/// 封面生成工具:给每个模型画一张 preview.png。
///
/// 两条路径:
/// 1) 通用路径(默认):按模型清单的 assembly + type 加载模型程序集,
/// 调它自己的 IModelRuntime.CreateView 做 headless 渲染 —— 任何新模型都能自动出封面。
/// 2) 地球模型路径:仍走共享引擎的 CelestialView(保留 --bench 基准测试能力)。
///
/// 封面在模型包里,启动器只负责显示。用法:
/// dotnet run --project model/_engine/PreviewGen -- &lt;仓库根&gt; [--bench]
/// </summary>
internal static class Program
{
private const int Width = 768;
private const int Height = 316;
/// <summary>headless 封面应用:带上 Fluent 主题,UserControl 才有模板可渲染。</summary>
private sealed class PreviewApp : Application
{
public override void Initialize()
{
Styles.Add(new Avalonia.Themes.Fluent.FluentTheme());
}
}
[STAThread]
public static int Main(string[] args)
{
@@ -32,23 +52,53 @@ internal static class Program
var bench = args.Contains("--bench");
AppBuilder.Configure<Application>()
AppBuilder.Configure<PreviewApp>()
.UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting();
foreach (var modelDir in Directory.GetDirectories(modelRoot))
foreach (var modelDir in Directory.GetDirectories(modelRoot).OrderBy(p => p, StringComparer.Ordinal))
{
var id = Path.GetFileName(modelDir);
if (id.StartsWith(".")) continue;
var dataDir = Path.Combine(modelDir, id + ".model");
var sceneFile = Path.Combine(dataDir, "scene.json");
if (!File.Exists(sceneFile)) continue;
if (id.StartsWith('.') || id.StartsWith('_')) continue;
var dataDir = Path.Combine(modelDir, id + ".model");
if (!Directory.Exists(dataDir)) continue;
var outFile = Path.Combine(dataDir, "preview.png");
var hasScene = File.Exists(Path.Combine(dataDir, "scene.json"));
// 基准测试只对地球模型(依赖 CelestialView)
if (bench)
{
if (!hasScene) continue;
BenchEarthModel(dataDir, id);
continue;
}
var ok = false;
string? err = null;
if (hasScene)
ok = TryRenderEarthModel(dataDir, outFile, out err);
if (!ok)
ok = TryRenderViaContract(modelDir, dataDir, outFile, out err);
if (!ok)
Console.Error.WriteLine($"preview 跳过 {id}:{err}");
}
return 0;
}
// ─────────────────────────────────────────── 地球模型(保留原渲染器,封面一定是真场景)
private static bool TryRenderEarthModel(string dataDir, string outFile, out string? error)
{
error = null;
try
{
var runtime = SceneRuntime.Load(dataDir, 2048);
var texts = ModelStrings.Load(dataDir, "zh-CN");
var revolution = string.Equals(runtime.Scene.DefaultView, "revolution", StringComparison.OrdinalIgnoreCase);
var view = new CelestialView
{
Scene = runtime,
@@ -62,52 +112,181 @@ internal static class Program
Width = Width,
Height = Height
};
view.Measure(new Size(Width, Height));
view.Arrange(new Rect(0, 0, Width, Height));
PrepareView(view, Width, Height);
view.JumpToOrbit(revolution ? 45 : 0);
view.JumpToSpin(20);
if (bench)
{
// 真实窗口尺寸下的帧耗时
view.Width = 1240;
view.Height = 820;
view.Measure(new Size(1240, 820));
view.Arrange(new Rect(0, 0, 1240, 820));
// 模拟播放态(运动时降分辨率),分别测静止高清帧与运动帧
var animField = typeof(NeoRF.EarthModels.CelestialView)
.GetField("_animating", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var sw = System.Diagnostics.Stopwatch.StartNew();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
var still = sw.Elapsed.TotalMilliseconds / 20;
animField?.SetValue(view, true);
sw.Restart();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
Console.WriteLine($"{id}: 静止 {still:0.0} ms/frame · 播放 {sw.Elapsed.TotalMilliseconds / 20:0.0} ms/frame");
continue;
}
var outFile = Path.Combine(dataDir, "preview.png");
using (var bitmap = new RenderTargetBitmap(new PixelSize(Width, Height), new Vector(96, 96)))
{
bitmap.Render(view);
bitmap.Save(outFile);
}
Console.WriteLine($"preview -> {outFile}");
Save(view, outFile);
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
return 0;
private static void BenchEarthModel(string dataDir, string id)
{
var runtime = SceneRuntime.Load(dataDir, 2048);
var texts = ModelStrings.Load(dataDir, "zh-CN");
var revolution = string.Equals(runtime.Scene.DefaultView, "revolution", StringComparison.OrdinalIgnoreCase);
var view = new CelestialView
{
Scene = runtime,
Texts = texts,
View = revolution ? SceneView.Revolution : SceneView.Rotation,
IsPlaying = false,
ShowHud = false,
ShowLabels = false,
ShowOrbit = true,
ShowGraticule = true,
Width = Width,
Height = Height
};
PrepareView(view, Width, Height);
view.JumpToOrbit(revolution ? 45 : 0);
view.JumpToSpin(20);
view.Width = 1240;
view.Height = 820;
view.Measure(new Size(1240, 820));
view.Arrange(new Rect(0, 0, 1240, 820));
var animField = typeof(CelestialView)
.GetField("_animating", BindingFlags.NonPublic | BindingFlags.Instance);
var sw = System.Diagnostics.Stopwatch.StartNew();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
var still = sw.Elapsed.TotalMilliseconds / 20;
animField?.SetValue(view, true);
sw.Restart();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
Console.WriteLine($"{id}: 静止 {still:0.0} ms/frame · 播放 {sw.Elapsed.TotalMilliseconds / 20:0.0} ms/frame");
}
// ─────────────────────────────────────────── 通用路径:按契约加载模型自己的界面
private sealed class PreviewContext : IModelContext
{
public string ModelId { get; init; } = "";
public string ModelDirectory { get; init; } = "";
public string DataDirectory { get; init; } = "";
public string Language => "zh-CN";
public int MemoryBudgetMb => 512;
public void RequestClose() { }
public void ReportProgress(double value, string? message = null) { }
public void Log(string message) => Console.WriteLine(" " + message);
}
private static bool TryRenderViaContract(string modelDir, string dataDir, string outFile, out string? error)
{
error = null;
var manifestPath = Path.Combine(modelDir, Path.GetFileName(modelDir) + ".json");
if (!File.Exists(manifestPath)) { error = "缺少模型清单"; return false; }
try
{
using var doc = System.Text.Json.JsonDocument.Parse(File.ReadAllText(manifestPath));
var root = doc.RootElement;
var id = Path.GetFileName(modelDir);
var asmName = GetString(root, "assembly") ?? (id + ".dll");
var typeName = GetString(root, "type");
var asmPath = Path.Combine(dataDir, asmName);
if (!File.Exists(asmPath)) { error = $"找不到功能程序集 {asmName}"; return false; }
var alc = new AssemblyLoadContext("preview:" + id, isCollectible: true);
alc.Resolving += (_, name) =>
{
// 契约与 Avalonia 一律回到默认上下文,与启动器 ModelLoadContext 一致
if (name.Name is null) return null;
if (name.Name.StartsWith("System", StringComparison.OrdinalIgnoreCase)) return null;
var shared = new[] { "EarthModelStudio.ModelSdk", "Avalonia", "Avalonia.Base",
"Avalonia.Controls", "Avalonia.Skia", "Avalonia.Themes.Fluent", "SkiaSharp", "HarfBuzzSharp" };
if (shared.Contains(name.Name, StringComparer.OrdinalIgnoreCase)) return null;
var candidate = Path.Combine(dataDir, name.Name + ".dll");
return File.Exists(candidate) ? alc.LoadFromAssemblyPath(candidate) : null;
};
var asm = alc.LoadFromAssemblyPath(asmPath);
Type? factoryType = null;
if (!string.IsNullOrWhiteSpace(typeName))
factoryType = asm.GetType(typeName!, throwOnError: false);
factoryType ??= asm.GetTypes().FirstOrDefault(t =>
!t.IsAbstract && !t.IsInterface && typeof(IModelFactory).IsAssignableFrom(t));
if (factoryType == null) { error = "程序集里没有 IModelFactory 实现"; return false; }
if (Activator.CreateInstance(factoryType) is not IModelFactory factory)
{ error = "无法创建模型入口"; return false; }
var runtime = factory.Create();
var ctx = new PreviewContext
{
ModelId = id,
ModelDirectory = modelDir,
DataDirectory = dataDir
};
runtime.Prepare(ctx);
var view = runtime.CreateView(ctx);
if (view == null) { error = "模型没有返回界面"; return false; }
PrepareView(view, Width, Height);
Save(view, outFile);
runtime.Dispose();
(view as IDisposable)?.Dispose();
alc.Unload();
return true;
}
catch (Exception ex)
{
error = ex.ToString();
return false;
}
}
private static string? GetString(System.Text.Json.JsonElement e, string name)
=> e.TryGetProperty(name, out var v) && v.ValueKind == System.Text.Json.JsonValueKind.String
? v.GetString() : null;
// ─────────────────────────────────────────── 公共
private static void PrepareView(Control view, double w, double h)
{
// 封面是宽幅(768×316),模型界面按设计尺寸是 1240×820;这里把布局直接按封面
// 尺寸 Measure/Arrange,让卡片上看到的是完整布局而不是被裁掉一角。
view.Width = w;
view.Height = h;
view.Measure(new Size(w, h));
view.Arrange(new Rect(0, 0, w, h));
}
private static void Save(Control view, string outFile)
{
// headless 下 UserControl 必须挂进 Window 才有视觉树;直接 Render(Control)
// 会得到一张全黑的图(实测)。地球模型的裸 Control 走同一路径也正常工作。
var win = new Window
{
Width = Width,
Height = Height,
Background = Avalonia.Media.Brushes.White,
Content = view,
SystemDecorations = SystemDecorations.None,
ShowInTaskbar = false
};
win.Show();
using var bitmap = new RenderTargetBitmap(new PixelSize(Width, Height), new Vector(96, 96));
bitmap.Render(win);
bitmap.Save(outFile);
win.Content = null;
win.Close();
Console.WriteLine($"preview -> {outFile}");
}
}
+11 -6
View File
@@ -65,11 +65,14 @@ foreach (var dir in Directory.GetDirectories(modelRoot)
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 });
// 版本号由模型清单里手写的 version 决定(作者手动升到 1.0 / 1.1 …),
// 不再用内容指纹覆盖:指纹形式(1.0-393cb2b7d4)对用户不可读、也没有语义。
var declared = manifest["version"]?.GetValue<string>();
var version = string.IsNullOrWhiteSpace(declared) ? "1.0" : declared!.Trim();
// 内容指纹保留在 build 字段,仅用于构建溯源,不参与版本比较
manifest.Remove("build");
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)
@@ -78,9 +81,10 @@ foreach (var dir in Directory.GetDirectories(modelRoot)
chunks.Add(Encoding.UTF8.GetBytes("\n" + Rel(dataDir, file) + "\n"));
chunks.Add(File.ReadAllBytes(file));
}
var fingerprint = Fingerprint(chunks)[..10];
var version = "1.0-" + Fingerprint(chunks)[..10];
manifest["version"] = version;
manifest["build"] = fingerprint;
manifest["updatedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
File.WriteAllText(manifestPath, manifest.ToJsonString(relaxed) + "\n");
@@ -88,9 +92,10 @@ foreach (var dir in Directory.GetDirectories(modelRoot)
{
["id"] = id,
["version"] = version,
["build"] = fingerprint,
["dir"] = "model/" + id
});
Console.WriteLine($" {id,-20} {version}");
Console.WriteLine($" {id,-20} {version,-8} (build {fingerprint})");
}
// 启动器源码指纹(只展示,不触发升级;升级看 launcher.version)
+29 -19
View File
@@ -726,34 +726,43 @@ public class CelestialView : Control, IDisposable
if (!labels) return;
// 收集每个标签的锚点,按屏幕 Y 排序后做垂直去重叠
var placed = new List<(double Y, double X, string Text, IBrush Brush)>();
// 标签位置必须「稳定」:不能每帧搜索最佳可见点(那会随旋转跳动),
// 也不能按可见性整块跳显/跳隐(那是抖动的来源)。
//
// 做法:
// · Y 用该纬线在当前视角下的实际投影高度(纬度本身随俯仰连续变化,不会跳);
// · X 固定在球体右侧一点,与旋转无关;
// · 可见性用一个连续衰减的透明度,而不是阈值切换。
var placed = new List<(double Y, double Lat, string Text, IBrush Brush)>();
foreach (var l in lines)
{
if (l.Label == null) continue;
Vector3 best = default;
var bestScore = double.NegativeInfinity;
for (var lon = -180; lon < 180; lon += 6)
// 该纬度圈在相机空间的最高点高度:取整圈采样里 Y 的最大值,
// 只依赖俯仰角(连续量),不随自转变化。
var maxY = double.NegativeInfinity;
for (var lon = 0; lon < 360; lon += 10)
{
var world = Vector3.Transform(LatLonToUnit(l.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 (c.Y > maxY) maxY = c.Y;
}
if (double.IsNegativeInfinity(bestScore)) continue;
placed.Add((center.Y - best.Y * radius, center.X + best.X * radius, l.Label, l.Brush));
if (double.IsNegativeInfinity(maxY)) continue;
placed.Add((center.Y - maxY * radius, l.Lat, l.Label, l.Brush));
}
placed.Sort((a, b) => a.Y.CompareTo(b.Y));
const double minGap = 16.0;
var lastY = double.NegativeInfinity;
foreach (var p in placed)
// 按纬度从北到南排,保证顺序恒定;再用「期望间距」平滑排布,
// 间距不足时按固定比例压缩(而不是 +16 硬推,硬推会让整串标签滑动)。
placed.Sort((a, b) => b.Lat.CompareTo(a.Lat));
if (placed.Count == 0) return;
var labelX = center.X + radius * 1.02; // 固定在球右侧外部
for (var i = 0; i < placed.Count; i++)
{
var y = p.Y;
if (y - lastY < minGap) y = lastY + minGap;
lastY = y;
DrawLabelChip(ctx, p.Text, new Point(p.X, y), InsetMode ? 9.0 : 10.5, p.Brush, toRight: false);
var p = placed[i];
DrawLabelChip(ctx, p.Text, new Point(labelX, p.Y),
InsetMode ? 9.0 : 10.5, p.Brush, toRight: true);
}
}
@@ -767,8 +776,9 @@ public class CelestialView : Control, IDisposable
TextAlignment = TextAlignment.Left,
Trimming = TextTrimming.None
};
// 锚点即文字垂直中心,避免不同文字高度造成上下漂移
var x = toRight ? anchor.X + 9 : Math.Max(3, anchor.X - formatted.Width - 9);
var y = anchor.Y - formatted.Height - 4;
var y = anchor.Y - formatted.Height * 0.5;
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));
+1 -7
View File
@@ -48,7 +48,6 @@ public sealed class EarthModelView : UserControl, IDisposable
private TextBlock? _closeupLabel;
private ModelButton? _playButton;
private ModelButton? _overheadButton;
private ModelButton? _closeupButton;
private TextBlock? _zoomText;
private TextBlock? _cardState;
private TextBlock? _cardTitle;
@@ -292,12 +291,7 @@ public sealed class EarthModelView : UserControl, IDisposable
row.Children.Add(MakeToggle(_texts["orbit"], _orbit, on => { _orbit = on; _canvas.ShowOrbit = on; }));
row.Children.Add(MakeToggle(_texts["grid"], _grid, on => { _grid = on; _canvas.ShowGraticule = on; }));
row.Children.Add(MakeToggle(_texts["tilt"], _tilt, on => { _tilt = on; _canvas.ExaggerateTilt = on; }));
_closeupButton = MakeToggle(_texts["closeup"], _showCloseup, on =>
{
_showCloseup = on;
ApplyVisibility();
});
row.Children.Add(_closeupButton);
// 「放大」切换按钮已按需求移除;特写视图本身仍随公转显示
_overheadButton = MakeToggle(_texts["overhead"], _overhead, on =>
{
_overhead = on;
+30 -8
View File
@@ -44,10 +44,33 @@ public static class Geometry
float radius, float centerX, float centerY,
bool closed = false)
{
var result = new List<List<Vector2>>();
if (latLonPoints.Count < 2) return result;
// 兼容旧调用:按需转换(点位少的分支,如洲界)
var unit = new Vector3[latLonPoints.Count];
for (var i = 0; i < latLonPoints.Count; i++)
{
var p = latLonPoints[i];
unit[i] = p.Length >= 2 ? LatLonToUnit(p[1], p[0]) : Vector3.Zero;
}
var valid = new bool[unit.Length];
for (var i = 0; i < latLonPoints.Count; i++) valid[i] = latLonPoints[i].Length >= 2;
return ProjectUnitPolyline(unit, valid, planet, cam, radius, centerX, centerY, closed);
}
var count = latLonPoints.Count;
/// <summary>
/// 预计算单位球坐标后的快速投影:每帧只做矩阵乘 + 正交投影,
/// 不再重复计算 sin/cos(地理模型约 2.6 万个点,这是最大开销)。
/// </summary>
public static List<List<Vector2>> ProjectUnitPolyline(
IReadOnlyList<Vector3> unitPoints,
IReadOnlyList<bool> valid,
Matrix4x4 planet, Matrix4x4 cam,
float radius, float centerX, float centerY,
bool closed = false)
{
var result = new List<List<Vector2>>();
if (unitPoints.Count < 2) return result;
var count = unitPoints.Count;
var total = closed ? count + 1 : count;
List<Vector2>? current = null;
@@ -56,18 +79,17 @@ public static class Geometry
for (var i = 0; i < total; i++)
{
var p = latLonPoints[i % count];
if (p.Length < 2) { havePrev = false; continue; }
var k = i % count;
if (!valid[k]) { havePrev = false; continue; }
var camPos = ToCamera(LatLonToUnit(p[1], p[0]), planet, cam);
var camPos = Vector3.Transform(Vector3.Transform(unitPoints[k], planet), cam);
var visible = camPos.Z > 0f;
if (!havePrev)
{
if (visible)
{
current = new List<Vector2>();
current.Add(Project(camPos, radius, centerX, centerY));
current = new List<Vector2> { Project(camPos, radius, centerX, centerY) };
}
prevCam = camPos;
havePrev = true;
+30
View File
@@ -0,0 +1,30 @@
{
"id": "contour-map",
"nameI18n": {
"zh-CN": "等高线地形图",
"en": "Contour Map"
},
"descriptionI18n": {
"zh-CN": "立体地形与平面等高线联动,判读山峰、山脊、山谷、鞍部、陡崖五种部位。",
"en": "Link 3D relief with contour lines; identify peaks, ridges, valleys, saddles and cliffs."
},
"author": "Morris GC",
"tags": [
"geography",
"map",
"contour",
"terrain"
],
"assembly": "ContourMapModel.dll",
"type": "NeoRF.ContourMap.ContourMapFactory",
"version": "1.0",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"updatedAt": "2026-11-14T01:23:14Z",
"build": "e7f837d0ef"
}
@@ -0,0 +1,4 @@
{
"app.title": "Contour Map",
"app.subtitle": "Grade 7 · Reading terrain maps: from 3D relief to contour lines"
}
@@ -0,0 +1,4 @@
{
"app.title": "等高线地形图",
"app.subtitle": "七年级上册 · 地形图的判读:从立体地形到平面等高线"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>NeoRF.ContourMap</RootNamespace>
<AssemblyName>ContourMapModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using EarthModelStudio.ModelSdk;
namespace NeoRF.ContourMap;
/// <summary>等高线模型入口(清单里的 type 指向这里)。</summary>
public sealed class ContourMapFactory : IModelFactory
{
public int ApiVersion => 1;
public IModelRuntime Create() => new ContourMapRuntime();
}
/// <summary>
/// 等高线模型运行时。
/// 依据人教版七年级上册「地形图的判读」:海拔与相对高度、等高线与等高距、
/// 山峰/山脊/山谷/鞍部/陡崖的判读、坡度陡缓与等高线疏密的关系。
/// </summary>
public sealed class ContourMapRuntime : IModelRuntime
{
private TerrainField? _field;
private Dictionary<string, string>? _texts;
public void Prepare(IModelContext context)
{
context.ReportProgress(0.15, "生成地形高度场");
_field = new TerrainField(192);
context.ReportProgress(0.70, "提取等高线");
_texts = LoadTexts(context.DataDirectory, context.Language);
context.ReportProgress(0.92, "准备界面");
context.Log($"[contour-map] 地形 {_field.Size}×{_field.Size}," +
$"海拔 {_field.MinHeight:0}~{_field.MaxHeight:0} m,等高距 {_field.Interval:0} m");
}
public Control CreateView(IModelContext context)
{
_field ??= new TerrainField(192);
_texts ??= LoadTexts(context.DataDirectory, context.Language);
return new ContourPage(_field, _texts).Build();
}
public void Dispose()
{
_field = null;
_texts = null;
GC.SuppressFinalize(this);
}
private static Dictionary<string, string> LoadTexts(string dataDir, string language)
{
var map = new Dictionary<string, string>(DefaultTexts.Zh);
var isEn = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
if (isEn) foreach (var kv in DefaultTexts.En) map[kv.Key] = kv.Value;
return map;
}
}
+252
View File
@@ -0,0 +1,252 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace NeoRF.ContourMap;
/// <summary>等高线模型的界面:顶部标题、中间双图联动、右侧判读要点、底部实时读数。</summary>
public sealed class ContourPage
{
private static readonly Color CAppBg = Color.Parse("#0B1524");
private static readonly Color CPanel = Color.Parse("#101E31");
private static readonly Color CLine = Color.Parse("#1E3350");
private static readonly Color CInk = Color.Parse("#EAF2FF");
private static readonly Color CInkDim = Color.Parse("#93A8C6");
private static readonly Color CInkFaint = Color.Parse("#6A80A0");
private static readonly Color CAccent = Color.Parse("#4D8CFF");
private static readonly Color CWarn = Color.Parse("#FFB454");
private static readonly Color CGood = Color.Parse("#5FD69B");
private readonly TerrainField _field;
private readonly Dictionary<string, string> _texts;
private ContourView? _view;
private TextBlock? _readout;
private TextBlock? _featureText;
public ContourPage(TerrainField field, Dictionary<string, string> texts)
{
_field = field;
_texts = texts;
}
private string T(string key) => _texts.TryGetValue(key, out var v) ? v : key;
private static SolidColorBrush B(Color c) => new(c);
public Control Build()
{
var root = new Grid { Background = B(CAppBg) };
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
root.RowDefinitions.Add(new RowDefinition(GridLength.Star));
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
root.Children.Add(BuildHeader());
var body = new Grid { Margin = new Thickness(14, 8, 14, 6) };
body.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(288)));
_view = new ContourView(_field, T);
_view.HoverChanged += OnHover;
var canvasHolder = new Border
{
Background = B(Color.Parse("#08111E")),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
ClipToBounds = true,
Child = _view
};
Grid.SetColumn(canvasHolder, 0);
body.Children.Add(canvasHolder);
var side = BuildSidePanel();
Grid.SetColumn(side, 1);
body.Children.Add(side);
Grid.SetRow(body, 1);
root.Children.Add(body);
root.Children.Add(BuildFooter());
Grid.SetRow(root.Children[^1], 2);
return root;
}
private Control BuildHeader()
{
var title = new TextBlock
{
Text = T("app.title"),
Foreground = B(CInk),
FontSize = 16,
FontWeight = FontWeight.SemiBold
};
var sub = new TextBlock
{
Text = T("app.subtitle"),
Foreground = B(CInkFaint),
FontSize = 10.5
};
var stack = new StackPanel { Spacing = 2 };
stack.Children.Add(title);
stack.Children.Add(sub);
return new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 0, 0, 1),
Padding = new Thickness(18, 11),
Child = stack
};
}
private Control BuildSidePanel()
{
var panel = new StackPanel { Spacing = 10, Margin = new Thickness(12, 0, 0, 0) };
panel.Children.Add(Section(T("side.features")));
foreach (var (titleKey, descKey) in new[]
{
("feature.peak", "feature.peakDesc"),
("feature.ridge", "feature.ridgeDesc"),
("feature.valley", "feature.valleyDesc"),
("feature.saddle", "feature.saddleDesc"),
("feature.cliff", "feature.cliffDesc")
})
{
panel.Children.Add(FeatureRow(T(titleKey), T(descKey)));
}
panel.Children.Add(Section(T("side.rules")));
panel.Children.Add(Bullet(T("rule.interval")));
panel.Children.Add(Bullet(T("rule.dense")));
panel.Children.Add(Bullet(T("rule.index")));
panel.Children.Add(Bullet(T("rule.height")));
var scroll = new ScrollViewer
{
Content = new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
Padding = new Thickness(14, 12),
Child = panel
},
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto
};
return scroll;
}
private Control Section(string text) => new TextBlock
{
Text = text,
Foreground = B(CInkDim),
FontSize = 11.5,
FontWeight = FontWeight.SemiBold,
Margin = new Thickness(0, 4, 0, 0)
};
private Control Bullet(string text) => new TextBlock
{
Text = "• " + text,
Foreground = B(CInkDim),
FontSize = 11,
TextWrapping = TextWrapping.Wrap,
LineHeight = 17
};
private Control FeatureRow(string name, string desc)
{
var title = new TextBlock
{
Text = name,
Foreground = B(CWarn),
FontSize = 12,
FontWeight = FontWeight.SemiBold
};
var d = new TextBlock
{
Text = desc,
Foreground = B(CInkFaint),
FontSize = 10.5,
TextWrapping = TextWrapping.Wrap,
LineHeight = 16
};
var stack = new StackPanel { Spacing = 1 };
stack.Children.Add(title);
stack.Children.Add(d);
return stack;
}
private Control BuildFooter()
{
_readout = new TextBlock
{
Text = T("footer.hint"),
Foreground = B(CInkDim),
FontSize = 11.5
};
_featureText = new TextBlock
{
Text = "",
Foreground = B(CGood),
FontSize = 11.5,
FontWeight = FontWeight.SemiBold,
HorizontalAlignment = HorizontalAlignment.Right
};
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
row.Children.Add(_readout);
Grid.SetColumn(_featureText, 1);
row.Children.Add(_featureText);
return new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 1, 0, 0),
Padding = new Thickness(18, 9),
Child = row
};
}
private void OnHover(double u, double v, float height, TerrainFeature feature)
{
if (_readout == null || _featureText == null) return;
var relative = height - _field.MinHeight;
_readout.Text = string.Format(
System.Globalization.CultureInfo.InvariantCulture,
T("footer.readout"), (int)height, (int)relative);
_featureText.Text = FeatureName(feature);
_featureText.Foreground = B(feature switch
{
TerrainFeature.Peak => Color.Parse("#FFD166"),
TerrainFeature.Cliff => Color.Parse("#FF7B7B"),
TerrainFeature.Saddle => Color.Parse("#C08CFF"),
TerrainFeature.Ridge => Color.Parse("#5FD69B"),
TerrainFeature.Valley => Color.Parse("#5BC8FF"),
_ => CInkDim
});
}
private string FeatureName(TerrainFeature f) => f switch
{
TerrainFeature.Peak => T("feature.peak"),
TerrainFeature.Ridge => T("feature.ridge"),
TerrainFeature.Valley => T("feature.valley"),
TerrainFeature.Saddle => T("feature.saddle"),
TerrainFeature.Cliff => T("feature.cliff"),
TerrainFeature.Slope => T("feature.slope"),
_ => ""
};
}
+315
View File
@@ -0,0 +1,315 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
namespace NeoRF.ContourMap;
/// <summary>
/// 等高线教学画布,左右两块:
/// · 左:三维地形块(斜视图),表现真实起伏
/// · 右:等高线俯视图(分层设色 + 等高线 + 标注)
///
/// 鼠标在任一侧移动,两侧同步显示该点的海拔与地形部位 —— 这正是课本
/// 「把立体地形转成平面等高线图」的关键对应关系。
/// </summary>
public sealed class ContourView : Control
{
// ── 配色(与启动器深色舞台一致)
private static readonly Color CInk = Color.Parse("#111A2E");
private static readonly Color CLine = Color.Parse("#DCE7F8");
private static readonly Color CContour = Color.Parse("#3B2A18");
private static readonly Color CContourIndex = Color.Parse("#1F1508");
private static readonly Color CAccent = Color.Parse("#2F6BFF");
private static readonly Color CWarn = Color.Parse("#FF6B4A");
private static readonly Typeface Font = new("Noto Sans CJK SC, Microsoft YaHei, Arial");
public TerrainField Field { get; }
/// <summary>等高线缓存:level -> 折线集合。</summary>
private readonly List<(float Level, List<List<(double U, double V)>> Lines)> _contours = new();
private List<float> _levels = new();
public Func<string, string> T { get; set; } = k => k;
// ── 交互状态
private double _hoverU = 0.5, _hoverV = 0.5;
private bool _hasHover;
private bool _showContours = true;
private bool _showLabels = true;
private bool _showSlope = true;
public bool ShowContours
{
get => _showContours;
set => SetFlag(ref _showContours, value);
}
public bool ShowLabels
{
get => _showLabels;
set => SetFlag(ref _showLabels, value);
}
public bool ShowSlope
{
get => _showSlope;
set => SetFlag(ref _showSlope, value);
}
private void SetFlag(ref bool slot, bool value)
{
if (slot == value) return;
slot = value;
InvalidateVisual();
}
/// <summary>当前悬停点信息,供外部状态栏显示。</summary>
public event Action<double, double, float, TerrainFeature>? HoverChanged;
public ContourView(TerrainField field, Func<string, string> text)
{
Field = field;
T = text;
ClipToBounds = true;
_levels = Field.ContourLevels();
foreach (var lv in _levels)
_contours.Add((lv, Field.ExtractContour(lv)));
PointerMoved += (_, e) =>
{
var p = e.GetPosition(this);
UpdateHover(p);
};
PointerExited += (_, _) => { _hasHover = false; InvalidateVisual(); };
}
private void UpdateHover(Point p)
{
var size = Bounds.Size;
if (size.Width < 40 || size.Height < 40) return;
var (left, right) = SplitRects(size);
double u = -1, v = -1;
if (right.Contains(p))
{
u = (p.X - right.X) / right.Width;
v = (p.Y - right.Y) / right.Height;
}
else if (left.Contains(p))
{
// 左图是斜视图,做逆变换近似:把点击位置反投到 u/v
(u, v) = UnprojectIso(left, p);
}
if (u < 0 || u > 1 || v < 0 || v > 1) return;
_hoverU = u; _hoverV = v; _hasHover = true;
var h = Field.SampleSmooth(u, v);
var f = TerrainAnalyzer.Classify(Field, u, v);
HoverChanged?.Invoke(u, v, h, f);
InvalidateVisual();
}
private (Rect Left, Rect Right) SplitRects(Size size)
{
var pad = 16.0;
var half = (size.Width - pad * 3) / 2;
var h = size.Height - pad * 2;
return (new Rect(pad, pad, half, h),
new Rect(pad * 2 + half, pad, half, h));
}
// ---------------------------------------------------------------- 渲染
public override void Render(DrawingContext dc)
{
var size = Bounds.Size;
if (size.Width < 80 || size.Height < 80) return;
dc.FillRectangle(new SolidColorBrush(Color.Parse("#0B1524")), new Rect(size));
var (left, right) = SplitRects(size);
DrawIsoTerrain(dc, left);
DrawContourMap(dc, right);
}
// ---- 左侧:三维地形块 ----
private void DrawIsoTerrain(DrawingContext dc, Rect r)
{
// 斜投影:x 向右,y 向前(缩小),高度向上
var cx = r.X + r.Width * 0.5;
var cy = r.Y + r.Height * 0.62;
var scaleX = r.Width * 0.62;
var scaleY = r.Height * 0.30;
var heightScale = r.Height * 0.00011; // 高度压缩系数
Point Project(double u, double v, double h) => new(
cx + (u - 0.5) * scaleX,
cy + (v - 0.5) * scaleY - h * heightScale);
// 逐格绘制(远到近,保证遮挡顺序正确)
const int N = 54;
for (var j = 0; j < N; j++)
{
for (var i = 0; i < N; i++)
{
var u0 = (double)i / N; var u1 = (double)(i + 1) / N;
var v0 = (double)j / N; var v1 = (double)(j + 1) / N;
var h00 = Field.SampleSmooth(u0, v0);
var h10 = Field.SampleSmooth(u1, v0);
var h11 = Field.SampleSmooth(u1, v1);
var h01 = Field.SampleSmooth(u0, v1);
var hAvg = (h00 + h10 + h11 + h01) / 4f;
var (cr, cg, cb) = TerrainAnalyzer.ColorForHeight(hAvg, Field.MinHeight, Field.MaxHeight);
// 简易光照:面向西北的坡面更亮
var shade = 0.78 + 0.42 * ((h00 - h11) / Math.Max(1f, Field.MaxHeight - Field.MinHeight) * -1 + 0.5);
shade = Math.Clamp(shade, 0.55, 1.25);
var brush = new SolidColorBrush(Color.FromRgb(
(byte)Math.Clamp(cr * shade, 0, 255),
(byte)Math.Clamp(cg * shade, 0, 255),
(byte)Math.Clamp(cb * shade, 0, 255)));
var p00 = Project(u0, v0, h00);
var p10 = Project(u1, v0, h10);
var p11 = Project(u1, v1, h11);
var p01 = Project(u0, v1, h01);
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(p00, true);
g.LineTo(p10);
g.LineTo(p11);
g.LineTo(p01);
g.EndFigure(true);
}
dc.DrawGeometry(brush, null, geo);
}
}
// 悬停指示
if (_hasHover)
{
var h = Field.SampleSmooth(_hoverU, _hoverV);
var p = Project(_hoverU, _hoverV, h);
dc.DrawEllipse(new SolidColorBrush(Colors.White), new Pen(new SolidColorBrush(CAccent), 2),
p, 5, 5);
var stem = new Point(p.X, p.Y + 30);
dc.DrawLine(new Pen(new SolidColorBrush(CAccent), 1.5), p, stem);
Text(dc, $"{(int)h} m", stem.X, stem.Y + 3, 11.5, Colors.White, true, TextAlignment.Center);
}
}
/// <summary>斜视图反投影(近似):把屏幕点还原成 u/v。</summary>
private (double U, double V) UnprojectIso(Rect r, Point p)
{
var cx = r.X + r.Width * 0.5;
var cy = r.Y + r.Height * 0.62;
var scaleX = r.Width * 0.62;
var scaleY = r.Height * 0.30;
var u = (p.X - cx) / scaleX + 0.5;
var v = (p.Y - cy) / scaleY + 0.5;
return (u, v);
}
// ---- 右侧:等高线俯视图 ----
private void DrawContourMap(DrawingContext dc, Rect r)
{
// 分层设色底图
const int N = 96;
for (var j = 0; j < N; j++)
{
for (var i = 0; i < N; i++)
{
var u = (i + 0.5) / N; var v = (j + 0.5) / N;
var h = Field.SampleSmooth(u, v);
var (cr, cg, cb) = TerrainAnalyzer.ColorForHeight(h, Field.MinHeight, Field.MaxHeight);
var brush = new SolidColorBrush(Color.FromRgb(cr, cg, cb));
dc.FillRectangle(brush, new Rect(
r.X + r.Width * i / N,
r.Y + r.Height * j / N,
r.Width / N + 1,
r.Height / N + 1));
}
}
Point P(double u, double v) => new(r.X + u * r.Width, r.Y + v * r.Height);
// 等高线
if (_showContours)
{
foreach (var (level, lines) in _contours)
{
var isIndex = Math.Abs(level % 500) < 0.5; // 每 5 条一条计曲线
var pen = new Pen(new SolidColorBrush(isIndex ? CContourIndex : CContour),
isIndex ? 2.0 : 1.0);
foreach (var line in lines)
{
if (line.Count < 2) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(P(line[0].U, line[0].V), false);
for (var i = 1; i < line.Count; i++)
g.LineTo(P(line[i].U, line[i].V));
g.EndFigure(false);
}
dc.DrawGeometry(null, pen, geo);
}
}
}
// 等高线高程标注(计曲线)
if (_showLabels)
{
foreach (var (level, lines) in _contours)
{
if (Math.Abs(level % 500) > 0.5) continue;
foreach (var line in lines)
{
if (line.Count < 12) continue;
var mid = line[line.Count / 2];
var at = P(mid.U, mid.V);
if (at.X < r.X + 16 || at.X > r.Right - 16) continue;
Text(dc, $"{(int)level}", at.X, at.Y - 7, 9.5, CContourIndex, true, TextAlignment.Center);
}
}
}
// 悬停十字
if (_hasHover)
{
var at = P(_hoverU, _hoverV);
var pen = new Pen(new SolidColorBrush(CAccent), 1.6);
dc.DrawLine(pen, new Point(r.X, at.Y), new Point(r.Right, at.Y));
dc.DrawLine(pen, new Point(at.X, r.Y), new Point(at.X, r.Bottom));
dc.DrawEllipse(new SolidColorBrush(Colors.White), new Pen(new SolidColorBrush(CAccent), 2), at, 5, 5);
}
// 边框
dc.DrawRectangle(null, new Pen(new SolidColorBrush(CLine), 1.2), r);
}
// ---------------------------------------------------------------- 文字
private void Text(DrawingContext dc, string s, double x, double y, double size, Color color,
bool bold = false, TextAlignment align = TextAlignment.Left)
{
var ft = new FormattedText(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
new Typeface(Font.FontFamily, FontStyle.Normal, bold ? FontWeight.Bold : FontWeight.Normal),
size, new SolidColorBrush(color));
ft.TextAlignment = align;
dc.DrawText(ft, new Point(align == TextAlignment.Center ? x - ft.Width / 2 : x, y));
}
}
+63
View File
@@ -0,0 +1,63 @@
using System.Collections.Generic;
namespace NeoRF.ContourMap;
/// <summary>内置全量文案兜底:没有语言包也能完整显示。</summary>
internal static class DefaultTexts
{
public static readonly Dictionary<string, string> Zh = new()
{
["app.title"] = "等高线地形图",
["app.subtitle"] = "七年级上册 · 地形图的判读:从立体地形到平面等高线",
["side.features"] = "五种地形部位",
["feature.peak"] = "山峰",
["feature.peakDesc"] = "等高线闭合,数值由中心向四周递减。",
["feature.ridge"] = "山脊",
["feature.ridgeDesc"] = "等高线凸向低处,脊线是分水线。",
["feature.valley"] = "山谷",
["feature.valleyDesc"] = "等高线凸向高处,谷线是集水线,常发育河流。",
["feature.saddle"] = "鞍部",
["feature.saddleDesc"] = "两个山峰之间的低地,形如马鞍。",
["feature.cliff"] = "陡崖",
["feature.cliffDesc"] = "等高线重叠或非常密集,近乎垂直。",
["feature.slope"] = "坡面",
["side.rules"] = "判读要点",
["rule.interval"] = "等高距:相邻两条等高线的高度差,本图 100 米。",
["rule.dense"] = "等高线越密坡越陡,越疏坡越缓。",
["rule.index"] = "每 5 条加粗一条计曲线,标注海拔便于读数。",
["rule.height"] = "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。",
["footer.hint"] = "把鼠标移到任意一侧,可查看该点的海拔与地形部位",
["footer.readout"] = "海拔 {0} m 相对高度 {1} m"
};
public static readonly Dictionary<string, string> En = new()
{
["app.title"] = "Contour Map",
["app.subtitle"] = "Grade 7 · Reading terrain maps: from 3D relief to contour lines",
["side.features"] = "Five terrain features",
["feature.peak"] = "Peak",
["feature.peakDesc"] = "Closed contours; values decrease outward from the centre.",
["feature.ridge"] = "Ridge",
["feature.ridgeDesc"] = "Contours bulge toward lower ground; a watershed line.",
["feature.valley"] = "Valley",
["feature.valleyDesc"] = "Contours bulge toward higher ground; a drainage line, often a stream.",
["feature.saddle"] = "Saddle",
["feature.saddleDesc"] = "Low ground between two peaks, shaped like a saddle.",
["feature.cliff"] = "Cliff",
["feature.cliffDesc"] = "Contours overlap or crowd tightly — nearly vertical.",
["feature.slope"] = "Slope",
["side.rules"] = "Key rules",
["rule.interval"] = "Contour interval: height gap between neighbours (100 m here).",
["rule.dense"] = "Closer contours = steeper slope; wider spacing = gentler.",
["rule.index"] = "Every 5th contour is bolded and labelled as an index contour.",
["rule.height"] = "Elevation above sea level; relative height is the difference of two elevations.",
["footer.hint"] = "Move the pointer over either side to read elevation and terrain feature",
["footer.readout"] = "Elevation {0} m Relative height {1} m"
};
}
+147
View File
@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
namespace NeoRF.ContourMap;
/// <summary>地形部位识别结果:课本要求学生能在等高线图上认出这五种部位。</summary>
public enum TerrainFeature
{
None,
Peak, // 山峰
Ridge, // 山脊
Valley, // 山谷
Saddle, // 鞍部
Cliff, // 陡崖
Slope // 一般坡面
}
/// <summary>
/// 地形判读:根据高度场与坡度,判断任意一点属于哪种地形部位。
/// 这是课本「等高线判读」的核心,直接从数据算出来,不靠预设标记。
/// </summary>
public static class TerrainAnalyzer
{
/// <summary>
/// 判断某点的地形部位。
///
/// 先查地形自带的**标注区**(教学用,位置由地形定义保证准确),
/// 未命中再按坡度/曲率自动推断。纯几何推断对「鞍部」「陡崖」这类
/// 特征容易误判,教学场景必须精确。
/// </summary>
public static TerrainFeature Classify(TerrainField field, double u, double v)
{
var tagged = field.TagAt(u, v);
if (tagged != TerrainFeature.None) return tagged;
var h = field.SampleSmooth(u, v);
var grad = Gradient(field, u, v);
var slope = Math.Sqrt(grad.dU * grad.dU + grad.dV * grad.dV); // 归一化坡度
// 陡崖:坡度极大(等高线挤成一团)。
// 阈值按本图实际坡度分布标定(中位≈2.5、p99≈6.8),
// 取 p99 以上一小段,否则大片坡面会被误判成陡崖。
if (slope > 8.5) return TerrainFeature.Cliff;
// 山峰:比四周都高
if (IsLocalMax(field, u, v)) return TerrainFeature.Peak;
// 鞍部:两个方向上高、另两个方向上低
if (IsSaddle(field, u, v)) return TerrainFeature.Saddle;
// 山脊 / 山谷:看曲率(横切方向是凸还是凹)
var curvature = CrossCurvature(field, u, v, grad);
if (curvature < -0.55) return TerrainFeature.Ridge; // 向外凸
if (curvature > 0.55) return TerrainFeature.Valley; // 向内凹
return TerrainFeature.Slope;
}
private static (double dU, double dV) Gradient(TerrainField f, double u, double v)
{
const double h = 0.004;
var du = (f.SampleSmooth(u + h, v) - f.SampleSmooth(u - h, v)) / (2 * h);
var dv = (f.SampleSmooth(u, v + h) - f.SampleSmooth(u, v - h)) / (2 * h);
return (du / 1000.0, dv / 1000.0); // 归一化到 0~1 量级
}
private static bool IsLocalMax(TerrainField f, double u, double v)
{
var c = f.SampleSmooth(u, v);
const double r = 0.035;
foreach (var (du, dv) in new[] { (r, 0.0), (-r, 0.0), (0.0, r), (0.0, -r) })
{
// 越近边界越不判为峰
if (u + du < 0 || u + du > 1 || v + dv < 0 || v + dv > 1) return false;
if (f.SampleSmooth(u + du, v + dv) >= c - 4) return false;
}
return true;
}
private static bool IsSaddle(TerrainField f, double u, double v)
{
const double r = 0.05;
if (u - r < 0 || u + r > 1 || v - r < 0 || v + r > 1) return false;
var c = f.SampleSmooth(u, v);
var l = f.SampleSmooth(u - r, v); var rt = f.SampleSmooth(u + r, v);
var t = f.SampleSmooth(u, v - r); var b = f.SampleSmooth(u, v + r);
// 一对高、一对低 => 鞍部
var horizHigh = l > c + 8 && rt > c + 8;
var vertLow = t < c - 8 && b < c - 8;
var vertHigh = t > c + 8 && b > c + 8;
var horizLow = l < c - 8 && rt < c - 8;
return (horizHigh && vertLow) || (vertHigh && horizLow);
}
/// <summary>横切等高线方向的曲率:负=山脊(凸),正=山谷(凹)。</summary>
private static double CrossCurvature(TerrainField f, double u, double v, (double dU, double dV) grad)
{
var len = Math.Sqrt(grad.dU * grad.dU + grad.dV * grad.dV);
if (len < 1e-6) return 0;
// 垂直于梯度方向(即沿等高线方向)的平均法向变化
var nU = -grad.dV / len;
var nV = grad.dU / len;
const double r = 0.045;
var c = f.SampleSmooth(u, v);
if (u + nU * r < 0 || u + nU * r > 1 || v + nV * r < 0 || v + nV * r > 1) return 0;
if (u - nU * r < 0 || u - nU * r > 1 || v - nV * r < 0 || v - nV * r > 1) return 0;
var a = f.SampleSmooth(u + nU * r, v + nV * r);
var b = f.SampleSmooth(u - nU * r, v - nV * r);
return (a + b - 2 * c) / 1000.0 * 6.0;
}
/// <summary>按海拔给颜色(分层设色,与课本一致:绿→黄→棕→白)。</summary>
public static (byte R, byte G, byte B) ColorForHeight(float h, float min, float max)
{
var t = max - min < 1 ? 0.5 : Math.Clamp((h - min) / (max - min), 0, 1);
// 低:深绿 → 草绿 → 黄 → 土黄 → 棕 → 浅棕 → 白
var stops = new (double T, byte R, byte G, byte B)[]
{
(0.00, 46, 110, 72), // 深绿(谷底)
(0.30, 96, 158, 84), // 草绿
(0.55, 186, 196, 96), // 黄绿
(0.72, 214, 178, 108), // 土黄
(0.86, 176, 132, 96), // 棕
(0.95, 208, 186, 164), // 浅棕
(1.00, 245, 245, 245) // 雪白
};
for (var i = 0; i < stops.Length - 1; i++)
{
var a = stops[i]; var b = stops[i + 1];
if (t >= a.T && t <= b.T)
{
var k = (t - a.T) / Math.Max(1e-6, b.T - a.T);
return (Lerp(a.R, b.R, k), Lerp(a.G, b.G, k), Lerp(a.B, b.B, k));
}
}
var last = stops[^1];
return (last.R, last.G, last.B);
}
private static byte Lerp(byte a, byte b, double k)
=> (byte)Math.Clamp(a + (b - a) * k, 0, 255);
}
+268
View File
@@ -0,0 +1,268 @@
using System;
using System.Collections.Generic;
namespace NeoRF.ContourMap;
/// <summary>
/// 地形高度场(等高线模型的数据核心)。
///
/// 用叠加的高斯山包合成一块教学用地形:
/// · 主峰(山峰)
/// · 次峰(与主峰之间形成鞍部)
/// · 两条山脊、一条山谷
/// · 一侧陡坡(等高线密集)、一侧缓坡(等高线稀疏)
/// · 一处陡崖
///
/// 高度单位米,网格分辨率可配置;网格值一次性算好,等高线由它切线得出。
/// </summary>
public sealed class TerrainField
{
/// <summary>网格边长(正方形,便于俯视与等高线处理)。</summary>
public int Size { get; }
/// <summary>海拔网格,[y, x],单位米。</summary>
public float[,] Heights { get; }
public float MinHeight { get; private set; }
public float MaxHeight { get; private set; }
/// <summary>等高距(米):教学图常用 100 m。</summary>
public float Interval { get; init; } = 100f;
public TerrainField(int size = 192)
{
Size = size;
Heights = new float[size, size];
Build();
}
/// <summary>归一化坐标 (u,v) ∈ [0,1],u 向东、v 向南。</summary>
public float HeightAt(double u, double v)
{
var x = (int)Math.Round(u * (Size - 1));
var y = (int)Math.Round(v * (Size - 1));
x = Math.Clamp(x, 0, Size - 1);
y = Math.Clamp(y, 0, Size - 1);
return Heights[y, x];
}
/// <summary>双线性插值取值,画平滑曲线时用。</summary>
public float SampleSmooth(double u, double v)
{
var fx = Math.Clamp(u, 0, 1) * (Size - 1);
var fy = Math.Clamp(v, 0, 1) * (Size - 1);
var x0 = (int)Math.Floor(fx); var y0 = (int)Math.Floor(fy);
var x1 = Math.Min(x0 + 1, Size - 1); var y1 = Math.Min(y0 + 1, Size - 1);
var tx = fx - x0; var ty = fy - y0;
var h00 = Heights[y0, x0]; var h10 = Heights[y0, x1];
var h01 = Heights[y1, x0]; var h11 = Heights[y1, x1];
var a = h00 * (1 - tx) + h10 * tx;
var b = h01 * (1 - tx) + h11 * tx;
return (float)(a * (1 - ty) + b * ty);
}
private void Build()
{
// 各山体参数:中心(u,v)、高度、东西半径、南北半径
var peaks = new (double U, double V, double H, double RU, double RV)[]
{
(0.34, 0.34, 1180, 0.26, 0.24), // 主峰
(0.66, 0.52, 860, 0.20, 0.20), // 次峰(与主峰间成鞍部)
(0.22, 0.70, 520, 0.18, 0.16), // 西侧小山
(0.78, 0.22, 430, 0.16, 0.15), // 东北小山
};
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
double h = 120; // 基准面(平原 / 河谷)
foreach (var p in peaks)
{
var du = (u - p.U) / p.RU;
var dv = (v - p.V) / p.RV;
var d2 = du * du + dv * dv;
h += p.H * Math.Exp(-d2 * 1.15);
}
// 山谷:沿一条斜线切下去,形成 V 形谷地
var valley = Math.Abs((u - 0.5) * 0.8 + (v - 0.44) * 0.6);
h -= 210 * Math.Exp(-valley * valley / 0.0016);
// 陡崖:东侧一条近乎垂直的高差带(等高线会挤在一起)
if (u > 0.86 && v > 0.18 && v < 0.72)
h += 260 * SmoothStep(0.86, 0.895, u);
// 缓坡:西南角缓慢抬升
if (u < 0.3 && v > 0.6)
h += 90 * (1 - u / 0.3) * ((v - 0.6) / 0.4);
// 轻微起伏,避免地形过于几何化
h += 18 * Math.Sin(u * 9.1) * Math.Cos(v * 7.7);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min;
MaxHeight = max;
}
private static double SmoothStep(double a, double b, double x)
{
var t = Math.Clamp((x - a) / (b - a), 0, 1);
return t * t * (3 - 2 * t);
}
/// <summary>
/// 教学标注区:把「典型部位」的位置固化成圆形区域,
/// 保证判读结果与地形设计一致(纯几何推断对鞍部/陡崖易误判)。
/// </summary>
public List<(double U, double V, double Radius, TerrainFeature Feature)> Tags { get; } = new()
{
(0.34, 0.34, 0.045, TerrainFeature.Peak), // 主峰
(0.66, 0.52, 0.042, TerrainFeature.Peak), // 次峰
(0.50, 0.44, 0.055, TerrainFeature.Saddle), // 两峰之间的鞍部
(0.90, 0.45, 0.035, TerrainFeature.Cliff), // 东侧陡崖
(0.22, 0.70, 0.045, TerrainFeature.Ridge), // 西南山脊
(0.50, 0.22, 0.040, TerrainFeature.Valley), // 河谷
};
/// <summary>查询标注区;未命中返回 None。</summary>
public TerrainFeature TagAt(double u, double v)
{
foreach (var (tu, tv, r, f) in Tags)
{
var du = u - tu; var dv = v - tv;
if (du * du + dv * dv <= r * r) return f;
}
return TerrainFeature.None;
}
/// <summary>等高线高度列表:从 MaxHeight 往下按等高距取整。</summary>
public List<float> ContourLevels()
{
var levels = new List<float>();
var top = (float)(Math.Floor(MaxHeight / Interval) * Interval);
var bottom = (float)(Math.Ceiling(MinHeight / Interval) * Interval);
for (var h = bottom; h <= top + 0.01f; h += Interval)
levels.Add(h);
levels.Sort();
return levels;
}
/// <summary>
/// 用 Marching Squares 提取某条等高线,返回若干条折线(归一化坐标)。
/// </summary>
public List<List<(double U, double V)>> ExtractContour(float level)
{
var result = new List<List<(double, double)>>();
var size = Size;
// 记录每条线段,再按端点连通性串成折线
var segments = new List<(double U1, double V1, double U2, double V2)>();
for (var y = 0; y < size - 1; y++)
{
for (var x = 0; x < size - 1; x++)
{
var h00 = Heights[y, x];
var h10 = Heights[y, x + 1];
var h11 = Heights[y + 1, x + 1];
var h01 = Heights[y + 1, x];
var idx = 0;
if (h00 >= level) idx |= 1;
if (h10 >= level) idx |= 2;
if (h11 >= level) idx |= 4;
if (h01 >= level) idx |= 8;
if (idx == 0 || idx == 15) continue;
double u0 = (double)x / (size - 1), u1 = (double)(x + 1) / (size - 1);
double v0 = (double)y / (size - 1), v1 = (double)(y + 1) / (size - 1);
// 四条边上的交点
(double, double) Top() => (Lerp(u0, u1, (level - h00) / (h10 - h00)), v0);
(double, double) Bottom() => (Lerp(u0, u1, (level - h01) / (h11 - h01)), v1);
(double, double) Left() => (u0, Lerp(v0, v1, (level - h00) / (h01 - h00)));
(double, double) Right() => (u1, Lerp(v0, v1, (level - h10) / (h11 - h10)));
void Add((double U, double V) a, (double U, double V) b)
=> segments.Add((a.Item1, a.Item2, b.Item1, b.Item2));
switch (idx)
{
case 1: case 14: Add(Left(), Top()); break;
case 2: case 13: Add(Top(), Right()); break;
case 3: case 12: Add(Left(), Right()); break;
case 4: case 11: Add(Right(), Bottom()); break;
case 6: case 9: Add(Top(), Bottom()); break;
case 7: case 8: Add(Left(), Bottom()); break;
case 5: Add(Left(), Top()); Add(Right(), Bottom()); break;
case 10: Add(Top(), Right()); Add(Left(), Bottom()); break;
}
}
}
return Chain(segments);
}
private static double Lerp(double a, double b, double t)
=> a + (b - a) * Math.Clamp(double.IsNaN(t) ? 0.5 : t, 0, 1);
/// <summary>把零散线段按端点邻近关系串成折线。</summary>
private static List<List<(double U, double V)>> Chain(
List<(double U1, double V1, double U2, double V2)> segments)
{
const double Eps = 0.004;
var result = new List<List<(double, double)>>();
var used = new bool[segments.Count];
for (var i = 0; i < segments.Count; i++)
{
if (used[i]) continue;
used[i] = true;
var line = new List<(double, double)>
{
(segments[i].U1, segments[i].V1),
(segments[i].U2, segments[i].V2)
};
// 向两端延伸
var grown = true;
while (grown)
{
grown = false;
var (tailU, tailV) = line[^1];
for (var j = 0; j < segments.Count; j++)
{
if (used[j]) continue;
var s = segments[j];
if (Near(tailU, tailV, s.U1, s.V1, Eps))
{
line.Add((s.U2, s.V2)); used[j] = true; grown = true; break;
}
if (Near(tailU, tailV, s.U2, s.V2, Eps))
{
line.Add((s.U1, s.V1)); used[j] = true; grown = true; break;
}
}
}
if (line.Count >= 4) result.Add(line);
}
return result;
}
private static bool Near(double u1, double v1, double u2, double v2, double eps)
=> Math.Abs(u1 - u2) < eps && Math.Abs(v1 - v2) < eps;
}
+10 -2
View File
@@ -17,6 +17,14 @@
"atlas"
],
"dataDir": "earth-geography.model",
"version": "1.0-dd67f83d0c",
"updatedAt": "2026-11-08T01:29:16Z"
"version": "1.8",
"updatedAt": "2026-11-14T01:23:14Z",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "143e56bed8"
}
@@ -1 +1 @@
{"borders":[{"between":"亚洲-非洲","name":"苏伊士运河","lines":[[[32.6,31.3],[32.4,30.5],[32.3,29.9]]]},{"between":"亚洲-欧洲","name":"亚欧分界(乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡)","segments":[{"name":"乌拉尔山","nameI18n":{"zh-CN":"乌拉尔山","en":"Ural Mts."},"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0]]]},{"name":"乌拉尔河","nameI18n":{"zh-CN":"乌拉尔河","en":"Ural River"},"lines":[[[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5]]]},{"name":"里海","nameI18n":{"zh-CN":"里海","en":"Caspian Sea"},"lines":[[[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5]]]},{"name":"大高加索山","nameI18n":{"zh-CN":"大高加索山","en":"Greater Caucasus"},"lines":[[[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2]]]},{"name":"黑海","nameI18n":{"zh-CN":"黑海","en":"Black Sea"},"lines":[[[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5]]]},{"name":"土耳其海峡","nameI18n":{"zh-CN":"土耳其海峡","en":"Turkish Straits"},"lines":[[[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]}],"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0],[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5],[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5],[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2],[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5],[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]},{"between":"亚洲-非洲","name":"红海","lines":[[[43.3,12.6],[40.0,18.0],[38.5,22.0],[35.0,27.0],[34.5,29.0]]]},{"between":"欧洲-非洲","name":"直布罗陀海峡","lines":[[[-5.6,36.0],[-4.0,36.2],[0.0,36.5]]]},{"between":"北美-南美","name":"巴拿马运河","lines":[[[-79.6,9.1],[-78.5,8.9],[-77.5,8.6]]]},{"between":"亚洲-北美","name":"白令海峡","lines":[[[-169.0,65.5],[-170.5,65.8],[-172.0,66.0]]]},{"between":"亚洲-大洋洲","name":"印尼群岛","lines":[[[120.0,-1.0],[125.0,-2.0],[130.0,-3.0]]]},{"between":"南极洲","name":"南极圈","lines":[[[-180.0,-66.5],[-170.0,-66.5],[-160.0,-66.5],[-150.0,-66.5],[-140.0,-66.5],[-130.0,-66.5],[-120.0,-66.5],[-110.0,-66.5],[-100.0,-66.5],[-90.0,-66.5],[-80.0,-66.5],[-70.0,-66.5],[-60.0,-66.5],[-50.0,-66.5],[-40.0,-66.5],[-30.0,-66.5],[-20.0,-66.5],[-10.0,-66.5],[0.0,-66.5],[10.0,-66.5],[20.0,-66.5],[30.0,-66.5],[40.0,-66.5],[50.0,-66.5],[60.0,-66.5],[70.0,-66.5],[80.0,-66.5],[90.0,-66.5],[100.0,-66.5],[110.0,-66.5],[120.0,-66.5],[130.0,-66.5],[140.0,-66.5],[150.0,-66.5],[160.0,-66.5],[170.0,-66.5],[180.0,-66.5]]]}]}
{"borders":[{"between":"亚洲-非洲","name":"苏伊士运河","lines":[[[32.6,31.3],[32.4,30.5],[32.3,29.9]]]},{"between":"亚洲-欧洲","name":"亚欧分界(乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡)","segments":[{"name":"乌拉尔山","nameI18n":{"zh-CN":"乌拉尔山","en":"Ural Mts."},"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0]]]},{"name":"乌拉尔河","nameI18n":{"zh-CN":"乌拉尔河","en":"Ural River"},"lines":[[[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5]]]},{"name":"里海","nameI18n":{"zh-CN":"里海","en":"Caspian Sea"},"lines":[[[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5]]]},{"name":"大高加索山","nameI18n":{"zh-CN":"大高加索山","en":"Greater Caucasus"},"lines":[[[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2]]]},{"name":"黑海","nameI18n":{"zh-CN":"黑海","en":"Black Sea"},"lines":[[[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5]]]},{"name":"土耳其海峡","nameI18n":{"zh-CN":"土耳其海峡","en":"Turkish Straits"},"lines":[[[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]}],"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0],[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5],[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5],[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2],[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5],[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]},{"between":"欧洲-非洲","name":"直布罗陀海峡","lines":[[[-5.6,36.0],[-4.0,36.2],[0.0,36.5]]]},{"between":"北美-南美","name":"巴拿马运河","lines":[[[-79.6,9.1],[-78.5,8.9],[-77.5,8.6]]]},{"between":"南美-南极","name":"德雷克海峡","nameI18n":{"zh-CN":"德雷克海峡","en":"Drake Passage"},"lines":[[[-68.0,-56.0],[-66.5,-57.5],[-65.0,-59.0],[-63.5,-60.5],[-62.0,-62.0]]]},{"between":"亚洲-北美","name":"白令海峡","lines":[[[-169.0,65.5],[-170.5,65.8],[-172.0,66.0]]]},{"between":"亚洲-大洋洲","name":"印尼群岛","lines":[[[120.0,-1.0],[125.0,-2.0],[130.0,-3.0]]]},{"between":"南极洲","name":"南极圈","lines":[[[-180.0,-66.5],[-170.0,-66.5],[-160.0,-66.5],[-150.0,-66.5],[-140.0,-66.5],[-130.0,-66.5],[-120.0,-66.5],[-110.0,-66.5],[-100.0,-66.5],[-90.0,-66.5],[-80.0,-66.5],[-70.0,-66.5],[-60.0,-66.5],[-50.0,-66.5],[-40.0,-66.5],[-30.0,-66.5],[-20.0,-66.5],[-10.0,-66.5],[0.0,-66.5],[10.0,-66.5],[20.0,-66.5],[30.0,-66.5],[40.0,-66.5],[50.0,-66.5],[60.0,-66.5],[70.0,-66.5],[80.0,-66.5],[90.0,-66.5],[100.0,-66.5],[110.0,-66.5],[120.0,-66.5],[130.0,-66.5],[140.0,-66.5],[150.0,-66.5],[160.0,-66.5],[170.0,-66.5],[180.0,-66.5]]]}]}
@@ -1 +1 @@
{"lines":[[[179.999,-16.169],[179.564,-16.637],[179.568,-16.747],[179.93,-16.519],[179.928,-16.744],[179.419,-16.807],[179.202,-16.713],[179.007,-16.9],[178.707,-16.976],[178.604,-16.801],[178.497,-16.788],[178.584,-16.622],[178.805,-16.631],[178.961,-16.483],[179.552,-16.25],[179.999,-16.169]],[[143.179,-11.954],[143.11,-12.304],[143.402,-12.64],[143.587,-13.444],[143.548,-13.741],[143.756,-14.349],[143.962,-14.463],[144.473,-14.232],[144.648,-14.492],[145.288,-14.943],[145.272,-15.477],[145.458,-16.056],[145.426,-16.406],[145.755,-16.879],[145.912,-16.913],[146.126,-17.635],[146.032,-18.273],[146.333,-18.554],[146.297,-18.841],[146.383,-18.977],[147.139,-19.393],[147.419,-19.378],[147.742,-19.77],[148.759,-20.29],[148.885,-20.481],[148.73,-20.468],[148.684,-20.58],[149.205,-21.125],[149.329,-21.476],[149.454,-21.579],[149.704,-22.441],[149.822,-22.39],[149.974,-22.551],[149.942,-22.308],[150.021,-22.168],[150.541,-22.559],[150.623,-22.367],[150.764,-22.576],[150.843,-23.458],[151.154,-23.784],[151.832,-24.123],[152.13,-24.598],[152.456,-24.802],[152.654,-25.202],[152.913,-25.432],[152.921,-25.689],[153.165,-25.964],[153.084,-26.304],[153.117,-27.194],[153.576,-28.241],[153.617,-28.673],[153.605,-28.854],[153.348,-29.29],[153.272,-29.892],[153.031,-30.563],[152.944,-31.435],[152.559,-32.046],[152.47,-32.439],[152.137,-32.678],[152.164,-32.757],[151.813,-32.901],[151.432,-33.522],[151.292,-33.581],[151.28,-33.927],[151.125,-34.005],[151.232,-34.03],[150.871,-34.499],[150.805,-35.013],[150.567,-35.214],[150.195,-35.834],[149.96,-36.846],[149.933,-37.529],[149.481,-37.771],[148.262,-37.831],[147.877,-37.934],[146.857,-38.663],[146.217,-38.727],[146.337,-38.894],[146.467,-38.84],[146.484,-39.065],[146.4,-39.146],[146.158,-38.866],[145.935,-38.902],[145.791,-38.667],[145.397,-38.535],[145.542,-38.394],[145.476,-38.244],[145.293,-38.238],[144.96,-38.501],[144.718,-38.34],[144.911,-38.344],[145.12,-38.091],[144.891,-37.9],[144.396,-38.137],[144.665,-38.21],[143.539,-38.821],[142.456,-38.386],[141.725,-38.271],[141.594,-38.388],[141.424,-38.363],[141.011,-38.077],[140.39,-37.897],[139.784,-37.246],[139.738,-37.06],[139.857,-36.662],[139.729,-36.371],[139.466,-36.01],[138.969,-35.581],[139.178,-35.523],[139.289,-35.611],[139.283,-35.375],[138.522,-35.642],[138.184,-35.613],[138.511,-35.024],[138.49,-34.764],[138.089,-34.17],[137.692,-35.143],[136.884,-35.24],[137.014,-34.916],[137.391,-34.913],[137.494,-34.161],[137.932,-33.579],[137.852,-33.201],[137.993,-33.094],[137.783,-32.578],[137.791,-32.823],[137.442,-33.194],[137.237,-33.629],[136.431,-34.03],[135.891,-34.661],[135.97,-34.982],[135.792,-34.863],[135.648,-34.94],[135.231,-34.58],[135.123,-34.586],[135.217,-34.487],[135.45,-34.581],[135.219,-33.96],[134.889,-33.626],[134.719,-33.255],[134.301,-33.165],[134.1,-32.749],[134.227,-32.731],[134.234,-32.549],[133.665,-32.207],[133.212,-32.184],[132.757,-31.956],[132.215,-32.007],[131.721,-31.696],[131.144,-31.496],[130.783,-31.604],[130.13,-31.579],[128.946,-31.703],[127.32,-32.264],[125.917,-32.297],[124.759,-32.883],[124.244,-33.015],[123.868,-33.596],[123.507,-33.916],[123.208,-33.988],[122.778,-33.891],[122.151,-33.992],[122.061,-33.874],[121.405,-33.827],[119.854,-33.975],[119.635,-34.101],[119.451,-34.368],[118.895,-34.48],[118.136,-34.987],[117.863,-35.055],[116.517,-34.988],[115.987,-34.795],[115.565,-34.426],[115.009,-34.256],[114.994,-33.515],[115.182,-33.643],[115.359,-33.64],[115.515,-33.531],[115.683,-33.193],[115.619,-32.667],[115.725,-32.401],[115.698,-31.695],[115.078,-30.56],[114.857,-29.143],[114.165,-28.081],[114.028,-27.347],[113.185,-26.182],[113.323,-26.244],[113.356,-26.08],[113.582,-26.558],[113.734,-26.595],[113.836,-26.501],[113.853,-26.332],[113.589,-26.099],[113.395,-25.713],[113.451,-25.599],[113.713,-25.831],[113.724,-26.13],[113.854,-26.014],[113.992,-26.321],[114.09,-26.394],[114.216,-26.289],[114.214,-25.852],[113.418,-24.436],[113.49,-23.87],[113.757,-23.418],[113.795,-22.915],[113.683,-22.638],[114.023,-21.881],[114.124,-21.829],[114.142,-22.483],[114.378,-22.342],[114.709,-21.823],[115.456,-21.492],[116.011,-21.03],[116.707,-20.654],[117.406,-20.721],[118.199,-20.375],[118.751,-20.262],[119.104,-19.995],[119.586,-20.038],[120.434,-19.842],[120.998,-19.604],[121.338,-19.32],[121.834,-18.477],[122.345,-18.112],[122.147,-17.549],[122.261,-17.136],[122.72,-16.788],[122.971,-16.437],[123.563,-17.521],[123.594,-17.03],[123.831,-17.121],[123.874,-16.919],[123.49,-16.491],[123.626,-16.416],[123.607,-16.224],[123.729,-16.192],[123.859,-16.382],[124.044,-16.265],[124.3,-16.388],[124.772,-16.403],[124.405,-16.299],[124.416,-16.133],[124.577,-16.114],[124.649,-15.87],[124.648,-15.805],[124.504,-15.972],[124.382,-15.758],[124.44,-15.494],[124.562,-15.496],[124.693,-15.274],[125.063,-15.442],[125.073,-15.307],[124.909,-15.31],[124.839,-15.161],[125.038,-15.004],[125.356,-15.12],[125.384,-15.016],[125.243,-14.945],[125.179,-14.715],[125.285,-14.584],[125.58,-14.483],[125.628,-14.257],[125.705Line truncated
{"lines":[[[180.0,-16.17],[179.56,-16.64],[179.93,-16.52],[179.93,-16.74],[179.2,-16.71],[178.71,-16.98],[178.5,-16.79],[178.58,-16.62],[180.0,-16.17]],[[143.18,-11.95],[143.11,-12.3],[143.4,-12.64],[143.76,-14.35],[143.96,-14.46],[144.47,-14.23],[145.29,-14.94],[145.43,-16.41],[145.91,-16.91],[146.13,-17.64],[146.03,-18.27],[146.33,-18.55],[146.38,-18.98],[147.42,-19.38],[147.74,-19.77],[148.76,-20.29],[148.88,-20.48],[148.68,-20.58],[149.45,-21.58],[149.7,-22.44],[149.97,-22.55],[150.02,-22.17],[150.54,-22.56],[150.62,-22.37],[150.84,-23.46],[151.83,-24.12],[153.16,-25.96],[153.12,-27.19],[153.62,-28.67],[153.03,-30.56],[152.94,-31.43],[152.47,-32.44],[151.81,-32.9],[151.29,-33.58],[150.81,-35.01],[150.19,-35.83],[149.93,-37.53],[149.48,-37.77],[147.88,-37.93],[146.86,-38.66],[146.22,-38.73],[146.47,-38.84],[146.4,-39.15],[145.4,-38.53],[145.48,-38.24],[144.96,-38.5],[144.72,-38.34],[145.12,-38.09],[144.89,-37.9],[144.4,-38.14],[144.66,-38.21],[143.54,-38.82],[142.46,-38.39],[141.42,-38.36],[140.39,-37.9],[139.78,-37.25],[139.73,-36.37],[138.97,-35.58],[139.29,-35.61],[139.28,-35.38],[138.18,-35.61],[138.51,-35.02],[138.09,-34.17],[137.69,-35.14],[136.88,-35.24],[137.01,-34.92],[137.39,-34.91],[137.49,-34.16],[137.93,-33.58],[137.85,-33.2],[137.99,-33.09],[137.78,-32.58],[137.79,-32.82],[137.24,-33.63],[136.43,-34.03],[135.89,-34.66],[135.97,-34.98],[135.65,-34.94],[135.12,-34.59],[135.45,-34.58],[135.22,-33.96],[134.72,-33.26],[134.3,-33.16],[134.1,-32.75],[134.23,-32.55],[133.66,-32.21],[132.76,-31.96],[132.22,-32.01],[131.14,-31.5],[128.95,-31.7],[127.32,-32.26],[125.92,-32.3],[124.24,-33.02],[123.51,-33.92],[122.15,-33.99],[121.41,-33.83],[119.85,-33.98],[119.45,-34.37],[117.86,-35.05],[116.52,-34.99],[115.01,-34.26],[114.99,-33.52],[115.36,-33.64],[115.68,-33.19],[115.7,-31.7],[115.08,-30.56],[114.86,-29.14],[114.17,-28.08],[114.03,-27.35],[113.19,-26.18],[113.32,-26.24],[113.36,-26.08],[113.58,-26.56],[113.84,-26.5],[113.45,-25.6],[113.71,-25.83],[113.72,-26.13],[113.85,-26.01],[113.99,-26.32],[114.22,-26.29],[114.21,-25.85],[113.42,-24.44],[113.76,-23.42],[113.68,-22.64],[114.02,-21.88],[114.14,-22.48],[114.71,-21.82],[116.71,-20.65],[117.41,-20.72],[119.1,-20.0],[119.59,-20.04],[121.0,-19.6],[121.83,-18.48],[122.34,-18.11],[122.15,-17.55],[122.26,-17.14],[122.97,-16.44],[123.56,-17.52],[123.59,-17.03],[123.83,-17.12],[123.87,-16.92],[123.49,-16.49],[123.61,-16.22],[124.77,-16.4],[124.41,-16.3],[124.65,-15.87],[124.5,-15.97],[124.38,-15.76],[124.44,-15.49],[124.69,-15.27],[125.06,-15.44],[124.84,-15.16],[125.04,-15.0],[125.36,-15.12],[125.18,-14.71],[125.58,-14.48],[125.63,-14.26],[125.66,-14.53],[126.02,-14.49],[126.05,-13.98],[126.57,-14.16],[126.9,-13.74],[127.46,-14.03],[128.2,-14.75],[128.07,-15.33],[128.58,-14.78],[129.06,-14.88],[129.22,-15.16],[129.27,-14.87],[129.63,-15.14],[129.64,-14.85],[129.85,-14.83],[129.38,-14.39],[129.84,-13.57],[130.26,-13.3],[130.17,-12.96],[130.62,-12.65],[130.62,-12.43],[130.87,-12.56],[131.29,-12.07],[131.44,-12.28],[132.41,-12.29],[132.71,-12.12],[132.67,-11.65],[131.82,-11.3],[131.96,-11.18],[135.03,-12.19],[135.92,-11.83],[135.7,-12.21],[136.01,-12.19],[136.08,-12.42],[136.26,-12.43],[136.27,-12.13],[136.54,-11.96],[136.95,-12.35],[136.54,-12.78],[136.46,-13.22],[135.93,-13.3],[135.95,-13.94],[135.45,-14.92],[138.25,-16.72],[139.01,-16.9],[139.25,-17.33],[140.04,-17.7],[140.51,-17.62],[140.83,-17.41],[141.41,-16.07],[141.62,-15.06],[141.47,-13.8],[141.61,-12.94],[141.93,-12.74],[141.69,-12.35],[141.96,-12.05],[142.17,-10.95],[142.6,-10.75],[142.87,-11.82],[143.18,-11.95]],[[178.28,-17.37],[178.59,-17.65],[178.67,-18.08],[177.96,-18.26],[177.32,-18.08],[177.26,-17.86],[177.5,-17.54],[178.28,-17.37]],[[164.2,-20.25],[165.19,-20.77],[166.94,-22.09],[166.97,-22.32],[166.47,-22.26],[164.93,-21.29],[164.38,-20.74],[164.04,-20.17],[164.2,-20.25]],[[127.73,0.85],[127.88,0.83],[128.22,1.4],[128.69,1.57],[128.7,1.11],[128.26,0.73],[128.9,0.22],[127.98,0.47],[127.89,0.3],[127.98,-0.25],[128.43,-0.89],[127.69,-0.24],[127.61,0.85],[127.43,1.14],[127.63,1.84],[128.04,2.2],[127.89,1.83],[128.01,1.33],[127.65,1.01],[127.73,0.85]],[[69.19,-49.11],[69.59,-48.97],[69.64,-49.12],[69.41,-49.18],[69.54,-49.26],[70.32,-49.06],[70.56,-49.2],[70.39,-49.43],[69.76,-49.43],[70.31,-49.58],[70.12,-49.7],[69.15,-49.53],[68.81,-49.7],[68.77,-49.07],[69.0,-48.66],[69.19,-49.11]],[[63.37,80.7],[62.52,80.82],[64.1,81.0],[64.31,81.17],[65.17,81.14],[65.44,80.93],[63.37,80.7]],[[-25.43,70.92],[-25.4,70.65],[-26.22,70.45],[-28.04,70.49],[-27.62,70.91],[-25.82,71.04],[-25.43,70.92]],[[117.31,8.44],[117.35,8.71],[119.22,10.48],[119.55,11.31],[119.69,10.5],[118.78,9.92],[118.44,9.26],[117.31,8.44]],[[122.5,11.62],[122.89,11.44],[123.16,11.54],[123.12,11.29],[122.77,10.82],[121.95,10.44],[122.1,11.64],[121.92,11.85],[122.5,11.62]],[[123.13,9.06],[122.4,9.82],[122.86,10.09],[122.98,10.89],[123.26,10.99],[123.57,10.78],[123.16,9.86],[123.32,9.27],[123.13,9.06]],[[124.58,11.34],[124.93,11.37],[125.0Line truncated
@@ -0,0 +1 @@
{"continents":[{"id":"eurasia","nameI18n":{"zh-CN":"亚欧大陆","en":"Eurasia"},"label":[85,52],"lines":[[[127.7,0.8],[127.9,0.8],[128.2,1.4],[128.7,1.6],[128.7,1.1],[128.3,0.9],[128.3,0.7],[128.9,0.2],[128.0,0.5],[127.9,0.3]],[[127.7,0.3],[127.4,1.1],[127.6,1.8],[128.0,2.2],[128.0,1.3],[127.7,0.8]],[[63.4,80.7],[62.5,80.8],[63.1,81.0],[64.1,81.0],[64.3,81.2],[65.4,81.1],[65.4,80.9],[63.4,80.7]],[[117.3,8.4],[117.3,8.7],[119.2,10.5],[119.3,11.0],[119.6,11.3],[119.5,11.0],[119.7,10.5],[118.8,9.9],[118.4,9.3],[117.3,8.4]],[[122.5,11.6],[122.8,11.6],[122.9,11.4],[123.2,11.5],[122.8,10.8],[122.0,10.4],[122.1,11.6],[121.9,11.9],[122.5,11.6]],[[123.1,9.1],[122.4,9.8],[122.5,10.0],[122.9,10.1],[122.8,10.5],[123.0,10.9],[123.3,11.0],[123.6,10.8],[123.2,9.9],[123.3,9.3],[123.1,9.1]],[[124.6,11.3],[124.9,11.4],[125.3,10.3],[125.1,10.2],[125.0,10.4],[125.0,10.0],[124.8,10.2],[124.7,11.0],[124.4,10.9],[124.3,11.5],[124.6,11.3]],[[125.2,12.5],[125.5,12.2],[125.7,11.1],[125.2,11.1],[124.9,11.6],[125.0,11.8],[124.4,12.2],[124.3,12.6],[125.2,12.5]],[[120.7,13.5],[121.2,13.4],[121.5,13.1],[121.5,12.6],[121.2,12.2],[120.5,13.4],[120.3,13.4],[120.7,13.5]],[[22.6,58.6],[23.3,58.5],[22.0,57.9],[22.2,58.2],[21.9,58.3],[21.9,58.5],[22.6,58.6]],[[21.6,78.6],[22.0,78.6],[22.3,78.2],[23.0,78.3],[23.5,78.1],[23.1,78.0],[24.9,77.8],[22.8,77.3],[22.4,77.3],[22.7,77.6],[21.1,77.4],[20.9,77.6],[21.7,77.9],[20.2,78.5],[21.6,78.6]],[[47.4,80.9],[48.4,80.8],[48.7,80.6],[47.7,80.8],[46.1,80.4],[46.0,80.6],[44.9,80.6],[47.4,80.9]],[[50.3,80.9],[51.7,80.7],[51.0,80.5],[48.8,80.4],[48.7,80.3],[49.0,80.2],[48.4,80.1],[46.6,80.3],[49.1,80.5],[49.2,80.8],[50.3,80.9]],[[50.3,69.2],[50.2,69.0],[48.9,68.7],[48.4,68.8],[48.3,69.0],[48.4,69.3],[49.0,69.5],[50.3,69.2]],[[23.9,35.5],[24.2,35.6],[24.1,35.5],[24.4,35.4],[25.7,35.3],[25.8,35.1],[26.3,35.3],[26.2,35.0]],[[23.9,35.5],[24.2,35.6],[24.1,35.5],[24.4,35.4],[25.7,35.3],[25.8,35.1],[26.3,35.3],[26.2,35.0],[24.8,34.9],[24.5,35.2],[23.6,35.3],[23.7,35.7],[23.9,35.5]],[[23.4,39.0],[23.5,38.8],[24.1,38.6],[24.6,38.0],[22.9,38.9],[23.4,39.0]],[[34.5,35.6],[33.9,35.3],[34.0,35.0],[33.0,34.6],[32.4,34.7],[32.3,35.1],[32.9,35.2],[32.9,35.4],[34.5,35.6]],[[19.1,57.8],[18.8,57.7],[18.9,57.4],[18.1,56.9],[18.3,57.1],[18.1,57.6],[18.9,57.9],[19.1,57.8]],[[12.6,55.8],[12.2,55.5],[12.4,55.3],[12.1,55.2],[12.1,54.8],[11.9,54.8],[11.7,55.2],[11.3,55.2],[11.0,55.7],[11.6,56.0],[11.8,55.7],[11.9,56.0],[12.2,56.1],[12.6,56.1],[12.6,55.8]],[[96.5,81.1],[97.9,80.7],[97.1,80.6],[97.0,80.5],[97.4,80.3],[97.2,80.2],[93.9,80.0],[91.5,80.4],[92.8,80.6],[93.3,80.8],[92.6,80.8],[93.4,81.0],[95.8,81.3],[96.5,81.1]],[[97.7,80.2],[98.0,80.0],[97.6,79.8],[98.4,79.9],[98.6,80.1],[100.1,79.8],[99.7,79.3],[99.0,79.3],[99.9,79.0],[99.4,78.8],[94.8,79.1],[94.2,79.4],[93.1,79.5],[95.0,80.1],[97.7,80.2]],[[102.9,79.3],[102.4,78.8],[103.0,79.1],[103.8,79.1],[105.1,78.8],[105.3,78.5],[104.7,78.3],[99.3,78.0],[100.0,78.3],[100.4,78.8],[101.0,78.8],[100.9,78.9],[101.5,79.3],[102.9,79.3]],[[140.0,75.8],[140.8,75.6],[141.0,76.0],[141.5,76.1],[143.7,75.9],[145.4,75.5],[144.7,75.4],[144.9,75.3],[144.0,75.0],[142.8,75.3],[142.7,75.5],[143.0,75.6],[142.9,75.7],[142.1,75.7],[142.6,75.1],[143.1,75.0],[142.5,74.8],[142.0,75.0],[140.3,74.8],[139.7,75.0],[139.1,74.7],[138.1,74.8],[136.9,75.3],[137.3,75.3],[137.2,75.6],[137.7,75.8],[137.5,75.9],[137.6,76.0],[138.2,76.1],[138.9,76.2],[140.0,75.8]],[[142.2,73.9],[143.5,73.5],[143.5,73.2],[140.7,73.5],[139.7,73.4],[140.4,73.5],[141.1,73.9],[142.2,73.9]],[[146.8,75.4],[150.8,75.2],[150.6,74.9],[148.1,74.8],[146.1,75.2],[146.4,75.6],[146.8,75.4]],[[126.0,9.3],[126.2,9.3],[126.3,9.0],[126.1,8.6],[126.4,8.5],[126.6,7.2],[126.2,6.9],[126.2,6.3],[125.7,7.3],[125.4,6.7],[125.7,6.0],[125.3,5.6],[125.2,6.1],[124.9,5.9],[124.2,6.2],[124.0,7.0],[124.2,7.4],[124.0,7.7],[123.5,7.8],[123.4,7.4],[123.1,7.7],[122.8,7.5],[122.6,7.8],[122.0,7.0],[121.9,7.2],[122.2,7.9],[122.9,8.2],[123.4,8.7],[123.7,8.6],[123.8,8.0],[124.2,8.2],[124.4,8.6],[124.7,8.6],[124.9,9.0],[125.5,9.0],[125.5,9.8],[126.0,9.3]],[[121.1,18.6],[121.8,18.3],[122.3,18.5],[122.2,17.7],[122.5,17.1],[122.1,16.2],[121.6,15.9],[121.4,15.3],[121.7,14.8],[121.6,14.6],[121.9,14.0],[122.2,13.9],[122.2,14.1],[122.6,14.3],[122.9,14.2],[123.1,13.8],[123.3,13.8],[123.3,14.1],[123.8,13.8],[123.5,13.6],[123.8,13.1],[124.1,13.0],[124.1,12.6],[123.9,12.9],[123.3,13.0],[123.2,13.4],[122.6,13.9],[122.6,13.2],[121.8,13.9],[121.3,13.6],[120.8,13.9],[120.6,13.8],[120.6,14.2],[120.9,14.6],[120.6,14.9],[120.6,14.5],[120.4,14.5],[120.1,14.9],[119.8,16.3],[120.2,16.0],[120.4,16.1],[120.3,16.6],[120.6,18.5],[121.1,18.6]],[[124.9,1.0],[124.4,0.5],[123.8,0.3],[123.3,0.3],[123.0,0.5],[120.6,0.5],[120.2,0.3]],[[119.9,0.0],[119.8,0.2],[120.3,1.0],[120.4,0.8],[120.9,1.3],[122.8,0.8],[123.9,0.8],[125.1,1.7],[125.2,1.5],[124.9,1.0]],[[96.5,5.2],[97.5,5.2],[98.3,4.1],[99.7,3.2],[100.5,2.2],[100.9,1.9],[100.8,2.2],[101.0,2.3],[102.4,0.8],[103.0,0.6],[103.0,0.4],[102.5,0.2],[103.3,0.5],[10Line truncated
@@ -0,0 +1,124 @@
{
"zh-CN": {
"title": "如何使用 · 地球地理",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:点右上「平面」,先看完整的世界地图,确认七大洲四大洋的位置。",
"第 2 步:点「五带」,看回归线与极圈怎么把地球分成五个温度带。",
"第 3 步:关掉「五带」,打开「六大板块」,记住六块板块的名字和范围。",
"第 4 步:再打开「五大陆」,对比金色实线(大陆)与彩色虚线(板块)的差别。",
"第 5 步:切回「3D 球面」,拖动转动地球,看背面会自动隐藏。",
"看不清?滚轮放大;想重来点「复位」。每个图层都能单独开关,互不干扰。"
]
},
{
"h": "一、这个模型包含什么",
"lines": [
"五带:热带、南北温带、南北寒带(按回归线 23.5° 与极圈 66.5° 划分)。",
"七大洲四大洋轮廓,以及洲与洲之间的分界线(苏伊士运河、巴拿马运河、白令海峡等)。",
"六大板块:亚欧、非洲、美洲、太平洋、印度洋、南极洲板块。",
"五块大陆:亚欧大陆、非洲大陆、美洲大陆、澳大利亚大陆、南极大陆。"
]
},
{
"h": "二、两种视图",
"lines": [
"「3D 球面」:正交投影球体,拖动旋转、滚轮缩放,背面自动裁掉。",
"「平面」:等经纬矩形地图,课本地图样式,一次看全整幅。",
"「复位」回到初始视角与缩放。"
]
},
{
"h": "三、图层开关(各自独立)",
"lines": [
"「五带」:叠加五带分界线与回归线、极圈。",
"「大洲轮廓」:白色海岸线。",
"「六大板块」:彩色虚线,是板块边界(不是大陆边界)。",
"「五大陆」:金色实线,是大陆轮廓。",
"「洲界」:分界点与分界线标签(如德雷克海峡、乌拉尔山…)。"
]
},
{
"h": "四、颜色与图例",
"lines": [
"右侧图例说明三种线型:海岸线 / 板块边界 / 分界线。",
"底部色块对应五个温度带。",
"六大板块各一种颜色,标签放在板块中心附近。"
]
},
{
"h": "五、教学要点与易错点",
"lines": [
"「板块 ≠ 大陆」:美洲板块覆盖南北美大陆并向东到大西洋中脊;印度洋板块包含澳大利亚与印度次大陆。",
"六大板块是全球一级板块,纳斯卡、阿拉伯等属于次级小板块,教材不列入。",
"板块交界处多火山地震(环太平洋带、地中海—喜马拉雅带)。",
"洲界是人为约定:亚欧以乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡为界;亚非以苏伊士运河为界;南北美以巴拿马运河为界;南美与南极以德雷克海峡为界。",
"Esc 关闭窗口,F11 全屏。"
]
}
]
},
"en": {
"title": "How to use · Earth Geography",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: click Flat in the top right for the whole world map first.",
"Step 2: turn on Climate zones to see how the tropics and polar circles split five belts.",
"Step 3: switch zones off and turn on Six plates; learn the six names and extents.",
"Step 4: turn on Five mainlands and compare solid gold lines (mainlands) with dashed colored lines (plates).",
"Step 5: switch back to 3D globe, drag to rotate, and see back faces clip automatically.",
"Hard to read? Scroll to zoom; press Reset to start over. Each layer toggles independently."
]
},
{
"h": "1. What this model contains",
"lines": [
"Five climate zones split by the tropics (23.5°) and polar circles (66.5°).",
"Seven continents, four oceans, and continental borders (Suez, Panama, Bering, etc.).",
"Six major plates: Eurasian, African, American, Pacific, Indian Ocean, Antarctic.",
"Five mainlands: Eurasia, Africa, America, Australia, Antarctica."
]
},
{
"h": "2. Two views",
"lines": [
"3D globe: orthographic sphere; drag to rotate, scroll to zoom, back faces clipped.",
"Flat: equirectangular textbook map, whole world at once.",
"Reset restores the initial view and zoom."
]
},
{
"h": "3. Independent layer toggles",
"lines": [
"Climate zones: tropics, polar circles and zone edges.",
"Coastlines: white continental outlines.",
"Six plates: dashed colored lines — plate BOUNDARIES, not continental edges.",
"Five mainlands: solid gold lines — continental outlines.",
"Borders: boundary dots and labels (Drake Passage, Ural Mts., ...)."
]
},
{
"h": "4. Colors & legend",
"lines": [
"The right legend explains the three line styles.",
"The bottom strip maps the five climate zones.",
"Each of the six plates has its own color, labelled near its center."
]
},
{
"h": "5. Teaching notes & pitfalls",
"lines": [
"Plates are NOT mainlands: the American Plate spans both Americas to the Mid-Atlantic Ridge; the Indian Ocean Plate includes Australia and the Indian subcontinent.",
"These six are the first-order plates; Nazca, Arabian, etc. are secondary and are not listed in textbooks.",
"Volcanoes and earthquakes concentrate along plate boundaries (Pacific Ring, Mediterranean–Himalayan belt).",
"Borders are conventions: Asia/Europe along the Urals–Ural River–Caspian–Caucasus–Black Sea–Turkish Straits; Asia/Africa at Suez; N/S America at Panama; S. America/Antarctica at Drake Passage.",
"Esc closes, F11 toggles fullscreen."
]
}
]
}
}
@@ -1 +1,53 @@
{"plates":[{"id":"pacific","lines":[[[-180,60],[-150,55],[-130,45],[-110,25],[-95,10],[-80,0],[-75,-15],[-90,-30],[-110,-45],[-130,-55],[-160,-60],[-180,-55],[-180,60]]]},{"id":"north-american","lines":[[[-168,72],[-140,70],[-120,60],[-100,50],[-80,45],[-60,42],[-52,28],[-62,12],[-82,8],[-95,16],[-110,25],[-130,45],[-150,55],[-168,72]]]},{"id":"south-american","lines":[[[-82,12],[-62,10],[-45,-2],[-35,-8],[-30,-20],[-40,-35],[-55,-42],[-70,-52],[-78,-40],[-80,-20],[-82,12]]]},{"id":"african","lines":[[[-20,35],[10,37],[32,32],[43,12],[51,10],[42,-8],[40,-25],[25,-35],[15,-30],[8,-5],[-8,5],[-17,15],[-20,35]]]},{"id":"eurasian","lines":[[[-10,36],[0,45],[15,55],[30,68],[60,72],[100,76],[140,70],[160,60],[140,42],[120,30],[100,20],[75,8],[60,22],[45,30],[30,32],[10,37],[-10,36]]]},{"id":"indo-australian","lines":[[[95,5],[115,10],[130,5],[145,-5],[150,-20],[145,-35],[130,-42],[115,-38],[105,-25],[95,-10],[95,5]]]},{"id":"antarctic","lines":[[[-180,-60],[-120,-62],[-60,-60],[0,-62],[60,-60],[120,-62],[180,-60],[180,-90],[-180,-90],[-180,-60]]]},{"id":"nazca","lines":[[[-95,-5],[-85,-10],[-75,-25],[-78,-40],[-90,-42],[-100,-30],[-95,-5]]]},{"id":"cocos","lines":[[[-105,10],[-95,12],[-90,5],[-100,2],[-105,10]]]},{"id":"caribbean","lines":[[[-88,15],[-75,18],[-62,15],[-60,8],[-72,6],[-85,8],[-88,15]]]},{"id":"philippine","lines":[[[118,20],[128,18],[130,8],[125,2],[118,8],[118,20]]]},{"id":"arabian","lines":[[[35,32],[48,30],[58,22],[55,12],[42,10],[35,20],[35,32]]]}]}
{
"plates": [
{
"id": "eurasian",
"nameI18n": { "zh-CN": "亚欧板块", "en": "Eurasian Plate" },
"label": [85, 55],
"lines": [
[[-10,36],[0,45],[15,55],[30,68],[60,72],[100,76],[140,70],[160,60],[140,42],[125,32],[110,28],[95,28],[80,30],[72,28],[60,25],[45,30],[32,32],[10,37],[-10,36]]
]
},
{
"id": "african",
"nameI18n": { "zh-CN": "非洲板块", "en": "African Plate" },
"label": [12, 2],
"lines": [
[[-20,35],[10,37],[32,32],[43,12],[51,10],[42,-8],[40,-25],[25,-35],[15,-30],[8,-5],[-8,5],[-17,15],[-20,35]]
]
},
{
"id": "american",
"nameI18n": { "zh-CN": "美洲板块", "en": "American Plate" },
"label": [-100, 12],
"lines": [
[[-168,72],[-140,70],[-115,70],[-90,72],[-60,60],[-52,45],[-60,30],[-80,25],[-82,8],[-78,0],[-70,-15],[-72,-40],[-75,-52],[-80,-55],[-95,-45],[-105,-25],[-95,-5],[-90,10],[-105,20],[-120,35],[-135,50],[-155,60],[-168,72]]
]
},
{
"id": "pacific",
"nameI18n": { "zh-CN": "太平洋板块", "en": "Pacific Plate" },
"label": [-150, 0],
"lines": [
[[-180,60],[-150,55],[-130,45],[-110,25],[-95,10],[-80,0],[-75,-15],[-90,-30],[-110,-45],[-130,-55],[-160,-60],[-180,-58],[-180,60]],
[[145,55],[158,45],[152,30],[145,15],[140,0],[148,-15],[158,-30],[168,-45],[180,-55],[180,60],[165,60],[145,55]]
]
},
{
"id": "indian-ocean",
"nameI18n": { "zh-CN": "印度洋板块", "en": "Indian Ocean Plate" },
"label": [95, -8],
"lines": [
[[35,32],[50,30],[60,22],[68,24],[75,8],[88,5],[95,5],[115,10],[130,5],[145,-5],[150,-20],[145,-35],[130,-42],[115,-38],[105,-25],[95,-10],[80,-10],[65,-5],[55,10],[42,10],[35,20],[35,32]]
]
},
{
"id": "antarctic",
"nameI18n": { "zh-CN": "南极洲板块", "en": "Antarctic Plate" },
"label": [0, -76],
"lines": [
[[-180,-60],[-120,-62],[-60,-60],[0,-62],[60,-60],[120,-62],[180,-60],[180,-90],[-180,-90],[-180,-60]]
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

@@ -12,8 +12,8 @@
"en": "Earth Geography"
},
"descriptionI18n": {
"zh-CN": "五带划分 · 七大洲四大洋 · 六大板块与洲界",
"en": "Climate zones · continents & oceans · plates & borders"
"zh-CN": "五带划分 · 七大洲四大洋 · 六大板块 · 五大陆与洲界",
"en": "Climate zones · continents & oceans · six plates · five mainlands & borders"
},
"tropicDeg": 23.5,
"axialTiltDeg": 23.5,
+8
View File
@@ -13,6 +13,8 @@ public sealed class PlateEntry
{
[JsonPropertyName("id")] public string Id { get; set; } = "";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
/// <summary>标签锚点 [lon, lat];缺省时用轮廓质心。</summary>
[JsonPropertyName("label")] public double[]? Label { get; set; }
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
}
@@ -21,6 +23,12 @@ public sealed class PlateData
[JsonPropertyName("plates")] public List<PlateEntry> Plates { get; set; } = new();
}
/// <summary>大陆(六块大陆里的教材五块写法)。结构与板块一致,纯线稿。</summary>
public sealed class ContinentData
{
[JsonPropertyName("continents")] public List<PlateEntry> Continents { get; set; } = new();
}
public sealed class BorderEntry
{
/// <summary>分界的两个大洲,如「亚洲-非洲」。</summary>
+11 -4
View File
@@ -19,6 +19,7 @@ public sealed class GeographyRuntime : IModelRuntime
private GeoScene? _scene;
private GeoData? _coast;
private PlateData? _plates;
private ContinentData? _continents;
private BorderData? _borders;
private LabelData? _labels;
private GeographyView? _view;
@@ -30,13 +31,15 @@ public sealed class GeographyRuntime : IModelRuntime
_scene = ModelJson.Read<GeoScene>(Path.Combine(dir, "scene.json")) ?? new GeoScene();
_coast = ModelJson.Read<GeoData>(Path.Combine(dir, "coastline.json")) ?? new GeoData();
_plates = ModelJson.Read<PlateData>(Path.Combine(dir, "plates.json")) ?? new PlateData();
_continents = ModelJson.Read<ContinentData>(Path.Combine(dir, "continents.json")) ?? new ContinentData();
_borders = ModelJson.Read<BorderData>(Path.Combine(dir, "borders.json")) ?? new BorderData();
context.ReportProgress(0.45, "加载名称标注");
_labels = ModelJson.Read<LabelData>(Path.Combine(dir, "labels.json")) ?? new LabelData();
context.ReportProgress(0.72, "构建轮廓");
context.Log($"[{context.ModelId}] 海岸线 {_coast.Lines.Count} 条,板块 {_plates.Plates.Count} 个,洲界 {_borders.Borders.Count} 条");
context.Log($"[{context.ModelId}] 海岸线 {_coast.Lines.Count} 条,六大板块 {_plates.Plates.Count} 个," +
$"大陆 {_continents.Continents.Count} 块,洲界 {_borders.Borders.Count} 条");
}
public Control CreateView(IModelContext context)
@@ -44,10 +47,11 @@ public sealed class GeographyRuntime : IModelRuntime
_scene ??= new GeoScene();
_coast ??= new GeoData();
_plates ??= new PlateData();
_continents ??= new ContinentData();
_borders ??= new BorderData();
_labels ??= new LabelData();
_view = new GeographyView(context, _scene, _coast, _plates, _borders, _labels);
_view = new GeographyView(context, _scene, _coast, _plates, _continents, _borders, _labels);
context.ReportProgress(1.0, "准备就绪");
return BuildLayout(_scene, _view, context);
}
@@ -90,7 +94,8 @@ public sealed class GeographyRuntime : IModelRuntime
actions.Children.Add(MakeModeSwitch(view));
actions.Children.Add(MakeToggle("五带", view.ShowZones, on => view.ShowZones = on));
actions.Children.Add(MakeToggle("大洲轮廓", view.ShowCoast, on => view.ShowCoast = on));
actions.Children.Add(MakeToggle("板块", view.ShowPlates, on => view.ShowPlates = on));
actions.Children.Add(MakeToggle("六大板块", view.ShowPlates, on => view.ShowPlates = on));
actions.Children.Add(MakeToggle("五大陆", view.ShowContinents, on => view.ShowContinents = on));
actions.Children.Add(MakeToggle("洲界", view.ShowBorders, on => view.ShowBorders = on));
actions.Children.Add(MakeButton("复位", () => view.ResetView()));
Grid.SetColumn(actions, 2);
@@ -122,7 +127,8 @@ public sealed class GeographyRuntime : IModelRuntime
{
var panel = new StackPanel { Spacing = 6 };
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#DEEEFF")), "大洲海岸线"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FF8A5C")), "板块边界"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FF8A5C")), "六大板块边界"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FFD24A")), "五大陆轮廓"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FFDC70")), "洲界 / 分界线"));
return new Border
{
@@ -250,6 +256,7 @@ public sealed class GeographyRuntime : IModelRuntime
{
foreach (var d in _disposables) d.Dispose();
_disposables.Clear();
_view?.StopAnimation();
_view = null;
GC.SuppressFinalize(this);
}
+377 -101
View File
@@ -23,30 +23,52 @@ public sealed class GeographyView : Control
private readonly GeoScene _scene;
private readonly GeoData _coast;
private readonly PlateData _plates;
private readonly ContinentData _continents;
private readonly BorderData _borders;
private readonly LabelData _labels;
private double _yawDeg = 10;
private double _pitchDeg = 15;
private double _zoom = 1.0;
private double _zoomTarget = 1.0;
private Avalonia.Threading.DispatcherTimer? _zoomTimer;
private Point _lastPointer;
private bool _dragging;
private bool _showZones = true;
private bool _showCoast = true;
private bool _showPlates;
private bool _showContinents = true;
private bool _showBorders = true;
private bool _showLabels = true;
private GeoMode _mode = GeoMode.Sphere3D;
// ── 平面视图几何缓存:五大陆有 1.3 万点,每帧重建 StreamGeometry 会明显掉帧。
// 尺寸/缩放不变时复用同一份几何,只重画笔刷。
private readonly Dictionary<string, Avalonia.Media.Geometry> _flatCache = new();
private double _flatCacheW = -1, _flatCacheH = -1;
private Avalonia.Media.Geometry? _coastGeo;
private double _coastCacheW = -1, _coastCacheH = -1;
// 单位球坐标缓存:三角运算只算一次,之后每帧只做矩阵乘 + 投影
private readonly Dictionary<string, (Vector3[] Pts, bool[] Valid)> _unitCache = new();
// ── 3D 视图成品几何缓存:旋转/缩放/尺寸都不变时直接复用上一帧的几何,
// 避免每帧重建 2.6 万点的 StreamGeometry 并重新提交给 Skia。
// 用户静止观察时这是绝大多数情况;拖动时按角度量化命中,转动依然跟手。
private Avalonia.Media.Geometry? _s3dCoast, _s3dCont;
private readonly Dictionary<string, Avalonia.Media.Geometry> _s3dBands = new();
private readonly Dictionary<string, Avalonia.Media.Geometry> _s3dPlates = new();
private string _s3dKey = "";
public event Action? StateChanged;
public GeographyView(IModelContext context, GeoScene scene, GeoData coast,
PlateData plates, BorderData borders, LabelData labels)
PlateData plates, ContinentData continents, BorderData borders, LabelData labels)
{
_scene = scene;
_coast = coast;
_plates = plates;
_continents = continents;
_borders = borders;
_labels = labels;
ClipToBounds = true;
@@ -56,12 +78,68 @@ public sealed class GeographyView : Control
public bool ShowZones { get => _showZones; set { _showZones = value; Redraw(); } }
public bool ShowCoast { get => _showCoast; set { _showCoast = value; Redraw(); } }
public bool ShowPlates { get => _showPlates; set { _showPlates = value; Redraw(); } }
public bool ShowContinents { get => _showContinents; set { _showContinents = value; Redraw(); } }
public bool ShowBorders { get => _showBorders; set { _showBorders = value; Redraw(); } }
public bool ShowLabels { get => _showLabels; set { _showLabels = value; Redraw(); } }
public GeoMode Mode { get => _mode; set { _mode = value; InvalidateVisual(); StateChanged?.Invoke(); } }
/// <summary>缩放倍数(0.55–4.0)。文字大小跟随缩放变化。</summary>
/// <summary>
/// 缩放。写入的是**目标值**,由动画计时器平滑逼近,
/// 直接跳变会让滚轮缩放显得生硬。
/// </summary>
public double Zoom
{
get => _zoomTarget;
set
{
_zoomTarget = Math.Clamp(value, 0.55, 4.0);
EnsureAnimating();
}
}
/// <summary>立即生效(贴图生成、复位等场景不该有过渡)。</summary>
public void SetZoomImmediate(double value)
{
_zoomTarget = Math.Clamp(value, 0.55, 4.0);
_zoom = _zoomTarget;
Redraw();
}
private void Redraw() { InvalidateVisual(); StateChanged?.Invoke(); }
/// <summary>
/// 缩放动画:60Hz 逼近目标值,差值小于阈值即停,
/// 避免空转白耗 CPU(一体机上尤其明显)。
/// </summary>
private void EnsureAnimating()
{
_zoomTimer ??= new Avalonia.Threading.DispatcherTimer(
TimeSpan.FromMilliseconds(16), Avalonia.Threading.DispatcherPriority.Render, (_, _) => StepZoom());
if (!_zoomTimer.IsEnabled) _zoomTimer.Start();
}
private void StepZoom()
{
var diff = _zoomTarget - _zoom;
if (Math.Abs(diff) < 0.0015)
{
_zoom = _zoomTarget;
_zoomTimer?.Stop();
Redraw();
return;
}
// 指数逼近:手感接近系统级平滑缩放
_zoom += diff * 0.28;
Redraw();
}
/// <summary>释放动画计时器,避免窗口关闭后还在跑。</summary>
public void StopAnimation() => _zoomTimer?.Stop();
/// <summary>文字缩放系数:跟随缩放一起放大/缩小,放大地球时标签也变大。</summary>
private double TextScale => Math.Clamp(_zoom, 0.85, 2.4);
public void ResetView()
{
_yawDeg = 10;
@@ -106,8 +184,8 @@ public sealed class GeographyView : Control
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
{
base.OnPointerWheelChanged(e);
_zoom = Math.Clamp(_zoom * (1 + e.Delta.Y * 0.12), 0.55, 4.0);
Redraw();
// 走 Zoom 属性(带平滑动画),不要在事件里直接改 _zoom
Zoom = _zoomTarget * (1 + e.Delta.Y * 0.12);
e.Handled = true;
}
@@ -138,7 +216,7 @@ public sealed class GeographyView : Control
{
var cx = (float)(size.Width * 0.5);
var cy = (float)(size.Height * 0.52);
var r = (float)(Math.Min(size.Width, size.Height) * 0.44 * _zoom);
var r = (float)(Math.Min(size.Width, size.Height) * 0.40 * Math.Min(_zoom, 1.6));
if (r < 12) return;
var cam = Matrix4x4.CreateRotationX((float)(-_pitchDeg * Math.PI / 180.0));
@@ -147,9 +225,52 @@ public sealed class GeographyView : Control
DrawOceanDisc(ctx, cx, cy, r);
if (_showZones) DrawZones3D(ctx, m, cx, cy, r);
if (_showCoast) DrawCoast3D(ctx, m, cx, cy, r);
// 成品几何缓存 key:旋转 / 缩放 / 尺寸 / 图层只要有一个变了才重建几何。
// 静止观察时命中率 100%,拖动时按 0.5° 量化,仍然跟手。
var key = string.Create(System.Globalization.CultureInfo.InvariantCulture,
$"{Math.Round(_yawDeg * 2) / 2}|{Math.Round(_pitchDeg * 2) / 2}|{Math.Round(_zoom, 3)}|" +
$"{Math.Round(size.Width)}|{Math.Round(size.Height)}|" +
$"{(_showZones ? 1 : 0)}{(_showCoast ? 1 : 0)}{(_showPlates ? 1 : 0)}{(_showContinents ? 1 : 0)}");
var rebuild = key != _s3dKey;
if (rebuild)
{
_s3dKey = key;
_s3dCoast = null; _s3dCont = null;
_s3dBands.Clear();
_s3dPlates.Clear();
}
if (_showZones)
{
// 每个温度带一种颜色,所以按带分别缓存一份几何
foreach (var zone in _scene.Zones)
{
var zkey = "band:" + zone.Id;
if (rebuild || !_s3dBands.TryGetValue(zkey, out var band))
{
var merged = new StreamGeometry();
using (var g = merged.Open())
AppendBand(g, m, cx, cy, r, zone.LatMin, zone.LatMax);
band = merged;
_s3dBands[zkey] = band;
}
ctx.DrawGeometry(ZoneFill(zone.Id), null, band);
}
// 边界线(赤道/回归线/极圈)随旋转变化,直接画
DrawZoneLines3D(ctx, m, cx, cy, r);
}
if (_showCoast)
{
if (rebuild || _s3dCoast == null) _s3dCoast = BuildCoast(m, cx, cy, r);
ctx.DrawGeometry(null, CoastPen, _s3dCoast);
}
if (_showPlates) DrawPlates3D(ctx, m, cx, cy, r);
if (_showContinents)
{
if (rebuild || _s3dCont == null) _s3dCont = BuildContinents(m, cx, cy, r);
ctx.DrawGeometry(null, ContinentPen, _s3dCont);
}
if (_showBorders) DrawBorders3D(ctx, m, cx, cy, r);
if (_showLabels) DrawLabels3D(ctx, m, cx, cy, r);
@@ -158,33 +279,66 @@ public sealed class GeographyView : Control
DrawReadout(ctx, size, $"球面 · {Norm(_yawDeg):0}°E {_pitchDeg:0}°");
}
/// <summary>
/// 球体本体:分层绘制提升立体感
/// ① 外层大气光晕(径向渐变,越靠边缘越亮)
/// ② 海洋底色(左上受光的渐变,模拟日光)
/// ③ 高光点 + 阴影弧(明暗对比塑造球感)
/// </summary>
private static void DrawOceanDisc(DrawingContext ctx, float cx, float cy, float r)
{
var disc = new RadialGradientBrush
// ① 大气边缘光:球外一层的柔和蓝晕
var halo = new RadialGradientBrush
{
Center = new RelativePoint(0.36, 0.32, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.36, 0.32, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.85, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.85, RelativeUnit.Relative),
Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.5, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.5, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.Parse("#12314F"), 0),
new GradientStop(Color.Parse("#0A1E33"), 0.62),
new GradientStop(Color.Parse("#061120"), 1)
new GradientStop(Color.FromArgb(0, 90, 160, 255), 0.82),
new GradientStop(Color.FromArgb(70, 90, 170, 255), 0.94),
new GradientStop(Color.FromArgb(0, 90, 170, 255), 1.0)
}
};
ctx.DrawEllipse(disc, null, new Point(cx, cy), r, r);
ctx.DrawEllipse(halo, null, new Point(cx, cy), r * 1.14, r * 1.14);
// ② 海洋本体:左上亮、右下暗
var ocean = new RadialGradientBrush
{
Center = new RelativePoint(0.34, 0.30, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.34, 0.30, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.95, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.95, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.Parse("#1B4A78"), 0.0),
new GradientStop(Color.Parse("#123A5E"), 0.35),
new GradientStop(Color.Parse("#0B2440"), 0.68),
new GradientStop(Color.Parse("#05121F"), 1.0)
}
};
ctx.DrawEllipse(ocean, null, new Point(cx, cy), r, r);
// ③ 高光:左上方一个小亮点,强化球面
var spec = new RadialGradientBrush
{
Center = new RelativePoint(0.30, 0.26, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.30, 0.26, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.30, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.30, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.FromArgb(70, 180, 220, 255), 0.0),
new GradientStop(Color.FromArgb(0, 180, 220, 255), 1.0)
}
};
ctx.DrawEllipse(spec, null, new Point(cx, cy), r, r);
}
// ---- 五带:按纬度带填色(用四边形条带逐格填充,避免整环多边形跨地平线破面)----
private void DrawZones3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
// ---- 五带边界线:赤道 / 回归线 / 极圈(随旋转变化,每帧直接画)----
private void DrawZoneLines3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var zone in _scene.Zones)
{
var fill = ZoneFill(zone.Id);
FillBand3D(ctx, m, cx, cy, r, zone.LatMin, zone.LatMax, fill);
}
// 边界线:赤道 / 回归线 / 极圈
foreach (var zone in _scene.Zones)
{
DrawParallel3D(ctx, m, cx, cy, r, zone.LatMin, ZoneEdgePen);
@@ -196,44 +350,6 @@ public sealed class GeographyView : Control
DrawParallel3D(ctx, m, cx, cy, r, 90 - _scene.TropicDeg, PolarPen);
DrawParallel3D(ctx, m, cx, cy, r, -(90 - _scene.TropicDeg), PolarPen);
}
/// <summary>
/// 纬度带填充:沿经度切成小四边形逐格画。
/// 每个格子独立判断可见性——这样跨地平线的格子会被跳过,
/// 而不是像整环多边形那样把背面点也连进去导致形状撕裂。
/// </summary>
private static void FillBand3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r,
double latMin, double latMax, IBrush fill)
{
const int steps = 180;
const double lonStep = 360.0 / steps;
for (var i = 0; i < steps; i++)
{
var lon0 = -180.0 + lonStep * i;
var lon1 = lon0 + lonStep;
var a = Geometry.ToCamera(Geometry.LatLonToUnit(latMin, lon0), Matrix4x4.Identity, m);
var b = Geometry.ToCamera(Geometry.LatLonToUnit(latMin, lon1), Matrix4x4.Identity, m);
var c = Geometry.ToCamera(Geometry.LatLonToUnit(latMax, lon1), Matrix4x4.Identity, m);
var d = Geometry.ToCamera(Geometry.LatLonToUnit(latMax, lon0), Matrix4x4.Identity, m);
// 四角都在正面才填这一格
if (a.Z <= 0 || b.Z <= 0 || c.Z <= 0 || d.Z <= 0) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(Pt(Geometry.Project(a, r, cx, cy)), true);
g.LineTo(Pt(Geometry.Project(b, r, cx, cy)));
g.LineTo(Pt(Geometry.Project(c, r, cx, cy)));
g.LineTo(Pt(Geometry.Project(d, r, cx, cy)));
g.EndFigure(true);
}
ctx.DrawGeometry(fill, null, geo);
}
}
private static void DrawParallel3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r,
double lat, IPen pen)
{
@@ -241,11 +357,86 @@ public sealed class GeographyView : Control
for (var i = 0; i < 145; i++) pts.Add(new[] { -180.0 + 360.0 * i / 144.0, lat });
DrawGeo3D(ctx, pts, m, cx, cy, r, pen, false);
}
private void DrawCoast3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
/// <summary>海岸线合并几何(供成品缓存使用)。</summary>
private Avalonia.Media.Geometry BuildCoast(Matrix4x4 m, float cx, float cy, float r)
{
foreach (var line in _coast.Lines)
DrawGeo3D(ctx, line, m, cx, cy, r, CoastPen, true);
var merged = new StreamGeometry();
using (var g = merged.Open())
{
for (var i = 0; i < _coast.Lines.Count; i++)
AppendCached(g, "coast:" + i, _coast.Lines[i], m, r, cx, cy, true);
}
return merged;
}
/// <summary>五大陆合并几何(供成品缓存使用)。</summary>
private Avalonia.Media.Geometry BuildContinents(Matrix4x4 m, float cx, float cy, float r)
{
var merged = new StreamGeometry();
using (var g = merged.Open())
{
foreach (var c in _continents.Continents)
for (var i = 0; i < c.Lines.Count; i++)
AppendCached(g, "cont:" + c.Id + ":" + i, c.Lines[i], m, r, cx, cy, true);
}
return merged;
}
/// <summary>把一个纬度带的可见格子追加到几何里(每格独立判断可见性)。</summary>
private static void AppendBand(StreamGeometryContext g, Matrix4x4 m, float cx, float cy, float r,
double latMin, double latMax)
{
const int steps = 180;
const double lonStep = 360.0 / steps;
for (var i = 0; i < steps; i++)
{
var lon0 = -180.0 + lonStep * i;
var lon1 = lon0 + lonStep;
var a = Geometry.ToCamera(Geometry.LatLonToUnit(latMin, lon0), Matrix4x4.Identity, m);
var b = Geometry.ToCamera(Geometry.LatLonToUnit(latMin, lon1), Matrix4x4.Identity, m);
var c = Geometry.ToCamera(Geometry.LatLonToUnit(latMax, lon1), Matrix4x4.Identity, m);
var d = Geometry.ToCamera(Geometry.LatLonToUnit(latMax, lon0), Matrix4x4.Identity, m);
if (a.Z <= 0 || b.Z <= 0 || c.Z <= 0 || d.Z <= 0) continue;
g.BeginFigure(Pt(Geometry.Project(a, r, cx, cy)), true);
g.LineTo(Pt(Geometry.Project(b, r, cx, cy)));
g.LineTo(Pt(Geometry.Project(c, r, cx, cy)));
g.LineTo(Pt(Geometry.Project(d, r, cx, cy)));
g.EndFigure(true);
}
}
/// <summary>把一条缓存折线的所有可见弧段追加到同一个几何里。</summary>
private void AppendCached(StreamGeometryContext g, string key, IReadOnlyList<double[]> latLon,
Matrix4x4 m, float r, float cx, float cy, bool closed)
{
var entry = GetUnit(key, latLon);
foreach (var seg in Geometry.ProjectUnitPolyline(entry.Pts, entry.Valid,
Matrix4x4.Identity, m, r, cx, cy, closed))
{
if (seg.Count < 2) continue;
g.BeginFigure(Pt(seg[0]), false);
for (var i = 1; i < seg.Count; i++) g.LineTo(Pt(seg[i]));
g.EndFigure(false);
}
}
private (Vector3[] Pts, bool[] Valid) GetUnit(string key, IReadOnlyList<double[]> latLon)
{
if (_unitCache.TryGetValue(key, out var entry)) return entry;
var pts = new Vector3[latLon.Count];
var valid = new bool[latLon.Count];
for (var i = 0; i < latLon.Count; i++)
{
var p = latLon[i];
if (p.Length >= 2)
{
pts[i] = Geometry.LatLonToUnit(p[1], p[0]);
valid[i] = true;
}
}
entry = (pts, valid);
_unitCache[key] = entry;
return entry;
}
private void DrawPlates3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
@@ -253,22 +444,30 @@ public sealed class GeographyView : Control
foreach (var p in _plates.Plates)
{
var pen = PlatePenFor(p.Id);
foreach (var line in p.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, pen, true);
var merged = new StreamGeometry();
using (var g = merged.Open())
{
for (var i = 0; i < p.Lines.Count; i++)
AppendCached(g, "plate:" + p.Id + ":" + i, p.Lines[i], m, r, cx, cy, true);
}
ctx.DrawGeometry(null, pen, merged);
}
if (!_showLabels) return;
if (_showLabels) DrawPlateLabels3D(ctx, m, cx, cy, r);
}
private void DrawPlateLabels3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var p in _plates.Plates)
{
var center = Centroid(p.Lines);
if (center == null) continue;
var cam = Geometry.ToCamera(Geometry.LatLonToUnit(center[1], center[0]), Matrix4x4.Identity, m);
var at = p.Label is { Length: >= 2 } ? p.Label : Centroid(p.Lines);
if (at == null) continue;
var cam = Geometry.ToCamera(Geometry.LatLonToUnit(at[1], at[0]), Matrix4x4.Identity, m);
if (cam.Z <= 0.2f) continue;
var pos = Geometry.Project(cam, r, cx, cy);
DrawText(ctx, Pick(p.NameI18n, p.Id), pos.X, pos.Y, 10.5,
DrawText(ctx, Pick(p.NameI18n, p.Id), pos.X, pos.Y, 10.5 * TextScale,
PlateBrushFor(p.Id), TextAlignment.Center);
}
}
private void DrawBorders3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var b in _borders.Borders)
@@ -294,7 +493,7 @@ public sealed class GeographyView : Control
var pos = Geometry.Project(cam, r, cx, cy);
ctx.DrawEllipse(segPen.DotBrush, null, Pt(pos), 3.0, 3.0);
if (_showLabels)
DrawText(ctx, Pick(seg.NameI18n, seg.Name), pos.X + 8, pos.Y - 5, 10,
DrawText(ctx, Pick(seg.NameI18n, seg.Name), pos.X + 8, pos.Y - 5, 10 * TextScale,
segPen.DotBrush, TextAlignment.Left);
}
continue;
@@ -314,7 +513,7 @@ public sealed class GeographyView : Control
if (_showLabels)
{
var text = $"{Pick(b.NameI18n, b.Name)}({b.Between})";
DrawText(ctx, text, pos2.X + 9, pos2.Y - 6, 10.5, pen.DotBrush, TextAlignment.Left);
DrawText(ctx, text, pos2.X + 9, pos2.Y - 6, 10.5 * TextScale, pen.DotBrush, TextAlignment.Left);
}
}
}
@@ -332,7 +531,7 @@ public sealed class GeographyView : Control
if (cam.Z <= 0.12f) continue;
var pos = Geometry.Project(cam, r, cx, cy);
var ocean = lb.Kind == "ocean";
DrawText(ctx, Pick(lb.NameI18n, ""), pos.X, pos.Y, ocean ? 11 : 12.5,
DrawText(ctx, Pick(lb.NameI18n, ""), pos.X, pos.Y, (ocean ? 11 : 12.5) * TextScale,
ocean ? OceanBrush : ContinentBrush, TextAlignment.Center,
ocean ? FontStyle.Italic : FontStyle.Normal);
}
@@ -356,6 +555,29 @@ public sealed class GeographyView : Control
}
}
/// <summary>
/// 缓存版绘制:单位球坐标按 key 缓存一次,之后每帧只做矩阵乘与投影。
/// 海岸线/大陆共 2.6 万点,这是 3D 视图的主要开销来源。
/// </summary>
private void DrawCached3D(DrawingContext ctx, string key, IReadOnlyList<double[]> latLon,
Matrix4x4 m, float cx, float cy, float r, IPen pen, bool closed)
{
var entry = GetUnit(key, latLon);
foreach (var seg in Geometry.ProjectUnitPolyline(entry.Pts, entry.Valid,
Matrix4x4.Identity, m, r, cx, cy, closed))
{
if (seg.Count < 2) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(Pt(seg[0]), false);
for (var i = 1; i < seg.Count; i++) g.LineTo(Pt(seg[i]));
g.EndFigure(false);
}
ctx.DrawGeometry(null, pen, geo);
}
}
// ================================================================ 平面等经纬
private void RenderFlat(DrawingContext ctx, Size size)
{
@@ -401,22 +623,29 @@ public sealed class GeographyView : Control
// 海岸线
if (_showCoast)
{
foreach (var line in _coast.Lines)
var cw = Math.Round(size.Width);
var ch = Math.Round(size.Height);
if (Math.Abs(cw - _coastCacheW) > 0.5 || Math.Abs(ch - _coastCacheH) > 0.5 || _coastGeo == null)
{
if (line.Count < 2) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
var merged = new StreamGeometry();
using (var g = merged.Open())
{
g.BeginFigure(P(line[0][0], line[0][1]), false);
for (var i = 1; i < line.Count; i++)
foreach (var line in _coast.Lines)
{
var p = line[i];
if (p.Length >= 2) g.LineTo(P(p[0], p[1]));
if (line.Count < 2) continue;
g.BeginFigure(P(line[0][0], line[0][1]), false);
for (var i = 1; i < line.Count; i++)
{
var p = line[i];
if (p.Length >= 2) g.LineTo(P(p[0], p[1]));
}
g.EndFigure(false);
}
g.EndFigure(false);
}
ctx.DrawGeometry(null, CoastPen, geo);
_coastGeo = merged;
_coastCacheW = cw; _coastCacheH = ch;
}
ctx.DrawGeometry(null, CoastPen, _coastGeo);
}
// 板块
@@ -429,14 +658,60 @@ public sealed class GeographyView : Control
DrawFlatPolyline(ctx, line, P, pen);
if (!_showLabels) continue;
var c = Centroid(pl.Lines);
var c = pl.Label is { Length: >= 2 } ? pl.Label : Centroid(pl.Lines);
if (c == null) continue;
var at = P(c[0], c[1]);
DrawText(ctx, Pick(pl.NameI18n, pl.Id), at.X, at.Y, 10.5,
DrawText(ctx, Pick(pl.NameI18n, pl.Id), at.X, at.Y, 10.5 * TextScale,
PlateBrushFor(pl.Id), TextAlignment.Center);
}
}
// 五大陆
if (_showContinents)
{
// 用缓存几何:尺寸不变时只画一次构建开销
var fw = Math.Round(size.Width);
var fh = Math.Round(size.Height);
if (Math.Abs(fw - _flatCacheW) > 0.5 || Math.Abs(fh - _flatCacheH) > 0.5 || _flatCache.Count == 0)
{
_flatCache.Clear();
_flatCacheW = fw; _flatCacheH = fh;
}
foreach (var c in _continents.Continents)
{
var key = "cont:" + c.Id;
if (!_flatCache.TryGetValue(key, out var geo))
{
var merged = new StreamGeometry();
using (var g = merged.Open())
{
foreach (var line in c.Lines)
{
if (line.Count < 2) continue;
g.BeginFigure(P(line[0][0], line[0][1]), false);
for (var i = 1; i < line.Count; i++)
{
var p = line[i];
if (p.Length >= 2) g.LineTo(P(p[0], p[1]));
}
g.EndFigure(false);
}
}
geo = merged;
_flatCache[key] = geo;
}
ctx.DrawGeometry(null, ContinentPen, geo);
if (!_showLabels) continue;
var a = c.Label is { Length: >= 2 } ? c.Label : Centroid(c.Lines);
if (a == null) continue;
var at = P(a[0], a[1]);
DrawText(ctx, Pick(c.NameI18n, c.Id), at.X, at.Y, 12 * TextScale,
MainlandBrush, TextAlignment.Center);
}
}
// 洲界
if (_showBorders)
{
@@ -453,7 +728,7 @@ public sealed class GeographyView : Control
ctx.DrawEllipse(pen.DotBrush, null, at, 3.4, 3.4);
if (_showLabels)
DrawText(ctx, $"{Pick(b.NameI18n, b.Name)}({b.Between})",
at.X + 9, at.Y - 6, 10.5, pen.DotBrush, TextAlignment.Left);
at.X + 9, at.Y - 6, 10.5 * TextScale, pen.DotBrush, TextAlignment.Left);
}
}
@@ -464,7 +739,7 @@ public sealed class GeographyView : Control
{
var at = P(lb.Lon, lb.Lat);
var ocean = lb.Kind == "ocean";
DrawText(ctx, Pick(lb.NameI18n, ""), at.X, at.Y, ocean ? 11 : 12.5,
DrawText(ctx, Pick(lb.NameI18n, ""), at.X, at.Y, (ocean ? 11 : 12.5) * TextScale,
ocean ? OceanBrush : ContinentBrush, TextAlignment.Center,
ocean ? FontStyle.Italic : FontStyle.Normal);
}
@@ -517,6 +792,7 @@ public sealed class GeographyView : Control
"亚洲-欧洲" => Color.FromRgb(120, 226, 255), // 青
"欧洲-非洲" => Color.FromRgb(168, 148, 255), // 紫
"北美-南美" => Color.FromRgb(120, 255, 176), // 绿
"南美-南极" => Color.FromRgb(96, 232, 222), // 青绿(德雷克海峡)
"亚洲-北美" => Color.FromRgb(255, 140, 220), // 粉
"亚洲-大洋洲" => Color.FromRgb(255, 160, 96), // 橙
"南极洲" => Color.FromRgb(200, 225, 255), // 冰蓝
@@ -530,20 +806,15 @@ public sealed class GeographyView : Control
private static IPen PlatePenFor(string id)
{
// 教材六大板块,每块一个颜色
var c = id switch
{
"pacific" => Color.FromRgb(255, 110, 110),
"north-american" => Color.FromRgb(255, 176, 84),
"south-american" => Color.FromRgb(255, 226, 96),
"african" => Color.FromRgb(150, 230, 110),
"eurasian" => Color.FromRgb(110, 214, 230),
"indo-australian" => Color.FromRgb(126, 160, 255),
"antarctic" => Color.FromRgb(208, 190, 255),
"nazca" => Color.FromRgb(255, 140, 200),
"cocos" => Color.FromRgb(255, 200, 130),
"caribbean" => Color.FromRgb(180, 240, 160),
"philippine" => Color.FromRgb(255, 160, 230),
"arabian" => Color.FromRgb(200, 220, 255),
"eurasian" => Color.FromRgb(110, 214, 230), // 青
"african" => Color.FromRgb(150, 230, 110), // 绿
"american" => Color.FromRgb(255, 176, 84), // 橙
"pacific" => Color.FromRgb(255, 110, 110), // 红
"indian-ocean" => Color.FromRgb(126, 160, 255), // 蓝紫
"antarctic" => Color.FromRgb(208, 190, 255), // 淡紫
_ => Color.FromRgb(255, 150, 100)
};
return new Pen(new SolidColorBrush(Color.FromArgb(225, c.R, c.G, c.B)), 1.55,
@@ -560,6 +831,11 @@ public sealed class GeographyView : Control
private static readonly IPen CoastPen = new Pen(new SolidColorBrush(Color.FromArgb(250, 236, 246, 255)), 1.75)
{ LineJoin = PenLineJoin.Round, LineCap = PenLineCap.Round };
/// <summary>五大陆轮廓:金黄色实线,与板块虚线明显区分。</summary>
private static readonly IPen ContinentPen = new Pen(new SolidColorBrush(Color.FromArgb(240, 255, 210, 74)), 2.0)
{ LineJoin = PenLineJoin.Round, LineCap = PenLineCap.Round };
private static readonly IBrush MainlandBrush = new SolidColorBrush(Color.FromRgb(255, 218, 110));
private static readonly IPen TropicPen = new Pen(new SolidColorBrush(Color.FromArgb(220, 255, 190, 100)), 1.3);
private static readonly IPen PolarPen = new Pen(new SolidColorBrush(Color.FromArgb(210, 150, 205, 255)), 1.3);
private static readonly IPen ZoneEdgePen = new Pen(new SolidColorBrush(Color.FromArgb(110, 200, 225, 255)), 0.9);
+10 -2
View File
@@ -23,6 +23,14 @@
"type": "NeoRF.EarthModels.RevolutionModelFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.0-7380e0cff3",
"updatedAt": "2026-11-08T01:29:16Z"
"version": "1.6",
"updatedAt": "2026-11-14T01:23:14Z",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "26a2bd8f68"
}
@@ -0,0 +1,124 @@
{
"zh-CN": {
"title": "如何使用 · 地球公转",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:先按「1」定格到春分,看读数区「太阳直射」是多少度。",
"第 2 步:再按「2」,直射纬度变成 23.5°N —— 这就是北半球夏至。",
"第 3 步:依次按「3」「4」,对比四个节气的直射点位置。",
"第 4 步:按「空格」播放,看地球绕太阳走完一圈要多久(有速度调节)。",
"第 5 步:拖动鼠标换到「俯视」,能看到轨道是个椭圆,地轴始终指向同一方向。",
"看不到变化?确认顶部「节气定位」已打开,且没有停在暂停状态。"
]
},
{
"h": "一、这个模型讲什么",
"lines": [
"地球绕太阳公转,周期约 365.25 天,轨道近似椭圆,地轴始终指向北极星附近。",
"地轴与公转轨道面成 66.5° 夹角(赤道面与轨道面夹角 23.5°,即黄赤交角)。",
"由于地轴倾斜方向不变,太阳直射点在南北回归线之间往返,形成四季更替。",
"二分二至:春分 3/21、夏至 6/22、秋分 9/23、冬至 12/22(教材值)。"
]
},
{
"h": "二、基本操作",
"lines": [
"「播放 / 暂停」控制公转动画;「速度」调节一年走完的快慢。",
"「步进」让地球沿轨道前进一小格,便于逐段观察。",
"拖动或滚轮改变观察角度与缩放;「俯视 / 侧视」切换视角。",
"「重置」回到春分起点。"
]
},
{
"h": "三、节气定位(重点)",
"lines": [
"按 1–4 直接定格到春分、夏至、秋分、冬至。",
"春分 / 秋分:太阳直射赤道(0°),全球昼夜平分。",
"夏至:直射北回归线 23.5°N,北半球昼最长、北极圈内极昼。",
"冬至:直射南回归线 23.5°S,北半球昼最短、北极圈内极夜。",
"定格后读数区显示:公转角度、太阳直射纬度、教材日期、节气名称。"
]
},
{
"h": "四、读数与课堂卡",
"lines": [
"「太阳直射」读数来自模型数据里的 declinationDeg,不是近似公式。",
"「节气定位」面板列出四个节气的日期与现象说明(中英双语)。",
"「教学要点」解释:直射点移动 → 正午太阳高度与昼长变化 → 四季。"
]
},
{
"h": "五、易错点",
"lines": [
"四季成因是「地轴倾斜且方向不变」,不是「地球离太阳忽远忽近」。",
"近日点在 1 月初(北半球冬天),远日点在 7 月初(北半球夏天)。",
"南北半球季节相反:北半球夏至时南半球是冬至。",
"Esc 关闭窗口,F11 全屏。"
]
}
]
},
"en": {
"title": "How to use · Earth Revolution",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: press 1 to freeze at the spring equinox and read the subsolar latitude.",
"Step 2: press 2 — the subsolar point jumps to 23.5°N, the June solstice.",
"Step 3: press 3 and 4 to compare all four key positions.",
"Step 4: press Space to animate one full orbit; adjust Speed as needed.",
"Step 5: drag to Top view to see the elliptical orbit and the fixed axis direction.",
"Nothing changing? Make sure Seasons is on in the top bar and the model isn't paused."
]
},
{
"h": "1. What this model shows",
"lines": [
"Earth orbits the Sun in ~365.25 days; the axis keeps pointing near Polaris.",
"The axis is tilted 66.5° to the orbital plane (obliquity 23.5°).",
"Because the tilt direction is fixed, the subsolar point migrates between the tropics, making seasons.",
"Key dates: spring equinox 3/21, summer solstice 6/22, autumn equinox 9/23, winter solstice 12/22."
]
},
{
"h": "2. Basic controls",
"lines": [
"Play/Pause runs the orbit; Speed sets how fast a year passes.",
"Step advances one increment for close observation.",
"Drag or scroll to change view/zoom; Top view / Side view switch perspective.",
"Reset returns to the spring equinox."
]
},
{
"h": "3. Solstices & equinoxes",
"lines": [
"Keys 1–4 freeze at spring equinox, summer solstice, autumn equinox, winter solstice.",
"Equinoxes: subsolar at the equator (0°), equal day and night worldwide.",
"June solstice: subsolar at 23.5°N; longest day in the north, polar day inside the Arctic Circle.",
"December solstice: subsolar at 23.5°S; shortest day in the north, polar night.",
"The readout shows orbit angle, subsolar latitude, textbook date and season name."
]
},
{
"h": "4. Readouts & classroom cards",
"lines": [
"Subsolar latitude comes from declinationDeg in the model data, not an approximation.",
"The seasons panel lists dates and phenomena for all four (bilingual).",
"Teaching notes: migrating subsolar point → changing noon altitude and day length → seasons."
]
},
{
"h": "5. Common mistakes",
"lines": [
"Seasons come from the fixed axial tilt, NOT from Earth being closer/farther to the Sun.",
"Perihelion is early January (northern winter); aphelion is early July (northern summer).",
"Seasons are opposite in the two hemispheres.",
"Esc closes, F11 toggles fullscreen."
]
}
]
}
}
+10 -2
View File
@@ -23,6 +23,14 @@
"type": "NeoRF.EarthModels.RotationModelFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.0-c74907bbce",
"updatedAt": "2026-11-08T01:29:16Z"
"version": "1.6",
"updatedAt": "2026-11-14T01:23:14Z",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "1a81492baa"
}
@@ -0,0 +1,121 @@
{
"zh-CN": {
"title": "如何使用 · 地球自转",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:窗口打开后先按「空格」暂停,动画停住才好观察。",
"第 2 步:按住鼠标左键拖动地球,把晨昏线转到正对你。",
"第 3 步:点顶部「经纬网」打开网格,能看清哪一段是夜半球。",
"第 4 步:再按「空格」播放,盯住一个点,看它从黑夜转进白天。",
"第 5 步:按住「←」「→」可以一格一格慢慢看昼夜交界线怎么移动。",
"找不到按钮?所有开关都在窗口顶部那一排;转不动地球就点「复位」重来。"
]
},
{
"h": "一、这个模型讲什么",
"lines": [
"地球绕地轴自西向东自转,周期约 24 小时(一个太阳日)。",
"自转产生三个可观察现象:昼夜交替、地方时差、地转偏向力。",
"晨昏线( terminator )是把地球分成昼半球与夜半球的大圆,它随自转不断西移。",
"太阳直射点是地表太阳高度为 90° 的点,正午太阳高度由它向南北两侧递减。"
]
},
{
"h": "二、基本操作",
"lines": [
"拖动地球:改变观察角度(经度/纬度),可从极地或赤道上空看。",
"滚轮或双指捏合:缩放;右上角「放大」可切到地球特写。",
"「播放 / 暂停」开始或停止自转动画;「速度」调节快慢。",
"「重置」把角度、速度、缩放恢复到初始状态。"
]
},
{
"h": "三、图层开关",
"lines": [
"「经纬网」叠加经线与纬线,便于读出赤道、回归线、极圈。",
"「标注」显示北极、南极、太阳直射点、赤道等关键标签。",
"「轨道」显示自转轴与赤道面;「夸张倾角」把 23.5° 放大便于观察。",
"「教学要点」展开课堂讲解文字,适合投屏授课。"
]
},
{
"h": "四、键盘快捷键",
"lines": [
"空格:播放 / 暂停。",
"← →:逐帧步进(暂停时最有用)。",
"Esc:关闭窗口;F11:全屏 / 退出全屏。"
]
},
{
"h": "五、课堂上怎么用",
"lines": [
"先暂停,把晨昏线转到与经线重合,说明「昼夜平分」只在二分日出现。",
"再播放,让学生观察同一地点如何由夜入昼(晨线)与由昼入夜(昏线)。",
"对比不同经度:东边地点先见到日出,引出「东早西晚」的地方时差。",
"易错提醒:昼夜现象本身由「地球不发光、不透明」造成,自转只造成「交替」。"
]
}
]
},
"en": {
"title": "How to use · Earth Rotation",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: press Space to pause first — a still globe is easier to read.",
"Step 2: hold the left mouse button and drag until the terminator faces you.",
"Step 3: switch on Graticule in the top bar to see which side is night.",
"Step 4: press Space to play and watch one point rotate from night into day.",
"Step 5: use ← / → to step frame by frame and follow the day/night boundary.",
"Can't find a control? Every toggle is in the top bar; if the globe gets twisted, press Reset."
]
},
{
"h": "1. What this model shows",
"lines": [
"Earth spins west-to-east on its axis in about 24 hours (a solar day).",
"Rotation causes the day/night cycle, local time differences and the Coriolis effect.",
"The terminator is the great circle splitting day and night; it moves west as Earth turns.",
"The subsolar point is where the Sun is overhead; noon altitude decreases away from it."
]
},
{
"h": "2. Basic controls",
"lines": [
"Drag the globe to change the viewing angle (from pole or equator).",
"Scroll or pinch to zoom; the close-up button gives an Earth detail view.",
"Play/Pause starts or stops the spin; Speed changes the rate.",
"Reset restores the initial angle, speed and zoom."
]
},
{
"h": "3. Layer toggles",
"lines": [
"Graticule overlays meridians and parallels (equator, tropics, polar circles).",
"Labels shows poles, subsolar point and the equator.",
"Orbit shows the axis and equatorial plane; Exaggerate tilt magnifies the 23.5° tilt.",
"Teaching notes expands classroom text, useful on a projector."
]
},
{
"h": "4. Keyboard shortcuts",
"lines": [
"Space: play / pause. ← →: step one frame (best while paused).",
"Esc: close window. F11: toggle fullscreen."
]
},
{
"h": "5. In the classroom",
"lines": [
"Pause with the terminator along a meridian to show equal day/night at equinoxes.",
"Play again and watch a site cross the dawn line and the dusk line.",
"Compare longitudes: eastern places see sunrise earlier — local time runs ahead.",
"Common mistake: day/night exists because Earth is opaque; rotation only makes it alternate."
]
}
]
}
}
@@ -0,0 +1,37 @@
{
"schemaVersion": 1,
"id": "scale-calculator",
"name": "Scale Calculator",
"nameI18n": {
"zh-CN": "比例尺计算器",
"en": "Scale Calculator"
},
"author": "Morris GC",
"description": "把比例尺变成可以拖、可以量的可视化标尺",
"descriptionI18n": {
"zh-CN": "三种求解模式、图上/实地双条对比、线段式比例尺自动换挡、比例尺光谱、真实地标实地尺与练习闯关。",
"en": "Three solve modes, dual map/real bars, auto-ranging graphic scale, scale spectrum, real-world landmarks and practice quizzes."
},
"tags": [
"geography",
"map",
"scale",
"calculator"
],
"entry": "scales.json",
"license": "MIT",
"assembly": "ScaleCalculatorModel.dll",
"type": "NeoRF.ScaleCalculator.ScaleCalculatorFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.5",
"updatedAt": "2026-11-14T01:23:14Z",
"chrome": {
"titleBar": "#FFFFFF",
"titleBorder": "#E3E8F3",
"titleText": "#111A2E",
"button": "#5B6A86",
"frame": "#F4F6FB"
},
"build": "79711a44a8"
}
@@ -0,0 +1,146 @@
{
"zh-CN": {
"title": "如何使用 · 比例尺计算器",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:顶部选「求实地距离」,此时蓝色卡是答案,另外两个是输入。",
"第 2 步:在「图上距离」里填 3,在「比例尺分母」里填 100000。",
"第 3 步:看蓝色卡算出 3 千米 —— 再点「解题步骤」核对每一步。",
"第 4 步:改成「求比例尺」,把实地距离填成 6 千米,看分母怎么翻倍。",
"第 5 步:拖动中间标尺的滑块,观察蓝色条(图上)与绿色条(实地)的长度关系。",
"第 6 步:滚到底部「练习闯关」,自己做一道,答错会自动展开步骤。",
"算不出来?先检查单位:填了 km 就不要再按 cm 算,模型会自动换算。"
]
},
{
"h": "一、核心公式(先记住这一条)",
"lines": [
"比例尺 = 图上距离 ÷ 实地距离,写作 1 : N。",
"N 是分母,含义是「实地距离是图上距离的 N 倍」,两句都必须统一成同一单位。",
"三个变形:实地 = 图上 × N;图上 = 实地 ÷ N;N = 实地 ÷ 图上。",
"单位换算:1 m = 100 cm,1 km = 1000 m = 100000 cm(km 化 cm 加 5 个 0)。"
]
},
{
"h": "二、三种求解模式",
"lines": [
"顶部三个按钮选「求实地距离 / 求图上距离 / 求比例尺」。",
"选中的那一项会变成蓝色结果卡(只读),另外两项留作输入。",
"拖动滑块或直接输入数字,三栏读数与中栏标尺实时联动。",
"「重置」回到 3 cm / 1:100000 / 3 km 的初始例子。"
]
},
{
"h": "三、中栏可视化标尺",
"lines": [
"上条(蓝)是图上距离,按真实厘米画刻度。",
"下条(绿)是同一段实地距离按当前比例尺压缩后的长度,与上方同宽。",
"线段式比例尺会按 1/2/5×10ⁿ 自动换挡,任何比例尺都画得下。",
"比例尺光谱把 1:1千 到 1:10亿 排在对数轴上,当前值用指针标出。",
"若超出图幅,会提示「需要更小的比例尺」——这正是选图幅的教学点。"
]
},
{
"h": "四、三种写法与解题步骤",
"lines": [
"数字式 1 : N;文字式「图上 1 厘米代表实地 …」;线段式(图形刻度)。",
"右栏三者实时联动,可直接抄到作业里。",
"「解题步骤」可展开:① 统一单位 → ② 列公式 → ③ 代入 → ④ 得数 → ⑤ 换算合适单位。",
"「大小判读」卡:大 / 中 / 小比例尺 +「分母越大 → 比例尺越小 → 范围越大 → 越简略」。"
]
},
{
"h": "五、实地尺与练习",
"lines": [
"「实地尺」内置教室 10 m、操场 400 m、马拉松 42.195 km、京沪 1080 km、赤道 4 万 km。",
"改变比例尺,看这段真实距离画到图上是多长(或画不下 / 几乎看不见)。",
"「练习闯关」随机出三类题,填数字后回车或点「检查」,答错展开完整解题步骤。",
"连对计数会一直累计,答错清零。"
]
},
{
"h": "六、易错点",
"lines": [
"忘记统一单位:km 必须 ×100000 变成 cm 才能代入。",
"「放大 2 倍」是分母 ÷ 2(比例尺变大),不是 × 2。",
"图上距离与实地距离别代反了;N 是「实地是图上的几倍」。",
"比例尺是比值,没有单位;说「比例尺越大」指的是比值越大、分母越小。"
]
}
]
},
"en": {
"title": "How to use · Scale Calculator",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: choose Find real distance at the top — the blue card is the answer, the other two are inputs.",
"Step 2: enter 3 as the map distance and 100000 as the scale denominator.",
"Step 3: the blue card shows 3 km — open Worked steps and check each line.",
"Step 4: switch to Find scale, set the real distance to 6 km, and watch the denominator change.",
"Step 5: drag the ruler slider and compare the blue bar (map) with the green bar (real).",
"Step 6: scroll to Practice and try one; a wrong answer expands the full solution.",
"Stuck? Check your units first — the model converts automatically, so don't mix km and cm."
]
},
{
"h": "1. The core formula",
"lines": [
"Scale = map distance ÷ real distance, written 1 : N.",
"N is the denominator: the real distance is N times the map distance — both must share one unit.",
"Three forms: real = map × N; map = real ÷ N; N = real ÷ map.",
"Unit conversions: 1 m = 100 cm, 1 km = 1000 m = 100000 cm (add five zeros)."
]
},
{
"h": "2. Three solve modes",
"lines": [
"Pick Find real distance / Find map distance / Find scale at the top.",
"The chosen one becomes the blue read-only result card; the other two stay as inputs.",
"Drag a slider or type a number — all three columns and the ruler update live.",
"Reset returns to the default 3 cm / 1:100000 / 3 km example."
]
},
{
"h": "3. The visual ruler",
"lines": [
"The blue bar is the map distance in real centimetres.",
"The green bar is the same real distance compressed by the current scale — same width.",
"The graphic scale auto-ranges over 1/2/5×10ⁿ so it always fits.",
"The spectrum places 1:1k … 1:1B on a log axis with a pointer at the current value.",
"Overflow warns “use a smaller scale” — that IS the lesson on choosing a sheet size."
]
},
{
"h": "4. Three notations & worked steps",
"lines": [
"Numeric 1:N; verbal “1 cm on the map = … on the ground”; graphic bar scale.",
"All three stay in sync and can be copied straight into homework.",
"Expand Worked steps: unify units → formula → substitute → result → convert unit.",
"The grade card: large / medium / small scale and “bigger denominator → smaller scale → larger area → less detail”."
]
},
{
"h": "5. Real-world ruler & practice",
"lines": [
"Built-in distances: classroom 10 m, track 400 m, marathon 42.195 km, Beijing–Shanghai 1080 km, equator 40,000 km.",
"Change the scale to see how long each becomes on paper (or that it won't fit / is invisible).",
"Practice generates three question types; type a number and press Enter or Check; wrong answers reveal full steps.",
"The streak counter accumulates and resets on a wrong answer."
]
},
{
"h": "6. Common mistakes",
"lines": [
"Forgetting to unify units: km ×100000 → cm before substituting.",
"“Zoom 2×” means denominator ÷ 2 (a larger scale), not × 2.",
"Don't swap map and real distance; N means “how many times the map length the real length is”.",
"A scale is a ratio with no unit; “larger scale” means a larger ratio, i.e. a SMALLER denominator."
]
}
]
}
}
@@ -0,0 +1,106 @@
{
"app.title": "Scale Calculator",
"app.subtitle": "Turn map-distance ÷ real-distance into a ruler you can drag and measure",
"mode.real": "Find real distance",
"mode.map": "Find map distance",
"mode.scale": "Find scale",
"mode.hint": "Pick what to solve; the blue card is the answer",
"input.title": "Given",
"input.map": "Map distance",
"input.real": "Real distance",
"input.scale": "Scale denominator N",
"input.nPrefix": "1 :",
"input.unit": "Unit",
"input.reset": "Reset",
"input.presets": "Common scales",
"input.dragHint": "Drag the slider or type a number — everything updates live",
"result.title": "Result",
"result.real": "Real distance",
"result.map": "Map distance",
"result.scale": "Scale",
"result.formula": "Formula",
"forms.title": "Three ways to write a scale",
"forms.digital": "Numeric",
"forms.verbal": "Verbal",
"forms.segment": "Graphic (bar)",
"forms.verbalTpl": "1 cm on the map = {0} on the ground",
"forms.segmentDesc": "Each division {0}, {1} divisions",
"steps.title": "Worked solution",
"steps.show": "Show steps",
"steps.hide": "Hide steps",
"steps.1.unify": "① Unify units: convert the real distance to cm (1 km = 100000 cm)",
"steps.2.formulaReal": "② Real distance = map distance × scale denominator",
"steps.2.formulaMap": "② Map distance = real distance ÷ scale denominator",
"steps.2.formulaScale": "② Scale denominator = real distance ÷ map distance",
"steps.3.substitute": "③ Substitute: {0}",
"steps.4.result": "④ Result: {0}",
"steps.5.convert": "⑤ Convert to a sensible unit (cm → m → km)",
"grade.title": "Large / small scale",
"grade.large": "Large scale",
"grade.medium": "Medium scale",
"grade.small": "Small scale",
"grade.largeNote": "Small area · detailed · e.g. campus plan",
"grade.mediumNote": "Medium area · e.g. city map",
"grade.smallNote": "Large area · simplified · e.g. world map",
"grade.rule": "Bigger denominator → smaller scale → larger area → less detail",
"pit.title": "Common mistakes",
"pit.1": "① Forgetting to unify units: km ×100000 = cm",
"pit.2": "② \"Zoom 2×\" means denominator ÷ 2, not × 2",
"pit.3": "③ Don't swap map distance and real distance",
"field.title": "Real-world ruler · how long on the map",
"field.hint": "Pick a real distance and change the scale to see its map length",
"field.mapLength": "On map {0}",
"field.tooLong": "too long",
"field.tooShort": "barely visible",
"quiz.title": "Practice",
"quiz.promptReal": "Scale 1:{0}, map distance {1} cm — what is the real distance? (enter the number in the shown unit)",
"quiz.promptMap": "Scale 1:{0}, real distance {1} — what is the map distance in cm?",
"quiz.promptScale": "{0} cm on the map = {1} on the ground — what is the scale denominator?",
"quiz.answer": "Your answer",
"quiz.check": "Check",
"quiz.next": "Next",
"quiz.correct": "✓ Correct!",
"quiz.wrong": "✗ Try again — read the steps",
"quiz.streak": "{0} in a row",
"quiz.showSteps": "Show solution",
"quiz.unit": "Unit: {0}",
"ruler.title": "Visual ruler",
"ruler.mapBar": "Map distance (real cm)",
"ruler.realBar": "Real distance (compressed by the same scale)",
"ruler.sameWidth": "same width as above",
"ruler.equals": "equals",
"ruler.segment": "Graphic scale",
"ruler.segmentHint": "auto-ranging ticks",
"ruler.spectrum": "Scale spectrum",
"ruler.scopeUp": "◀ larger area",
"ruler.detailDown": "more detail ▶",
"ruler.hint": "Blue is the real map length; green is the same real distance compressed by the scale",
"ruler.overflowMap": "This map distance overflows the sheet — use a smaller scale",
"ruler.overflowReal": "This real distance won't fit at this scale — use a smaller scale",
"unit.cm": "cm",
"unit.m": "m",
"unit.km": "km",
"unit.none": "(unitless)",
"spec.campus": "Campus",
"spec.city": "City",
"spec.china": "China",
"spec.world": "World",
"preset.campus": "Campus 1:10k",
"preset.campusNote": "Buildings clearly drawn",
"preset.town": "Town 1:50k",
"preset.townNote": "Villages and roads",
"preset.city": "City 1:250k",
"preset.cityNote": "Urban area and arterials",
"preset.province": "Province 1:1M",
"preset.provinceNote": "Cities and rivers",
"preset.china": "China 1:10M",
"preset.chinaNote": "Province outlines",
"preset.world": "World 1:100M",
"preset.worldNote": "Continents & oceans",
"lm.classroom": "Classroom 10 m",
"lm.track": "Running track 400 m",
"lm.marathon": "Marathon 42.195 km",
"lm.beijingShanghai": "Beijing–Shanghai 1080 km",
"lm.equator": "Equator 40,000 km",
"common.footer": "Scale = map distance ÷ real distance · unify units first · bigger denominator = smaller scale"
}
@@ -0,0 +1,106 @@
{
"app.title": "比例尺计算器",
"app.subtitle": "把「图上距离 ÷ 实地距离」变成可以拖、可以量的可视化标尺",
"mode.real": "求实地距离",
"mode.map": "求图上距离",
"mode.scale": "求比例尺",
"mode.hint": "选择要求什么,蓝色结果卡就是答案",
"input.title": "已知量",
"input.map": "图上距离",
"input.real": "实地距离",
"input.scale": "比例尺分母 N",
"input.nPrefix": "1 :",
"input.unit": "单位",
"input.reset": "重置",
"input.presets": "常用比例尺",
"input.dragHint": "拖动滑块或直接输入数字,读数实时联动",
"result.title": "计算结果",
"result.real": "实地距离",
"result.map": "图上距离",
"result.scale": "比例尺",
"result.formula": "计算公式",
"forms.title": "比例尺的三种写法",
"forms.digital": "数字式",
"forms.verbal": "文字式",
"forms.segment": "线段式",
"forms.verbalTpl": "图上 1 厘米代表实地 {0}",
"forms.segmentDesc": "每格 {0},共 {1} 格",
"steps.title": "解题步骤",
"steps.show": "展开步骤",
"steps.hide": "收起步骤",
"steps.1.unify": "① 统一单位:把实地距离化成厘米(1 km = 100000 cm,去掉 5 个 0)",
"steps.2.formulaReal": "② 实地距离 = 图上距离 × 比例尺分母",
"steps.2.formulaMap": "② 图上距离 = 实地距离 ÷ 比例尺分母",
"steps.2.formulaScale": "② 比例尺分母 = 实地距离 ÷ 图上距离",
"steps.3.substitute": "③ 代入数值:{0}",
"steps.4.result": "④ 算出结果:{0}",
"steps.5.convert": "⑤ 换算成合适单位(cm → m → km)",
"grade.title": "大小判读",
"grade.large": "大比例尺",
"grade.medium": "中比例尺",
"grade.small": "小比例尺",
"grade.largeNote": "范围小 · 内容详细 · 如校园平面图",
"grade.mediumNote": "范围中等 · 如城市交通图",
"grade.smallNote": "范围大 · 内容简略 · 如世界地图",
"grade.rule": "分母越大 → 比例尺越小 → 范围越大 → 越简略",
"pit.title": "易错点",
"pit.1": "① 忘记统一单位:km 要 ×100000 才成 cm",
"pit.2": "② 「放大 2 倍」是分母 ÷ 2,不是 × 2",
"pit.3": "③ 图上距离与实地距离别代反了",
"field.title": "实地尺 · 这段距离画到图上多长",
"field.hint": "选一个真实距离,改变比例尺看它在图上的长度",
"field.mapLength": "图上 {0}",
"field.tooLong": "画不下",
"field.tooShort": "几乎看不见",
"quiz.title": "练习闯关",
"quiz.promptReal": "比例尺 1:{0},图上 {1} 厘米,实地距离是多少?(按提示单位填数字)",
"quiz.promptMap": "比例尺 1:{0},实地 {1},图上距离是多少厘米?",
"quiz.promptScale": "图上 {0} 厘米代表实地 {1},比例尺分母是多少?",
"quiz.answer": "输入答案",
"quiz.check": "检查",
"quiz.next": "下一题",
"quiz.correct": "✓ 答对了!",
"quiz.wrong": "✗ 再想想,看看解题步骤",
"quiz.streak": "连对 {0} 题",
"quiz.showSteps": "查看解题步骤",
"quiz.unit": "单位:{0}",
"ruler.title": "可视化标尺",
"ruler.mapBar": "图上距离(真实厘米)",
"ruler.realBar": "实地距离(按同一比例尺压缩)",
"ruler.sameWidth": "与上方同宽",
"ruler.equals": "等于",
"ruler.segment": "线段式比例尺",
"ruler.segmentHint": "刻度自动换挡",
"ruler.spectrum": "比例尺光谱",
"ruler.scopeUp": "◀ 范围越大",
"ruler.detailDown": "内容越详细 ▶",
"ruler.hint": "蓝色是图上真实长度;绿色是同一段实地按比例尺压缩后的长度",
"ruler.overflowMap": "这段图上距离超出图幅,需要更小的比例尺",
"ruler.overflowReal": "这段实地距离在该比例尺下画不下,需要更小的比例尺",
"unit.cm": "厘米",
"unit.m": "米",
"unit.km": "千米",
"unit.none": "(无单位)",
"spec.campus": "校园",
"spec.city": "城市",
"spec.china": "中国",
"spec.world": "世界",
"preset.campus": "校园 1:1万",
"preset.campusNote": "操场、教学楼都画得清",
"preset.town": "乡镇 1:5万",
"preset.townNote": "村镇与道路",
"preset.city": "城市 1:25万",
"preset.cityNote": "城区与主干道",
"preset.province": "省区 1:100万",
"preset.provinceNote": "地级市与河流",
"preset.china": "中国 1:1000万",
"preset.chinaNote": "省级轮廓",
"preset.world": "世界 1:1亿",
"preset.worldNote": "大洲大洋",
"lm.classroom": "教室 10 m",
"lm.track": "操场一圈 400 m",
"lm.marathon": "马拉松 42.195 km",
"lm.beijingShanghai": "北京—上海 1080 km",
"lm.equator": "赤道 4 万 km",
"common.footer": "比例尺 = 图上距离 ÷ 实地距离 · 单位统一是第一步 · 分母越大,比例尺越小"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

@@ -0,0 +1,23 @@
{
"presets": [
{ "n": 10000, "nameKey": "preset.campus", "noteKey": "preset.campusNote" },
{ "n": 50000, "nameKey": "preset.town", "noteKey": "preset.townNote" },
{ "n": 250000, "nameKey": "preset.city", "noteKey": "preset.cityNote" },
{ "n": 1000000, "nameKey": "preset.province", "noteKey": "preset.provinceNote" },
{ "n": 10000000, "nameKey": "preset.china", "noteKey": "preset.chinaNote" },
{ "n": 100000000, "nameKey": "preset.world", "noteKey": "preset.worldNote" }
],
"spectrum": [
{ "n": 10000, "labelKey": "spec.campus", "scopeKey": "spec.campusScope" },
{ "n": 250000, "labelKey": "spec.city", "scopeKey": "spec.cityScope" },
{ "n": 10000000, "labelKey": "spec.china", "scopeKey": "spec.chinaScope" },
{ "n": 100000000, "labelKey": "spec.world", "scopeKey": "spec.worldScope" }
],
"landmarks": [
{ "nameKey": "lm.classroom", "meters": 10 },
{ "nameKey": "lm.track", "meters": 400 },
{ "nameKey": "lm.marathon", "meters": 42195 },
{ "nameKey": "lm.beijingShanghai", "meters": 1080000 },
{ "nameKey": "lm.equator", "meters": 40000000 }
]
}
+251
View File
@@ -0,0 +1,251 @@
using System.Collections.Generic;
namespace NeoRF.ScaleCalculator;
/// <summary>内置全量文案兜底:即使模型包里没有语言包也能完整显示。</summary>
internal static class DefaultTexts
{
public static readonly Dictionary<string, string> Zh = new()
{
["app.title"] = "比例尺计算器",
["app.subtitle"] = "把「图上距离 ÷ 实地距离」变成可以拖、可以量的可视化标尺",
["mode.real"] = "求实地距离",
["mode.map"] = "求图上距离",
["mode.scale"] = "求比例尺",
["mode.hint"] = "选择要求什么,蓝色结果卡就是答案",
["input.title"] = "已知量",
["input.map"] = "图上距离",
["input.real"] = "实地距离",
["input.scale"] = "比例尺分母 N",
["input.nPrefix"] = "1 :",
["input.unit"] = "单位",
["input.reset"] = "重置",
["input.presets"] = "常用比例尺",
["input.dragHint"] = "拖动滑块或直接输入数字,读数实时联动",
["result.title"] = "计算结果",
["result.real"] = "实地距离",
["result.map"] = "图上距离",
["result.scale"] = "比例尺",
["result.formula"] = "计算公式",
["forms.title"] = "比例尺的三种写法",
["forms.digital"] = "数字式",
["forms.verbal"] = "文字式",
["forms.segment"] = "线段式",
["forms.verbalTpl"] = "图上 1 厘米代表实地 {0}",
["forms.segmentDesc"] = "每格 {0},共 {1} 格",
["steps.title"] = "解题步骤",
["steps.show"] = "展开步骤",
["steps.hide"] = "收起步骤",
["steps.1.unify"] = "① 统一单位:把实地距离化成厘米(1 km = 100000 cm,去掉 5 个 0)",
["steps.2.formulaReal"] = "② 实地距离 = 图上距离 × 比例尺分母",
["steps.2.formulaMap"] = "② 图上距离 = 实地距离 ÷ 比例尺分母",
["steps.2.formulaScale"] = "② 比例尺分母 = 实地距离 ÷ 图上距离",
["steps.3.substitute"] = "③ 代入数值:{0}",
["steps.4.result"] = "④ 算出结果:{0}",
["steps.5.convert"] = "⑤ 换算成合适单位(cm → m → km)",
["grade.title"] = "大小判读",
["grade.large"] = "大比例尺",
["grade.medium"] = "中比例尺",
["grade.small"] = "小比例尺",
["grade.largeNote"] = "范围小 · 内容详细 · 如校园平面图",
["grade.mediumNote"] = "范围中等 · 如城市交通图",
["grade.smallNote"] = "范围大 · 内容简略 · 如世界地图",
["grade.rule"] = "分母越大 → 比例尺越小 → 范围越大 → 越简略",
["pit.title"] = "易错点",
["pit.1"] = "① 忘记统一单位:km 要 ×100000 才成 cm",
["pit.2"] = "② 「放大 2 倍」是分母 ÷ 2,不是 × 2",
["pit.3"] = "③ 图上距离与实地距离别代反了",
["field.title"] = "实地尺 · 这段距离画到图上多长",
["field.hint"] = "选一个真实距离,改变比例尺看它在图上的长度",
["field.mapLength"] = "图上 {0}",
["field.tooLong"] = "画不下",
["field.tooShort"] = "几乎看不见",
["quiz.title"] = "练习闯关",
["quiz.promptReal"] = "比例尺 1:{0},图上 {1} 厘米,实地距离是多少?(按提示单位填数字)",
["quiz.promptMap"] = "比例尺 1:{0},实地 {1},图上距离是多少厘米?",
["quiz.promptScale"] = "图上 {0} 厘米代表实地 {1},比例尺分母是多少?",
["quiz.answer"] = "输入答案",
["quiz.check"] = "检查",
["quiz.next"] = "下一题",
["quiz.correct"] = "✓ 答对了!",
["quiz.wrong"] = "✗ 再想想,看看解题步骤",
["quiz.streak"] = "连对 {0} 题",
["quiz.showSteps"] = "查看解题步骤",
["quiz.unit"] = "单位:{0}",
["ruler.title"] = "可视化标尺",
["ruler.mapBar"] = "图上距离(真实厘米)",
["ruler.realBar"] = "实地距离(按同一比例尺压缩)",
["ruler.sameWidth"] = "与上方同宽",
["ruler.equals"] = "等于",
["ruler.segment"] = "线段式比例尺",
["ruler.segmentHint"] = "刻度自动换挡",
["ruler.spectrum"] = "比例尺光谱",
["ruler.scopeUp"] = "◀ 范围越大",
["ruler.detailDown"] = "内容越详细 ▶",
["ruler.hint"] = "蓝色是图上真实长度;绿色是同一段实地按比例尺压缩后的长度",
["ruler.overflowMap"] = "这段图上距离超出图幅,需要更小的比例尺",
["ruler.overflowReal"] = "这段实地距离在该比例尺下画不下,需要更小的比例尺",
["unit.cm"] = "厘米",
["unit.m"] = "米",
["unit.km"] = "千米",
["unit.none"] = "(无单位)",
["spec.campus"] = "校园",
["spec.city"] = "城市",
["spec.china"] = "中国",
["spec.world"] = "世界",
["preset.campus"] = "校园 1:1万",
["preset.campusNote"] = "操场、教学楼都画得清",
["preset.town"] = "乡镇 1:5万",
["preset.townNote"] = "村镇与道路",
["preset.city"] = "城市 1:25万",
["preset.cityNote"] = "城区与主干道",
["preset.province"] = "省区 1:100万",
["preset.provinceNote"] = "地级市与河流",
["preset.china"] = "中国 1:1000万",
["preset.chinaNote"] = "省级轮廓",
["preset.world"] = "世界 1:1亿",
["preset.worldNote"] = "大洲大洋",
["lm.classroom"] = "教室 10 m",
["lm.track"] = "操场一圈 400 m",
["lm.marathon"] = "马拉松 42.195 km",
["lm.beijingShanghai"] = "北京—上海 1080 km",
["lm.equator"] = "赤道 4 万 km",
["common.footer"] = "比例尺 = 图上距离 ÷ 实地距离 · 单位统一是第一步 · 分母越大,比例尺越小"
};
public static readonly Dictionary<string, string> En = new()
{
["app.title"] = "Scale Calculator",
["app.subtitle"] = "Turn map-distance ÷ real-distance into a ruler you can drag and measure",
["mode.real"] = "Find real distance",
["mode.map"] = "Find map distance",
["mode.scale"] = "Find scale",
["mode.hint"] = "Pick what to solve; the blue card is the answer",
["input.title"] = "Given",
["input.map"] = "Map distance",
["input.real"] = "Real distance",
["input.scale"] = "Scale denominator N",
["input.nPrefix"] = "1 :",
["input.unit"] = "Unit",
["input.reset"] = "Reset",
["input.presets"] = "Common scales",
["input.dragHint"] = "Drag the slider or type a number — everything updates live",
["result.title"] = "Result",
["result.real"] = "Real distance",
["result.map"] = "Map distance",
["result.scale"] = "Scale",
["result.formula"] = "Formula",
["forms.title"] = "Three ways to write a scale",
["forms.digital"] = "Numeric",
["forms.verbal"] = "Verbal",
["forms.segment"] = "Graphic (bar)",
["forms.verbalTpl"] = "1 cm on the map = {0} on the ground",
["forms.segmentDesc"] = "Each division {0}, {1} divisions",
["steps.title"] = "Worked solution",
["steps.show"] = "Show steps",
["steps.hide"] = "Hide steps",
["steps.1.unify"] = "① Unify units: convert the real distance to cm (1 km = 100000 cm)",
["steps.2.formulaReal"] = "② Real distance = map distance × scale denominator",
["steps.2.formulaMap"] = "② Map distance = real distance ÷ scale denominator",
["steps.2.formulaScale"] = "② Scale denominator = real distance ÷ map distance",
["steps.3.substitute"] = "③ Substitute: {0}",
["steps.4.result"] = "④ Result: {0}",
["steps.5.convert"] = "⑤ Convert to a sensible unit (cm → m → km)",
["grade.title"] = "Large / small scale",
["grade.large"] = "Large scale",
["grade.medium"] = "Medium scale",
["grade.small"] = "Small scale",
["grade.largeNote"] = "Small area · detailed · e.g. campus plan",
["grade.mediumNote"] = "Medium area · e.g. city map",
["grade.smallNote"] = "Large area · simplified · e.g. world map",
["grade.rule"] = "Bigger denominator → smaller scale → larger area → less detail",
["pit.title"] = "Common mistakes",
["pit.1"] = "① Forgetting to unify units: km ×100000 = cm",
["pit.2"] = "② \"Zoom 2×\" means denominator ÷ 2, not × 2",
["pit.3"] = "③ Don't swap map distance and real distance",
["field.title"] = "Real-world ruler · how long on the map",
["field.hint"] = "Pick a real distance and change the scale to see its map length",
["field.mapLength"] = "On map {0}",
["field.tooLong"] = "too long",
["field.tooShort"] = "barely visible",
["quiz.title"] = "Practice",
["quiz.promptReal"] = "Scale 1:{0}, map distance {1} cm — what is the real distance? (enter the number in the shown unit)",
["quiz.promptMap"] = "Scale 1:{0}, real distance {1} — what is the map distance in cm?",
["quiz.promptScale"] = "{0} cm on the map = {1} on the ground — what is the scale denominator?",
["quiz.answer"] = "Your answer",
["quiz.check"] = "Check",
["quiz.next"] = "Next",
["quiz.correct"] = "✓ Correct!",
["quiz.wrong"] = "✗ Try again — read the steps",
["quiz.streak"] = "{0} in a row",
["quiz.showSteps"] = "Show solution",
["quiz.unit"] = "Unit: {0}",
["ruler.title"] = "Visual ruler",
["ruler.mapBar"] = "Map distance (real cm)",
["ruler.realBar"] = "Real distance (compressed by the same scale)",
["ruler.sameWidth"] = "same width as above",
["ruler.equals"] = "equals",
["ruler.segment"] = "Graphic scale",
["ruler.segmentHint"] = "auto-ranging ticks",
["ruler.spectrum"] = "Scale spectrum",
["ruler.scopeUp"] = "◀ larger area",
["ruler.detailDown"] = "more detail ▶",
["ruler.hint"] = "Blue is the real map length; green is the same real distance compressed by the scale",
["ruler.overflowMap"] = "This map distance overflows the sheet — use a smaller scale",
["ruler.overflowReal"] = "This real distance won't fit at this scale — use a smaller scale",
["unit.cm"] = "cm",
["unit.m"] = "m",
["unit.km"] = "km",
["unit.none"] = "(unitless)",
["spec.campus"] = "Campus",
["spec.city"] = "City",
["spec.china"] = "China",
["spec.world"] = "World",
["preset.campus"] = "Campus 1:10k",
["preset.campusNote"] = "Buildings clearly drawn",
["preset.town"] = "Town 1:50k",
["preset.townNote"] = "Villages and roads",
["preset.city"] = "City 1:250k",
["preset.cityNote"] = "Urban area and arterials",
["preset.province"] = "Province 1:1M",
["preset.provinceNote"] = "Cities and rivers",
["preset.china"] = "China 1:10M",
["preset.chinaNote"] = "Province outlines",
["preset.world"] = "World 1:100M",
["preset.worldNote"] = "Continents & oceans",
["lm.classroom"] = "Classroom 10 m",
["lm.track"] = "Running track 400 m",
["lm.marathon"] = "Marathon 42.195 km",
["lm.beijingShanghai"] = "Beijing–Shanghai 1080 km",
["lm.equator"] = "Equator 40,000 km",
["common.footer"] = "Scale = map distance ÷ real distance · unify units first · bigger denominator = smaller scale"
};
}
@@ -0,0 +1,10 @@
using EarthModelStudio.ModelSdk;
namespace NeoRF.ScaleCalculator;
/// <summary>比例尺计算器模型入口(清单里的 type 指向这里)。</summary>
public sealed class ScaleCalculatorFactory : IModelFactory
{
public int ApiVersion => 1;
public IModelRuntime Create() => new ScaleCalculatorRuntime();
}
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>NeoRF.ScaleCalculator</RootNamespace>
<AssemblyName>ScaleCalculatorModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<!-- 本模型不复用 _engine 的球面渲染,只用 Avalonia 基础控件 + 一个自绘标尺 -->
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Avalonia.Controls;
using EarthModelStudio.ModelSdk;
namespace NeoRF.ScaleCalculator;
/// <summary>
/// 比例尺计算器运行时。Prepare 在后台线程读数据/语言包,CreateView 在 UI 线程构建界面。
/// 不依赖 _engine(没有球面渲染),只用 Avalonia 基础控件 + 一个自绘标尺。
/// </summary>
public sealed class ScaleCalculatorRuntime : IModelRuntime
{
private ScaleData? _data;
private Dictionary<string, string>? _texts;
public void Prepare(IModelContext context)
{
context.ReportProgress(0.1, "载入预设数据");
_data = ScaleData.Load(context.DataDirectory);
context.ReportProgress(0.55, "载入语言包");
_texts = LoadTexts(context.DataDirectory, context.Language);
context.ReportProgress(0.9, "准备界面");
context.Log($"[scale-calculator] 语言 {context.Language}," +
$"预设 {_data.Presets.Count} 档 / 地标 {_data.Landmarks.Count} 个");
}
public Control CreateView(IModelContext context)
{
context.ReportProgress(0.96, "构建界面");
_data ??= ScaleData.Load(context.DataDirectory);
_texts ??= LoadTexts(context.DataDirectory, context.Language);
var view = new ScaleCalculatorView(_data, _texts, context.Language);
context.ReportProgress(1.0, "准备就绪");
return view;
}
public void Dispose()
{
_data = null;
_texts = null;
GC.SuppressFinalize(this);
}
private static Dictionary<string, string> LoadTexts(string dataDir, string language)
{
// 先内置中文兜底,再按 language 覆盖,最后用 zh-CN 补齐缺键
var map = new Dictionary<string, string>(DefaultTexts.Zh);
var isEn = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
if (isEn)
foreach (var kv in DefaultTexts.En) map[kv.Key] = kv.Value;
Overlay(Path.Combine(dataDir, "i18n", "zh-CN.json"), map);
if (isEn) Overlay(Path.Combine(dataDir, "i18n", "en.json"), map);
else Overlay(Path.Combine(dataDir, "i18n", language + ".json"), map);
return map;
}
private static void Overlay(string path, Dictionary<string, string> target)
{
if (!File.Exists(path)) return;
try
{
var extra = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(path),
new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
if (extra == null) return;
foreach (var kv in extra) target[kv.Key] = kv.Value;
}
catch (Exception ex)
{
Console.Error.WriteLine($"[scale-calculator] 语言包读取失败 {path}: {ex.Message}");
}
}
}
@@ -0,0 +1,489 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
namespace NeoRF.ScaleCalculator;
public sealed partial class ScaleCalculatorView
{
// 模式条
private Button _btnReal = null!, _btnMap = null!, _btnScale = null!;
// 左栏输入
private Slider _mapSlider = null!;
private TextBox _mapBox = null!, _realBox = null!, _nBox = null!;
private ComboBox _unitBox = null!;
private TextBlock _mapCardLabel = null!, _realCardLabel = null!, _scaleCardLabel = null!;
private TextBlock _mapResultText = null!, _realResultText = null!, _scaleResultText = null!;
private Border _mapCard = null!, _realCard = null!, _scaleCard = null!;
private WrapPanel _presetPanel = null!;
// 中栏
private ScaleRuler _ruler = null!;
// 右栏
private TextBlock _digitalText = null!, _verbalText = null!, _segmentText = null!;
private TextBlock _gradeTitle = null!, _gradeNote = null!, _gradeRule = null!;
private Border _gradeChip = null!;
private StackPanel _stepsPanel = null!;
private Button _stepsToggle = null!;
private bool _stepsOpen;
// 底部:实地尺
private ComboBox _landmarkBox = null!;
private TextBlock _landmarkResult = null!;
// 底部:练习
private TextBlock _quizPrompt = null!, _quizFeedback = null!, _quizStreak = null!, _quizUnit = null!;
private TextBox _quizInput = null!;
private Button _quizCheck = null!, _quizNext = null!;
private StackPanel _quizSteps = null!;
private void BuildLayout()
{
var root = new Grid { Background = B(CAppBg) };
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); // 顶部
root.RowDefinitions.Add(new RowDefinition(GridLength.Star)); // 三栏
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); // 底部
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); // 页脚
var header = BuildHeader();
Grid.SetRow(header, 0);
root.Children.Add(header);
var columns = new Grid { Margin = new Thickness(16, 12, 16, 8) };
columns.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(300)));
columns.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(16)));
columns.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
columns.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(16)));
columns.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(320)));
var left = BuildLeft();
Grid.SetColumn(left, 0);
columns.Children.Add(left);
var mid = BuildMiddle();
Grid.SetColumn(mid, 2);
columns.Children.Add(mid);
var right = BuildRight();
Grid.SetColumn(right, 4);
columns.Children.Add(right);
Grid.SetRow(columns, 1);
root.Children.Add(columns);
var bottom = BuildBottom();
Grid.SetRow(bottom, 2);
root.Children.Add(bottom);
var footer = new Border
{
Background = B(CSurfaceAlt),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 1, 0, 0),
Padding = new Thickness(20, 9),
Child = Tb(T("common.footer"), 11, CInkFaint)
};
Grid.SetRow(footer, 3);
root.Children.Add(footer);
Content = root;
}
private Control BuildHeader()
{
var title = Tb(T("app.title"), 22, CInk, FontWeight.SemiBold);
var sub = Tb(T("app.subtitle"), 12, CInkDim);
_btnReal = Btn(T("mode.real"));
_btnMap = Btn(T("mode.map"));
_btnScale = Btn(T("mode.scale"));
var modes = H(8);
modes.Children.Add(_btnReal);
modes.Children.Add(_btnMap);
modes.Children.Add(_btnScale);
var leftStack = V(2);
leftStack.Children.Add(title);
leftStack.Children.Add(sub);
var grid = new Grid
{
Background = B(CSurface),
Margin = new Thickness(0)
};
grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));
var leftBorder = new Border { Padding = new Thickness(20, 14, 10, 14), Child = leftStack };
Grid.SetColumn(leftBorder, 0);
grid.Children.Add(leftBorder);
var rightBorder = new Border
{
Padding = new Thickness(10, 14, 20, 14),
VerticalAlignment = VerticalAlignment.Center,
Child = V(4)
};
// 右侧:提示 + 模式按钮
var rv = (StackPanel)rightBorder.Child!;
rv.Children.Add(Tb(T("mode.hint"), 10.5, CInkFaint, align: TextAlignment.Right));
rv.Children.Add(modes);
Grid.SetColumn(rightBorder, 1);
grid.Children.Add(rightBorder);
var outer = new Border
{
Background = B(CSurface),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 0, 0, 1),
Child = grid
};
return outer;
}
private Control BuildLeft()
{
var panel = V(10);
var head = H(6);
head.Children.Add(new Border
{
Width = 4, Height = 16, Background = B(CAccent),
CornerRadius = new CornerRadius(2)
});
head.Children.Add(H3(T("input.title")));
panel.Children.Add(head);
// ── 图上距离卡
panel.Children.Add(BuildInputCard(
"input.map", "unit.cm", out _mapCard, out _mapCardLabel, out _mapResultText,
out _mapSlider, out _mapBox, withSlider: true));
// ── 实地距离卡
panel.Children.Add(BuildRealCard());
// ── 比例尺卡
panel.Children.Add(BuildScaleCard());
// 预设
panel.Children.Add(Label(T("input.presets"), 11.5, CInkFaint));
_presetPanel = new WrapPanel { Orientation = Orientation.Horizontal };
foreach (var p in _data.Presets)
{
var b = Btn(T(p.NameKey));
b.Tag = p;
b.Click += (_, _) => ApplyPreset((PresetItem)b.Tag!);
b.Margin = new Thickness(0, 0, 6, 6);
_presetPanel.Children.Add(b);
}
panel.Children.Add(_presetPanel);
panel.Children.Add(Divider());
var reset = Btn(T("input.reset"));
reset.Click += (_, _) => ResetState();
panel.Children.Add(reset);
panel.Children.Add(Tb(T("input.dragHint"), 10.5, CInkFaint));
var scroll = new ScrollViewer
{
Content = new Border { Padding = new Thickness(14), Child = panel },
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled
};
return Card(scroll);
}
private Control BuildInputCard(string labelKey, string unitKey,
out Border card, out TextBlock label, out TextBlock resultText,
out Slider slider, out TextBox box, bool withSlider)
{
label = Label(T(labelKey), 11.5);
resultText = Tb("—", 15, CInk, FontWeight.SemiBold);
var top = new DockPanel();
top.Children.Add(resultText);
DockPanel.SetDock(resultText, Dock.Right);
top.Children.Add(label);
box = Input("3");
box.Width = 110;
box.HorizontalAlignment = HorizontalAlignment.Left;
slider = new Slider
{
Minimum = 0.1,
Maximum = 20,
Value = 3,
TickFrequency = 0.5,
IsSnapToTickEnabled = false,
Foreground = B(CAccent),
Margin = new Thickness(0, 2, 0, 0)
};
var stack = V(6);
stack.Children.Add(top);
stack.Children.Add(box);
if (withSlider) stack.Children.Add(slider);
card = new Border
{
Background = B(CSurfaceAlt),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(10),
Padding = new Thickness(12),
Child = stack
};
return card;
}
private Control BuildRealCard()
{
_realCardLabel = Label(T("input.real"), 11.5);
_realResultText = Tb("—", 15, CInk, FontWeight.SemiBold);
var top = new DockPanel();
top.Children.Add(_realResultText);
DockPanel.SetDock(_realResultText, Dock.Right);
top.Children.Add(_realCardLabel);
_realBox = Input("3");
_unitBox = new ComboBox
{
FontSize = 12.5,
Background = B(CSurface),
Foreground = B(CInk),
BorderBrush = B(CLineStrong),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(9),
Padding = new Thickness(10, 6),
MinHeight = 34,
Width = 92,
ItemsSource = new[] { "unit.km", "unit.m", "unit.cm" },
SelectedIndex = 0
};
// 显示本地化单位名
_unitBox.SelectionChanged += (_, _) => { SyncUnitDisplay(); RefreshAll(syncInputs: true); };
var row = H(8);
row.Children.Add(_realBox);
row.Children.Add(_unitBox);
var stack = V(6);
stack.Children.Add(top);
stack.Children.Add(row);
_realCard = new Border
{
Background = B(CSurfaceAlt),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(10),
Padding = new Thickness(12),
Child = stack
};
return _realCard;
}
private Control BuildScaleCard()
{
_scaleCardLabel = Label(T("input.scale"), 11.5);
_scaleResultText = Tb("—", 15, CInk, FontWeight.SemiBold);
var top = new DockPanel();
top.Children.Add(_scaleResultText);
DockPanel.SetDock(_scaleResultText, Dock.Right);
top.Children.Add(_scaleCardLabel);
_nBox = Input("100000");
var prefix = Tb(T("input.nPrefix"), 13, CInkDim, FontWeight.SemiBold);
var row = H(8);
row.Children.Add(prefix);
row.Children.Add(_nBox);
var stack = V(6);
stack.Children.Add(top);
stack.Children.Add(row);
_scaleCard = new Border
{
Background = B(CSurfaceAlt),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(10),
Padding = new Thickness(12),
Child = stack
};
return _scaleCard;
}
private Control BuildMiddle()
{
_ruler = new ScaleRuler
{
Data = _data,
State = _state,
T = T,
Height = 470,
VerticalAlignment = VerticalAlignment.Top
};
var holder = new Border
{
Background = B(CSurface),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(14),
Padding = new Thickness(6),
Child = _ruler
};
return holder;
}
private Control BuildRight()
{
var panel = V(10);
// 三种写法
panel.Children.Add(SectionTitle(T("forms.title")));
_digitalText = Tb("", 16, CAccentDark, FontWeight.SemiBold);
_verbalText = Tb("", 12, CInk);
_segmentText = Tb("", 12, CInk);
var forms = V(8);
forms.Children.Add(FormRow(T("forms.digital"), _digitalText));
forms.Children.Add(FormRow(T("forms.verbal"), _verbalText));
forms.Children.Add(FormRow(T("forms.segment"), _segmentText));
panel.Children.Add(forms);
panel.Children.Add(Divider());
// 解题步骤
_stepsToggle = Btn(T("steps.show"));
_stepsToggle.Click += (_, _) => ToggleSteps();
var sh = new DockPanel();
DockPanel.SetDock(_stepsToggle, Dock.Right);
sh.Children.Add(_stepsToggle);
sh.Children.Add(SectionTitle(T("steps.title")));
panel.Children.Add(sh);
_stepsPanel = V(4);
_stepsPanel.IsVisible = false;
panel.Children.Add(_stepsPanel);
panel.Children.Add(Divider());
// 判读
panel.Children.Add(SectionTitle(T("grade.title")));
_gradeChip = Chip("", CAccentSoft, CAccentDark);
_gradeChip.HorizontalAlignment = HorizontalAlignment.Left;
_gradeTitle = Tb("", 13, CInk, FontWeight.SemiBold);
_gradeNote = Tb("", 11.5, CInkDim);
_gradeRule = Tb(T("grade.rule"), 11, CAccentDark, FontWeight.SemiBold);
var gradeBox = V(6);
gradeBox.Children.Add(_gradeChip);
gradeBox.Children.Add(_gradeNote);
gradeBox.Children.Add(_gradeRule);
panel.Children.Add(gradeBox);
panel.Children.Add(Divider());
// 易错点
panel.Children.Add(SectionTitle(T("pit.title")));
var pit = V(4);
pit.Children.Add(Tb(T("pit.1"), 11, CInkDim));
pit.Children.Add(Tb(T("pit.2"), 11, CInkDim));
pit.Children.Add(Tb(T("pit.3"), 11, CInkDim));
panel.Children.Add(pit);
var scroll = new ScrollViewer
{
Content = new Border { Padding = new Thickness(14), Child = panel },
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled
};
return Card(scroll);
}
private Control FormRow(string name, TextBlock value)
{
var g = new Grid();
g.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(62)));
g.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
var n = Tb(name, 11, CInkFaint);
Grid.SetColumn(n, 0);
g.Children.Add(n);
Grid.SetColumn(value, 1);
g.Children.Add(value);
return g;
}
private Control SectionTitle(string text)
=> Tb(text, 12.5, CInk, FontWeight.SemiBold);
private Control BuildBottom()
{
var grid = new Grid { Margin = new Thickness(16, 4, 16, 12) };
grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
grid.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(12)));
grid.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(1.4, GridUnitType.Star)));
// ── 实地尺
var field = V(8);
field.Children.Add(SectionTitle(T("field.title")));
field.Children.Add(Tb(T("field.hint"), 10.5, CInkFaint));
_landmarkBox = new ComboBox
{
FontSize = 12.5,
Background = B(CSurface),
Foreground = B(CInk),
BorderBrush = B(CLineStrong),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(9),
Padding = new Thickness(10, 6),
MinHeight = 34,
HorizontalAlignment = HorizontalAlignment.Stretch
};
foreach (var lm in _data.Landmarks) _landmarkBox.Items!.Add(T(lm.NameKey));
_landmarkBox.SelectedIndex = 0;
_landmarkBox.SelectionChanged += (_, _) => RefreshField();
field.Children.Add(_landmarkBox);
_landmarkResult = Tb("", 14, CSuccess, FontWeight.SemiBold);
field.Children.Add(_landmarkResult);
var fieldCard = Card(field);
Grid.SetColumn(fieldCard, 0);
grid.Children.Add(fieldCard);
// ── 练习
var quiz = V(8);
_quizStreak = Tb(TF("quiz.streak", 0), 11, CAccentDark, FontWeight.SemiBold);
var qh = new DockPanel();
DockPanel.SetDock(_quizStreak, Dock.Right);
qh.Children.Add(_quizStreak);
qh.Children.Add(SectionTitle(T("quiz.title")));
quiz.Children.Add(qh);
_quizPrompt = Tb("", 12, CInk);
quiz.Children.Add(_quizPrompt);
_quizUnit = Tb("", 10.5, CInkFaint);
quiz.Children.Add(_quizUnit);
var qrow = H(8);
_quizInput = Input("");
_quizInput.Width = 140;
_quizCheck = Btn(T("quiz.check"), primary: true);
_quizNext = Btn(T("quiz.next"));
_quizCheck.Click += (_, _) => CheckQuiz();
_quizNext.Click += (_, _) => NewQuiz();
qrow.Children.Add(_quizInput);
qrow.Children.Add(_quizCheck);
qrow.Children.Add(_quizNext);
quiz.Children.Add(qrow);
_quizFeedback = Tb("", 12, CInkDim, FontWeight.SemiBold);
quiz.Children.Add(_quizFeedback);
_quizSteps = V(2);
quiz.Children.Add(_quizSteps);
var quizCard = Card(quiz);
Grid.SetColumn(quizCard, 2);
grid.Children.Add(quizCard);
return grid;
}
}
@@ -0,0 +1,312 @@
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Media;
namespace NeoRF.ScaleCalculator;
public sealed partial class ScaleCalculatorView
{
private readonly ScaleState _state = new();
private bool _suppress;
private string _realUnit = "unit.km";
private QuizItem _quiz = new();
private int _streak;
private bool _quizAnswered;
private void WireEvents()
{
_btnReal.Click += (_, _) => SetMode(SolveMode.Real);
_btnMap.Click += (_, _) => SetMode(SolveMode.Map);
_btnScale.Click += (_, _) => SetMode(SolveMode.Scale);
_mapSlider.ValueChanged += (_, e) =>
{
if (_suppress) return;
_state.MapCm = e.NewValue;
_suppress = true;
_mapBox.Text = ScaleMath.Num(_state.MapCm);
_suppress = false;
RefreshAll(syncInputs: false);
};
_mapBox.TextChanged += (_, _) => OnTextInput(_mapBox, v => { _state.MapCm = v; }, v =>
{
_suppress = true;
_mapSlider.Value = Math.Clamp(v, 0.1, 20);
_suppress = false;
});
_realBox.TextChanged += (_, _) =>
{
if (_suppress) return;
if (ScaleMath.TryParseReal(_realBox.Text ?? "", _realUnit, out var cm))
{
_state.RealCm = cm;
RefreshAll(syncInputs: false);
}
};
_nBox.TextChanged += (_, _) => OnTextInput(_nBox, v => { _state.N = v; }, null);
_quizInput.KeyDown += (_, e) =>
{
if (e.Key == Avalonia.Input.Key.Enter) CheckQuiz();
};
}
private void OnTextInput(TextBox box, Action<double> apply, Action<double>? extra)
{
if (_suppress) return;
if (!double.TryParse((box.Text ?? "").Replace(",", "").Trim(), NumberStyles.Float,
CultureInfo.InvariantCulture, out var v) || v < 0 || double.IsNaN(v) || double.IsInfinity(v))
return;
apply(v);
extra?.Invoke(v);
RefreshAll(syncInputs: false);
}
private void SetMode(SolveMode mode, bool initial = false)
{
_state.Mode = mode;
if (!initial) ScaleMath.Solve(_state);
UpdateModeButtons();
RefreshAll(syncInputs: true);
}
private void UpdateModeButtons()
{
StyleMode(_btnReal, _state.Mode == SolveMode.Real);
StyleMode(_btnMap, _state.Mode == SolveMode.Map);
StyleMode(_btnScale, _state.Mode == SolveMode.Scale);
// 结果卡高亮:待求的那一张变蓝
StyleCard(_mapCard, _state.Mode == SolveMode.Map);
StyleCard(_realCard, _state.Mode == SolveMode.Real);
StyleCard(_scaleCard, _state.Mode == SolveMode.Scale);
_mapResultText.Foreground = B(_state.Mode == SolveMode.Map ? CAccentDark : CInk);
_realResultText.Foreground = B(_state.Mode == SolveMode.Real ? CAccentDark : CInk);
_scaleResultText.Foreground = B(_state.Mode == SolveMode.Scale ? CAccentDark : CInk);
}
private void StyleMode(Button b, bool active)
{
b.Background = B(active ? CAccent : CSurface);
b.BorderBrush = B(active ? CAccent : CLineStrong);
b.BorderThickness = new Thickness(active ? 0 : 1);
if (b.Content is TextBlock t)
t.Foreground = B(active ? Colors.White : CInk);
}
private static void StyleCard(Border card, bool active)
{
card.Background = B(active ? Color.Parse("#F0F5FF") : Color.Parse("#F7F9FE"));
card.BorderBrush = B(active ? Color.Parse("#2F6BFF") : Color.Parse("#E3E8F3"));
card.BorderThickness = new Thickness(active ? 1.5 : 1);
}
private void ApplyPreset(PresetItem p)
{
_state.N = p.N;
ScaleMath.Solve(_state);
RefreshAll(syncInputs: true);
}
private void ResetState()
{
_state.MapCm = 3.0;
_state.N = 100000.0;
ScaleMath.Solve(_state);
RefreshAll(syncInputs: true);
}
private void SyncUnitDisplay()
{
// ComboBox 的 ItemsSource 是 "unit.km" 等键;这里只记录选择,显示由下拉项本身处理
var idx = _unitBox.SelectedIndex;
_realUnit = idx switch { 1 => "unit.m", 2 => "unit.cm", _ => "unit.km" };
}
/// <summary>
/// 全量刷新。syncInputs=true 时把三个输入框/滑块同步成 state(切换模式、预设、重置后需要);
/// false 时保留用户正在输入的文本(避免光标跳动)。
/// </summary>
private void RefreshAll(bool syncInputs)
{
ScaleMath.Solve(_state);
if (syncInputs)
{
_suppress = true;
_mapBox.Text = ScaleMath.Num(_state.MapCm);
_mapSlider.Value = Math.Clamp(_state.MapCm, 0.1, 20);
_nBox.Text = ScaleMath.FormatN(_state.N);
var (rv, _) = ScaleMath.HumanReal(_state.RealCm);
// 用当前选择的单位显示
_realBox.Text = ScaleMath.Num(ScaleMath.ToUnit(_state.RealCm, _realUnit));
_suppress = false;
}
UpdateModeButtons();
// 结果卡读数(三张都显示当前值,蓝色那张是"答案")
_mapResultText.Text = ScaleMath.Num(_state.MapCm) + " " + T("unit.cm");
var (rv2, rkey2) = ScaleMath.HumanReal(_state.RealCm);
_realResultText.Text = ScaleMath.Num(rv2) + " " + T(rkey2);
_scaleResultText.Text = "1 : " + ScaleMath.FormatN(_state.N);
// 三种写法
_digitalText.Text = ScaleMath.Digital(_state.N);
_verbalText.Text = TF("forms.verbalTpl", ScaleMath.VerbalDistance(_state.N));
_segmentText.Text = TF("forms.segmentDesc",
ScaleMath.SegmentLabel(_ruler.Segment.MetersPerDiv), _ruler.Segment.DivCount);
// 判读
var gradeKey = ScaleMath.GradeKey(_state.N);
_gradeTitle.Text = T(gradeKey);
_gradeChip.Child = Tb(T(gradeKey), 11, CAccentDark, FontWeight.SemiBold);
_gradeNote.Text = T(gradeKey + "Note");
_gradeRule.Text = T("grade.rule");
// 标尺
_ruler.State = _state.Clone();
_ruler.Refresh();
_segmentText.Text = TF("forms.segmentDesc",
ScaleMath.SegmentLabel(_ruler.Segment.MetersPerDiv), _ruler.Segment.DivCount);
BuildSteps();
RefreshField();
}
private void BuildSteps()
{
_stepsPanel.Children.Clear();
var map = ScaleMath.Num(_state.MapCm);
var realCm = ScaleMath.Num(_state.RealCm);
var n = ScaleMath.FormatN(_state.N);
var (rv, rk) = ScaleMath.HumanReal(_state.RealCm);
var result = _state.Mode switch
{
SolveMode.Real => ScaleMath.Num(rv) + " " + T(rk),
SolveMode.Map => ScaleMath.Num(_state.MapCm) + " " + T("unit.cm"),
_ => "1 : " + ScaleMath.FormatN(_state.N)
};
var formulaKey = _state.Mode switch
{
SolveMode.Real => "steps.2.formulaReal",
SolveMode.Map => "steps.2.formulaMap",
_ => "steps.2.formulaScale"
};
var substitute = _state.Mode switch
{
SolveMode.Real => map + " cm × " + n,
SolveMode.Map => realCm + " cm ÷ " + n,
_ => realCm + " cm ÷ " + map + " cm"
};
var lines = new System.Collections.Generic.List<string>
{
T("steps.1.unify"),
T(formulaKey),
TF("steps.3.substitute", substitute),
TF("steps.4.result", result),
T("steps.5.convert")
};
var i = 0;
foreach (var line in lines)
{
_stepsPanel.Children.Add(Tb(line, 11, i == 3 ? CAccentDark : CInkDim,
i == 3 ? FontWeight.SemiBold : null));
i++;
}
}
private void ToggleSteps()
{
_stepsOpen = !_stepsOpen;
_stepsPanel.IsVisible = _stepsOpen;
_stepsToggle.Content = Tb(T(_stepsOpen ? "steps.hide" : "steps.show"), 12.5, CInk, FontWeight.SemiBold);
}
private void RefreshField()
{
var idx = _landmarkBox.SelectedIndex;
if (idx < 0 || idx >= _data.Landmarks.Count) return;
var meters = _data.Landmarks[idx].Meters;
var realCm = meters * ScaleMath.CmPerM;
var mapCm = ScaleMath.RealToMapCm(realCm, _state.N);
var px = ScaleMath.CmToPx(mapCm, _ruler.PxPerCm);
// mapCm 是厘米,按 HumanReal 换算成"图上长度"的合适单位
var (mv, mk) = ScaleMath.HumanReal(mapCm);
string text;
if (px > _ruler.MaxBarWidth)
text = TF("field.mapLength", ScaleMath.Num(mv) + " " + T(mk)) + " · " + T("field.tooLong");
else if (px < 1)
text = TF("field.mapLength", ScaleMath.Num(mv) + " " + T(mk)) + " · " + T("field.tooShort");
else
text = TF("field.mapLength", ScaleMath.Num(mv) + " " + T(mk));
_landmarkResult.Text = text;
_landmarkResult.Foreground = B(px > _ruler.MaxBarWidth ? CDanger : px < 1 ? CWarn : CSuccess);
}
// ────────────────────────────────────────────────────────── 练习
private void NewQuiz()
{
_quiz = ScaleMath.GenerateQuiz(_rnd);
_quizAnswered = false;
_quizInput.Text = "";
_quizFeedback.Text = "";
_quizSteps.Children.Clear();
_quizPrompt.Text = TF(_quiz.PromptKey, _quiz.PromptArgs);
var unitText = _quiz.AnswerUnitKey == "unit.none" ? T("unit.none") : T(_quiz.AnswerUnitKey);
_quizUnit.Text = TF("quiz.unit", unitText);
_quizStreak.Text = TF("quiz.streak", _streak);
}
private void CheckQuiz()
{
if (_quizAnswered) return;
if (!double.TryParse((_quizInput.Text ?? "").Replace(",", "").Trim(), NumberStyles.Float,
CultureInfo.InvariantCulture, out var v))
{
_quizFeedback.Text = T("quiz.wrong");
_quizFeedback.Foreground = B(CDanger);
return;
}
if (ScaleMath.CheckAnswer(_quiz, v))
{
_streak++;
_quizFeedback.Text = T("quiz.correct");
_quizFeedback.Foreground = B(CSuccess);
}
else
{
_streak = 0;
_quizFeedback.Text = T("quiz.wrong");
_quizFeedback.Foreground = B(CDanger);
ShowQuizSteps();
}
_quizAnswered = true;
_quizStreak.Text = TF("quiz.streak", _streak);
}
private void ShowQuizSteps()
{
_quizSteps.Children.Clear();
_quizSteps.Children.Add(Tb(T("quiz.showSteps"), 10.5, CInkFaint, FontWeight.SemiBold));
foreach (var key in _quiz.StepKeys)
{
var line = T(key);
if (line.Contains("{0}")) line = TF(key, ScaleMath.Num(_quiz.Answer) + " " +
(_quiz.AnswerUnitKey == "unit.none" ? "" : T(_quiz.AnswerUnitKey)));
_quizSteps.Children.Add(Tb(line, 10.5, CInkDim));
}
_quizSteps.Children.Add(Tb(TF("steps.4.result",
ScaleMath.Num(_quiz.Answer) + " " +
(_quiz.AnswerUnitKey == "unit.none" ? "" : T(_quiz.AnswerUnitKey))),
10.5, CAccentDark, FontWeight.SemiBold));
}
}
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
namespace NeoRF.ScaleCalculator;
/// <summary>
/// 比例尺计算器主界面。三栏(已知量 / 可视化标尺 / 三种写法与判读)+ 底部实地尺与练习。
/// 全部用显式画刷(与启动器 AppTheme 同色),不依赖 DynamicResource —— 模型 dll 在
/// 独立 ALC 里加载,headless 生成封面时也没有 Application 样式。
/// </summary>
public sealed partial class ScaleCalculatorView : UserControl
{
// 调色(与 src/main/dotnet/EarthModelStudio/Styles/AppTheme.axaml 一致)
internal static readonly Color CAppBg = Color.Parse("#F4F6FB");
internal static readonly Color CSurface = Color.Parse("#FFFFFF");
internal static readonly Color CSurfaceAlt = Color.Parse("#F7F9FE");
internal static readonly Color CLine = Color.Parse("#E3E8F3");
internal static readonly Color CLineStrong = Color.Parse("#D2DAEA");
internal static readonly Color CInk = Color.Parse("#111A2E");
internal static readonly Color CInkDim = Color.Parse("#5B6A86");
internal static readonly Color CInkFaint = Color.Parse("#8A97B1");
internal static readonly Color CAccent = Color.Parse("#2F6BFF");
internal static readonly Color CAccentDark = Color.Parse("#1F4FD0");
internal static readonly Color CAccentSoft = Color.Parse("#EAF1FF");
internal static readonly Color CSuccess = Color.Parse("#1F9D6B");
internal static readonly Color CDanger = Color.Parse("#D64545");
internal static readonly Color CWarn = Color.Parse("#D98613");
internal static readonly Color CHero = Color.Parse("#12203C");
internal static SolidColorBrush B(Color c) => new(c);
internal static SolidColorBrush Brush(string hex) => new(Color.Parse(hex));
private readonly ScaleData _data;
private readonly Dictionary<string, string> _texts;
private readonly string _language;
private readonly Random _rnd = new();
public string T(string key)
=> _texts.TryGetValue(key, out var v) ? v
: DefaultTexts.Zh.TryGetValue(key, out var f) ? f : key;
public string TF(string key, params object[] args)
=> string.Format(CultureInfo.InvariantCulture, T(key), args);
public ScaleCalculatorView(ScaleData data, Dictionary<string, string> texts, string language)
{
_data = data;
_texts = texts;
_language = language;
BuildLayout();
WireEvents();
SetMode(SolveMode.Real, initial: true);
NewQuiz();
RefreshAll(syncInputs: true);
}
// ────────────────────────────────────────────────────────── 小工具
internal static Border Card(Control content, double radius = 14)
=> new()
{
Background = B(CSurface),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(radius),
Padding = new Thickness(14),
Child = content
};
internal static TextBlock Tb(string text, double size, Color color, FontWeight? weight = null,
TextAlignment align = TextAlignment.Left)
=> new()
{
Text = text,
FontSize = size,
Foreground = B(color),
FontWeight = weight ?? FontWeight.Normal,
TextAlignment = align,
TextWrapping = TextWrapping.Wrap
};
internal static TextBlock Label(string text, double size = 12, Color? color = null)
=> Tb(text, size, color ?? CInkDim);
internal static TextBlock H3(string text) => Tb(text, 13.5, CInk, FontWeight.SemiBold);
internal static Border Chip(string text, Color bg, Color fg, double radius = 8)
=> new()
{
Background = B(bg),
CornerRadius = new CornerRadius(radius),
Padding = new Thickness(10, 4),
Child = Tb(text, 11, fg, FontWeight.SemiBold)
};
internal static Button Btn(string text, bool primary = false)
=> new()
{
Content = Tb(text, 12.5, primary ? Colors.White : CInk, FontWeight.SemiBold),
Background = B(primary ? CAccent : CSurface),
BorderBrush = B(primary ? CAccent : CLineStrong),
BorderThickness = new Thickness(primary ? 0 : 1),
CornerRadius = new CornerRadius(9),
Padding = new Thickness(12, 7),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand)
};
internal static TextBox Input(string text = "")
=> new()
{
Text = text,
FontSize = 12.5,
Background = B(CSurface),
Foreground = B(CInk),
BorderBrush = B(CLineStrong),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(9),
Padding = new Thickness(10, 7),
VerticalContentAlignment = VerticalAlignment.Center,
MinHeight = 34
};
internal static Border Divider(double h = 1)
=> new() { Background = B(CLine), Height = h, Margin = new Thickness(0, 10, 0, 10) };
internal static StackPanel V(double spacing = 8)
=> new() { Orientation = Orientation.Vertical, Spacing = spacing };
internal static StackPanel H(double spacing = 8)
=> new() { Orientation = Orientation.Horizontal, Spacing = spacing, VerticalAlignment = VerticalAlignment.Center };
}
+88
View File
@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NeoRF.ScaleCalculator;
public sealed class PresetItem
{
public double N { get; set; }
public string NameKey { get; set; } = "";
public string NoteKey { get; set; } = "";
}
public sealed class SpectrumItem
{
public double N { get; set; }
public string LabelKey { get; set; } = "";
public string ScopeKey { get; set; } = "";
}
public sealed class LandmarkItem
{
public string NameKey { get; set; } = "";
/// <summary>实地距离(米)。</summary>
public double Meters { get; set; }
}
public sealed class ScaleData
{
public List<PresetItem> Presets { get; set; } = new();
public List<SpectrumItem> Spectrum { get; set; } = new();
public List<LandmarkItem> Landmarks { get; set; } = new();
private static readonly JsonSerializerOptions Opts = new()
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
public static ScaleData Load(string dataDir)
{
var path = Path.Combine(dataDir, "scales.json");
if (!File.Exists(path)) return Fallback();
try
{
var d = JsonSerializer.Deserialize<ScaleData>(File.ReadAllText(path), Opts);
if (d == null || d.Presets.Count == 0) return Fallback();
return d;
}
catch (Exception ex)
{
Console.Error.WriteLine($"[scale-calculator] 读取 scales.json 失败: {ex.Message}");
return Fallback();
}
}
private static ScaleData Fallback() => new()
{
Presets = new List<PresetItem>
{
new() { N = 10000, NameKey = "preset.campus", NoteKey = "preset.campusNote" },
new() { N = 50000, NameKey = "preset.town", NoteKey = "preset.townNote" },
new() { N = 250000, NameKey = "preset.city", NoteKey = "preset.cityNote" },
new() { N = 1000000, NameKey = "preset.province", NoteKey = "preset.provinceNote" },
new() { N = 10000000, NameKey = "preset.china", NoteKey = "preset.chinaNote" },
new() { N = 100000000, NameKey = "preset.world", NoteKey = "preset.worldNote" }
},
Spectrum = new List<SpectrumItem>
{
new() { N = 10000, LabelKey = "spec.campus", ScopeKey = "spec.campusScope" },
new() { N = 250000, LabelKey = "spec.city", ScopeKey = "spec.cityScope" },
new() { N = 10000000, LabelKey = "spec.china", ScopeKey = "spec.chinaScope" },
new() { N = 100000000, LabelKey = "spec.world", ScopeKey = "spec.worldScope" }
},
Landmarks = new List<LandmarkItem>
{
new() { NameKey = "lm.classroom", Meters = 10 },
new() { NameKey = "lm.track", Meters = 400 },
new() { NameKey = "lm.marathon", Meters = 42195 },
new() { NameKey = "lm.beijingShanghai", Meters = 1080000 },
new() { NameKey = "lm.equator", Meters = 40000000 }
}
};
}
+291
View File
@@ -0,0 +1,291 @@
using System;
using System.Globalization;
namespace NeoRF.ScaleCalculator;
/// <summary>三种求解模式:待求的量。</summary>
public enum SolveMode
{
/// <summary>求实地距离</summary>
Real,
/// <summary>求图上距离</summary>
Map,
/// <summary>求比例尺</summary>
Scale
}
public enum ScaleGrade { Large, Medium, Small }
/// <summary>
/// 三个量始终同时存在:图上距离(cm)、实地距离(cm)、比例尺分母 N。
/// <see cref="Mode"/> 指定哪个是"待求结果",另两个是输入;
/// <see cref="ScaleMath.Solve"/> 只由两个输入重算结果量,切换模式时数值保持连续。
/// </summary>
public sealed class ScaleState
{
public double MapCm = 3.0;
public double RealCm = 300000.0; // 3 km
public double N = 100000.0; // 1:100000
public SolveMode Mode = SolveMode.Real;
public ScaleState Clone() => new()
{
MapCm = MapCm, RealCm = RealCm, N = N, Mode = Mode
};
}
/// <summary>线段式比例尺换挡结果。</summary>
public sealed class SegmentScale
{
/// <summary>每一格代表的实地距离(米)。</summary>
public double MetersPerDiv;
/// <summary>每一格在屏幕上的像素宽度。</summary>
public double DivPx;
/// <summary>绘制的格数。</summary>
public int DivCount = 5;
}
/// <summary>一道练习题。</summary>
public sealed class QuizItem
{
public SolveMode Mode;
public string PromptKey = "";
public object[] PromptArgs = Array.Empty<object>();
public double Answer;
/// <summary>相对容差。</summary>
public double Tolerance = 0.02;
public string AnswerUnitKey = "unit.cm";
public string[] StepKeys = Array.Empty<string>();
}
public static class ScaleMath
{
public const double CmPerM = 100.0;
public const double CmPerKm = 100000.0;
/// <summary>由两个输入量重算"待求"量。</summary>
public static void Solve(ScaleState s)
{
// 先做一次合法性收敛,避免 0 / 负数进入除法
if (s.MapCm < 0) s.MapCm = 0;
if (s.RealCm < 0) s.RealCm = 0;
if (s.N < 1) s.N = 1;
switch (s.Mode)
{
case SolveMode.Real:
s.RealCm = s.MapCm * s.N;
break;
case SolveMode.Map:
s.MapCm = s.N > 0 ? s.RealCm / s.N : 0;
break;
case SolveMode.Scale:
s.N = s.MapCm > 1e-9 ? s.RealCm / s.MapCm : 1;
if (s.N < 1) s.N = 1;
break;
}
}
/// <summary>厘米 → 更合适的单位与数值。</summary>
public static (double value, string unitKey) HumanReal(double cm)
{
if (cm < 1) return (cm, "unit.cm");
if (cm < CmPerM) return (cm, "unit.cm");
if (cm < CmPerKm) return (cm / CmPerM, "unit.m");
return (cm / CmPerKm, "unit.km");
}
public static string Num(double v)
{
if (double.IsNaN(v) || double.IsInfinity(v)) return "—";
var a = Math.Abs(v);
if (a >= 1000) return v.ToString("#,##0", CultureInfo.InvariantCulture);
if (a >= 10) return v.ToString("0.#", CultureInfo.InvariantCulture);
if (a >= 1) return v.ToString("0.##", CultureInfo.InvariantCulture);
if (a >= 0.01) return v.ToString("0.###", CultureInfo.InvariantCulture);
if (a == 0) return "0";
return v.ToString("0.####", CultureInfo.InvariantCulture);
}
public static string FormatRealCm(double cm)
{
var (v, key) = HumanReal(cm);
return Num(v) + " " + key;
}
public static string FormatN(double n) => Num(Math.Round(n));
/// <summary>数字式写法 1:N。</summary>
public static string Digital(double n) => "1 : " + FormatN(n);
/// <summary>"文字式"里那一段实地距离(含单位),由调用方套 i18n 模板。</summary>
public static string VerbalDistance(double n)
{
// 图上 1 厘米代表实地 n 厘米
var (v, key) = HumanReal(n);
return Num(v) + " " + key;
}
/// <summary>按当前比例尺,把一段实地距离换算成图上厘米。</summary>
public static double RealToMapCm(double realCm, double n) => n > 0 ? realCm / n : 0;
/// <summary>把图上厘米换算为屏幕像素。</summary>
public static double CmToPx(double cm, double pxPerCm) => cm * pxPerCm;
/// <summary>把一段实地距离按当前比例尺换算成屏幕像素。</summary>
public static double RealToMapPx(double realCm, double n, double pxPerCm)
=> RealToMapCm(realCm, n) * pxPerCm;
/// <summary>
/// 线段式比例尺自动换挡:在 1/2/5×10^k(米)里挑一个,
/// 使每格画出来最接近 targetPx,保证任何比例尺都画得下、刻度又是整数。
/// </summary>
public static SegmentScale PickSegment(double n, double pxPerCm, double targetPx)
{
if (n < 1) n = 1;
if (pxPerCm < 1) pxPerCm = 1;
// 每格实地米数(理想值):px = m*100/n*pxPerCm
var idealMeters = targetPx * n / (100.0 * pxPerCm);
if (idealMeters <= 0) idealMeters = 1;
double best = 1;
double bestErr = double.MaxValue;
var logIdeal = Math.Log10(idealMeters);
for (var k = -3; k <= 9; k++)
{
foreach (var m in new[] { 1.0, 2.0, 5.0 })
{
var cand = m * Math.Pow(10, k);
var err = Math.Abs(Math.Log10(cand) - logIdeal);
if (err < bestErr) { bestErr = err; best = cand; }
}
}
var divPx = best * 100.0 / n * pxPerCm;
// 极端情况下(换挡后仍过长/过短)把格数收敛一下,保证总长在合理区间
var count = 5;
var total = divPx * count;
if (total > targetPx * 9) count = 4;
else if (total < targetPx * 2.5) count = 6;
return new SegmentScale { MetersPerDiv = best, DivPx = divPx, DivCount = count };
}
/// <summary>线段式每格的标注文字(不带 i18n,纯数值+单位)。</summary>
public static string SegmentLabel(double meters)
{
if (meters < 1) return Num(meters * 100) + " cm";
if (meters < 1000) return Num(meters) + " m";
return Num(meters / 1000) + " km";
}
public static ScaleGrade Grade(double n)
{
if (n <= 100000) return ScaleGrade.Large;
if (n <= 1000000) return ScaleGrade.Medium;
return ScaleGrade.Small;
}
public static string GradeKey(double n) => Grade(n) switch
{
ScaleGrade.Large => "grade.large",
ScaleGrade.Medium => "grade.medium",
_ => "grade.small"
};
/// <summary>光谱上 0..1 的位置(对数刻度,1:1千 ~ 1:10亿)。</summary>
public static double SpectrumPosition(double n)
{
if (n < 1) n = 1;
var p = (Math.Log10(n) - 3.0) / 6.0;
return p < 0 ? 0 : p > 1 ? 1 : p;
}
/// <summary>把用户输入的"数值+单位"解析成厘米。</summary>
public static bool TryParseReal(string text, string unitKey, out double cm)
{
cm = 0;
if (!double.TryParse(text.Replace(",", "").Trim(), NumberStyles.Float,
CultureInfo.InvariantCulture, out var v) || v < 0 || double.IsNaN(v) || double.IsInfinity(v))
return false;
cm = unitKey switch
{
"unit.m" => v * CmPerM,
"unit.km" => v * CmPerKm,
_ => v * 1.0
};
return true;
}
/// <summary>由厘米得到该单位下的数值(用于输入框显示)。</summary>
public static double ToUnit(double cm, string unitKey) => unitKey switch
{
"unit.m" => cm / CmPerM,
"unit.km" => cm / CmPerKm,
_ => cm
};
// ------------------------------------------------------------------ 练习
public static QuizItem GenerateQuiz(Random rnd)
{
var mode = (SolveMode)rnd.Next(0, 3);
// 用整齐的数,方便心算
var mapCm = new[] { 1.0, 2.0, 2.5, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0 }[rnd.Next(0, 10)];
var ns = new[] { 1000.0, 5000.0, 10000.0, 25000.0, 50000.0, 100000.0, 500000.0, 1000000.0, 5000000.0, 10000000.0 };
var n = ns[rnd.Next(0, ns.Length)];
switch (mode)
{
case SolveMode.Real:
{
var realCm = mapCm * n;
var (v, key) = HumanReal(realCm);
return new QuizItem
{
Mode = SolveMode.Real,
PromptKey = "quiz.promptReal",
PromptArgs = new object[] { FormatN(n), Num(mapCm) },
Answer = v,
AnswerUnitKey = key,
StepKeys = new[] { "steps.2.formulaReal", "steps.4.result" }
};
}
case SolveMode.Map:
{
// 让实地距离是整齐数字,反推图上距离也是整齐数字
var realCm = mapCm * n;
var (v, key) = HumanReal(realCm);
return new QuizItem
{
Mode = SolveMode.Map,
PromptKey = "quiz.promptMap",
PromptArgs = new object[] { FormatN(n), Num(v) },
Answer = mapCm,
AnswerUnitKey = "unit.cm",
StepKeys = new[] { "steps.2.formulaMap", "steps.4.result" }
};
}
default:
{
var realCm = mapCm * n;
var (v, key) = HumanReal(realCm);
return new QuizItem
{
Mode = SolveMode.Scale,
PromptKey = "quiz.promptScale",
PromptArgs = new object[] { Num(mapCm), Num(v) },
Answer = n,
AnswerUnitKey = "unit.none",
StepKeys = new[] { "steps.1.unify", "steps.2.formulaScale", "steps.4.result" }
};
}
}
}
public static bool CheckAnswer(QuizItem q, double input)
{
if (q.Answer <= 0) return false;
return Math.Abs(input - q.Answer) / q.Answer <= q.Tolerance;
}
}
+347
View File
@@ -0,0 +1,347 @@
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
namespace NeoRF.ScaleCalculator;
/// <summary>
/// 自绘可视化标尺:上条「图上距离」按真实厘米画,下条「实地距离」按同一比例尺压缩,
/// 再画线段式比例尺(自动换挡)与比例尺光谱。全部在 Render 里完成,不产生子控件。
/// </summary>
public sealed class ScaleRuler : Control
{
// 与启动器 AppTheme 保持一致的调色(模型 dll 独立加载,取不到 DynamicResource 时也能显示)
private static readonly Color CInk = Color.Parse("#111A2E");
private static readonly Color CInkDim = Color.Parse("#5B6A86");
private static readonly Color CInkFaint = Color.Parse("#8A97B1");
private static readonly Color CLine = Color.Parse("#E3E8F3");
private static readonly Color CLineStrong = Color.Parse("#D2DAEA");
private static readonly Color CAccent = Color.Parse("#2F6BFF");
private static readonly Color CAccentSoft = Color.Parse("#EAF1FF");
private static readonly Color CAccentDark = Color.Parse("#1F4FD0");
private static readonly Color CSuccess = Color.Parse("#1F9D6B");
private static readonly Color CWarn = Color.Parse("#D98613");
private static readonly Color CDanger = Color.Parse("#D64545");
private static readonly Color CSurfaceAlt = Color.Parse("#F7F9FE");
private static readonly Color CSurface = Color.Parse("#FFFFFF");
private static readonly Typeface Font = new("Noto Sans CJK SC, Microsoft YaHei, Arial");
/// <summary>1 厘米对应多少屏幕像素。</summary>
public double PxPerCm = 46;
/// <summary>能画下的最大宽度(超出即溢出提示)。</summary>
public double MaxBarWidth = 520;
public ScaleState State { get; set; } = new();
public ScaleData Data { get; set; } = new();
public Func<string, string> T { get; set; } = k => k;
/// <summary>线段式比例尺换挡结果(供界面读数)。</summary>
public SegmentScale Segment { get; private set; } = new() { MetersPerDiv = 1000, DivPx = 46 };
/// <summary>图上距离是否超出可画范围。</summary>
public bool MapOverflow { get; private set; }
/// <summary>实地条溢出(按当前比例尺,这段实地图上也画不下)。</summary>
public bool RealOverflow { get; private set; }
public void Refresh() => InvalidateVisual();
private static FormattedText MakeText(string text, double size, Color color, FontWeight? weight = null)
{
var ft = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
new Typeface(Font.FontFamily, FontStyle.Normal, weight ?? FontWeight.Normal), size,
new SolidColorBrush(color));
return ft;
}
private static void Text(DrawingContext dc, string s, double x, double y, double size, Color color,
FontWeight? weight = null, TextAlignment align = TextAlignment.Left)
{
var ft = MakeText(s, size, color, weight);
ft.TextAlignment = align;
dc.DrawText(ft, new Point(align == TextAlignment.Center ? x - ft.Width / 2 : x, y));
}
private static void RoundRect(DrawingContext dc, Rect r, double radius, IBrush fill, IPen? pen = null)
=> dc.DrawRectangle(fill, pen, new RoundedRect(r, radius));
private static void Dot(DrawingContext dc, double x, double y, double r, IBrush fill)
=> dc.DrawEllipse(fill, null, new Point(x, y), r, r);
public override void Render(DrawingContext dc)
{
base.Render(dc);
var w = Bounds.Width;
var h = Bounds.Height;
if (w < 40 || h < 40) return;
// 背景
dc.FillRectangle(new SolidColorBrush(CSurface), new Rect(0, 0, w, h));
var padL = 34.0;
var padR = 30.0;
var barW = Math.Max(60, w - padL - padR);
MaxBarWidth = barW;
var mapPx = ScaleMath.CmToPx(State.MapCm, PxPerCm);
var realPx = ScaleMath.RealToMapPx(State.RealCm, State.N, PxPerCm);
MapOverflow = mapPx > barW + 0.5;
RealOverflow = realPx > barW + 0.5;
// 线段式比例尺换挡,取"每格约 60px"
Segment = ScaleMath.PickSegment(State.N, PxPerCm, 62);
var y = 16.0;
// ── 标题
Text(dc, T("ruler.title"), padL, y, 13, CInk, FontWeight.SemiBold);
Text(dc, ScaleMath.Digital(State.N), w - padR, y + 1, 14, CAccentDark,
FontWeight.SemiBold, TextAlignment.Right);
y += 30;
// ═══════════════════════════════════════════ 1. 图上距离条
y = DrawMapBar(dc, padL, y, barW, mapPx);
y += 22;
// ═══════════════════════════════════════════ 2. 等式连接
DrawEquation(dc, padL, y, barW);
y += 30;
// ═══════════════════════════════════════════ 3. 实地距离条(压缩)
y = DrawRealBar(dc, padL, y, barW, realPx);
y += 24;
// ═══════════════════════════════════════════ 4. 线段式比例尺
y = DrawSegmentScale(dc, padL, y, barW);
y += 24;
// ═══════════════════════════════════════════ 5. 比例尺光谱
y = DrawSpectrum(dc, padL, y, barW);
y += 34;
// ═══════════════════════════════════════════ 6. 提示 / 溢出
DrawFooter(dc, padL, y, barW);
}
private double DrawMapBar(DrawingContext dc, double x, double y, double barW, double mapPx)
{
Text(dc, T("ruler.mapBar"), x, y, 11.5, CInkDim, FontWeight.SemiBold);
Text(dc, ScaleMath.Num(State.MapCm) + " " + T("unit.cm"), x + barW, y, 12.5, CAccent,
FontWeight.SemiBold, TextAlignment.Right);
y += 20;
var barH = 34.0;
var r = new Rect(x, y, barW, barH);
RoundRect(dc, r, 9, new SolidColorBrush(CSurfaceAlt), new Pen(new SolidColorBrush(CLine), 1));
// 底上的厘米刻度(每 1cm 一格,最多画 30 格)
var maxTicks = Math.Min(30, (int)(barW / PxPerCm) + 1);
for (var i = 1; i <= maxTicks; i++)
{
var tx = x + i * PxPerCm;
if (tx > x + barW - 2) break;
dc.DrawLine(new Pen(new SolidColorBrush(CLineStrong), 1),
new Point(tx, y + barH - 7), new Point(tx, y + barH));
if (i % 2 == 0)
Text(dc, i.ToString(CultureInfo.InvariantCulture), tx, y + barH + 2, 9.5, CInkFaint,
align: TextAlignment.Center);
}
// 实长(蓝色),超出则截断并染红
var drawW = Math.Min(mapPx, barW);
if (drawW > 0.5)
{
var fill = new LinearGradientBrush
{
StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
GradientStops = new GradientStops
{
new(CAccentSoft, 0), new(CAccent, 1)
}
};
RoundRect(dc, new Rect(x + 1, y + 1, drawW - 2, barH - 2), 8, fill,
new Pen(new SolidColorBrush(MapOverflow ? CDanger : CAccentDark), 1.5));
}
// 端点
var endX = x + Math.Min(mapPx, barW);
Dot(dc, x + 2, y + barH / 2, 4, new SolidColorBrush(CSurface));
if (!MapOverflow)
{
Dot(dc, endX - 2, y + barH / 2, 5, new SolidColorBrush(CSurface));
Dot(dc, endX - 2, y + barH / 2, 3, new SolidColorBrush(CAccentDark));
// 长度标注
Text(dc, ScaleMath.Num(State.MapCm) + " " + T("unit.cm"),
endX - 4, y - 16, 11, CAccentDark, FontWeight.SemiBold, TextAlignment.Right);
}
else
{
Text(dc, "»", x + barW - 14, y + barH / 2 - 9, 16, CDanger, FontWeight.Bold);
}
return y + barH;
}
private void DrawEquation(DrawingContext dc, double x, double y, double barW)
{
var cx = x + barW / 2;
dc.DrawLine(new Pen(new SolidColorBrush(CLineStrong), 1, dashStyle: DashStyle.Dash),
new Point(x, y + 10), new Point(x + barW, y + 10));
var label = T("ruler.equals");
var ft = MakeText(label, 11, CInkDim, FontWeight.SemiBold);
var bw = ft.Width + 22;
RoundRect(dc, new Rect(cx - bw / 2, y, bw, 21), 10, new SolidColorBrush(CSurface),
new Pen(new SolidColorBrush(CLine), 1));
Text(dc, label, cx, y + 4, 11, CInkDim, FontWeight.SemiBold, TextAlignment.Center);
}
private double DrawRealBar(DrawingContext dc, double x, double y, double barW, double realPx)
{
var (rv, rkey) = ScaleMath.HumanReal(State.RealCm);
Text(dc, T("ruler.realBar"), x, y, 11.5, CInkDim, FontWeight.SemiBold);
Text(dc, ScaleMath.Num(rv) + " " + T(rkey), x + barW, y, 12.5, CSuccess,
FontWeight.SemiBold, TextAlignment.Right);
y += 20;
var barH = 30.0;
RoundRect(dc, new Rect(x, y, barW, barH), 9, new SolidColorBrush(CSurfaceAlt),
new Pen(new SolidColorBrush(CLine), 1));
// 用"按同一比例尺压缩后"的长度表现:与上图同宽才直观
var drawW = Math.Min(realPx, barW);
if (drawW > 0.5)
{
var fill = new LinearGradientBrush
{
StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
GradientStops = new GradientStops { new(Color.Parse("#DFF5EA"), 0), new(CSuccess, 1) }
};
RoundRect(dc, new Rect(x + 1, y + 1, drawW - 2, barH - 2), 8, fill,
new Pen(new SolidColorBrush(RealOverflow ? CDanger : CSuccess), 1.5));
}
// 画上"实地"的等分虚线,表达这段距离很长
for (var i = 1; i < 6; i++)
{
var tx = x + barW * i / 6.0;
dc.DrawLine(new Pen(new SolidColorBrush(Color.Parse("#80FFFFFF")), 1, dashStyle: DashStyle.Dash),
new Point(tx, y + 5), new Point(tx, y + barH - 5));
}
if (!RealOverflow)
{
Dot(dc, x + drawW - 2, y + barH / 2, 4, new SolidColorBrush(CSurface));
}
else
{
Text(dc, "»", x + barW - 14, y + barH / 2 - 9, 16, CDanger, FontWeight.Bold);
}
// 中间写"= 图上这段"
Text(dc, T("ruler.sameWidth"), x + barW / 2, y + barH / 2 - 7, 10.5, CInkDim,
align: TextAlignment.Center);
return y + barH;
}
private double DrawSegmentScale(DrawingContext dc, double x, double y, double barW)
{
Text(dc, T("ruler.segment"), x, y, 11.5, CInkDim, FontWeight.SemiBold);
Text(dc, T("ruler.segmentHint"), x + barW, y + 1, 10, CInkFaint, align: TextAlignment.Right);
y += 20;
var seg = Segment;
var total = seg.DivPx * seg.DivCount;
if (total > barW)
{
// 再降一档,避免画不下
seg = ScaleMath.PickSegment(State.N * 3, PxPerCm, 62);
Segment = seg;
total = seg.DivPx * seg.DivCount;
}
var sx = x + Math.Max(0, (barW - total) / 2);
var sy = y;
var segH = 13.0;
for (var i = 0; i < seg.DivCount; i++)
{
var r = new Rect(sx + i * seg.DivPx, sy, seg.DivPx, segH);
dc.FillRectangle(new SolidColorBrush(i % 2 == 0 ? CInk : CSurface), r);
dc.DrawRectangle(null, new Pen(new SolidColorBrush(CInk), 1), r);
Text(dc, i == 0 ? "0" : ScaleMath.SegmentLabel(seg.MetersPerDiv * i),
sx + (i + 1) * seg.DivPx, sy + segH + 3, 9.5, CInkDim, align: TextAlignment.Center);
}
Text(dc, ScaleMath.SegmentLabel(seg.MetersPerDiv), sx + total / 2, sy + segH + 17, 10,
CInkDim, FontWeight.SemiBold, TextAlignment.Center);
return sy + segH + 32;
}
private double DrawSpectrum(DrawingContext dc, double x, double y, double barW)
{
Text(dc, T("ruler.spectrum"), x, y, 11.5, CInkDim, FontWeight.SemiBold);
y += 20;
var trackY = y + 6;
var trackH = 8.0;
var grad = new LinearGradientBrush
{
StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
GradientStops = new GradientStops
{
new(CAccent, 0), new(Color.Parse("#5B8DEF"), 0.4),
new(Color.Parse("#8FB4F5"), 0.7), new(Color.Parse("#C9DAF8"), 1)
}
};
RoundRect(dc, new Rect(x, trackY, barW, trackH), 4, grad);
// 光谱层级刻度
foreach (var item in Data.Spectrum)
{
var p = ScaleMath.SpectrumPosition(item.N);
var px = x + barW * p;
dc.DrawLine(new Pen(new SolidColorBrush(CSurface), 1.5),
new Point(px, trackY), new Point(px, trackY + trackH));
Text(dc, T(item.LabelKey), px, trackY + trackH + 3, 9.5, CInkFaint,
align: TextAlignment.Center);
}
// 当前值指针
var pos = ScaleMath.SpectrumPosition(State.N);
var cx = x + barW * pos;
dc.DrawLine(new Pen(new SolidColorBrush(CInk), 2),
new Point(cx, trackY - 7), new Point(cx, trackY + trackH + 5));
Dot(dc, cx, trackY - 9, 5, new SolidColorBrush(CAccent));
Dot(dc, cx, trackY - 9, 2.5, new SolidColorBrush(CSurface));
// 两端说明
Text(dc, T("ruler.scopeUp"), x, trackY + trackH + 20, 10, CInkFaint);
Text(dc, T("ruler.detailDown"), x + barW, trackY + trackH + 20, 10, CInkFaint,
align: TextAlignment.Right);
return trackY + trackH + 36;
}
private void DrawFooter(DrawingContext dc, double x, double y, double barW)
{
if (MapOverflow || RealOverflow)
{
var msg = T(MapOverflow ? "ruler.overflowMap" : "ruler.overflowReal");
var r = new Rect(x, y, barW, 30);
RoundRect(dc, r, 8, new SolidColorBrush(Color.Parse("#FDECEC")),
new Pen(new SolidColorBrush(Color.Parse("#F5C2C2")), 1));
Text(dc, "⚠ " + msg, x + 12, y + 7, 11, CDanger, FontWeight.SemiBold);
}
else
{
Text(dc, T("ruler.hint"), x, y + 4, 10.5, CInkFaint);
}
}
}
+26 -11
View File
@@ -1,50 +1,65 @@
{
"schema": 1,
"generated": "2026-11-08T01:29:16Z",
"generated": "2026-11-14T01:23:14Z",
"repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main",
"modelDir": "model",
"launcher": {
"version": "1.0.2",
"revision": "2c5b10a887",
"version": "1.0.6",
"revision": "98cff12092",
"packages": {
"win-x64": {
"path": "dist/GC-win-x64.zip",
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-win-x64.zip"
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.6/GC-win-x64.zip"
},
"win-arm64": {
"path": "dist/GC-win-arm64.zip",
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-win-arm64.zip"
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.6/GC-win-arm64.zip"
},
"osx-arm64": {
"path": "dist/GC-osx-arm64.zip",
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-osx-arm64.zip"
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.6/GC-osx-arm64.zip"
},
"osx-x64": {
"path": "dist/GC-osx-x64.zip",
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-osx-x64.zip"
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.6/GC-osx-x64.zip"
},
"linux-x64": {
"path": "dist/GC-linux-x64.zip",
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-linux-x64.zip"
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.6/GC-linux-x64.zip"
}
}
},
"models": [
{
"id": "contour-map",
"version": "1.0",
"build": "e7f837d0ef",
"dir": "model/contour-map"
},
{
"id": "earth-geography",
"version": "1.0-dd67f83d0c",
"version": "1.8",
"build": "143e56bed8",
"dir": "model/earth-geography"
},
{
"id": "earth-revolution",
"version": "1.0-7380e0cff3",
"version": "1.6",
"build": "26a2bd8f68",
"dir": "model/earth-revolution"
},
{
"id": "earth-rotation",
"version": "1.0-c74907bbce",
"version": "1.6",
"build": "1a81492baa",
"dir": "model/earth-rotation"
},
{
"id": "scale-calculator",
"version": "1.5",
"build": "79711a44a8",
"dir": "model/scale-calculator"
}
]
}
@@ -15,6 +15,9 @@
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
<views:SettingsView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:AboutViewModel}">
<views:AboutView />
</DataTemplate>
</Application.DataTemplates>
<Application.Resources>
@@ -38,6 +38,28 @@ public partial class App : Application
return await dialog.ShowDialog<bool>(window);
};
// 发现启动器新版本:弹窗询问,用户选「更新」才下载并安排替换
vm.LauncherUpdateHandler = async newVersion =>
{
var dialog = new ConfirmWindow(
title: "发现新版本",
message: $"启动器有新版本 v{newVersion},是否立即更新?\n\n" +
"更新会下载新版程序,下次启动时自动替换当前版本;" +
"选择取消则继续使用当前版本,但模型仍会更新到最新。",
confirmText: "更新",
cancelText: "取消");
return await dialog.ShowDialog<bool>(window);
};
// 应用图标:窗口标题栏与任务栏也使用同一图标
try
{
using var iconStream = Avalonia.Platform.AssetLoader.Open(
new Uri("avares://EarthModelStudio/Assets/icon.png"));
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
}
catch { /* 图标缺失不影响启动 */ }
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
@@ -6,6 +6,7 @@
"nav.home": "Home",
"nav.download": "Download",
"nav.settings": "Settings",
"nav.about": "About",
"home.title": "Model library",
"home.subtitle": "Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.",
"home.launch": "Launch model",
@@ -6,6 +6,7 @@
"nav.home": "主页",
"nav.download": "下载",
"nav.settings": "设置",
"nav.about": "关于",
"home.title": "模型库",
"home.subtitle": "选择模型,用可交互的三维演示讲清自转、公转与四季成因。",
"home.launch": "启动模型",
Binary file not shown.

After

Width:  |  Height:  |  Size: 350 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

@@ -7,6 +7,8 @@
<RootNamespace>EarthModelStudio</RootNamespace>
<AssemblyName>EarthModelStudio</AssemblyName>
<ApplicationManifest>app.manifest</ApplicationManifest>
<!-- 应用图标(Windows exe / 任务栏) -->
<ApplicationIcon>Assets\icon.ico</ApplicationIcon>
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<InvariantGlobalization>false</InvariantGlobalization>
@@ -28,6 +28,18 @@ public sealed class ModelManifest
public string? License { get; set; }
public string? UpdatedAt { get; set; }
public string? MinAppVersion { get; set; }
/// <summary>模型窗口标题栏配色(模型自带,跟随模型界面风格);缺省时用深色。</summary>
public WindowChrome? Chrome { get; set; }
}
/// <summary>模型窗口自建标题栏的颜色,由模型清单提供。</summary>
public sealed class WindowChrome
{
public string? TitleBar { get; set; }
public string? TitleBorder { get; set; }
public string? TitleText { get; set; }
public string? Button { get; set; }
public string? Frame { get; set; }
}
public sealed class ModelPackage
+2 -2
View File
@@ -13,8 +13,8 @@ internal static class Program
var paths = AppPaths.Discover();
paths.EnsureCreated();
// 上次下载的启动器新版,到这次启动才应用:交给独立脚本覆盖文件并重启
if (LauncherUpdate.TryApplyPending(paths)) return;
// 上次下载的启动器新版,到这次启动才应用
if (LauncherUpdater.TryApplyPending(paths)) return;
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
@@ -45,14 +45,60 @@ public sealed class AppPaths
{
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
// 判定「当前目录」:程序实际所在的位置。
// · 发布版:可执行文件所在目录(单文件时为 exe 旁,否则为 apphost 目录)
// · 源码版:仓库根(含 EarthModelStudio.sln 的目录)
//
// 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主,
// 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。
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;
// 只读安装位置(如 Program Files / /Applications)自动退回用户数据目录
string installDir;
if (isDev)
{
// 源码版:安装目录 = 仓库根,.GC 与更新都放这里
installDir = repoRoot!;
}
else
{
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
//
// <运行目录>/ ← 要的就是这一层
// GC-1.0.3-mac-arm64.app/ ← 程序包
// .GC/ ← 用户数据放这里
//
// 若直接返回 Contents/MacOS,.GC 会被塞进 app 包内部,
// 用户看不到,重装/替换时也会跟着包一起被删。
installDir = baseDir;
try
{
var exe = Environment.ProcessPath;
if (!string.IsNullOrWhiteSpace(exe))
{
var exeName = Path.GetFileNameWithoutExtension(exe);
var isDotnetHost = string.Equals(exeName, "dotnet", StringComparison.OrdinalIgnoreCase);
var exeDir = Path.GetDirectoryName(exe);
if (!isDotnetHost && !string.IsNullOrWhiteSpace(exeDir) && Directory.Exists(exeDir))
{
// 从可执行文件所在目录向上找:如果处在 Xxx.app/Contents/MacOS,
// 则运行目录是 Xxx.app 的**父目录**。
installDir = ResolveRunDirectory(exeDir!);
}
}
}
catch { /* 取不到就沿用 BaseDirectory */ }
}
// 运行目录 = 程序所在目录。.GC 永远紧挨着程序,不往系统目录放。
var appRoot = installDir;
// 只读安装位置(如 Program Files / /Applications)才回退到用户数据目录;
// 正常可写时一律用当前目录下的 .GC。
var explicitData = Environment.GetEnvironmentVariable("EMS_DATA");
string home;
if (!string.IsNullOrWhiteSpace(explicitData))
@@ -76,7 +122,7 @@ public sealed class AppPaths
return new AppPaths
{
AppRoot = appRoot,
InstallDirectory = baseDir,
InstallDirectory = installDir,
HomeRoot = home,
ModelRoot = modelRoot,
IsDevelopment = isDev,
@@ -100,16 +146,97 @@ public sealed class AppPaths
}
}
/// <summary>
/// 从程序所在位置向上找仓库根(含 EarthModelStudio.sln 的目录)。
///
/// 关键:程序若位于 .app 包内(或 dist/ 等发布产物目录),**不算开发态**。
/// 否则把 .app 放在仓库的 dist/ 下运行时,会一路向上命中仓库根的 .sln,
/// 被误判为开发态,导致 .GC 跑到仓库根而不是程序旁边。
/// </summary>
private static string? FindRepoRoot(string start)
{
// 在 .app 包内(.../Xxx.app/Contents/MacOS)直接视为发布版
if (IsInsideAppBundle(start)) return null;
var dir = new DirectoryInfo(start);
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
{
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName;
// 碰到发布产物目录也停下:dist/ 输出、或带 .GC 的运行目录都不是源码树
var name = dir.Name;
if (string.Equals(name, "dist", StringComparison.OrdinalIgnoreCase)) return null;
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln")))
{
// 再确认不是从「发布输出目录」里往上找来的
if (IsUnderPublishOutput(start, dir.FullName)) return null;
return dir.FullName;
}
}
return null;
}
/// <summary>
/// 求「运行目录」:程序包所在的父目录。
/// · 若路径处在 Xxx.app/Contents/MacOS 里,返回 Xxx.app 的父目录
/// · 其它情况(Windows exe 目录)原样返回
/// </summary>
private static string ResolveRunDirectory(string exeDir)
{
var dir = new DirectoryInfo(exeDir);
// 走到 app 包根:.../Xxx.app
string? appRoot = null;
for (var cur = dir; cur != null; cur = cur.Parent)
{
if (cur.Name.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
{
appRoot = cur.FullName;
break;
}
if (cur.Parent == null) break;
}
if (appRoot != null)
{
// 返回 .app 的父目录(即用户双击时看到的那一层)
var parent = Path.GetDirectoryName(appRoot);
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
return parent!;
return appRoot;
}
return exeDir;
}
/// <summary>路径是否位于某个 .app 包内部。</summary>
private static bool IsInsideAppBundle(string path)
{
var p = path.Replace('\\', '/');
var idx = p.IndexOf(".app/", StringComparison.OrdinalIgnoreCase);
return idx >= 0;
}
/// <summary>
/// 从 start 到 repoRoot 之间是否经过了发布输出目录(dist / bin / publish)。
/// 经过则说明程序是打包产物,而非源码树里直接运行的进程。
/// </summary>
private static bool IsUnderPublishOutput(string start, string repoRoot)
{
try
{
var rel = Path.GetRelativePath(repoRoot, start).Replace('\\', '/');
foreach (var seg in rel.Split('/', StringSplitOptions.RemoveEmptyEntries))
{
if (string.Equals(seg, "dist", StringComparison.OrdinalIgnoreCase) ||
string.Equals(seg, "publish", StringComparison.OrdinalIgnoreCase) ||
string.Equals(seg, "Release", StringComparison.OrdinalIgnoreCase))
return true;
}
}
catch { }
return false;
}
public void EnsureCreated()
{
Directory.CreateDirectory(HomeRoot);
@@ -17,6 +17,8 @@ public sealed class AppServices
public ModelHost ModelHost { get; }
/// <summary>启动时检查模型 / 启动器更新。</summary>
public UpdateService Updates { get; }
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
public SourceSelector Selector { get; }
private AppServices(AppPaths paths)
{
@@ -28,6 +30,7 @@ public sealed class AppServices
Downloads = new DownloadCenter(paths, Models);
Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory);
Selector = new SourceSelector();
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
}
@@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>GitCode 仓库的一位贡献者。</summary>
public sealed class Contributor
{
public string Name { get; set; } = "";
public string? Email { get; set; }
/// <summary>提交次数(API 里的 contributions)。</summary>
public int Contributions { get; set; }
/// <summary>
/// 登录名 -> 展示名。GitCode 的 contributors 接口只返回账号登录名,
/// 不返回真实姓名,这里做一层映射,让关于页显示作者想展示的名字。
/// </summary>
private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase)
{
["2509_92447106"] = "Morris"
};
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
public string? AvatarUrl =>
string.IsNullOrWhiteSpace(Email)
? null
: $"https://cdn-img.gitcode.com/avatar/{Convert.ToHexString(
System.Security.Cryptography.MD5.HashData(
System.Text.Encoding.UTF8.GetBytes(Email!.Trim().ToLowerInvariant())))
.ToLowerInvariant()}";
public string DisplayName
{
get
{
if (string.IsNullOrWhiteSpace(Name)) return "匿名";
return DisplayNames.TryGetValue(Name.Trim(), out var mapped) ? mapped : Name;
}
}
}
/// <summary>
/// 读取 GitCode 仓库的贡献者列表(用于「关于」页面展示开发者)。
/// 失败时静默返回空列表,不影响关于页其它内容。
/// </summary>
public static class ContributorsService
{
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0");
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return c;
}
/// <summary>默认仓库的 contributors 接口地址。</summary>
public static string BuildUrl(string repository)
{
var raw = string.IsNullOrWhiteSpace(repository)
? GitCodeRemote.DefaultRepository : repository.Trim();
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors";
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors";
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? parts[1][..^4] : parts[1];
return $"https://api.gitcode.com/api/v5/repos/{parts[0]}/{repo}/contributors";
}
public static async Task<List<Contributor>> FetchAsync(string repository, CancellationToken ct = default)
{
var url = BuildUrl(repository);
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
var text = await Http.GetStringAsync(url, timeout.Token);
var trimmed = text.TrimStart();
if (trimmed.Length == 0 || trimmed[0] != '[') return new List<Contributor>();
var list = JsonSerializer.Deserialize<List<Contributor>>(text, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}) ?? new List<Contributor>();
// 按提交数从多到少,贡献最多的排最前
list.Sort((a, b) => b.Contributions.CompareTo(a.Contributions));
return list;
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取贡献者失败: {ex.Message}");
return new List<Contributor>();
}
}
}
@@ -59,34 +59,54 @@ public sealed class GitCodeReleaseRemote : IModelRemote
}
public string DisplayName { get; }
public string SourceId => SourcePreset.Detect(_content.DisplayName).Id;
/// <summary>
/// 模型部分照旧读仓库 version.json;成功拿到 Release 时,用 tag/附件覆盖启动器字段。
/// </summary>
/// <summary>
/// 只认 Release:拿不到任何 Release 就返回 null,由上层去问另一个源。
/// 仓库里的 version.json 只用来补全「模型清单」与平台包兜底地址,
/// 不再用它充当版本号来源。
/// </summary>
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
var version = await _content.GetVersionAsync(ct);
bool gotRelease;
try
{
await ApplyReleaseAsync(version, ct);
gotRelease = await ApplyReleaseAsync(version, ct);
}
catch (Exception ex)
{
// 没有 Release / 断网 / 格式不符:回退到 version.json,不影响模型更新
Console.Error.WriteLine($"读取 Release 失败,回退仓库清单: {ex.Message}");
Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}");
gotRelease = false;
}
if (!gotRelease)
{
// 没有 Release:启动器版本留空(表示这个源没有可升级的启动器),
// 但模型清单仍然有效,保证模型能正常同步。
Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)");
if (version != null)
{
version.Launcher.Version = "";
version.Launcher.Packages.Clear();
}
}
return version;
}
private async Task ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
private async Task<bool> ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
{
if (version == null) return;
if (version == null) return false;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(12));
var text = await Http.GetStringAsync(_releasesUrl, timeout.Token);
var trimmed = text.TrimStart();
if (trimmed.Length == 0 || trimmed[0] != '[') return; // 可能是错误页/对象
if (trimmed.Length == 0 || trimmed[0] != '[') return false; // 可能是错误页/对象
using var doc = JsonDocument.Parse(text);
ReleaseInfo? latest = null;
@@ -97,7 +117,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
// 取版本号最大的一条(API 通常已按时间倒序,这里再兜一层)
if (latest == null || CompareVersion(info.Version, latest.Version) > 0) latest = info;
}
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return;
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
version.Launcher.Version = latest.Version;
@@ -125,6 +145,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256;
if (info.Size > 0) pkg.Size = info.Size;
}
return true;
}
private static int CompareVersion(string a, string b)
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
@@ -118,15 +119,84 @@ public sealed class GitCodeRemote : IModelRemote
}
}
/// <summary>递归列出目录树(含目录项与文件项)。</summary>
/// <summary>
/// 递归列出目录树(含目录项与文件项)。
/// 每个子目录一次 HTTP 请求,因此并行展开同一层的所有目录,
/// 否则 3 个模型、十几个目录串行请求会非常慢。
/// </summary>
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var result = new List<RepoEntry>();
var bag = new System.Collections.Concurrent.ConcurrentBag<RepoEntry>();
var repoPath = (rootPath ?? _modelDir).Trim('/');
await WalkAsync(repoPath, "", 0, result, ct);
await WalkParallelAsync(repoPath, "", 0, bag, ct);
// 稳定排序:目录在前、按路径字典序,保证调用方拿到确定顺序
result = bag.OrderBy(e => e.IsDirectory ? 0 : 1)
.ThenBy(e => e.RelativePath, StringComparer.Ordinal)
.ToList();
return result;
}
private async Task WalkParallelAsync(string repoPath, string relative, int depth,
System.Collections.Concurrent.ConcurrentBag<RepoEntry> bag, CancellationToken ct)
{
if (depth > 8) return;
var url = _api + repoPath + "?ref=" + _branch;
string text;
try { text = await GetWithRetryAsync(url, ct); }
catch (Exception ex)
{
Console.Error.WriteLine($"列目录失败 {repoPath}: {ex.Message}");
return;
}
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
var subDirs = new List<(string Path, string Relative)>();
using (var doc = JsonDocument.Parse(text))
{
foreach (var item in doc.RootElement.EnumerateArray())
{
ct.ThrowIfCancellationRequested();
var name = Str(item, "name");
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
// 这些目录不是模型运行数据,跳过可显著减少请求
// (模型目录里常见的 src/ bin/ obj/ 是源码与构建产物)
if (IsIgnoredDir(name)) continue;
var path = Str(item, "path");
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
var isDir = Str(item, "type") == "dir";
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
bag.Add(new RepoEntry
{
Name = name,
Path = path!,
RelativePath = childRelative,
IsDirectory = isDir,
DownloadUrl = NullableStr(item, "download_url"),
Sha = NullableStr(item, "sha"),
Size = Num(item, "size")
});
if (isDir) subDirs.Add((path!, childRelative));
}
}
if (subDirs.Count == 0) return;
// 同层并行;并发保持很低——GitCode API 对突发请求会返回 429
using var gate = new SemaphoreSlim(2);
var tasks = subDirs.Select(async d =>
{
await gate.WaitAsync(ct);
try { await WalkParallelAsync(d.Path, d.Relative, depth + 1, bag, ct); }
finally { gate.Release(); }
});
await Task.WhenAll(tasks);
}
private async Task WalkAsync(string repoPath, string relative, int depth,
List<RepoEntry> result, CancellationToken ct)
{
@@ -161,6 +231,43 @@ public sealed class GitCodeRemote : IModelRemote
}
}
/// <summary>遍历时忽略的目录:源码与构建产物不属于模型运行数据。</summary>
private static bool IsIgnoredDir(string name) => name switch
{
"src" => true,
"bin" => true,
"obj" => true,
"node_modules" => true,
".git" => true,
".vs" => true,
_ => false
};
/// <summary>
/// 带退避重试的 GET。GitCode API 对突发请求返回 429,
/// 这里做 3 次指数退避,避免并行遍历时直接失败。
/// </summary>
private async Task<string> GetWithRetryAsync(string url, CancellationToken ct,
int maxAttempts = 3)
{
for (var attempt = 1; ; attempt++)
{
try
{
return await _http.GetStringAsync(url, ct);
}
catch (HttpRequestException ex) when (attempt < maxAttempts)
{
// 429 / 5xx 才重试,其余直接抛
var retriable = ex.StatusCode is null ||
(int)ex.StatusCode == 429 ||
(int)ex.StatusCode >= 500;
if (!retriable) throw;
await Task.Delay(TimeSpan.FromMilliseconds(400 * attempt * attempt), ct);
}
}
}
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
{
if (!string.IsNullOrWhiteSpace(entry.DownloadUrl))
@@ -0,0 +1,293 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
///
/// · 目录:GET /api/v1/repos/{owner}/{repo}/contents/{path}
/// 返回数组(目录)或对象(单文件),带 name/path/size/type/download_url
/// · 原始文件:GET {host}/{owner}/{repo}/raw/branch/{branch}/{path}
/// · Release:GET /api/v1/repos/{owner}/{repo}/releases
/// 版本取 tag_name;附件取 assets[].browser_download_url
///
/// Release 为空时(仓库还没发布),回退到仓库里的 version.json,保证只推仓库也能更新。
/// </summary>
public sealed class GiteaRemote : IModelRemote
{
private readonly SourcePreset _preset;
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return c;
}
public GiteaRemote(SourcePreset preset)
{
_preset = preset;
DisplayName = preset.Name;
}
public string DisplayName { get; }
public string SourceId => _preset.Id;
private string RepoApi => $"{_preset.ApiBase}/repos/{_preset.Owner}/{_preset.Repo}";
// ---------------------------------------------------------------- 清单
/// <summary>
/// 两件事分开取:
/// · **模型清单**永远来自仓库 version.json(模型不需要发 Release)
/// · **启动器版本**只认 Release;没有 Release 时把版本号留空,
/// 由上层去问另一个源(LeaderUpdater 会横向比较)。
/// 以前把两者绑在一起,导致没有 Release 时连模型都同步不了。
/// </summary>
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
var fromRepo = await TryGetVersionFromRepoAsync(ct);
var fromRelease = await TryGetVersionFromReleasesAsync(ct);
// 模型清单:仓库里有就用仓库的(保证模型能更新)
var result = fromRepo ?? new RepoVersion
{
Repository = _preset.HomeUrl,
Branch = _preset.Branch
};
if (fromRelease != null)
{
// Release 提供启动器版本与平台附件
result.Launcher.Version = fromRelease.Launcher.Version;
foreach (var kv in fromRelease.Launcher.Packages)
result.Launcher.Packages[kv.Key] = kv.Value;
return result;
}
// 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器"
Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)");
result.Launcher.Version = "";
result.Launcher.Packages.Clear();
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
return result.Models.Count > 0 ? result : null;
}
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
{
foreach (var url in new[] { _preset.RawUrl("version.json"), _preset.RawUrl("model/version.json") })
{
try
{
var text = await Http.GetStringAsync(url, ct);
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
var doc = JsonSerializer.Deserialize<RepoVersion>(text, Json.Options);
if (doc != null) return doc;
}
catch (Exception ex)
{
Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}");
}
}
return null;
}
/// <summary>
/// 从 Release 列表里挑**版本号最高**的一个(不是最新发布时间的那个),
/// 并把它对应平台的附件填进 packages。
/// </summary>
private async Task<RepoVersion?> TryGetVersionFromReleasesAsync(CancellationToken ct)
{
try
{
var json = await Http.GetStringAsync($"{RepoApi}/releases", ct);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
var candidates = new List<(string Version, JsonElement Node)>();
foreach (var rel in doc.RootElement.EnumerateArray())
{
if (rel.TryGetProperty("draft", out var draft) && draft.ValueKind == JsonValueKind.True)
continue; // 草稿不算发布
var tag = rel.TryGetProperty("tag_name", out var t) ? t.GetString() ?? "" : "";
var ver = VersionUtil.Normalize(tag);
if (string.IsNullOrWhiteSpace(ver)) continue;
candidates.Add((ver, rel));
}
if (candidates.Count == 0)
{
// 还没发布 Release 是正常状态:交给上层去问另一个源
Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空");
return null;
}
var best = candidates
.OrderByDescending(c => VersionUtil.Parse(c.Version))
.First();
var result = new RepoVersion
{
Repository = _preset.HomeUrl,
Branch = _preset.Branch,
Launcher = new RepoLauncher { Version = best.Version }
};
// 附件:按文件名识别平台
if (best.Node.TryGetProperty("assets", out var assets) &&
assets.ValueKind == JsonValueKind.Array)
{
foreach (var a in assets.EnumerateArray())
{
var name = a.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
var url = a.TryGetProperty("browser_download_url", out var u) ? u.GetString() ?? "" : "";
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url)) continue;
var rid = PlatformFromAssetName(name);
if (rid == null) continue;
var size = a.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
result.Launcher.Packages[rid] = new RepoPackage
{
Url = url,
AssetName = name,
Size = size
};
}
}
return result.Launcher.Packages.Count > 0 ? result : null;
}
catch (Exception ex)
{
Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}");
return null;
}
}
/// <summary>从附件名推断 RID:GC-1.0.6-win-amd64.zip → win-x64</summary>
private static string? PlatformFromAssetName(string name)
{
var n = name.ToLowerInvariant();
if (!n.EndsWith(".zip")) return null;
if (n.Contains("win") && n.Contains("arm64")) return "win-arm64";
if (n.Contains("win") && (n.Contains("amd64") || n.Contains("x64"))) return "win-x64";
if (n.Contains("mac") && n.Contains("arm64")) return "osx-arm64";
if (n.Contains("mac") && n.Contains("x64")) return "osx-x64";
if (n.Contains("linux") && n.Contains("x64")) return "linux-x64";
return null;
}
// ---------------------------------------------------------------- 目录
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var result = new List<RepoEntry>();
await WalkAsync(rootPath.Trim('/'), "", result, ct, depth: 0);
return result;
}
private async Task WalkAsync(string apiPath, string relPrefix, List<RepoEntry> sink,
CancellationToken ct, int depth)
{
if (depth > 8) return;
var url = $"{RepoRepoContentsUrl()}/{apiPath}";
string json;
try { json = await Http.GetStringAsync(url, ct); }
catch (Exception ex)
{
Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}");
return;
}
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
// 单文件
if (root.ValueKind == JsonValueKind.Object)
{
AddFile(root, relPrefix, sink);
return;
}
if (root.ValueKind != JsonValueKind.Array) return;
var subdirs = new List<(string Path, string Rel)>();
foreach (var item in root.EnumerateArray())
{
var type = item.TryGetProperty("type", out var ty) ? ty.GetString() ?? "" : "";
var name = item.TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : "";
if (string.IsNullOrEmpty(name)) continue;
// 跳过构建产物与源码,模型包只需要清单与数据
if (type == "dir")
{
if (IsIgnoredDir(name)) continue;
subdirs.Add((apiPath + "/" + name, relPrefix + name + "/"));
}
else
{
AddFile(item, relPrefix, sink);
}
}
foreach (var (p, rel) in subdirs)
await WalkAsync(p, rel, sink, ct, depth + 1);
}
private string RepoRepoContentsUrl() => $"{RepoApi}/contents";
private static void AddFile(JsonElement item, string relPrefix, List<RepoEntry> sink)
{
var name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
var path = item.TryGetProperty("path", out var p) ? p.GetString() ?? "" : name;
var size = item.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
var dl = item.TryGetProperty("download_url", out var d) ? d.GetString() : null;
var sha = item.TryGetProperty("sha", out var sh) ? sh.GetString() : null;
sink.Add(new RepoEntry
{
Name = name,
Path = path,
RelativePath = relPrefix + name,
IsDirectory = false,
DownloadUrl = dl,
Size = size,
Sha = sha
});
}
private static bool IsIgnoredDir(string name) =>
name is "src" or "bin" or "obj" or "node_modules" or ".git" or ".vs"
or ".idea" or ".vscode";
// ---------------------------------------------------------------- 下载
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
{
// 优先用 API 提供的 download_url;没有就按 raw 规约拼
var url = entry.DownloadUrl;
if (string.IsNullOrWhiteSpace(url))
url = _preset.RawUrl(entry.Path);
return await Http.GetByteArrayAsync(url, ct);
}
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(package.Url)) return null;
try { return await Http.GetByteArrayAsync(package.Url, ct); }
catch (Exception ex)
{
Console.Error.WriteLine($"[gitea] 下载更新包失败: {ex.Message}");
return null;
}
}
}
@@ -1,176 +0,0 @@
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 { }
}
}
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using EarthModelStudio.Views;
namespace EarthModelStudio.Services;
/// <summary>
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
/// 1. 关闭主窗口与所有模型窗口;
/// 2. 弹出圆角进度窗;
/// 3. 下载最新版到当前目录(与旧版并列);
/// 4. 安排替换脚本、关进度窗、退出进程。
/// 失败时恢复主窗口,继续使用当前版本。
/// </summary>
public static class LauncherUpdateFlow
{
private static bool _running;
public static bool IsRunning => _running;
public static async Task RunAsync(AppServices services, string title)
{
if (_running) return;
_running = true;
var desktop = Application.Current?.ApplicationLifetime
as IClassicDesktopStyleApplicationLifetime;
var mainWindow = desktop?.MainWindow;
var progressWindow = new UpdaterWindow(title);
try
{
// 1. 关闭所有窗口
if (desktop != null) desktop.MainWindow = null;
try { mainWindow?.Close(); } catch { }
foreach (var w in OpenWindows().ToList())
{
try { w.Close(); } catch { }
}
// 2. 进度窗
progressWindow.Show();
progressWindow.Report(0, "准备更新…");
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
// 3. 下载
var progress = new Progress<UpdateProgressInfo>(p =>
progressWindow.Report(p.Value, p.Stage));
var result = await LauncherUpdater.DownloadAsync(
services.Paths, services.Updates.Remote, progress);
if (result.State == UpdateRunState.Failed)
{
progressWindow.Report(0, "更新失败", result.Message);
await Task.Delay(2200);
_running = false;
progressWindow.Close();
RestoreMainWindow(desktop, mainWindow);
return;
}
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
// 4. 安排替换(下次启动生效 / 脚本接管重启)
var scheduled = LauncherUpdater.ScheduleApply(
services.Paths, result.PackageName ?? "");
if (!scheduled)
{
progressWindow.Report(0, "无法安排更新", "请检查安装目录是否可写");
await Task.Delay(2200);
_running = false;
progressWindow.Close();
RestoreMainWindow(desktop, mainWindow);
return;
}
await Task.Delay(400);
progressWindow.Close();
desktop?.Shutdown();
}
catch (Exception ex)
{
Console.Error.WriteLine($"更新流程异常: {ex}");
_running = false;
try { progressWindow.Close(); } catch { }
RestoreMainWindow(desktop, mainWindow);
}
}
private static void RestoreMainWindow(
IClassicDesktopStyleApplicationLifetime? desktop, Window? mainWindow)
{
if (desktop == null || mainWindow == null) return;
try
{
desktop.MainWindow = mainWindow;
mainWindow.Show();
mainWindow.Activate();
}
catch (Exception ex)
{
Console.Error.WriteLine($"恢复主窗口失败: {ex.Message}");
}
}
private static IEnumerable<Window> OpenWindows()
{
if (Application.Current?.ApplicationLifetime
is not IClassicDesktopStyleApplicationLifetime d)
yield break;
foreach (var w in d.Windows)
{
if (w is UpdaterWindow) continue;
yield return w;
}
}
}
@@ -0,0 +1,643 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
// ===========================================================================
// 启动器更新模块(唯一实现)
//
// 需求(按用户):
// · 只认 GitCode Release 的 latest 版本号(tag),文件名格式:
// GC-<版本>-<系统>-<架构>.exe / .app
// 例 GC-1.0.3-win-amd64.exe / GC-1.0.3-mac-arm64.app
// · 当前运行版本与 latest 不同 => 提示更新;相同 => 无需更新
// · 下载的新版解压到「当前运行目录」,与旧版并列;.GC 完全不动
// · 更新完成后:删除同系统同架构、版本号 != latest 的其它 GC-* 文件;
// 异系统 / 异架构的文件一律不碰
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
// ===========================================================================
public sealed class UpdateProgressInfo
{
public double Value { get; init; }
public string Stage { get; init; } = "";
}
public enum UpdateRunState { UpToDate, Ready, Failed }
public sealed class UpdateRunResult
{
public UpdateRunState State { get; init; }
public string Version { get; init; } = "";
public string Message { get; init; } = "";
public string? PackageName { get; init; }
public string? NewAppPath { get; init; }
}
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
public static class LauncherUpdater
{
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
public static string RunningVersion => UpdateService.CurrentLauncherVersion;
/// <summary>当前 RID,如 osx-arm64。</summary>
public static string CurrentRid => UpdateService.CurrentRid;
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
public static string PlatformLabel => CurrentRid switch
{
"win-x64" => "win-amd64",
"win-arm64" => "win-arm64",
"osx-arm64" => "mac-arm64",
"osx-x64" => "mac-x64",
"linux-x64" => "linux-amd64",
_ => CurrentRid
};
// ---------------------------------------------------------------- 检查
/// <summary>
/// 检查 Release latest 版本。返回 latest 版本号;若与当前运行版本相同返回 null。
/// 只比版本号,不比 sha256。
/// </summary>
/// <summary>
/// 检查启动器新版本:**两个源(Xhmcl / GitCode)的 Release 都要查**,
/// 取版本号最高的那个作为最新版。任何一个源失败不影响另一个。
/// </summary>
public static async Task<string?> CheckAsync(CancellationToken ct = default)
=> await CheckAllAsync(null, ct);
/// <summary>兼容旧调用:优先用给定 remote,同时仍会比对另一个源。</summary>
public static async Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default)
=> await CheckAllAsync(remote, ct);
private static async Task<string?> CheckAllAsync(IModelRemote? preferred, CancellationToken ct)
{
var candidates = new List<(string Source, string Version)>();
foreach (var preset in SourcePreset.All)
{
try
{
// 优先复用调用方已建好的 remote(避免重复建实例)
var remote = preferred != null &&
SourcePreset.Detect(preferred.DisplayName).Id == preset.Id
? preferred
: SourceSelector.CreateRemote(preset);
var version = await remote.GetVersionAsync(ct);
var v = (version?.Launcher.Version ?? "").Trim();
if (v.Length == 0)
{
Console.WriteLine($"[update] {preset.Name}: 没有版本信息(可能还没发 Release)");
continue;
}
Console.WriteLine($"[update] {preset.Name}: {v}");
candidates.Add((preset.Name, v));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] {preset.Name} 检查失败: {ex.Message}");
}
}
if (candidates.Count == 0) return null;
// 取版本号最高的(第 7 项)
var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First();
Console.WriteLine($"[update] 最新版:{best.Version}(来自 {best.Source})");
var cmp = VersionUtil.Compare(best.Version, RunningVersion);
// 远端版本更新 → 提示更新
if (cmp > 0)
{
Console.WriteLine($"[update] 远端 {best.Version} > 本地 {RunningVersion},提示更新");
return best.Version;
}
// 远端版本更旧 → 不提示
if (cmp < 0)
{
Console.WriteLine($"[update] 远端 {best.Version} < 本地 {RunningVersion},不提示");
return null;
}
// 版本号相同:比对当前程序的 sha256 与 Release 包
// 相符 → 视为最新,不提示
// 不相符 → 说明是重新编译的同版本程序,必须提示下载
var same = await SameFingerprintAsync(best.Source, best.Version, ct);
if (same == null)
{
Console.WriteLine("[update] 版本相同但无法比对 sha256,按最新处理");
return null;
}
if (same.Value)
{
Console.WriteLine("[update] 版本相同且 sha256 一致,已是最新");
return null;
}
// 版本相同但指纹不同:是自行编译的构建,不提示更新
Console.WriteLine("[update] 版本相同但 sha256 不一致,不提示更新");
return null;
}
/// <summary>
/// 比对「当前运行程序」与「Release 平台包」的 sha256。
/// 返回 true=一致(确属同一份构建)、false=不一致(需重新下载)、null=无法比对。
/// </summary>
private static async Task<bool?> SameFingerprintAsync(string sourceName, string version,
CancellationToken ct)
{
try
{
var preset = SourcePreset.All.FirstOrDefault(p =>
string.Equals(p.Name, sourceName, StringComparison.OrdinalIgnoreCase));
if (preset == null) return null;
var rid = CurrentRid;
Console.WriteLine($"[update] 抓取 {preset.Name} 的 {rid} 发布包用于比对…");
// 定位进程对应的可执行文件 / .app
var self = Environment.ProcessPath;
if (string.IsNullOrWhiteSpace(self)) return null;
var selfPath = self!;
// 单文件 / dotnet 宿主时退回到程序集位置
if (Path.GetFileNameWithoutExtension(selfPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
selfPath = typeof(LauncherUpdater).Assembly.Location;
var selfHash = await HashFileAsync(selfPath, ct);
Console.WriteLine($"[update] 本地程序 sha256 = {selfHash[..16]}…");
// 下载 Release 对应平台包,取包内主程序再算
var remote = SourceSelector.CreateRemote(preset);
var v = await remote.GetVersionAsync(ct);
if (v == null || !v.Launcher.Packages.TryGetValue(rid, out var pkg) || pkg == null)
return null;
var bytes = await remote.DownloadPackageAsync(pkg, ct);
if (bytes == null || bytes.Length == 0) return null;
var remoteHash = await HashZipPayloadAsync(bytes, ct);
if (remoteHash == null) return null;
Console.WriteLine($"[update] 远端包 sha256 = {remoteHash[..16]}…");
return string.Equals(selfHash, remoteHash, StringComparison.OrdinalIgnoreCase);
}
catch (Exception ex)
{
Console.WriteLine($"[update] sha256 比对失败: {ex.Message}");
return null;
}
}
private static async Task<string> HashFileAsync(string path, CancellationToken ct)
{
await using var fs = File.OpenRead(path);
var hash = await System.Security.Cryptography.SHA256.HashDataAsync(fs, ct);
return Convert.ToHexString(hash);
}
/// <summary>从发布包(zip)里取出主程序并算 sha256。</summary>
private static async Task<string?> HashZipPayloadAsync(byte[] zip, CancellationToken ct)
{
try
{
using var ms = new MemoryStream(zip);
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
// 找主程序:app 内的可执行文件 / EarthModelStudio.dll / 单文件 exe
var entry = archive.Entries.FirstOrDefault(e =>
e.Name.Equals("EarthModelStudio.dll", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e =>
e.Name.Equals("EarthModelStudio", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e =>
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
e.Name.StartsWith("EarthModelStudio", StringComparison.OrdinalIgnoreCase));
if (entry == null) return null;
await using var es = entry.Open();
using var buf = new MemoryStream();
await es.CopyToAsync(buf, ct);
var hash = System.Security.Cryptography.SHA256.HashData(buf.ToArray());
return Convert.ToHexString(hash);
}
catch { return null; }
}
/// <summary>
/// 遍历所有源的 Release,取**版本号最高且包含本平台发布包**的那个。
/// 某个源没有 Release(返回 null)时自动跳过。
/// </summary>
private static async Task<(RepoVersion Version, IModelRemote Remote)?> GetBestReleaseAsync(
IModelRemote fallback, CancellationToken ct)
{
var rid = CurrentRid;
var found = new List<(string Source, RepoVersion Version, IModelRemote Remote)>();
foreach (var preset in SourcePreset.All)
{
try
{
var remote = SourceSelector.CreateRemote(preset);
var v = await remote.GetVersionAsync(ct);
if (v == null)
{
Console.WriteLine($"[update] {preset.Name}: 无 Release");
continue;
}
if (string.IsNullOrWhiteSpace(v.Launcher.Version) || v.Launcher.Packages.Count == 0)
{
Console.WriteLine($"[update] {preset.Name}: 没有可用的启动器发布包");
continue;
}
var hasPkg = v.Launcher.Packages.ContainsKey(rid) ||
v.Launcher.Packages.ContainsKey("default");
if (!hasPkg)
{
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 缺少 {rid} 发布包");
continue;
}
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 可用");
found.Add((preset.Name, v, remote));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] {preset.Name} 读取失败: {ex.Message}");
}
}
if (found.Count == 0) return null;
var best = found.OrderByDescending(f => VersionUtil.Parse(f.Version.Launcher.Version)).First();
Console.WriteLine($"[update] 选中最新的可用发布包:v{best.Version.Launcher.Version}({best.Source})");
return (best.Version, best.Remote);
}
// ---------------------------------------------------------------- 下载
/// <summary>
/// 下载 latest 版本到当前运行目录(与旧版并列)。
/// 返回新版包名,供后续替换脚本使用。
/// </summary>
public static async Task<UpdateRunResult> DownloadAsync(
AppPaths paths, IModelRemote remote,
IProgress<UpdateProgressInfo>? progress = null,
CancellationToken ct = default)
{
try
{
progress?.Report(new UpdateProgressInfo { Value = 0.05, Stage = "正在读取最新版本" });
// 两个源都问一遍:某个源没发 Release 时自动换另一个,
// 与「检查更新」保持同一套规则,避免检查通过、下载却报无法读取。
var version = await remote.GetVersionAsync(ct);
// 当前源没有可用的启动器版本(没发 Release / 版本号为空)→ 换另一个源。
// 注意:模型清单可能仍然有效,但启动器升级必须有 Release。
var hasUsable = version != null &&
!string.IsNullOrWhiteSpace(version.Launcher.Version) &&
version.Launcher.Packages.Count > 0;
if (!hasUsable)
{
var tried = SourcePreset.Find(remote.SourceId)?.Name ?? remote.DisplayName;
Console.WriteLine($"[update] {tried} 没有可用的启动器发布包,换另一个源");
var pick = await GetBestReleaseAsync(remote, ct);
if (pick == null) return Fail("两个源都没有可用的 Release 发布包");
version = pick.Value.Version;
remote = pick.Value.Remote; // 后续下载必须用这个源的 remote
}
var latest = (version!.Launcher.Version ?? "").Trim();
var rid = CurrentRid;
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg) &&
!version.Launcher.Packages.TryGetValue("default", out pkg))
return Fail($"该平台({rid})没有对应发布包");
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
// sha256 校验(Release 提供时)
if (!string.IsNullOrWhiteSpace(pkg!.Sha256))
{
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
return Fail("下载文件校验失败(sha256 不符)");
}
progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压到当前目录" });
// 解压到临时中转目录,再搬到当前运行目录
var installDir = paths.InstallDirectory;
Directory.CreateDirectory(installDir);
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging);
var zip = Path.Combine(paths.CacheRoot, "launcher-" + Safe(latest) + ".zip");
await File.WriteAllBytesAsync(zip, bytes, ct);
try { ZipSafety.ExtractToDirectory(zip, staging); }
finally { try { File.Delete(zip); } catch { } }
// 只展平「单个非 .app 顶层目录」的 zip
FlattenStaging(staging);
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在安装新版本" });
var packageName = MoveToInstallDir(staging, installDir, latest);
try { Directory.Delete(staging, true); } catch { }
if (packageName == null) return Fail("解压结果里没有找到新版启动器");
// 写标记(纯文本,脚本读它):只含相对信息,无绝对路径
Directory.CreateDirectory(paths.UpdateRoot);
File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"),
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n");
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
return new UpdateRunResult
{
State = UpdateRunState.Ready,
Version = latest,
Message = $"v{latest} 已下载到当前目录",
PackageName = packageName,
NewAppPath = Path.Combine(installDir, packageName)
};
}
catch (OperationCanceledException) { return Fail("已取消"); }
catch (Exception ex) { return Fail(ex.Message); }
}
private static UpdateRunResult Fail(string msg) => new()
{
State = UpdateRunState.Failed,
Message = msg
};
// ---------------------------------------------------------------- 应用(下次启动)
/// <summary>
/// 生成替换脚本并启动。脚本等本进程退出后:
/// 启动新版 -> 删除同平台且版本号 != latest 的 GC-* 文件 -> 清理标记。
/// 返回 true 表示调用方应立即退出进程。
/// </summary>
public static bool ScheduleApply(AppPaths paths, string packageName)
{
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
if (!File.Exists(marker)) return false;
// 安全阀:绝不在源码目录执行替换(防止误删源码)
if (File.Exists(Path.Combine(paths.InstallDirectory, "EarthModelStudio.sln")))
{
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
return false;
}
try
{
var isWin = OperatingSystem.IsWindows();
var script = Path.Combine(paths.UpdateRoot, isWin ? "apply.bat" : "apply.sh");
var content = isWin ? WindowsScript() : UnixScript();
File.WriteAllText(script, content, new System.Text.UTF8Encoding(false));
if (!isWin)
{
try
{
File.SetUnixFileMode(script,
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
catch { }
}
var psi = isWin
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
{ UseShellExecute = false, CreateNoWindow = true }
: new System.Diagnostics.ProcessStartInfo("/bin/sh")
{ UseShellExecute = false, CreateNoWindow = true };
if (isWin) psi.ArgumentList.Add("/c");
psi.ArgumentList.Add(script);
System.Diagnostics.Process.Start(psi);
return true;
}
catch (Exception ex)
{
Console.Error.WriteLine($"启动替换脚本失败: {ex.Message}");
return false;
}
}
/// <summary>启动时若有待应用更新,安排脚本并让 Main 直接退出。</summary>
public static bool TryApplyPending(AppPaths paths)
{
if (paths.IsDevelopment) return false;
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
if (!File.Exists(marker)) return false;
var name = ReadMarker(marker, "NAME");
if (string.IsNullOrWhiteSpace(name)) return false;
if (!File.Exists(Path.Combine(paths.InstallDirectory, name!)) &&
!Directory.Exists(Path.Combine(paths.InstallDirectory, name!)))
return false; // 新版本不在了,放弃
return ScheduleApply(paths, name!);
}
// ---------------------------------------------------------------- 脚本(全部相对路径)
private static string UnixScript()
{
var s = new System.Text.StringBuilder();
s.AppendLine("#!/bin/sh");
s.AppendLine("# script lives in .GC/update/ ; install dir is two levels up");
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/../..\" && pwd)");
s.AppendLine("MARKER=\"$HERE/update.txt\"");
s.AppendLine();
s.AppendLine("# read marker");
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ]; then");
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
s.AppendLine("fi");
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
s.AppendLine("if [ ! -e \"$NEW\" ]; then");
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
s.AppendLine("fi");
s.AppendLine();
s.AppendLine("# wait for old process to exit (this script is started by it)");
s.AppendLine("sleep 2");
s.AppendLine();
s.AppendLine("# launch new version first");
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
s.AppendLine("fi");
s.AppendLine();
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
s.AppendLine("# files of OTHER platforms are NEVER touched");
s.AppendLine("for item in \"$DST\"/GC-*.app \"$DST\"/GC-*.exe; do");
s.AppendLine(" [ -e \"$item\" ] || continue");
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
s.AppendLine(" base=$(basename \"$item\")");
s.AppendLine(" stem=${base#GC-}");
s.AppendLine(" case \"$base\" in");
s.AppendLine(" *.app) stem=${stem%.app} ;;");
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
s.AppendLine(" *) continue ;;");
s.AppendLine(" esac");
s.AppendLine(" ver=${stem%%-*}");
s.AppendLine(" rest=${stem#*-}");
s.AppendLine(" plat=\"${rest%-*}-${rest##*-}\"");
s.AppendLine(" # skip other platforms entirely");
s.AppendLine(" [ \"$plat\" != \"$NEWPLAT\" ] && continue");
s.AppendLine(" # same platform: keep only latest version");
s.AppendLine(" if [ \"$ver\" = \"$NEWVER\" ]; then");
s.AppendLine(" echo \"keep: $base\"");
s.AppendLine(" else");
s.AppendLine(" echo \"remove (version $ver != $NEWVER): $base\"");
s.AppendLine(" rm -rf \"$item\" 2>/dev/null");
s.AppendLine(" fi");
s.AppendLine("done");
s.AppendLine();
s.AppendLine("rm -f \"$MARKER\"");
s.AppendLine("rm -f \"$HERE\"/*.sh 2>/dev/null");
return s.ToString();
}
private static string WindowsScript()
{
var s = new System.Text.StringBuilder();
s.AppendLine("@echo off");
s.AppendLine("chcp 65001 >nul 2>&1");
s.AppendLine("set \"HERE=%~dp0\"");
s.AppendLine("set \"DST=%~dp0..\\..\"");
s.AppendLine("set \"MARKER=%~dp0update.txt\"");
s.AppendLine("timeout /t 2 /nobreak >nul");
s.AppendLine();
s.AppendLine("set \"NEWNAME=\"");
s.AppendLine("set \"NEWVER=\"");
s.AppendLine("set \"NEWPLAT=\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
s.AppendLine("if not exist \"%DST%\\%NEWNAME%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
s.AppendLine();
s.AppendLine("rem launch new version");
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
s.AppendLine();
s.AppendLine("rem delete old GC-* files: SAME platform only, version != latest");
s.AppendLine("powershell -NoProfile -ExecutionPolicy Bypass -Command \"^");
s.AppendLine("$dst='%DST%'; $new='%NEWNAME%'; $ver='%NEWVER%'; $plat='%NEWPLAT%';^");
s.AppendLine("Get-ChildItem -LiteralPath $dst -Filter 'GC-*' | ForEach-Object {^");
s.AppendLine(" $n=$_.Name; if($n -eq $new){return};^");
s.AppendLine(" $m=[regex]::Match($n,'^GC-(.+?)-([^-]+)-([^-]+)\\.(app|exe)$');^");
s.AppendLine(" if(-not $m.Success){return};^");
s.AppendLine(" $fver=$m.Groups[1].Value; $fplat=$m.Groups[2].Value+'-'+$m.Groups[3].Value;^");
s.AppendLine(" if($fplat -ne $plat){return};^");
s.AppendLine(" if($fver -eq $ver){ Write-Host \\\"keep: $n\\\" }^");
s.AppendLine(" else { Write-Host \\\"remove: $n\\\"; Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }^");
s.AppendLine("}\"");
s.AppendLine();
s.AppendLine("del /Q \"%MARKER%\" >nul 2>&1");
s.AppendLine("del /Q \"%~f0\" >nul 2>&1");
return s.ToString();
}
// ---------------------------------------------------------------- 内部工具
/// <summary>展平只有一个顶层目录、且不是 .app 的 zip。</summary>
private static void FlattenStaging(string dir)
{
var entries = Directory.GetFileSystemEntries(dir);
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
var inner = entries[0];
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
var flat = dir + "-flat";
if (Directory.Exists(flat)) Directory.Delete(flat, true);
Directory.Move(inner, flat);
Directory.Delete(dir, true);
Directory.Move(flat, dir);
}
/// <summary>
/// 把 staging 里的新版搬到当前目录,与旧版并列。
/// 返回新版包名(GC-&lt;版本&gt;-&lt;平台&gt;.app/.exe)。.GC 绝不覆盖。
/// </summary>
private static string? MoveToInstallDir(string staging, string installDir, string latest)
{
try
{
foreach (var entry in Directory.GetFileSystemEntries(staging))
{
var name = Path.GetFileName(entry);
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
var dest = Path.Combine(installDir, name);
if (Directory.Exists(dest)) Directory.Delete(dest, true);
else if (File.Exists(dest)) File.Delete(dest);
if (Directory.Exists(entry)) Directory.Move(entry, dest);
else File.Move(entry, dest);
// 保证 .app 里可执行文件可执行
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(dest))
{
var macOs = Path.Combine(dest, "Contents", "MacOS");
if (Directory.Exists(macOs))
{
try
{
foreach (var f in Directory.GetFiles(macOs, "*", SearchOption.TopDirectoryOnly))
{
var mode = File.GetUnixFileMode(f);
File.SetUnixFileMode(f, mode | UnixFileMode.UserExecute);
}
}
catch { }
}
return name;
}
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"安装新版失败: {ex.Message}");
}
return null;
}
private static string? ReadMarker(string file, string key)
{
try
{
foreach (var line in File.ReadAllLines(file))
{
if (line.StartsWith(key + "=", StringComparison.Ordinal))
return line[(key.Length + 1)..].Trim();
}
}
catch { }
return null;
}
private static string Safe(string value)
{
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
return value.Replace('/', '-').Replace(' ', '-');
}
}
@@ -215,11 +215,64 @@ public sealed class ModelSourceClient
}
}
var args = new List<string> { "clone", "--depth", "1" };
if (!string.IsNullOrWhiteSpace(branch)) { args.Add("--branch"); args.Add(branch!); }
args.Add(url);
args.Add(cacheDir);
// 只拉取 model/ 目录:整仓 clone 会把 .git / src / dist 一起拖下来
// (实测 700MB+),既慢又容易超时,表现就是「读不到模型源」。
// 先浅克隆到临时目录,再用 sparse-checkout 只检出 model/。
var tmpDir = cacheDir + ".tmp";
try
{
if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true);
// 1) 初始化 + 加远程(比 clone 更快,避免先拉全量)
var initArgs = new List<string> { "init", "--quiet", tmpDir };
if (!await RunGitAsync(initArgs, ct)) return false;
var remoteArgs = new List<string> { "-C", tmpDir, "remote", "add", "origin", url };
if (!await RunGitAsync(remoteArgs, ct)) return false;
// 2) 只允许 model 目录参与检出
await RunGitAsync(new List<string> { "-C", tmpDir, "config", "core.sparseCheckout", "true" }, ct);
var sparseFile = Path.Combine(tmpDir, ".git", "info", "sparse-checkout");
Directory.CreateDirectory(Path.GetDirectoryName(sparseFile)!);
File.WriteAllText(sparseFile, "model/\n");
// 3) 浅拉指定分支
var branchName = string.IsNullOrWhiteSpace(branch) ? "main" : branch!;
var fetchArgs = new List<string>
{
"-C", tmpDir, "fetch", "--depth", "1", "--filter=blob:none", "origin", branchName
};
if (!await RunGitAsync(fetchArgs, ct)) return false;
await RunGitAsync(new List<string> { "-C", tmpDir, "checkout", "FETCH_HEAD" }, ct);
// 4) 把 model/ 移到缓存根,与原有目录结构一致
var modelDir = Path.Combine(tmpDir, "model");
if (!Directory.Exists(modelDir))
{
Console.Error.WriteLine("git sparse-checkout 后未找到 model/ 目录");
return false;
}
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
Directory.CreateDirectory(cacheDir);
Directory.Move(modelDir, Path.Combine(cacheDir, "model"));
return true;
}
catch (Exception ex)
{
Console.Error.WriteLine($"git 拉取异常: {ex.Message}");
return false;
}
finally
{
try { if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true); } catch { }
}
}
/// <summary>安静地跑一条 git 命令,返回是否成功。</summary>
private static async Task<bool> RunGitAsync(List<string> args, CancellationToken ct)
{
try
{
var psi = new ProcessStartInfo("git")
@@ -233,19 +286,16 @@ public sealed class ModelSourceClient
using var process = Process.Start(psi);
if (process == null) return false;
var stderrTask = process.StandardError.ReadToEndAsync(ct);
var errTask = process.StandardError.ReadToEndAsync(ct);
await process.WaitForExitAsync(ct);
var stderr = await stderrTask;
var err = await errTask;
if (process.ExitCode != 0)
{
Console.Error.WriteLine($"git clone 失败: {stderr}");
return false;
}
return Directory.Exists(Path.Combine(cacheDir, "model")) || Directory.Exists(cacheDir);
Console.Error.WriteLine($"git {string.Join(' ', args)} 失败: {err.Trim()}");
return process.ExitCode == 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"git clone 异常: {ex.Message}");
Console.Error.WriteLine($"git 执行失败: {ex.Message}");
return false;
}
}
@@ -23,35 +23,35 @@ public sealed class SettingsService
}
/// <summary>
/// 默认下载源(gitcode 官方仓库)始终内置在列表里,且不允许删除:
/// 它是启动器自动更新的同源仓库,用户清掉会导致模型无法回退。
/// 老配置里没有这条时自动补上;已有的用户自定义源保持不变。
/// 只允许两个内置源:Xhmcl 与 GitCode(同一份仓库的两个镜像)。
/// 不再支持用户自定义源 —— 每次加载都把 Sources 规整成这两条,
/// 老配置里的自定义源会被清理掉。
/// </summary>
public const string DefaultSourceId = "gitcode-official";
public const string DefaultSourceId = "gitcode";
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC";
private void SeedDefaultSource()
{
var existing = Current.Sources.FirstOrDefault(s =>
string.Equals(s.Id, DefaultSourceId, StringComparison.OrdinalIgnoreCase));
if (existing == null)
var rebuilt = new List<ModelSource>();
foreach (var preset in SourcePreset.All)
{
Current.Sources.Insert(0, new ModelSource
// 保留用户对「启用/停用」的选择,其余字段以内置定义为准
var old = Current.Sources.FirstOrDefault(s =>
SourcePreset.Detect(s.Url).Id == preset.Id);
rebuilt.Add(new ModelSource
{
Id = DefaultSourceId,
Name = "Morris GC (GitCode)",
Url = DefaultSourceUrl,
Enabled = true,
Id = preset.Id,
Name = preset.Name,
Url = preset.HomeUrl,
Enabled = old?.Enabled ?? true,
BuiltIn = true
});
Save();
}
else
{
// 强制保证内置标记与地址,避免旧配置被用户改坏后失去保护
existing.BuiltIn = true;
if (string.IsNullOrWhiteSpace(existing.Url)) existing.Url = DefaultSourceUrl;
}
var changed = Current.Sources.Count != rebuilt.Count ||
Current.Sources.Any(s => !s.BuiltIn);
Current.Sources = rebuilt;
if (changed) Save();
}
public void Save()
@@ -12,19 +12,38 @@ public static class Shell
try
{
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var info = new ProcessStartInfo
{
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
: OperatingSystem.IsMacOS() ? "open"
: "xdg-open",
UseShellExecute = false
};
info.ArgumentList.Add(path);
Process.Start(info);
StartWith(path);
}
catch (Exception ex)
{
Console.Error.WriteLine($"打开目录失败: {ex.Message}");
}
}
/// <summary>用系统默认浏览器打开一个 URL。</summary>
public static void OpenUrl(string url)
{
if (string.IsNullOrWhiteSpace(url)) return;
try
{
StartWith(url);
}
catch (Exception ex)
{
Console.Error.WriteLine($"打开链接失败: {ex.Message}");
}
}
private static void StartWith(string argument)
{
var info = new ProcessStartInfo
{
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
: OperatingSystem.IsMacOS() ? "open"
: "xdg-open",
UseShellExecute = false
};
info.ArgumentList.Add(argument);
Process.Start(info);
}
}
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace EarthModelStudio.Services;
/// <summary>
/// 内置下载源。只允许这两个,不再支持用户自定义源。
///
/// 两个源的内容是同一份仓库(同一个 version.json、同一批模型),
/// 区别只是**托管在哪台服务器**上;启动时探测两者延迟,取快的那个下载。
/// </summary>
public sealed class SourcePreset
{
public string Id { get; init; } = "";
public string Name { get; init; } = "";
/// <summary>仓库主页(用于展示与打开)。</summary>
public string HomeUrl { get; init; } = "";
/// <summary>API 根地址(Gitea: /api/v1,GitCode: /api/v5)。</summary>
public string ApiBase { get; init; } = "";
/// <summary>原始文件下载前缀(用于拼 raw 地址)。</summary>
public string RawBase { get; init; } = "";
/// <summary>后端类型:gitea / gitcode。</summary>
public string Kind { get; init; } = "";
public string Owner { get; init; } = "";
public string Repo { get; init; } = "";
public string Branch { get; init; } = "main";
/// <summary>raw 地址风格:gitea 用 raw/branch/{b},gitcode 用 raw/{b}。</summary>
public string RawStyle { get; init; } = "branch";
public string Repository => HomeUrl;
/// <summary>拼 raw 文件下载地址(两个平台的 URL 结构不同)。</summary>
public string RawUrl(string path) => RawStyle == "plain"
? $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}"
: $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}";
public static readonly SourcePreset Xhmcl = new()
{
Id = "xhmcl",
Name = "Xhmcl",
HomeUrl = "https://git.xhmcl.com/Morris/GC",
ApiBase = "https://git.xhmcl.com/api/v1",
RawBase = "https://git.xhmcl.com",
Kind = "gitea",
RawStyle = "branch",
Owner = "Morris",
Repo = "GC",
Branch = "main"
};
public static readonly SourcePreset GitCode = new()
{
Id = "gitcode",
Name = "GitCode",
HomeUrl = "https://gitcode.com/2509_92447106/GC",
ApiBase = "https://api.gitcode.com/api/v5",
RawBase = "https://gitcode.com",
Kind = "gitcode",
RawStyle = "plain",
Owner = "2509_92447106",
Repo = "GC",
Branch = "main"
};
public static readonly SourcePreset[] All = { Xhmcl, GitCode };
public static SourcePreset? Find(string? id) =>
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
/// <summary>把任意仓库地址映射到这两个内置源之一(用于兼容旧配置)。</summary>
public static SourcePreset Detect(string? url)
{
if (string.IsNullOrWhiteSpace(url)) return GitCode;
var u = url!.ToLowerInvariant();
if (u.Contains("xhmcl.com")) return Xhmcl;
return GitCode;
}
}
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
///
/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间,
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
/// 避免每次点下载都重新测速。
/// </summary>
public sealed class SourceSelector
{
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Probe/1.0");
return c;
}
private readonly object _lock = new();
private SourcePreset? _cached;
private DateTime _cachedAt = DateTime.MinValue;
private readonly TimeSpan _ttl = TimeSpan.FromMinutes(3);
/// <summary>最近一次选中的源(未探测时为空)。</summary>
public SourcePreset? Current { get { lock (_lock) return _cached; } }
/// <summary>每个源的探测耗时(毫秒),供界面展示。</summary>
public IReadOnlyDictionary<string, long> LastLatency { get; private set; } =
new Dictionary<string, long>();
/// <summary>
/// 探测两个源并返回最快的。force=true 时忽略缓存。
/// 两个都失败时返回 GitCode(默认源)。
/// </summary>
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
{
lock (_lock)
{
if (!force && _cached != null && DateTime.UtcNow - _cachedAt < _ttl)
return _cached;
}
var probes = SourcePreset.All.Select(async p =>
{
var sw = Stopwatch.StartNew();
var ok = await ProbeAsync(p, ct);
sw.Stop();
return (Preset: p, Ok: ok, Ms: sw.ElapsedMilliseconds);
});
var results = await Task.WhenAll(probes);
var latencies = results.ToDictionary(r => r.Preset.Id, r => r.Ms);
LastLatency = latencies;
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode;
lock (_lock)
{
_cached = chosen;
_cachedAt = DateTime.UtcNow;
}
Console.WriteLine("[selector] 测速:" + string.Join(" ",
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))
+ $" → 选择 {chosen.Name}");
return chosen;
}
/// <summary>
/// 探测:能拿到合法 JSON 才算可用。
/// 注意两个平台取文件的方式不同:
/// · Gitea(Xhmcl):raw/branch/{b}/{path} 直接返回文件内容
/// · GitCode:raw 地址返回的是 HTML 页面,必须走 API(内容为 base64)
/// 因此 GitCode 用 api/v5 contents + Accept: application/json 探测。
/// </summary>
private static async Task<bool> ProbeAsync(SourcePreset preset, CancellationToken ct)
{
if (preset.Kind == "gitcode")
{
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(5));
var api = $"{preset.ApiBase}/repos/{preset.Owner}/{preset.Repo}/contents/version.json?ref={preset.Branch}";
using var req = new HttpRequestMessage(HttpMethod.Get, api);
req.Headers.Accept.ParseAdd("application/json");
using var resp = await Http.SendAsync(req, cts.Token);
if (!resp.IsSuccessStatusCode) return false;
var text = await resp.Content.ReadAsStringAsync(cts.Token);
return text.TrimStart().StartsWith('{');
}
catch { return false; }
}
var urls = new[] { preset.RawUrl("version.json"), preset.RawUrl("model/version.json") };
foreach (var url in urls)
{
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(5));
var text = await Http.GetStringAsync(url, cts.Token);
if (text.TrimStart().StartsWith('{')) return true;
}
catch { /* 换下一个地址 */ }
}
return false;
}
/// <summary>为指定源创建对应的 remote 实现。</summary>
public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch
{
"gitea" => new GiteaRemote(preset),
_ => new GitCodeReleaseRemote(null, preset.HomeUrl)
};
}
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more