commit 60113ab76e86669487e461b31e41662539e9b18f Author: 2509_92447106 <2509_92447106@noreply.gitcode.com> Date: Sat Nov 7 16:05:56 2026 +0800 上传 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8d4637e --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +bin/ +obj/ +dist/ +build/ +*.user +.DS_Store +.vs/ +.venv/ +venv/ +env/ +.idea/ +.vscode/ +__pycache__/ +*.pyc +*.pyo +*.log +node_modules/ +.pytest_cache/ +.mypy_cache/ diff --git a/.workbuddy/memory/2026-11-07.md b/.workbuddy/memory/2026-11-07.md new file mode 100644 index 0000000..8dcb403 --- /dev/null +++ b/.workbuddy/memory/2026-11-07.md @@ -0,0 +1,40 @@ +# 2026-11-07 + +## Earth Model Studio(新建项目) +- 用户要求:C#/.NET8(可切10),多目录结构(曾要求 gradle 命名,后明确改为标准 .NET 命名,勿再用 gradle 字样) +- 结构:src/main/dotnet + src/test/dotnet + src/main/resources + model/ + examples/ + dist/ + Directory.Build.props + build.sh/build.ps1 +- 三平台一次性编译:`./build.sh publish` → dist/{mac-arm64(.app),win-x64,win-arm64},自包含单文件 + 内置 model/ + examples/ +- 技术栈:Avalonia 11.3.9 + CommunityToolkit.Mvvm 8.2.2(本地 NuGet 已缓存);纯 CPU 球面像素渲染(SphereRaster + CelestialView) +- 模型格式:model//.json + .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//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 diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..77b9071 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,22 @@ + + + + net8.0 + + + latest + enable + disable + 11.3.9 + 8.2.2 + 1.0.0 + NeoRF + Earth Model Studio + zh-Hans + + diff --git a/EarthModelStudio.sln b/EarthModelStudio.sln new file mode 100644 index 0000000..0d3bc4c --- /dev/null +++ b/EarthModelStudio.sln @@ -0,0 +1,127 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "main", "main", "{ABAA6554-252E-13CE-1B40-0464A7DBA771}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{F2BBD9FE-F148-5687-ED21-3ABA515A9B22}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio", "src\main\dotnet\EarthModelStudio\EarthModelStudio.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.Tests", "src\test\dotnet\EarthModelStudio.Tests\EarthModelStudio.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.ModelSdk", "model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "earth-rotation", "earth-rotation", "{EBCD2737-5E64-9C5F-5D8B-D0375EC50F43}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{13F93445-B061-AC9E-97CA-8C4FA55DC418}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRotationModel", "model\earth-rotation\src\EarthRotationModel.csproj", "{64556F71-7456-43B2-890C-CF01AD29D386}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "earth-revolution", "earth-revolution", "{0B92F86C-37C2-3C12-904C-85123CE34F4C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EADF0841-BEC2-9A74-4322-069D7B5A6EBB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|x64.ActiveCfg = Debug|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|x64.Build.0 = Debug|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|x86.ActiveCfg = Debug|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|x86.Build.0 = Debug|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|Any CPU.Build.0 = Release|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x64.ActiveCfg = Release|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x64.Build.0 = Release|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x86.ActiveCfg = Release|Any CPU + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x86.Build.0 = Release|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x64.ActiveCfg = Debug|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x64.Build.0 = Debug|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x86.ActiveCfg = Debug|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x86.Build.0 = Debug|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|Any CPU.Build.0 = Release|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x64.ActiveCfg = Release|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x64.Build.0 = Release|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x86.ActiveCfg = Release|Any CPU + {D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x86.Build.0 = Release|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x64.ActiveCfg = Debug|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x64.Build.0 = Debug|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x86.ActiveCfg = Debug|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x86.Build.0 = Debug|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|Any CPU.Build.0 = Release|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x64.ActiveCfg = Release|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x64.Build.0 = Release|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x86.ActiveCfg = Release|Any CPU + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x86.Build.0 = Release|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Debug|Any CPU.Build.0 = Debug|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x64.ActiveCfg = Debug|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x64.Build.0 = Debug|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x86.ActiveCfg = Debug|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x86.Build.0 = Debug|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Release|Any CPU.ActiveCfg = Release|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Release|Any CPU.Build.0 = Release|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Release|x64.ActiveCfg = Release|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Release|x64.Build.0 = Release|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Release|x86.ActiveCfg = Release|Any CPU + {64556F71-7456-43B2-890C-CF01AD29D386}.Release|x86.Build.0 = Release|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x64.ActiveCfg = Debug|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x64.Build.0 = Debug|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x86.ActiveCfg = Debug|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x86.Build.0 = Debug|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|Any CPU.Build.0 = Release|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.ActiveCfg = Release|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU + {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {ABAA6554-252E-13CE-1B40-0464A7DBA771} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {F2BBD9FE-F148-5687-ED21-3ABA515A9B22} = {ABAA6554-252E-13CE-1B40-0464A7DBA771} + {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {F2BBD9FE-F148-5687-ED21-3ABA515A9B22} + {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} + {D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B} + {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4} + {EBCD2737-5E64-9C5F-5D8B-D0375EC50F43} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE} + {13F93445-B061-AC9E-97CA-8C4FA55DC418} = {EBCD2737-5E64-9C5F-5D8B-D0375EC50F43} + {64556F71-7456-43B2-890C-CF01AD29D386} = {13F93445-B061-AC9E-97CA-8C4FA55DC418} + {0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE} + {EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C} + {6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md new file mode 100644 index 0000000..3155880 --- /dev/null +++ b/README.md @@ -0,0 +1,126 @@ +# Earth Model Studio + +天文教学模型**启动器**:主页管理/启动模型、从链接导入模型源并下载、设置模型源与启动内存分配。 + +> **分层约定(重要)** +> - `src/` = 启动器:扫描、下载、开窗口、显示启动进度。**不渲染、不含任何模型内容、不预置模型源**。 +> - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。 +> +> 结论:**模型相关代码全部直接存在模型目录里**,仓库根目录没有 `model-src/` / `model-sdk/` 这类旁路目录。 +> 启动器只负责下载和启动;想加新内容 = 在 `model//` 里放模型,`src` 一行都不用改。 + +- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台 +- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载 +- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**,一条命令全部编译 + +## 目录结构 + +``` +EarthModelStudio/ +├── EarthModelStudio.sln +├── Directory.Build.props # 公共构建属性(-p:TargetFramework=net10.0 可切 .NET 10) +├── build.sh / build.ps1 # 构建脚本(build/run/test/publish/models/pack-models) +├── src/ # ★ 启动器(没有渲染逻辑) +│ └── main/dotnet/EarthModelStudio/ +│ ├── Models/ # 模型清单、设置(只有启动器需要的元数据) +│ ├── Services/ # 目录探测/设置/i18n/模型库/模型源/下载/内存预算/**ModelHost** +│ ├── ViewModels/ Views/ # 主页、下载、设置、模型窗口壳 +│ └── Assets/i18n/ # 启动器界面语言包 +├── src/test/dotnet/…Tests/ # 离屏校验(启动器页面 + 真实加载模型窗口) +├── model/ # ★ 模型的一切(源码 + 数据 + dll + 封面 + 语言包) +│ ├── _sdk/EarthModelStudio.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码) +│ ├── _engine/ # 共享引擎源码(渲染、界面、交互) +│ │ ├── src/ # CelestialView / PlanetTexture / EarthModelView … +│ │ └── PreviewGen/ # 用模型渲染器生成封面 +│ ├── earth-rotation/ +│ │ ├── earth-rotation.json # 清单 +│ │ ├── src/ # 本模型源码(csproj + 入口工厂) +│ │ └── earth-rotation.model/ # dll + scene.json/land.json + preview.png + i18n +│ └── earth-revolution/ # 同上结构,封面是公转场景 +└── dist/ # 发布产物(启动器 + 单独打包的模型) +``` + +模型库查找顺序:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 可执行文件旁 `model/` → 用户数据目录。 + +## 构建与运行 + +```bash +./build.sh build # 编译启动器 +./build.sh models # 编译模型 dll + 生成封面(写进 model/) +./build.sh run # 运行 +./build.sh test # 离屏校验:页面截图 + 真实加载模型窗口截图 +./build.sh publish # 一次性编译三个平台(启动器,不含模型) +./build.sh pack-models # 编译模型后打包 -> dist/models-.zip +./build.sh clean +``` + +Windows 用 `.\build.ps1`(参数相同)。 + +| 产物 | 平台 | +| --- | --- | +| `dist/mac-arm64/EarthModelStudio.app` | macOS Apple Silicon | +| `dist/win-x64/EarthModelStudio.exe` | Windows x64 | +| `dist/win-arm64/EarthModelStudio.exe` | Windows on ARM | + +均为自包含单文件启动器,`model/` 目录为空(只有 README)。模型用 `pack-models` 单独分发。 + +## 模型契约 + +```csharp +public interface IModelFactory // 模型入口 +{ + int ApiVersion { get; } // 目前为 1 + IModelRuntime Create(); +} + +public interface IModelRuntime : IDisposable +{ + void Prepare(IModelContext context); // 后台线程:读数据、烘焙纹理、汇报进度 + Control CreateView(IModelContext context); // UI 线程:模型自己做界面 +} + +public interface IModelContext +{ + string ModelId { get; } + string ModelDirectory { get; } + string DataDirectory { get; } + string Language { get; } + int MemoryBudgetMb { get; } + void RequestClose(); + void ReportProgress(double value, string? message = null); + void Log(string message); +} +``` + +启动器先弹进度窗,在后台调用 `Prepare`(模型用 `ReportProgress` 汇报真实进度), +再在 UI 线程调用 `CreateView`,把返回的控件直接铺满窗口 —— 除此之外什么都不做。 + +详细清单字段、数据格式、封面生成见 [`model/README.md`](model/README.md)。 + +## 模型窗口 + +- 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口 +- 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集 +- 快捷键 `Esc` 关闭、`F11` 全屏(其余快捷键由模型自己决定) + +## 地球模型(model/_engine + model//src) + +- **地表**:加载时烘焙 1024×512 等经纬度纹理 —— 海洋深度、沙漠/雨林/针叶林/苔原分带、极地冰盖、 + 山脉起伏(高度梯度参与光照)、云层、夜间城市辉光;每帧只做双线性采样 + 地形光照,60 FPS +- **自转**:球面像素渲染、晨昏线、大气边缘光、经纬网、地轴、太阳直射点;只有自转视角, + **没有节气定位**(节气属于公转) +- **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定位、HUD +- **交互**:滚轮 / 工具栏 −+ 缩放(0.6×–6×,带缓动);暂停后拖动可旋转地球或沿轨道拖动公转位置; + 松手有惯性;缩放、视角、面板都有过渡动画 +- 两个模型共用 `model/_engine` 的代码,各自 `src/` 只提供入口工厂;界面、文案、封面都在模型包里 + +## 模型源(git 仓库) + +模型源就是普通 git 仓库,**仓库根目录下的 `model/` 文件夹即模型列表**。 +支持 `https://github.com//.git`(GitLab / Gitee 同理,走 zip 归档,失败回退 `git clone --depth 1`)、 +zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/`,下载时把模型目录复制进本地 `model/`。 + +## 启动时运行内存分配 + +设置页的「启动时运行内存分配」类似启动器的 -Xmx:启动器把这份预算通过 `IModelContext.MemoryBudgetMb` +交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。 diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..37da280 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,110 @@ +# --------------------------------------------------------------------------- +# Earth Model Studio 构建脚本(Windows PowerShell) +# +# .\build.ps1 编译 +# .\build.ps1 run 运行 +# .\build.ps1 test 离屏渲染校验 +# .\build.ps1 publish 一次性编译三个平台 -> dist\ +# .\build.ps1 models 编译模型功能程序集 + 生成封面 +# .\build.ps1 pack-models 编译模型后整体打包 -> dist\models-x.y.z.zip +# .\build.ps1 clean 清理 +# +# 分层约定:src\ 只是启动器,不含任何模型数据;模型全部放在 model\(外置数据)。 +# --------------------------------------------------------------------------- +param( + [Parameter(Position = 0)] + [ValidateSet('build', 'run', 'test', 'publish', 'models', 'pack-models', 'clean', 'doctor')] + [string]$Task = 'build' +) + +$ErrorActionPreference = 'Stop' +$Root = $PSScriptRoot +Set-Location $Root + +$AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj' +$TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj' +$Sln = 'EarthModelStudio.sln' +$Version = '1.0.0' + +function Publish-Rid([string]$Rid, [string]$OutDir) { + Write-Host "==> 编译 $Rid -> $OutDir" + dotnet publish $AppProj -c Release -r $Rid --self-contained true ` + -p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true ` + -p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false -o "$Root/$OutDir" + if (Test-Path "$Root/$OutDir/model") { Remove-Item -Recurse -Force "$Root/$OutDir/model" } + if (Test-Path "$Root/$OutDir/examples") { Remove-Item -Recurse -Force "$Root/$OutDir/examples" } + # 启动器不带模型:只建空的模型库目录,模型作为独立内容放置 / 下载 + New-Item -ItemType Directory -Force -Path "$Root/$OutDir/model" | Out-Null + if (Test-Path "$Root/model/README.md") { + Copy-Item -Force "$Root/model/README.md" "$Root/$OutDir/model/README.md" + } +} + +function 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 } + 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 +} + +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 +} + +switch ($Task) { + 'build' { dotnet build $Sln -c Debug } + 'run' { dotnet run --project $AppProj -c Debug } + 'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" } + 'publish' { + New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null + Publish-Rid 'osx-arm64' 'dist/mac-arm64' + Publish-Rid 'win-x64' 'dist/win-x64' + Publish-Rid 'win-arm64' 'dist/win-arm64' + Write-Host '==> 三个平台编译完成(启动器不含模型数据),见 dist\' -ForegroundColor Green + Write-Host ' 模型数据用 .\build.ps1 pack-models 单独打包,或放进 <安装目录>\model 后再启动' + } + 'models' { + Build-Models + } + 'pack-models' { + Build-Models + Pack-Models + } + '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 } +} diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..b3e41f0 --- /dev/null +++ b/build.sh @@ -0,0 +1,159 @@ +#!/bin/sh +# --------------------------------------------------------------------------- +# Earth Model Studio 构建脚本(macOS / Linux) +# +# ./build.sh build 编译(Debug) +# ./build.sh run 本机运行 +# ./build.sh test 离屏渲染校验,截图输出到 build/screenshots +# ./build.sh publish 一次性编译三个平台 -> dist/ +# ./build.sh models 编译模型功能程序集 + 生成模型封面(写进 model//.model) +# ./build.sh pack-models 编译模型后把 model/ 整体打包 -> dist/models-x.y.z.zip +# ./build.sh clean 清理 +# +# 分层约定:src/ 只是启动器,不含任何模型数据;模型全部放在 model/(外置数据)。 +# +# publish 产出(启动器,模型库目录为空): +# dist/mac-arm64/EarthModelStudio.app macOS Apple Silicon +# dist/win-x64/EarthModelStudio.exe Windows x86_64 +# dist/win-arm64/EarthModelStudio.exe Windows on ARM +# --------------------------------------------------------------------------- +set -e + +ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +cd "$ROOT_DIR" + +APP_PROJ="src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj" +PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj" +TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj" +SLN="EarthModelStudio.sln" +VERSION="1.0.0" +TASK="${1:-build}" + +publish_rid() { + RID="$1"; OUT="$2" + echo "" + echo "==> 编译 ${RID} -> ${OUT}" + dotnet publish "$APP_PROJ" \ + -c Release \ + -r "$RID" \ + --self-contained true \ + -p:Version="$VERSION" \ + -p:DebugType=none \ + -p:PublishSingleFile=true \ + -p:IncludeNativeLibrariesForSelfExtract=true \ + -p:PublishTrimmed=false \ + -o "$ROOT_DIR/$OUT" + # 启动器不带模型:只留一个空模型库目录,模型作为独立内容放置 / 下载 + rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples" + mkdir -p "$ROOT_DIR/$OUT/model" + cp "$ROOT_DIR/model/README.md" "$ROOT_DIR/$OUT/model/README.md" 2>/dev/null || true +} + +# 编译模型自己的功能程序集,并把 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" +} + +# 把 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" +} + +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" < + + + + CFBundleNameEarth Model Studio + CFBundleDisplayNameEarth Model Studio + CFBundleIdentifiercn.neorf.earthmodelstudio + CFBundleVersion${VERSION} + CFBundleShortVersionString${VERSION} + CFBundlePackageTypeAPPL + CFBundleExecutableEarthModelStudio + CFBundleInfoDictionaryVersion6.0 + LSMinimumSystemVersion11.0 + NSHighResolutionCapable + + +PLIST + for f in "$DIST"/*; do + base=$(basename "$f") + [ "$base" = "EarthModelStudio.app" ] && continue + mv "$f" "$APP/Contents/MacOS/" + done + chmod +x "$APP/Contents/MacOS/EarthModelStudio" + echo "==> 已打包 $APP" +} + +case "$TASK" in + build) + 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) + mkdir -p "$ROOT_DIR/dist" + publish_rid "osx-arm64" "dist/mac-arm64" + publish_rid "win-x64" "dist/win-x64" + publish_rid "win-arm64" "dist/win-arm64" + package_mac_app + echo "" + echo "==> 三个平台编译完成(启动器不含模型数据):" + du -sh "$ROOT_DIR/dist"/* 2>/dev/null || true + echo " 模型数据用 ./build.sh pack-models 单独打包,或放进 <安装目录>/model 后再启动" + ;; + models) + build_models + ;; + pack-models) + build_models + pack_models + ;; + 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 | pack-models | clean | doctor" + exit 1 + ;; +esac diff --git a/model/README.md b/model/README.md new file mode 100644 index 0000000..2a548d0 --- /dev/null +++ b/model/README.md @@ -0,0 +1,125 @@ +# 模型库(model/) + +这个目录是**模型**,包含模型自己的**源码 + 数据 + 功能程序集 + 封面 + 语言包**。 +`src/`(启动器)只做三件事:扫描模型、下载模型、开窗口加载模型。**启动器没有任何渲染逻辑**。 + +> 模型相关的一切都在 `model/` 里:共享引擎源码 `model/_engine/`、契约源码 `model/_sdk/`、 +> 每个模型自己的源码 `model//src/`,编译产物与数据 `model//.model/`。 +> 仓库根目录只有 `src/`(启动器)和 `model/`,没有任何旁路目录。 + +- 启动器查找模型库的顺序:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 可执行文件旁边 `model/` → 用户数据目录 +- 一个模型 = 一个文件夹,文件夹名即模型 id;`_sdk/`、`_engine/` 是下划线开头的共享目录,不会被当成模型 +- 模型可以单独打包、单独分发,也可以放进 git 仓库当模型源 + +## 目录结构 + +``` +model/ + _sdk/EarthModelStudio.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码) + _engine/ # 共享引擎源码(可选,只有地球模型用) + src/ # CelestialView / PlanetTexture / EarthModelView / SphereRaster… + PreviewGen/ # 用模型渲染器生成封面的小工具 + <模型 id>/ + <模型 id>.json # 清单:名称、i18n、版本、程序集入口、封面 + src/ # 模型自己的源码(csproj + IModelFactory 实现) + <模型 id>.model/ # 模型包(可分发的部分) + EarthRotationModel.dll # 功能程序集(实现 IModelFactory) + scene.json # 场景数据(内容由模型定义) + land.json # 贴图/轮廓数据(可选) + preview.png # 封面图(启动器只显示,不渲染) + i18n/zh-CN.json # 界面文案(模型自己读) + i18n/en.json +``` + +## `.json`(模型清单,启动器只读它) + +```json +{ + "id": "earth-rotation", + "name": "Earth Rotation", + "nameI18n": { "zh-CN": "地球自转", "en": "Earth Rotation" }, + "description": "……", + "descriptionI18n": { "zh-CN": "……", "en": "……" }, + "version": "1.0.0", + "author": "NeoRF", + "tags": ["astronomy", "geography"], + "assembly": "EarthRotationModel.dll", + "type": "NeoRF.EarthModels.RotationModelFactory", + "preview": "preview.png", + "apiVersion": 1 +} +``` + +| 字段 | 作用 | +| --- | --- | +| `assembly` | 功能程序集文件名,相对 `.model`;留空按 `.dll` 找 | +| `type` | 实现 `IModelFactory` 的完整类型名;留空则自动找第一个实现 | +| `preview` | 封面图,默认 `preview.png` | +| `apiVersion` | 模型契约版本,目前为 1 | + +## 模型契约(model/_sdk) + +模型只依赖一个极小的契约程序集 `EarthModelStudio.ModelSdk`(源码在 `model/_sdk/`): + +```csharp +public interface IModelFactory +{ + int ApiVersion { get; } + IModelRuntime Create(); +} + +public interface IModelRuntime : IDisposable +{ + void Prepare(IModelContext context); // 后台线程:读数据、算纹理,可汇报进度 + Control CreateView(IModelContext context); // UI 线程:构建界面 +} + +public interface IModelContext +{ + string ModelId { get; } + string ModelDirectory { get; } + string DataDirectory { get; } + string Language { get; } + int MemoryBudgetMb { get; } + void RequestClose(); + void ReportProgress(double value, string? message = null); + void Log(string message); +} +``` + +模型 `CreateView` 返回的控件会铺满窗口客户区 —— **工具栏、动画、文字、交互全由模型自己实现**。 +启动器只提供窗口、语言、内存预算和关闭能力。 + +## `scene.json` / `land.json` + +这两个文件的内容完全由模型自己定义(启动器不解析)。地球模型用的是: + +- `scene.json`:`defaultView`、`views`、行星参数、颜色、轨道、`lessons` 教学要点 +- `land.json`:大陆轮廓,`{ "polygons": [ { "name": "...", "points": [[lon,lat], ...] } ] }` + +## 语言包 + +`.model/i18n/.json` 是扁平的 `键: 文案` 映射,模型自己读取。 +地球模型用到的键:`title`、`view.rotation`、`play`、`pause`、`speed`、`reset`、`labels`、`orbit`、`grid`、`tilt`、 +`lessons`、`seasons`、`close`、`sun`、`earth`、`north`、`south`、`subsolar`、`spinInfo`、`orbitInfo`、 +`declinationInfo`、`dateInfo`、`season.*`。 + +## 封面 + +封面是 `preview.png`,由 `model/_engine/PreviewGen` 用**模型自己的渲染器**生成: + +```bash +./build.sh models # 编译模型 dll + 生成所有模型封面 +``` + +## 做一个新模型 + +1. 在 `model//src/` 里新建类库项目(可引用 `model/_engine/src` 的共享代码,也可完全自己写) +2. 写一个 `IModelFactory` 实现:`Prepare` 里读数据算纹理并 `ReportProgress`,`CreateView` 里返回控件 +3. 在 `model//` 放清单和 `.model/` 数据目录,用 `assembly` / `type` 指向你的 dll +4. `./build.sh models` 会自动编译每个模型、把 dll 复制进对应 `.model/`,并生成封面 + +## 作为模型源分发 + +把 `model/` 放到任意 git 仓库根目录并推送,用户在「下载」页粘贴仓库链接即可; +启动器读取仓库里的 `model/` 文件夹,一栏一个模型。 diff --git a/model/_engine/PreviewGen/PreviewGen.csproj b/model/_engine/PreviewGen/PreviewGen.csproj new file mode 100644 index 0000000..f8477ab --- /dev/null +++ b/model/_engine/PreviewGen/PreviewGen.csproj @@ -0,0 +1,27 @@ + + + + Exe + net8.0 + enable + disable + NeoRF.EarthModels + EarthModelPreview + true + + + + + + + + + + + + + + + + + diff --git a/model/_engine/PreviewGen/Program.cs b/model/_engine/PreviewGen/Program.cs new file mode 100644 index 0000000..7c7d80b --- /dev/null +++ b/model/_engine/PreviewGen/Program.cs @@ -0,0 +1,113 @@ +using System; +using System.IO; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Headless; +using Avalonia.Media.Imaging; +using NeoRF.EarthModels; + +namespace NeoRF.EarthModels.Preview; + +/// +/// 封面生成工具:用模型自己的渲染器给每个模型画一张封面 preview.png。 +/// 封面在模型包里,启动器只负责显示 —— 所以公转模型的封面一定就是公转场景。 +/// 用法:dotnet run --project model-src/tools/PreviewGen -- <仓库根> +/// +internal static class Program +{ + private const int Width = 768; + private const int Height = 316; + + [STAThread] + public static int Main(string[] args) + { + var root = args.Length > 0 ? args[0] : Directory.GetCurrentDirectory(); + var modelRoot = Path.Combine(root, "model"); + if (!Directory.Exists(modelRoot)) + { + Console.Error.WriteLine($"找不到模型库: {modelRoot}"); + return 1; + } + + var bench = args.Contains("--bench"); + + AppBuilder.Configure() + .UseSkia() + .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }) + .SetupWithoutStarting(); + + foreach (var modelDir in Directory.GetDirectories(modelRoot)) + { + 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; + + 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 + }; + view.Measure(new Size(Width, Height)); + view.Arrange(new Rect(0, 0, 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}"); + } + + return 0; + } +} diff --git a/model/_engine/src/CelestialView.cs b/model/_engine/src/CelestialView.cs new file mode 100644 index 0000000..ffc3c9b --- /dev/null +++ b/model/_engine/src/CelestialView.cs @@ -0,0 +1,1056 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Numerics; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using Avalonia.Threading; + +namespace NeoRF.EarthModels; + +public enum SceneView +{ + Rotation, + Revolution +} + +/// +/// 天文场景画布:地球自转 / 地球公转。 +/// 纯 CPU 像素着色 + 矢量标注,无外部贴图依赖,三平台表现一致。 +/// 交互约定:单指/鼠标拖动只改变地球自身的角度,视角平面保持不变;双指捏合缩放。 +/// +public class CelestialView : Control +{ + // ---------------------------------------------------------------- 属性 + public static readonly StyledProperty SceneProperty = + AvaloniaProperty.Register(nameof(Scene)); + + public static readonly StyledProperty ViewProperty = + AvaloniaProperty.Register(nameof(View)); + + public static readonly StyledProperty IsPlayingProperty = + AvaloniaProperty.Register(nameof(IsPlaying), true); + + public static readonly StyledProperty SpeedProperty = + AvaloniaProperty.Register(nameof(Speed), 1.0); + + public static readonly StyledProperty ShowLabelsProperty = + AvaloniaProperty.Register(nameof(ShowLabels), true); + + public static readonly StyledProperty ShowOrbitProperty = + AvaloniaProperty.Register(nameof(ShowOrbit), true); + + public static readonly StyledProperty ShowGraticuleProperty = + AvaloniaProperty.Register(nameof(ShowGraticule), true); + + public static readonly StyledProperty ExaggerateTiltProperty = + AvaloniaProperty.Register(nameof(ExaggerateTilt)); + + public static readonly StyledProperty FrameRateProperty = + AvaloniaProperty.Register(nameof(FrameRate), 30); + + public static readonly StyledProperty ShowHudProperty = + AvaloniaProperty.Register(nameof(ShowHud), true); + + public static readonly StyledProperty ShowCloudsProperty = + AvaloniaProperty.Register(nameof(ShowClouds), true); + + public static readonly StyledProperty ZoomProperty = + AvaloniaProperty.Register(nameof(Zoom), 1.0); + + /// 自转视图里太阳直射点的纬度(公转视图由轨道角自动计算)。 + public static readonly StyledProperty DeclinationDegProperty = + AvaloniaProperty.Register(nameof(DeclinationDeg), 0.0); + + /// 显式视角俯仰角;NaN 表示使用视图默认值。它只由独立控件修改,绝不随拖动变化。 + public static readonly StyledProperty CameraElevationProperty = + AvaloniaProperty.Register(nameof(CameraElevation), double.NaN); + + /// 是否绘制赤道 / 南北回归线 / 南北极圈等教材纬线。 + public static readonly StyledProperty ShowKeyLatitudesProperty = + AvaloniaProperty.Register(nameof(ShowKeyLatitudes), true); + + /// 特写模式:隐藏 HUD、阳光箭头等,只保留地球与教材纬线。 + public static readonly StyledProperty InsetModeProperty = + AvaloniaProperty.Register(nameof(InsetMode)); + + public SceneRuntime? Scene { get => GetValue(SceneProperty); set => SetValue(SceneProperty, value); } + public SceneView View { get => GetValue(ViewProperty); set => SetValue(ViewProperty, value); } + public bool IsPlaying { get => GetValue(IsPlayingProperty); set => SetValue(IsPlayingProperty, value); } + public double Speed { get => GetValue(SpeedProperty); set => SetValue(SpeedProperty, value); } + public bool ShowLabels { get => GetValue(ShowLabelsProperty); set => SetValue(ShowLabelsProperty, value); } + public bool ShowOrbit { get => GetValue(ShowOrbitProperty); set => SetValue(ShowOrbitProperty, value); } + public bool ShowGraticule { get => GetValue(ShowGraticuleProperty); set => SetValue(ShowGraticuleProperty, value); } + public bool ExaggerateTilt { get => GetValue(ExaggerateTiltProperty); set => SetValue(ExaggerateTiltProperty, value); } + public int FrameRate { get => GetValue(FrameRateProperty); set => SetValue(FrameRateProperty, value); } + public bool ShowHud { get => GetValue(ShowHudProperty); set => SetValue(ShowHudProperty, value); } + public bool ShowClouds { get => GetValue(ShowCloudsProperty); set => SetValue(ShowCloudsProperty, value); } + public double DeclinationDeg { get => GetValue(DeclinationDegProperty); set => SetValue(DeclinationDegProperty, value); } + public double CameraElevation { get => GetValue(CameraElevationProperty); set => SetValue(CameraElevationProperty, value); } + public bool ShowKeyLatitudes { get => GetValue(ShowKeyLatitudesProperty); set => SetValue(ShowKeyLatitudesProperty, value); } + public bool InsetMode { get => GetValue(InsetModeProperty); set => SetValue(InsetModeProperty, value); } + + /// 缩放(0.6–6):滚轮、按钮或双指捏合,带平滑过渡。 + public double Zoom { get => GetValue(ZoomProperty); set => SetValue(ZoomProperty, value); } + + /// 本模型的文案(由模型界面注入,启动器不再提供)。 + public ModelStrings Texts { get; set; } = ModelStrings.Default; + + // ---------------------------------------------------------------- 状态 + private double _orbitDeg; + private double _spinDeg = 20; + private DispatcherTimer? _timer; + private WriteableBitmap? _sphere; + private int _sphereSize; + private long _lastTick; + private double _accum; + private bool _animating; + + /// 运动时的球面渲染边长:按实测帧耗时自适应,慢机器自动降一档。 + private int MotionResolution { get; set; } = 460; + + private double _zoom = 1; + private double _zoomTarget = 1; + private double _camElev = 8; + private double _camElevTarget = 8; + private double _cloudShift; + private double _spinVelocity; + private double _frameAverage; + + // 多点触控:每个手指一个 Pointer.Id,两指时切换为捏合缩放 + private readonly Dictionary _pointers = new(); + private bool _pinching; + private double _pinchStartDistance; + private double _pinchStartZoom; + private bool _dragging; + private Point _dragLast; + + public double OrbitAngle => _orbitDeg; + public double SpinAngle => _spinDeg; + + /// + /// 当前太阳直射纬度。公转视图按真实黄赤交角计算: + /// 春分/秋分 0°、夏至 +23.5°、冬至 −23.5°;夸张倾角只影响示意图形,不影响教学读数。 + /// + public double SubsolarLatitude + { + get + { + if (View == SceneView.Revolution) + { + var tilt = Math.Clamp(Scene?.Scene.Planet.AxialTiltDeg ?? 23.5, 0, 60); + return Math.Asin(Math.Sin(Deg2Rad(tilt)) * Math.Sin(Deg2Rad(_orbitDeg))) * 57.2957795; + } + return Math.Clamp(DeclinationDeg, -66.5, 66.5); + } + } + + public string DeclinationLabel => DeclinationText(SubsolarLatitude); + public string CurrentDate => DateForAngle(_orbitDeg); + public event Action? AnglesChanged; + /// 缩放目标变化(滚轮、按钮、捏合)。 + public event Action? ZoomChanged; + + static CelestialView() + { + AffectsRender(SceneProperty, ViewProperty, ShowLabelsProperty, ShowOrbitProperty, + ShowGraticuleProperty, ExaggerateTiltProperty, IsPlayingProperty, SpeedProperty, + DeclinationDegProperty, CameraElevationProperty, ShowKeyLatitudesProperty, InsetModeProperty, + ZoomProperty, ShowCloudsProperty, ShowHudProperty); + } + + private double DefaultElevation => double.IsNaN(CameraElevation) + ? (View == SceneView.Revolution ? 26 : 8) + : Math.Clamp(CameraElevation, 0, 82); + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (change.Property == ViewProperty || change.Property == CameraElevationProperty) + { + // 视角只由视图/独立控件决定,拖动永远不会改它 + _camElevTarget = DefaultElevation; + InvalidateVisual(); + } + else if (change.Property == DeclinationDegProperty || + change.Property == ShowKeyLatitudesProperty || + change.Property == InsetModeProperty) + { + InvalidateVisual(); + } + } + + public CelestialView() + { + ClipToBounds = true; + Focusable = true; + Cursor = new Cursor(StandardCursorType.SizeAll); + } + + // ---------------------------------------------------------------- 交互 + /// 设置绝对缩放。捏合时 immediate=true 保证跟手。 + public void SetZoom(double value, bool immediate = false) + { + _zoomTarget = Math.Clamp(value, 0.6, 6.0); + if (immediate) _zoom = _zoomTarget; + SetCurrentValue(ZoomProperty, _zoomTarget); + ZoomChanged?.Invoke(_zoomTarget); + InvalidateVisual(); + } + + public void ZoomBy(double factor) => SetZoom(_zoomTarget * factor); + + public void ResetView() + { + SetZoom(1.0, immediate: true); + _camElevTarget = DefaultElevation; + _spinVelocity = 0; + _lastTick = Stopwatch.GetTimestamp(); + InvalidateVisual(); + } + + protected override void OnPointerPressed(PointerPressedEventArgs e) + { + base.OnPointerPressed(e); + if (Scene == null) return; + + var p = e.GetPosition(this); + _pointers[e.Pointer.Id] = p; + e.Pointer.Capture(this); + + if (_pointers.Count >= 2) + { + BeginPinch(); + _dragging = false; + } + else + { + _dragging = true; + _pinching = false; + _spinVelocity = 0; + _dragLast = p; + } + e.Handled = true; + } + + protected override void OnPointerMoved(PointerEventArgs e) + { + base.OnPointerMoved(e); + if (!_pointers.ContainsKey(e.Pointer.Id)) return; + + var p = e.GetPosition(this); + _pointers[e.Pointer.Id] = p; + + if (_pointers.Count >= 2) + { + UpdatePinch(); + e.Handled = true; + return; + } + if (!_dragging) return; + + var dx = p.X - _dragLast.X; + _dragLast = p; + + // 只驱动地球自身的角度;视角俯仰、轨道平面、经纬网平面一律不动 + if (View == SceneView.Revolution) + { + _orbitDeg = Wrap360(_orbitDeg + dx * 0.32); + _spinVelocity = 0; + } + else + { + _spinDeg = Wrap360(_spinDeg + dx * 0.42); + _spinVelocity = dx * 0.42 * 55; + } + + AnglesChanged?.Invoke(); + InvalidateVisual(); + e.Handled = true; + } + + protected override void OnPointerReleased(PointerReleasedEventArgs e) + { + base.OnPointerReleased(e); + if (!_pointers.Remove(e.Pointer.Id)) return; + e.Pointer.Capture(null); + + if (_pointers.Count >= 2) + { + BeginPinch(); + _dragging = false; + } + else if (_pointers.Count == 1) + { + // 从捏合回到单指:重新建立拖动基准,避免地球突然跳一下 + _pinching = false; + _dragging = true; + _dragLast = _pointers.Values.First(); + _spinVelocity = 0; + } + else + { + _dragging = false; + _pinching = false; + } + e.Handled = true; + } + + protected override void OnPointerWheelChanged(PointerWheelEventArgs e) + { + base.OnPointerWheelChanged(e); + ZoomBy(Math.Pow(1.18, e.Delta.Y)); + e.Handled = true; + } + + private void BeginPinch() + { + var pts = _pointers.Values.Take(2).ToArray(); + _pinchStartDistance = Math.Max(8.0, Distance(pts[0], pts[1])); + _pinchStartZoom = _zoomTarget; + _pinching = true; + _spinVelocity = 0; + } + + private void UpdatePinch() + { + if (!_pinching) { BeginPinch(); return; } + var pts = _pointers.Values.Take(2).ToArray(); + var d = Math.Max(8.0, Distance(pts[0], pts[1])); + SetZoom(_pinchStartZoom * d / _pinchStartDistance, immediate: true); + } + + private static double Distance(Point a, Point b) + { + var dx = a.X - b.X; + var dy = a.Y - b.Y; + return Math.Sqrt(dx * dx + dy * dy); + } + + private static double Wrap360(double deg) => ((deg % 360) + 360) % 360; + + // ---------------------------------------------------------------- 动画 + protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) + { + base.OnAttachedToVisualTree(e); + _camElevTarget = DefaultElevation; + _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(16), DispatcherPriority.Render, OnTick); + _lastTick = Stopwatch.GetTimestamp(); + _timer.Start(); + } + + protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) + { + base.OnDetachedFromVisualTree(e); + _timer?.Stop(); + _timer = null; + } + + private void OnTick(object? sender, EventArgs e) + { + var now = Stopwatch.GetTimestamp(); + var dt = (now - _lastTick) / (double)Stopwatch.Frequency; + _lastTick = now; + if (dt > 0.25) dt = 0.25; + + if (Scene == null) + { + _animating = false; + return; + } + + _cloudShift += dt * (IsPlaying ? 1.6 : 0.18); + if (_cloudShift > 360) _cloudShift -= 360; + + if (_animating && dt > 0.001 && dt < 0.5) + { + _frameAverage = _frameAverage <= 0 ? dt : _frameAverage * 0.92 + dt * 0.08; + if (_frameAverage > 0.026 && MotionResolution > 320) MotionResolution -= 12; + else if (_frameAverage < 0.015 && MotionResolution < 460) MotionResolution += 6; + } + + var smoothing = Math.Min(1.0, dt * 10.0); + var viewChanged = false; + if (Math.Abs(_zoomTarget - _zoom) > 0.0005) + { + _zoom += (_zoomTarget - _zoom) * smoothing; + viewChanged = true; + } + if (Math.Abs(_camElevTarget - _camElev) > 0.01) + { + _camElev += (_camElevTarget - _camElev) * smoothing; + viewChanged = true; + } + + var frameInterval = 1.0 / Math.Clamp(FrameRate, 12, 120); + _accum += dt; + var due = _accum >= frameInterval; + if (!due && !viewChanged) return; + var step = _accum; + if (due) _accum = 0; + + // 手动转动/捏合时画面定格,松手后继续播放(不必先点暂停) + var holding = _dragging || _pinching; + if (IsPlaying && !holding) + { + var speed = Math.Clamp(Speed, 0.05, 8); + _spinDeg = (_spinDeg + step * speed * 60.0) % 360.0; + _orbitDeg = (_orbitDeg + step * speed * 12.0) % 360.0; + _spinVelocity = 0; + } + else if (!IsPlaying && !_dragging && Math.Abs(_spinVelocity) > 0.4 && View == SceneView.Rotation) + { + _spinDeg = Wrap360(_spinDeg + _spinVelocity * step); + _spinVelocity *= Math.Pow(0.02, step); + } + else + { + _spinVelocity = 0; + } + + var wasAnimating = _animating; + _animating = (IsPlaying && !holding) || _dragging || Math.Abs(_spinVelocity) > 0.4 || viewChanged; + InvalidateVisual(); + if (wasAnimating && !_animating) InvalidateVisual(); + } + + public void JumpToOrbit(double deg) + { + _orbitDeg = Wrap360(deg); + AnglesChanged?.Invoke(); + InvalidateVisual(); + } + + public void JumpToSpin(double deg) + { + _spinDeg = Wrap360(deg); + AnglesChanged?.Invoke(); + InvalidateVisual(); + } + + public void StepOrbit(double deltaDeg) + { + _orbitDeg = Wrap360(_orbitDeg + deltaDeg); + AnglesChanged?.Invoke(); + InvalidateVisual(); + } + + public void StepSpin(double deltaDeg) + { + _spinDeg = Wrap360(_spinDeg + deltaDeg); + AnglesChanged?.Invoke(); + InvalidateVisual(); + } + + public void ResetAnimation() + { + _orbitDeg = 0; + _spinDeg = 20; + AnglesChanged?.Invoke(); + InvalidateVisual(); + } + + /// 取离当前轨道角最近的节气(超过阈值返回 null)。 + public SeasonPoint? NearestSeason(double maxDistanceDeg = 8) + { + var seasons = Scene?.Scene.Orbit.Seasons; + if (seasons == null || seasons.Count == 0) return null; + SeasonPoint? best = null; + var bestDistance = double.MaxValue; + foreach (var s in seasons) + { + var d = Math.Abs(WrapSigned(s.AngleDeg - _orbitDeg)); + if (d < bestDistance) { bestDistance = d; best = s; } + } + return bestDistance <= maxDistanceDeg ? best : null; + } + + private static double WrapSigned(double deg) => ((deg + 180) % 360 + 360) % 360 - 180; + + // ---------------------------------------------------------------- 绘制 + public override void Render(DrawingContext ctx) + { + var size = Bounds.Size; + if (size.Width < 80 || size.Height < 80) return; + + DrawSpace(ctx, size); + + var runtime = Scene; + if (runtime == null) + { + DrawLoading(ctx, size); + return; + } + + if (View == SceneView.Revolution) RenderRevolution(ctx, size, runtime); + else RenderRotation(ctx, size, runtime); + } + + private void DrawSpace(DrawingContext ctx, Size size) + { + var bg = new LinearGradientBrush + { + StartPoint = new RelativePoint(0.15, 0, RelativeUnit.Relative), + EndPoint = new RelativePoint(0.85, 1, RelativeUnit.Relative), + GradientStops = + { + new GradientStop(Color.Parse("#080D1C"), 0), + new GradientStop(Color.Parse("#0B1226"), 0.55), + new GradientStop(Color.Parse("#04060E"), 1) + } + }; + ctx.FillRectangle(bg, new Rect(size)); + + foreach (var star in Stars) + { + var brush = star.Level switch + { + 0 => StarDim, + 1 => StarMid, + _ => StarBright + }; + ctx.DrawEllipse(brush, null, new Point(star.X * size.Width, star.Y * size.Height), star.R, star.R); + } + + var band = new RadialGradientBrush + { + Center = new RelativePoint(0.72, 0.18, RelativeUnit.Relative), + GradientOrigin = new RelativePoint(0.72, 0.18, RelativeUnit.Relative), + Radius = 1.1, + GradientStops = + { + new GradientStop(Color.FromArgb(26, 120, 150, 255), 0), + new GradientStop(Color.FromArgb(0, 120, 150, 255), 1) + } + }; + ctx.FillRectangle(band, new Rect(size)); + } + + private void DrawLoading(DrawingContext ctx, Size size) + { + DrawText(ctx, Texts["loading"], size.Width / 2, size.Height / 2 - 8, 14, MutedBrush, + FontWeight.Normal, TextAlignment.Center); + } + + // ---------------------------------------------------------------- 自转视图 + private void RenderRotation(DrawingContext ctx, Size size, SceneRuntime runtime) + { + var w = size.Width; + var h = size.Height; + var center = new Point(w * 0.5, h * 0.52); + var radius = Math.Min(w * 0.46, h * 0.44) * _zoom; + if (radius < 24) return; + + var cam = CameraMatrix(-12, _camElev); + var tilt = TiltDegrees(runtime); + var planet = Matrix4x4.Multiply(Matrix4x4.CreateRotationY(Deg2Rad(_spinDeg)), + Matrix4x4.CreateRotationZ(Deg2Rad(-tilt))); + + // 太阳光由「直射纬度」反推:直射点严格落在对应纬线上,且始终朝向右前方可见半球 + var light = RotationLight(cam, tilt); + + var glow = new RadialGradientBrush + { + Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), + GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), + Radius = 0.5, + GradientStops = + { + new GradientStop(Color.FromArgb(90, 70, 140, 235), 0.60), + new GradientStop(Color.FromArgb(34, 80, 150, 240), 0.80), + new GradientStop(Color.FromArgb(0, 80, 150, 240), 1.0) + } + }; + ctx.DrawEllipse(glow, null, center, radius * 1.16, radius * 1.16); + + var px = PixelSizeFor(radius); + if (px > 8 && runtime.Texture != null) + { + var bmp = EnsureSphereBitmap(px); + SphereRaster.Draw(bmp, px, cam, planet, light, runtime.Texture, _cloudShift, ShowClouds); + ctx.DrawImage(bmp, new Rect(0, 0, px, px), + new Rect(center.X - radius, center.Y - radius, radius * 2, radius * 2)); + } + + var showGrid = ShowGraticule && runtime.Scene.Planet.ShowGraticule && !InsetMode; + if (showGrid) DrawGraticule(ctx, cam, planet, center, radius); + if (ShowKeyLatitudes) + DrawKeyLatitudes(ctx, cam, planet, center, radius, runtime, ShowLabels && radius > 88); + + DrawTerminator(ctx, light, center, radius); + DrawSubsolarMarker(ctx, center, radius, light, ShowLabels && !InsetMode); + DrawAxis(ctx, cam, planet, center, radius, runtime, ShowLabels && !InsetMode); + + if (InsetMode) return; + DrawSunlightArrows(ctx, center, radius); + + var period = runtime.Scene.Planet.RotationHours; + if (ShowHud) DrawHud(ctx, new Point(20, 78), new[] + { + Texts.F("spinInfo", _spinDeg.ToString("0"), period.ToString("0.##")), + Texts.F("declinationInfo", DeclinationText(SubsolarLatitude)) + }); + } + + /// 构造相机空间的阳光方向,使其与地轴的夹角对应指定直射纬度。 + private Vector3 RotationLight(Matrix4x4 cam, double tiltDeg) + { + var axisCam = Vector3.TransformNormal(AxisWorld(tiltDeg), cam); + var forwardRight = Vector3.Normalize(new Vector3(0.86f, 0f, 0.50f)); + var u = forwardRight - axisCam * Vector3.Dot(forwardRight, axisCam); + if (u.Length() < 0.001f) u = new Vector3(1, 0, 0); + u = Vector3.Normalize(u); + var d = Deg2Rad(SubsolarLatitude); + return Vector3.Normalize(axisCam * (float)Math.Sin(d) + u * (float)Math.Cos(d)); + } + + private static Vector3 AxisWorld(double tiltDeg) + => Vector3.Transform(new Vector3(0, 1, 0), Matrix4x4.CreateRotationZ(Deg2Rad(-tiltDeg))); + + private static double TropicDegrees(SceneRuntime runtime) + { + var t = runtime.Scene.Planet.TropicDeg; + if (t <= 0 || t > 45) t = Math.Abs(runtime.Scene.Planet.AxialTiltDeg); + if (t <= 0 || t > 45) t = 23.5; + return t; + } + + /// 教材五带分界线:赤道、南北回归线(23.5°)、南北极圈(66.5°)。 + private void DrawKeyLatitudes(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet, + Point center, double radius, SceneRuntime runtime, bool labels) + { + var tropic = TropicDegrees(runtime); + var polar = 90.0 - tropic; + + DrawParallel(ctx, cam, planet, center, radius, 0, EquatorPen, + labels ? Texts["lat.equator"] : null, LabelBrush); + DrawParallel(ctx, cam, planet, center, radius, tropic, TropicPen, + labels ? Texts["lat.tropicN"] : null, TropicBrush); + DrawParallel(ctx, cam, planet, center, radius, -tropic, TropicPen, + labels ? Texts["lat.tropicS"] : null, TropicBrush); + DrawParallel(ctx, cam, planet, center, radius, polar, PolarPen, + labels ? Texts["lat.polarN"] : null, PolarBrush); + DrawParallel(ctx, cam, planet, center, radius, -polar, PolarPen, + labels ? Texts["lat.polarS"] : null, PolarBrush); + } + + private void DrawParallel(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet, + Point center, double radius, double lat, IPen pen, string? label, IBrush labelBrush) + { + DrawSpherePolyline(ctx, cam, planet, center, radius, pen, + t => LatLonToUnit(lat, t * 360.0), 144); + if (label == null) return; + + var world = Vector3.Transform(LatLonToUnit(lat, 64), planet); + var c = Vector3.Transform(world, cam); + if (c.Z <= 0.05f) return; + var p = new Point(center.X + c.X * radius, center.Y - c.Y * radius); + DrawText(ctx, label, p.X + 5, p.Y - 13, 10.5, labelBrush, FontWeight.SemiBold); + } + + private void DrawGraticule(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet, Point center, double radius) + { + for (var lat = -75; lat <= 75; lat += 15) + { + var pen = Math.Abs(lat) < 1 ? EquatorPen : GridPen; + DrawSpherePolyline(ctx, cam, planet, center, radius, pen, (t) => + { + var lon = t * 360.0; + return LatLonToUnit(lat, lon); + }, 120); + } + + for (var lon = 0; lon < 360; lon += 30) + { + var l = lon; + DrawSpherePolyline(ctx, cam, planet, center, radius, GridPen, (t) => + { + var lat = -90 + t * 180.0; + return LatLonToUnit(lat, l); + }, 90); + } + } + + private void DrawSpherePolyline(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet, Point center, + double radius, IPen pen, Func pointAt, int steps) + { + Point? prev = null; + for (var i = 0; i <= steps; i++) + { + var local = pointAt(i / (double)steps); + var world = Vector3.Transform(local, planet); + var c = Vector3.Transform(world, cam); + if (c.Z <= 0.02) + { + prev = null; + continue; + } + var p = new Point(center.X + c.X * radius, center.Y - c.Y * radius); + if (prev.HasValue) ctx.DrawLine(pen, prev.Value, p); + prev = p; + } + } + + private void DrawTerminator(DrawingContext ctx, Vector3 light, Point center, double radius) + { + var up = Math.Abs(light.Y) > 0.92f ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0); + var u = Vector3.Normalize(Vector3.Cross(light, up)); + var v = Vector3.Normalize(Vector3.Cross(light, u)); + + Point? prev = null; + for (var i = 0; i <= 180; i++) + { + var a = i / 180.0 * Math.PI * 2; + var n = u * (float)Math.Cos(a) + v * (float)Math.Sin(a); + if (n.Z <= 0.03f) + { + prev = null; + continue; + } + var p = new Point(center.X + n.X * radius, center.Y - n.Y * radius); + if (prev.HasValue) ctx.DrawLine(TerminatorPen, prev.Value, p); + prev = p; + } + } + + /// 球面直射点:黄圈 + 纬度读数,位置由光照方向(即日下点)精确投影。 + private void DrawSubsolarMarker(DrawingContext ctx, Point center, double radius, + Vector3 light, bool withLabel) + { + if (light.Z <= 0.02f) return; + var p = new Point(center.X + light.X * radius, center.Y - light.Y * radius); + ctx.DrawEllipse(SubsolarGlowBrush, null, p, 9, 9); + ctx.DrawEllipse(null, SubsolarPen, p, 5, 5); + if (withLabel) + DrawText(ctx, Texts["directPoint"] + " " + DeclinationText(SubsolarLatitude), + p.X + 12, p.Y - 9, 11.5, SubsolarBrush, FontWeight.SemiBold); + } + + private void DrawAxis(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet, Point center, double radius, + SceneRuntime runtime, bool showLabels) + { + var top = Vector3.Transform(Vector3.Transform(new Vector3(0, 1.32f, 0), planet), cam); + var bottom = Vector3.Transform(Vector3.Transform(new Vector3(0, -1.32f, 0), planet), cam); + var pTop = new Point(center.X + top.X * radius, center.Y - top.Y * radius); + var pBottom = new Point(center.X + bottom.X * radius, center.Y - bottom.Y * radius); + ctx.DrawLine(AxisPen, pTop, pBottom); + + if (!showLabels) return; + DrawText(ctx, Texts["north"], pTop.X + 8, pTop.Y - 16, 11.5, AxisBrush); + DrawText(ctx, Texts["south"], pBottom.X + 8, pBottom.Y + 2, 11.5, AxisBrush); + } + + private void DrawSunlightArrows(DrawingContext ctx, Point center, double radius) + { + for (var i = -1; i <= 1; i++) + { + var y = center.Y + i * radius * 0.42; + var x0 = center.X + radius * 1.42; + var x1 = center.X + radius * 1.06; + ctx.DrawLine(SunRayPen, new Point(x0, y), new Point(x1, y)); + ctx.DrawLine(SunRayPen, new Point(x1, y), new Point(x1 + 8, y - 5)); + ctx.DrawLine(SunRayPen, new Point(x1, y), new Point(x1 + 8, y + 5)); + } + } + + // ---------------------------------------------------------------- 公转视图 + private void RenderRevolution(DrawingContext ctx, Size size, SceneRuntime runtime) + { + var w = size.Width; + var h = size.Height; + var center = new Point(w * 0.5, h * 0.51); + var a = Math.Min(w * 0.36, h * 0.38) * _zoom; + if (a < 40) return; + + var earthR = Math.Clamp(Math.Min(w, h) * 0.052, 16, 34) * (0.65 + 0.35 * _zoom); + var sunR = earthR * 1.05; + var cam = CameraMatrix(0, _camElev); + + var theta = Deg2Rad(_orbitDeg); + var earthPos = new Vector3((float)(-a * Math.Sin(theta)), 0, (float)(a * Math.Cos(theta))); + var earthScreen = ToScreen(earthPos, cam, center); + var lightWorld = Vector3.Normalize(-earthPos); + var lightCam = Vector3.TransformNormal(lightWorld, cam); + + var sunGlow = new RadialGradientBrush + { + Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), + GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), + Radius = 0.5, + GradientStops = + { + new GradientStop(Color.FromArgb(120, 255, 196, 92), 0.10), + new GradientStop(Color.FromArgb(48, 255, 168, 60), 0.34), + new GradientStop(Color.FromArgb(0, 255, 150, 40), 1.0) + } + }; + ctx.DrawEllipse(sunGlow, null, center, sunR * 6.2, sunR * 6.2); + + var sunBody = new RadialGradientBrush + { + Center = new RelativePoint(0.42, 0.38, RelativeUnit.Relative), + GradientOrigin = new RelativePoint(0.42, 0.38, RelativeUnit.Relative), + Radius = 0.62, + GradientStops = + { + new GradientStop(Color.Parse("#FFF3D0"), 0), + new GradientStop(runtime.Star, 0.62), + new GradientStop(Color.Parse("#F08A1E"), 1) + } + }; + ctx.DrawEllipse(sunBody, null, center, sunR, sunR); + + if (ShowOrbit) DrawOrbit(ctx, cam, center, a); + + var tilt = TiltDegrees(runtime); + var planet = Matrix4x4.Multiply(Matrix4x4.CreateRotationY(Deg2Rad(_spinDeg)), + Matrix4x4.CreateRotationZ(Deg2Rad(-tilt))); + var px = PixelSizeFor(earthR); + if (px > 8) + { + ctx.DrawEllipse(new SolidColorBrush(Color.FromArgb(56, 70, 140, 235)), null, + earthScreen, earthR * 1.35, earthR * 1.35); + var bmp = EnsureSphereBitmap(px); + if (runtime.Texture != null) + SphereRaster.Draw(bmp, px, cam, planet, lightCam, runtime.Texture, _cloudShift, ShowClouds); + ctx.DrawImage(bmp, new Rect(0, 0, px, px), + new Rect(earthScreen.X - earthR, earthScreen.Y - earthR, earthR * 2, earthR * 2)); + } + + var axis = AxisWorld(tilt); + var axisTop = ToScreen(earthPos + axis * (float)(earthR * 1.9), cam, center); + var axisBottom = ToScreen(earthPos - axis * (float)(earthR * 1.9), cam, center); + ctx.DrawLine(AxisPen, axisTop, axisBottom); + if (ShowLabels) DrawText(ctx, Texts["north"], axisTop.X + 6, axisTop.Y - 14, 10.5, AxisBrush); + + ctx.DrawLine(SunRayPen, center, ToScreen(earthPos * 0.92f, cam, center)); + if (ShowLabels) DrawText(ctx, Texts["sun"], center.X, center.Y + sunR + 8, 12, SunLabelBrush, + FontWeight.SemiBold, TextAlignment.Center); + + if (ShowLabels) DrawSeasonMarkers(ctx, cam, center, a, runtime); + if (ShowLabels) DrawSubsolarMarker(ctx, earthScreen, earthR, lightCam, false); + + if (ShowLabels) + { + DrawText(ctx, Texts["earth"], earthScreen.X, earthScreen.Y - earthR - 20, 12, + PlanetLabelBrush, FontWeight.SemiBold, TextAlignment.Center); + } + + if (ShowHud) DrawHud(ctx, new Point(20, 78), new[] + { + Texts.F("orbitInfo", _orbitDeg.ToString("0")), + Texts.F("declinationInfo", DeclinationLabel), + Texts.F("dateInfo", CurrentDate) + }); + } + + private void DrawOrbit(DrawingContext ctx, Matrix4x4 cam, Point center, double a) + { + Point? prevBack = null; + Point? prevFront = null; + for (var i = 0; i <= 240; i++) + { + var t = i / 240.0 * Math.PI * 2; + var p = new Vector3((float)(-a * Math.Sin(t)), 0, (float)(a * Math.Cos(t))); + var c = Vector3.Transform(p, cam); + var sp = new Point(center.X + c.X, center.Y - c.Y); + if (c.Z < 0) + { + if (prevBack.HasValue) ctx.DrawLine(OrbitBackPen, prevBack.Value, sp); + prevBack = sp; + prevFront = null; + } + else + { + if (prevFront.HasValue) ctx.DrawLine(OrbitFrontPen, prevFront.Value, sp); + prevFront = sp; + prevBack = null; + } + } + } + + private void DrawSeasonMarkers(DrawingContext ctx, Matrix4x4 cam, Point center, double a, SceneRuntime runtime) + { + var seasons = runtime.Scene.Orbit.Seasons; + if (seasons.Count == 0) + { + seasons = new List + { + new() { AngleDeg = 0, Key = "season.springEquinox", Date = "3/21" }, + new() { AngleDeg = 90, Key = "season.summerSolstice", Date = "6/22" }, + new() { AngleDeg = 180, Key = "season.autumnEquinox", Date = "9/23" }, + new() { AngleDeg = 270, Key = "season.winterSolstice", Date = "12/22" } + }; + } + + foreach (var s in seasons) + { + var t = Deg2Rad(s.AngleDeg); + var pos = new Vector3((float)(-a * Math.Sin(t)), 0, (float)(a * Math.Cos(t))); + var outer = pos * 1.19f; + var p = ToScreen(outer, cam, center); + ctx.DrawEllipse(SeasonDotBrush, null, ToScreen(pos, cam, center), 2.4, 2.4); + + DrawText(ctx, Texts[s.Key], p.X, p.Y - 16, 12, SeasonBrush, FontWeight.SemiBold, TextAlignment.Center); + if (!string.IsNullOrEmpty(s.Date)) + DrawText(ctx, s.Date, p.X, p.Y - 2, 10, MutedBrush, FontWeight.Normal, TextAlignment.Center); + } + } + + // ---------------------------------------------------------------- 工具 + private static Matrix4x4 CameraMatrix(double azimDeg, double elevDeg) + => Matrix4x4.Multiply(Matrix4x4.CreateRotationY(Deg2Rad(azimDeg)), Matrix4x4.CreateRotationX(Deg2Rad(elevDeg))); + + private static Point ToScreen(Vector3 world, Matrix4x4 cam, Point center) + { + var c = Vector3.Transform(world, cam); + return new Point(center.X + c.X, center.Y - c.Y); + } + + private static Vector3 LatLonToUnit(double latDeg, double lonDeg) + { + var lat = Deg2Rad(latDeg); + var lon = Deg2Rad(lonDeg); + var cosLat = Math.Cos(lat); + return new Vector3((float)(cosLat * Math.Sin(lon)), (float)Math.Sin(lat), (float)(cosLat * Math.Cos(lon))); + } + + private double TiltDegrees(SceneRuntime runtime) + { + var tilt = runtime.Scene.Planet.AxialTiltDeg; + if (ExaggerateTilt) tilt *= 1.9; + return Math.Clamp(tilt, 0, 60); + } + + private int PixelSizeFor(double logicalRadius) + { + var scale = TopLevel.GetTopLevel(this)?.RenderScaling ?? 1.0; + var target = logicalRadius * 2 * scale; + var cap = _animating ? MotionResolution : 820; + return Math.Max(8, (int)Math.Round(Math.Min(target, cap))); + } + + private WriteableBitmap EnsureSphereBitmap(int px) + { + if (_sphere != null && _sphereSize == px) return _sphere; + _sphere = new WriteableBitmap(new PixelSize(px, px), new Avalonia.Vector(96, 96), + PixelFormat.Bgra8888, AlphaFormat.Premul); + _sphereSize = px; + return _sphere; + } + + private static float Deg2Rad(double deg) => (float)(deg * Math.PI / 180.0); + + private static readonly (double X, double Y, double R, int Level)[] Stars = BuildStars(); + + private static (double, double, double, int)[] BuildStars() + { + var rnd = new Random(20240501); + var list = new (double, double, double, int)[340]; + for (var i = 0; i < list.Length; i++) + { + var level = rnd.NextDouble() switch + { + < 0.62 => 0, + < 0.90 => 1, + _ => 2 + }; + list[i] = (rnd.NextDouble(), rnd.NextDouble(), level == 2 ? 1.5 : 0.7 + rnd.NextDouble() * 0.5, level); + } + return list; + } + + private static readonly IBrush StarDim = new SolidColorBrush(Color.FromArgb(80, 200, 218, 255)); + private static readonly IBrush StarMid = new SolidColorBrush(Color.FromArgb(145, 226, 238, 255)); + private static readonly IBrush StarBright = new SolidColorBrush(Color.FromArgb(225, 255, 255, 255)); + private static readonly IBrush MutedBrush = new SolidColorBrush(Color.FromArgb(165, 186, 204, 232)); + private static readonly IBrush LabelBrush = new SolidColorBrush(Color.FromArgb(235, 238, 246, 255)); + private static readonly IBrush SeasonBrush = new SolidColorBrush(Color.FromArgb(235, 255, 226, 168)); + private static readonly IBrush SeasonDotBrush = new SolidColorBrush(Color.FromArgb(210, 255, 214, 130)); + private static readonly IBrush SunLabelBrush = new SolidColorBrush(Color.FromArgb(240, 255, 214, 140)); + private static readonly IBrush PlanetLabelBrush = new SolidColorBrush(Color.FromArgb(240, 170, 210, 255)); + private static readonly IBrush AxisBrush = new SolidColorBrush(Color.FromArgb(220, 255, 214, 130)); + private static readonly IBrush SubsolarBrush = new SolidColorBrush(Color.FromArgb(240, 255, 236, 170)); + private static readonly IBrush SubsolarGlowBrush = new SolidColorBrush(Color.FromArgb(64, 255, 214, 110)); + private static readonly IBrush TropicBrush = new SolidColorBrush(Color.FromArgb(240, 255, 196, 120)); + private static readonly IBrush PolarBrush = new SolidColorBrush(Color.FromArgb(210, 164, 210, 255)); + private static readonly Pen SubsolarPen = new Pen(new SolidColorBrush(Color.FromArgb(230, 255, 226, 150)), 1.4); + private static readonly IPen GridPen = new Pen(new SolidColorBrush(Color.FromArgb(44, 190, 220, 255)), 0.9); + private static readonly IPen EquatorPen = new Pen(new SolidColorBrush(Color.FromArgb(150, 130, 235, 255)), 1.6); + private static readonly IPen TropicPen = new Pen(new SolidColorBrush(Color.FromArgb(210, 255, 186, 92)), 1.5, + new DashStyle(new double[] { 6, 4 }, 0)); + private static readonly IPen PolarPen = new Pen(new SolidColorBrush(Color.FromArgb(150, 140, 190, 255)), 1.2, + new DashStyle(new double[] { 3, 5 }, 0)); + private static readonly IPen AxisPen = new Pen(new SolidColorBrush(Color.FromArgb(190, 255, 210, 120)), 1.3, + new DashStyle(new double[] { 7, 5 }, 0)); + private static readonly IPen TerminatorPen = new Pen(new SolidColorBrush(Color.FromArgb(130, 255, 255, 255)), 1.1, + new DashStyle(new double[] { 4, 4 }, 0)); + private static readonly IPen SunRayPen = new Pen(new SolidColorBrush(Color.FromArgb(95, 255, 226, 160)), 1.0, + new DashStyle(new double[] { 5, 5 }, 0)); + private static readonly IPen OrbitFrontPen = new Pen(new SolidColorBrush(Color.FromArgb(120, 150, 190, 255)), 1.2); + private static readonly IPen OrbitBackPen = new Pen(new SolidColorBrush(Color.FromArgb(48, 150, 190, 255)), 1.0); + + private static void DrawText(DrawingContext ctx, string text, double x, double y, double fontSize, + IBrush brush, FontWeight weight = FontWeight.Normal, TextAlignment align = TextAlignment.Left) + { + var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, + new Typeface(FontFamily.Default, FontStyle.Normal, weight), fontSize, brush); + var px = align switch + { + TextAlignment.Center => x - formatted.Width / 2, + TextAlignment.Right => x - formatted.Width, + _ => x + }; + ctx.DrawText(formatted, new Point(px, y)); + } + + private static void DrawHud(DrawingContext ctx, Point at, string[] lines) + { + if (lines.Length == 0) return; + const double fontSize = 11.5; + var texts = new List(); + double width = 0; + double height = 0; + foreach (var line in lines) + { + var ft = new FormattedText(line, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, + new Typeface(FontFamily.Default, FontStyle.Normal, FontWeight.Normal), fontSize, LabelBrush); + texts.Add(ft); + width = Math.Max(width, ft.Width); + height += ft.Height + 3; + } + + var rect = new Rect(at.X, at.Y, width + 22, height + 12); + ctx.DrawRectangle(HudBrush, HudPen, rect, 8, 8); + var y = at.Y + 6; + foreach (var ft in texts) + { + ctx.DrawText(ft, new Point(at.X + 11, y)); + y += ft.Height + 3; + } + } + + private static readonly IBrush HudBrush = new SolidColorBrush(Color.FromArgb(96, 10, 20, 40)); + private static readonly IPen HudPen = new Pen(new SolidColorBrush(Color.FromArgb(46, 120, 170, 255)), 1); + + private string DeclinationText(double decl) + { + if (Math.Abs(decl) < 0.05) return "0° " + Texts["lat.equator"]; + var suffix = decl > 0 ? Texts["northShort"] : Texts["southShort"]; + return $"{Math.Abs(decl):0.0}°{suffix}"; + } + + private string DateForAngle(double deg) + { + var dayOfYear = 79 + deg / 360.0 * 365.2422; + var date = new DateTime(2025, 1, 1).AddDays(dayOfYear); + var chinese = Texts.Language.StartsWith("zh", StringComparison.OrdinalIgnoreCase); + return date.ToString(chinese ? "M月d日" : "MMM d", CultureInfo.InvariantCulture); + } +} diff --git a/model/_engine/src/EarthModelView.cs b/model/_engine/src/EarthModelView.cs new file mode 100644 index 0000000..93ab2cd --- /dev/null +++ b/model/_engine/src/EarthModelView.cs @@ -0,0 +1,560 @@ +using System; +using System.Collections.Generic; +using Avalonia; +using Avalonia.Animation; +using Avalonia.Animation.Easings; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Input; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; +using EarthModelStudio.ModelSdk; + +namespace NeoRF.EarthModels; + +/// +/// 模型自己的界面:画布 + 工具栏 + 速度条 + 教学要点。 +/// 带过渡动画、缩放控件与「暂停后可拖动」提示;启动器只负责开窗口。 +/// +public sealed class EarthModelView : UserControl +{ + private static readonly IBrush PanelBg = new SolidColorBrush(Color.Parse("#C40A1020")); + private static readonly IBrush ControlBg = new SolidColorBrush(Color.Parse("#16233C")); + private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#2E6BE6")); + private static readonly IBrush TitleBrush = new SolidColorBrush(Color.Parse("#F2F6FF")); + private static readonly IBrush TextBrush = new SolidColorBrush(Color.Parse("#DCE7FA")); + private static readonly IBrush MutedBrush = new SolidColorBrush(Color.Parse("#7E93B8")); + private static readonly IBrush FaintBrush = new SolidColorBrush(Color.Parse("#61779C")); + private static readonly IBrush BodyBrush = new SolidColorBrush(Color.Parse("#8CA0C4")); + + private static readonly TimeSpan HoverDuration = TimeSpan.FromMilliseconds(120); + private static readonly TimeSpan PanelDuration = TimeSpan.FromMilliseconds(190); + + private readonly IModelContext _context; + private readonly ModelStrings _texts; + private readonly SceneRuntime _runtime; + private readonly List _views; + private readonly List _viewButtons = new(); + private readonly CelestialView _canvas; + + private Border? _viewSwitch; + private StackPanel? _seasonPanel; + private Border? _lessons; + private ModelButton? _playButton; + private TextBlock? _zoomText; + + private bool _playing = true; + private bool _labels = true; + private bool _orbit = true; + private bool _grid = true; + private bool _tilt; + private bool _showLessons = true; + + public EarthModelView(IModelContext context, SceneRuntime runtime) + { + _context = context; + _runtime = runtime; + _texts = ModelStrings.Load(context.DataDirectory, context.Language); + _views = ResolveViews(runtime.Scene); + + Background = new SolidColorBrush(Color.Parse("#05070F")); + + _canvas = new CelestialView + { + Scene = runtime, + Texts = _texts, + ShowLabels = true, + ShowOrbit = true, + ShowGraticule = true, + FrameRate = 60, + View = IsRevolution ? SceneView.Revolution : SceneView.Rotation + }; + _canvas.JumpToOrbit(StartAngle); + _canvas.JumpToSpin(20); + _canvas.ZoomChanged += zoom => + { + if (_zoomText != null) _zoomText.Text = $"{zoom * 100:0}%"; + }; + + var root = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto") }; + + var top = BuildTopBar(); + root.Children.Add(top); + + var stage = new Grid(); + stage.Children.Add(_canvas); + _lessons = BuildLessonsPanel(); + stage.Children.Add(_lessons); + Grid.SetRow(stage, 1); + root.Children.Add(stage); + + var bottom = BuildBottomBar(); + Grid.SetRow(bottom, 2); + root.Children.Add(bottom); + + Content = root; + ApplyVisibility(); + + // 打开时整窗淡入,避免“啪”地出现 + Opacity = 0; + Transitions = new Transitions + { + new DoubleTransition + { + Property = OpacityProperty, + Duration = TimeSpan.FromMilliseconds(260), + Easing = new CubicEaseOut() + } + }; + AttachedToVisualTree += (_, _) => Opacity = 1; + } + + private string CurrentView { get; set; } = "rotation"; + + private double StartAngle => IsRevolution ? 60 : 0; + + private bool IsRevolution => string.Equals(CurrentView, "revolution", StringComparison.OrdinalIgnoreCase); + + private bool HasViewSwitch => _views.Count > 1; + + private static string NormalizeView(string? view) + => string.Equals(view, "revolution", StringComparison.OrdinalIgnoreCase) ? "revolution" : "rotation"; + + private List ResolveViews(SceneDefinition scene) + { + var list = new List(); + foreach (var v in scene.Views) + { + var normalized = NormalizeView(v); + if (!list.Contains(normalized)) list.Add(normalized); + } + if (list.Count == 0) list.Add(NormalizeView(scene.DefaultView)); + CurrentView = list[0]; + return list; + } + + // ---------------------------------------------------------------- 顶部 + private Control BuildTopBar() + { + var close = MakeButton(_texts["close"], () => _context.RequestClose()); + + var title = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center }; + title.Children.Add(new TextBlock + { + Text = _texts.Pick(_runtime.Scene.NameI18n, _texts["title"]), + Foreground = TitleBrush, + FontSize = 13, + FontWeight = FontWeight.SemiBold + }); + title.Children.Add(new TextBlock + { + Text = _texts.Pick(_runtime.Scene.DescriptionI18n, ""), + Foreground = MutedBrush, + FontSize = 10.5, + MaxWidth = 330, + TextTrimming = TextTrimming.CharacterEllipsis + }); + + var switchPanel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 }; + switchPanel.Children.Add(MakeViewButton("rotation", _texts["view.rotation"])); + switchPanel.Children.Add(MakeViewButton("revolution", _texts["view.revolution"])); + _viewSwitch = new Border + { + Background = ControlBg, + CornerRadius = new CornerRadius(10), + Padding = new Thickness(3), + Margin = new Thickness(16, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center, + Child = switchPanel + }; + + var actions = new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 7, + VerticalAlignment = VerticalAlignment.Center + }; + + // 缩放:− / 百分比 / + / 复位 + actions.Children.Add(MakeButton("−", () => _canvas.ZoomBy(1 / 1.25), compact: true)); + _zoomText = new TextBlock + { + Text = "100%", + Foreground = TextBrush, + FontSize = 11, + Width = 38, + VerticalAlignment = VerticalAlignment.Center, + TextAlignment = TextAlignment.Center + }; + actions.Children.Add(_zoomText); + actions.Children.Add(MakeButton("+", () => _canvas.ZoomBy(1.25), compact: true)); + actions.Children.Add(MakeButton("⟲", () => + { + _canvas.ResetView(); + _canvas.JumpToOrbit(StartAngle); + _canvas.JumpToSpin(20); + }, compact: true)); + + _playButton = MakeButton(_texts["pause"], TogglePlay); + actions.Children.Add(_playButton); + actions.Children.Add(MakeButton(_texts["reset"], () => + { + _canvas.ResetAnimation(); + _canvas.JumpToOrbit(StartAngle); + })); + actions.Children.Add(MakeToggle(_texts["labels"], _labels, on => { _labels = on; _canvas.ShowLabels = on; })); + actions.Children.Add(MakeToggle(_texts["orbit"], _orbit, on => { _orbit = on; _canvas.ShowOrbit = on; })); + actions.Children.Add(MakeToggle(_texts["grid"], _grid, on => { _grid = on; _canvas.ShowGraticule = on; })); + actions.Children.Add(MakeToggle(_texts["tilt"], _tilt, on => { _tilt = on; _canvas.ExaggerateTilt = on; })); + actions.Children.Add(MakeButton(_texts["lessons"], () => SetLessonsVisible(!_showLessons))); + + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") }; + grid.Children.Add(close); + Grid.SetColumn(title, 1); + title.Margin = new Thickness(14, 0, 0, 0); + grid.Children.Add(title); + Grid.SetColumn(_viewSwitch, 2); + grid.Children.Add(_viewSwitch); + Grid.SetColumn(actions, 4); + grid.Children.Add(actions); + + return new Border { Background = PanelBg, Padding = new Thickness(16, 11), Child = grid }; + } + + private ModelButton MakeViewButton(string view, string label) + { + var button = MakeButton(label, () => SwitchView(view)); + button.SetBase(string.Equals(CurrentView, view, StringComparison.OrdinalIgnoreCase) ? Accent : ControlBg); + button.Tag = view; + button.IsVisible = _views.Contains(view); + _viewButtons.Add(button); + return button; + } + + private ModelButton MakeToggle(string label, bool initial, Action changed) + { + var state = initial; + ModelButton? button = null; + button = MakeButton(label, () => + { + state = !state; + changed(state); + button?.SetBase(state ? Accent : ControlBg); + }); + button.SetBase(initial ? Accent : ControlBg); + return button; + } + + private void SwitchView(string view) + { + CurrentView = NormalizeView(view); + _canvas.View = IsRevolution ? SceneView.Revolution : SceneView.Rotation; + _canvas.JumpToOrbit(StartAngle); + foreach (var button in _viewButtons) + button.SetBase(string.Equals(button.Tag as string, CurrentView, StringComparison.OrdinalIgnoreCase) + ? Accent + : ControlBg); + ApplyVisibility(); + } + + // ---------------------------------------------------------------- 底部 + private Control BuildBottomBar() + { + var speedLabel = new TextBlock + { + Text = _texts["speed"], + Foreground = new SolidColorBrush(Color.Parse("#9DB0D0")), + VerticalAlignment = VerticalAlignment.Center + }; + + var slider = new Slider + { + Minimum = 0.25, + Maximum = 4, + Value = 1, + Margin = new Thickness(12, 0, 0, 0), + Width = 180 + }; + var speedText = new TextBlock + { + Text = "1×", + Foreground = TextBrush, + VerticalAlignment = VerticalAlignment.Center, + Width = 46, + Margin = new Thickness(6, 0, 0, 0) + }; + slider.ValueChanged += (_, e) => + { + _canvas.Speed = e.NewValue; + speedText.Text = $"{e.NewValue:0.##}×"; + }; + + var hint = new TextBlock + { + Text = _texts["hint"], + Foreground = FaintBrush, + FontSize = 10.5, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(22, 0, 0, 0), + TextTrimming = TextTrimming.CharacterEllipsis + }; + + _seasonPanel = new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 6, + VerticalAlignment = VerticalAlignment.Center + }; + _seasonPanel.Children.Add(new TextBlock + { + Text = _texts["seasons"], + Foreground = MutedBrush, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(0, 0, 6, 0) + }); + _seasonPanel.Children.Add(MakeSeasonButton(0)); + _seasonPanel.Children.Add(MakeSeasonButton(90)); + _seasonPanel.Children.Add(MakeSeasonButton(180)); + _seasonPanel.Children.Add(MakeSeasonButton(270)); + + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") }; + grid.Children.Add(speedLabel); + Grid.SetColumn(slider, 1); + grid.Children.Add(slider); + Grid.SetColumn(speedText, 2); + grid.Children.Add(speedText); + Grid.SetColumn(hint, 3); + grid.Children.Add(hint); + Grid.SetColumn(_seasonPanel, 4); + grid.Children.Add(_seasonPanel); + + return new Border { Background = PanelBg, Padding = new Thickness(16, 10), Child = grid }; + } + + private ModelButton MakeSeasonButton(double angle) + { + var key = angle switch + { + 0 => "season.springEquinox", + 90 => "season.summerSolstice", + 180 => "season.autumnEquinox", + _ => "season.winterSolstice" + }; + return MakeButton(_texts[key], () => + { + if (!IsRevolution) SwitchView("revolution"); + _canvas.JumpToOrbit(angle); + }); + } + + // ---------------------------------------------------------------- 教学要点 + private Border BuildLessonsPanel() + { + var header = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; + header.Children.Add(new TextBlock + { + Text = _texts["lessons"], + Foreground = TitleBrush, + FontWeight = FontWeight.SemiBold, + FontSize = 12.5, + VerticalAlignment = VerticalAlignment.Center + }); + var close = MakeButton("✕", () => SetLessonsVisible(false)); + close.SetBase(Brushes.Transparent); + Grid.SetColumn(close, 1); + header.Children.Add(close); + + var list = new StackPanel { Spacing = 2 }; + foreach (var lesson in _runtime.Scene.Lessons) + { + var title = new TextBlock + { + Text = _texts.Pick(lesson.TitleI18n, ""), + Foreground = new SolidColorBrush(Color.Parse("#CFE0FF")), + FontSize = 12, + FontWeight = FontWeight.SemiBold, + TextWrapping = TextWrapping.Wrap + }; + var body = new TextBlock + { + Text = _texts.Pick(lesson.BodyI18n, ""), + Foreground = BodyBrush, + FontSize = 11, + TextWrapping = TextWrapping.Wrap + }; + var stack = new StackPanel { Spacing = 3 }; + stack.Children.Add(title); + stack.Children.Add(body); + + var button = new Button + { + Content = stack, + Background = Brushes.Transparent, + BorderThickness = new Thickness(0), + HorizontalAlignment = HorizontalAlignment.Stretch, + HorizontalContentAlignment = HorizontalAlignment.Left, + Padding = new Thickness(8, 7), + Margin = new Thickness(0, 1), + Cursor = new Cursor(StandardCursorType.Hand), + Transitions = new Transitions + { + new BrushTransition { Property = BackgroundProperty, Duration = HoverDuration } + } + }; + var captured = lesson; + button.Click += (_, _) => ApplyLesson(captured); + button.PointerEntered += (_, _) => button.Background = new SolidColorBrush(Color.Parse("#1B2A47")); + button.PointerExited += (_, _) => button.Background = Brushes.Transparent; + list.Children.Add(button); + } + + var content = new StackPanel { Spacing = 8 }; + content.Children.Add(header); + content.Children.Add(new ScrollViewer + { + Content = list, + MaxHeight = 380, + VerticalScrollBarVisibility = ScrollBarVisibility.Auto + }); + + var panel = new Border + { + HorizontalAlignment = HorizontalAlignment.Right, + VerticalAlignment = VerticalAlignment.Center, + Width = 272, + Margin = new Thickness(0, 58, 16, 80), + Background = new SolidColorBrush(Color.Parse("#D00B1226")), + CornerRadius = new CornerRadius(14), + Padding = new Thickness(13), + BorderBrush = new SolidColorBrush(Color.Parse("#26374F")), + BorderThickness = new Thickness(1), + Child = content, + RenderTransform = new TranslateTransform(0, 0) + }; + panel.Transitions = new Transitions + { + new DoubleTransition { Property = OpacityProperty, Duration = PanelDuration, Easing = new CubicEaseOut() }, + new DoubleTransition + { + Property = TranslateTransform.XProperty, + Duration = PanelDuration, + Easing = new CubicEaseOut() + } + }; + return panel; + } + + private void SetLessonsVisible(bool visible) + { + _showLessons = visible; + if (_lessons == null) return; + + if (visible) + { + _lessons.IsVisible = true; + _lessons.Opacity = 1; + if (_lessons.RenderTransform is TranslateTransform transform) transform.X = 0; + return; + } + + _lessons.Opacity = 0; + if (_lessons.RenderTransform is TranslateTransform hidden) hidden.X = 26; + + var timer = new DispatcherTimer { Interval = PanelDuration }; + timer.Tick += (_, _) => + { + timer.Stop(); + if (!_showLessons && _lessons != null) _lessons.IsVisible = false; + }; + timer.Start(); + } + + private void ApplyLesson(Lesson lesson) + { + if (!string.IsNullOrWhiteSpace(lesson.View)) + { + var view = NormalizeView(lesson.View); + if (!string.Equals(view, CurrentView, StringComparison.OrdinalIgnoreCase)) SwitchView(view); + } + if (lesson.AngleDeg.HasValue) _canvas.JumpToOrbit(lesson.AngleDeg.Value); + } + + // ---------------------------------------------------------------- 工具 + private ModelButton MakeButton(string text, Action onClick, bool compact = false) + { + var button = new ModelButton + { + Content = new TextBlock { Text = text, FontSize = 11.5 }, + Foreground = TextBrush, + BorderThickness = new Thickness(0), + CornerRadius = new CornerRadius(8), + Padding = compact ? new Thickness(8, 4) : new Thickness(9, 5), + MinWidth = compact ? 26 : 0, + VerticalAlignment = VerticalAlignment.Center, + Cursor = new Cursor(StandardCursorType.Hand) + }; + button.SetBase(ControlBg); + button.Click += (_, _) => onClick(); + return button; + } + + private void TogglePlay() + { + _playing = !_playing; + _canvas.IsPlaying = _playing; + if (_playButton?.Content is TextBlock block) + block.Text = _playing ? _texts["pause"] : _texts["play"]; + } + + private void ApplyVisibility() + { + if (_viewSwitch != null) _viewSwitch.IsVisible = HasViewSwitch; + if (_lessons != null) _lessons.IsVisible = _showLessons; + if (_seasonPanel != null) _seasonPanel.IsVisible = IsRevolution; + } + + /// 带悬停过渡的按钮:本地基础色 + 悬停提亮。 + private sealed class ModelButton : Button + { + private IBrush _base = ControlBg; + private IBrush _hover = ControlBg; + + public ModelButton() + { + Transitions = new Transitions + { + new BrushTransition { Property = BackgroundProperty, Duration = HoverDuration } + }; + } + + public void SetBase(IBrush brush) + { + _base = brush; + _hover = Lighten(brush); + Background = brush; + } + + protected override void OnPointerEntered(PointerEventArgs e) + { + base.OnPointerEntered(e); + Background = _hover; + } + + protected override void OnPointerExited(PointerEventArgs e) + { + base.OnPointerExited(e); + Background = _base; + } + + private static IBrush Lighten(IBrush brush) + { + if (brush is not SolidColorBrush solid) return brush; + var c = solid.Color; + return new SolidColorBrush(Color.FromArgb(c.A, + (byte)Math.Min(255, c.R + 26), + (byte)Math.Min(255, c.G + 26), + (byte)Math.Min(255, c.B + 30))); + } + } +} diff --git a/model/_engine/src/EngineEntry.cs b/model/_engine/src/EngineEntry.cs new file mode 100644 index 0000000..a074ec2 --- /dev/null +++ b/model/_engine/src/EngineEntry.cs @@ -0,0 +1,37 @@ +using System; +using Avalonia.Controls; +using EarthModelStudio.ModelSdk; + +namespace NeoRF.EarthModels; + +/// +/// 地球模型共享运行时:读自己目录下的 scene.json / land.json / i18n, +/// 然后把自带界面交给启动器。启动器完全不知道“地球”“节气”这些东西。 +/// +public sealed class EarthModelRuntime : IModelRuntime +{ + public const int SupportedApiVersion = 1; + + private SceneRuntime? _scene; + + /// 后台准备:读场景、生成地表纹理(耗时都花在这里,进度条能实时走)。 + public void Prepare(IModelContext context) + { + context.ReportProgress(0.03, "读取场景数据"); + _scene = SceneRuntime.Load(context.DataDirectory, context.MemoryBudgetMb, context.ReportProgress); + context.Log($"[{context.ModelId}] 场景已加载:{_scene.Scene.DefaultView}," + + $"地表纹理 {(_scene.Texture == null ? "无" : _scene.Texture.Width + "×" + _scene.Texture.Height)}"); + } + + /// UI 线程构建界面(很快)。 + public Control CreateView(IModelContext context) + { + context.ReportProgress(0.78, "构建界面"); + _scene ??= SceneRuntime.Load(context.DataDirectory, context.MemoryBudgetMb, context.ReportProgress); + var view = new EarthModelView(context, _scene); + context.ReportProgress(1.0, "准备就绪"); + return view; + } + + public void Dispose() => GC.SuppressFinalize(this); +} diff --git a/model/_engine/src/LandMask.cs b/model/_engine/src/LandMask.cs new file mode 100644 index 0000000..d8e0bc0 --- /dev/null +++ b/model/_engine/src/LandMask.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace NeoRF.EarthModels; + +/// <id>.model/land.json —— 简化的大陆轮廓(经纬度多边形)。 +public sealed class LandData +{ + [JsonPropertyName("polygons")] public List Polygons { get; set; } = new(); + + public static LandData? Load(string path) + { + if (!File.Exists(path)) return null; + try + { + return JsonSerializer.Deserialize(File.ReadAllText(path), ModelJson.Options); + } + catch (Exception ex) + { + Console.Error.WriteLine($"解析地表数据失败 {path}: {ex.Message}"); + return null; + } + } +} + +public sealed class LandPolygon +{ + [JsonPropertyName("name")] public string? Name { get; set; } + /// [[lon, lat], ...] + [JsonPropertyName("points")] public List Points { get; set; } = new(); +} + +/// +/// 等经纬度栅格地表掩膜(0=海洋 255=陆地),双线性采样。 +/// 每个模型只生成一次,受内存预算约束。 +/// +public sealed class LandMask +{ + public int Width { get; init; } + public int Height { get; init; } + public byte[] Bits { get; init; } = Array.Empty(); + + public long ByteSize => Bits.LongLength; + + public static LandMask Build(LandData data, int width = 1440, int height = 720) + { + var bits = new byte[width * height]; + foreach (var poly in data.Polygons) + { + if (poly.Points.Count < 3) continue; + var pts = Unwrap(poly.Points); + if (pts.Count < 3) continue; + for (var shift = -1; shift <= 1; shift++) + Rasterize(bits, width, height, pts, shift * 360.0); + } + return new LandMask { Width = width, Height = height, Bits = bits }; + } + + private static List<(double Lon, double Lat)> Unwrap(List points) + { + var result = new List<(double, double)>(points.Count); + if (points.Count == 0 || points[0].Length < 2) return result; + var prev = points[0][0]; + result.Add((prev, points[0][1])); + for (var i = 1; i < points.Count; i++) + { + if (points[i].Length < 2) continue; + var lon = points[i][0]; + while (lon - prev > 180) lon -= 360; + while (prev - lon > 180) lon += 360; + result.Add((lon, points[i][1])); + prev = lon; + } + return result; + } + + private static void Rasterize(byte[] bits, int w, int h, List<(double Lon, double Lat)> pts, double lonShift) + { + var n = pts.Count; + var xs = new double[n]; + var ys = new double[n]; + double minY = double.MaxValue, maxY = double.MinValue; + for (var i = 0; i < n; i++) + { + xs[i] = (pts[i].Lon + lonShift + 180.0) / 360.0 * w; + ys[i] = (90.0 - pts[i].Lat) / 180.0 * h; + if (ys[i] < minY) minY = ys[i]; + if (ys[i] > maxY) maxY = ys[i]; + } + + var y0 = Math.Max(0, (int)Math.Floor(minY)); + var y1 = Math.Min(h - 1, (int)Math.Ceiling(maxY)); + var crossings = new List(16); + + for (var y = y0; y <= y1; y++) + { + var sy = y + 0.5; + crossings.Clear(); + for (var i = 0; i < n; i++) + { + var j = (i + 1) % n; + double ya = ys[i], yb = ys[j]; + if (!((ya <= sy && yb > sy) || (yb <= sy && ya > sy))) continue; + var t = (sy - ya) / (yb - ya); + crossings.Add(xs[i] + t * (xs[j] - xs[i])); + } + if (crossings.Count < 2) continue; + crossings.Sort(); + for (var k = 0; k + 1 < crossings.Count; k += 2) + { + var xa = (int)Math.Ceiling(crossings[k] - 0.5); + var xb = (int)Math.Floor(crossings[k + 1] - 0.5); + if (xb < xa) continue; + if (xb - xa >= w - 1) + { + for (var x = 0; x < w; x++) bits[y * w + x] = 255; + continue; + } + for (var x = xa; x <= xb; x++) + { + var mx = x % w; + if (mx < 0) mx += w; + bits[y * w + mx] = 255; + } + } + } + } + + /// 返回 0..1 的陆地覆盖度。 + public double Sample(double lonDeg, double latDeg) + { + var u = (lonDeg + 180.0) / 360.0 * Width - 0.5; + var v = (90.0 - latDeg) / 180.0 * Height - 0.5; + var x0 = (int)Math.Floor(u); + var y0 = (int)Math.Floor(v); + var fx = u - x0; + var fy = v - y0; + double sum = 0; + for (var dy = 0; dy < 2; dy++) + { + var y = y0 + dy; + if (y < 0) y = 0; + if (y >= Height) y = Height - 1; + var wy = dy == 0 ? 1 - fy : fy; + for (var dx = 0; dx < 2; dx++) + { + var x = x0 + dx; + var mx = x % Width; + if (mx < 0) mx += Width; + var wx = dx == 0 ? 1 - fx : fx; + sum += Bits[y * Width + mx] * wx * wy; + } + } + return sum / 255.0; + } +} diff --git a/model/_engine/src/ModelJson.cs b/model/_engine/src/ModelJson.cs new file mode 100644 index 0000000..9bd0a88 --- /dev/null +++ b/model/_engine/src/ModelJson.cs @@ -0,0 +1,27 @@ +using System.IO; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace NeoRF.EarthModels; + +/// 模型自己的 JSON 读写(不依赖启动器)。 +public static class ModelJson +{ + public static readonly JsonSerializerOptions Options = new() + { + PropertyNameCaseInsensitive = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip + }; + + public static T? Read(string path) + { + if (!File.Exists(path)) return default; + return JsonSerializer.Deserialize(File.ReadAllText(path), Options); + } +} diff --git a/model/_engine/src/ModelStrings.cs b/model/_engine/src/ModelStrings.cs new file mode 100644 index 0000000..48acc8e --- /dev/null +++ b/model/_engine/src/ModelStrings.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text.Json; + +namespace NeoRF.EarthModels; + +/// +/// 模型自己的一份文案。优先读模型数据目录里的 i18n/<language>.json, +/// 缺失时回退到代码内的默认文案,保证模型在没有语言包时也能完整显示。 +/// 启动器不再持有任何模型相关文案。 +/// +public sealed class ModelStrings +{ + private readonly Dictionary _texts; + + public string Language { get; } + + private ModelStrings(string language, Dictionary texts) + { + Language = language; + _texts = texts; + } + + public static ModelStrings Default { get; } = new("zh-CN", DefaultTexts.Zh); + + public string this[string key] + => _texts.TryGetValue(key, out var value) ? value + : DefaultTexts.Zh.TryGetValue(key, out var fallback) ? fallback + : key; + + public string F(string key, params object[] args) + => string.Format(CultureInfo.InvariantCulture, this[key], args); + + public string Pick(Dictionary? i18n, string fallback) + { + if (i18n == null) return fallback; + if (i18n.TryGetValue(Language, out var exact) && !string.IsNullOrWhiteSpace(exact)) return exact; + foreach (var pair in i18n) + { + if (Language.StartsWith(pair.Key, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(pair.Value)) + return pair.Value; + } + if (i18n.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh; + return fallback; + } + + public static ModelStrings Load(string dataDirectory, string language) + { + var zh = new Dictionary(DefaultTexts.Zh); + var isEnglish = language.StartsWith("en", StringComparison.OrdinalIgnoreCase); + var chosen = isEnglish ? new Dictionary(DefaultTexts.En) : new Dictionary(zh); + + // 语言包可以覆盖任意键:i18n/.json + var dir = Path.Combine(dataDirectory, "i18n"); + Overlay(Path.Combine(dir, language + ".json"), chosen); + if (!isEnglish) Overlay(Path.Combine(dir, "zh-CN.json"), chosen); + + return new ModelStrings(isEnglish ? "en" : "zh-CN", chosen); + } + + private static void Overlay(string path, Dictionary target) + { + if (!File.Exists(path)) return; + try + { + var map = JsonSerializer.Deserialize>(File.ReadAllText(path), ModelJson.Options); + if (map == null) return; + foreach (var pair in map) target[pair.Key] = pair.Value; + } + catch (Exception ex) + { + Console.Error.WriteLine($"读取模型语言包失败 {path}: {ex.Message}"); + } + } +} + +internal static class DefaultTexts +{ + public static readonly Dictionary Zh = new() + { + ["title"] = "地球模型", + ["view.rotation"] = "自转", + ["view.revolution"] = "公转", + ["play"] = "播放", + ["pause"] = "暂停", + ["speed"] = "速度", + ["reset"] = "重置", + ["labels"] = "标注", + ["orbit"] = "轨道", + ["grid"] = "经纬网", + ["tilt"] = "夸张倾角", + ["lessons"] = "教学要点", + ["seasons"] = "节气定位", + ["close"] = "关闭窗口", + ["hint"] = "双指捏合或滚轮缩放 · 拖动可转动地球", + ["shortcutHint"] = "空格 播放/暂停 · ←→ 步进 · 1–4 二分二至 · F 全屏", + ["classroom"] = "课堂演示", + ["directPoint"] = "太阳直射", + ["frozen"] = "已定格", + ["running"] = "播放中", + ["step"] = "步进", + ["closeup"] = "地球特写", + ["overhead"] = "俯视", + ["sideview"] = "侧视", + ["zoom"] = "缩放", + ["orbitTeach"] = "太阳直射点在南北回归线之间往返,形成四季更替。", + ["lat.equator"] = "赤道", + ["lat.tropicN"] = "北回归线 23.5°N", + ["lat.tropicS"] = "南回归线 23.5°S", + ["lat.polarN"] = "北极圈 66.5°N", + ["lat.polarS"] = "南极圈 66.5°S", + ["loading"] = "正在准备场景…", + ["subsolar"] = "太阳直射点", + ["north"] = "北极", + ["south"] = "南极", + ["northShort"] = "N", + ["southShort"] = "S", + ["sun"] = "太阳", + ["earth"] = "地球", + ["spinInfo"] = "自转 {0}° · 周期 {1} 小时", + ["orbitInfo"] = "公转 {0}°", + ["declinationInfo"] = "太阳直射 {0}", + ["dateInfo"] = "日期 {0}", + ["season.springEquinox"] = "春分", + ["season.summerSolstice"] = "夏至", + ["season.autumnEquinox"] = "秋分", + ["season.winterSolstice"] = "冬至" + }; + + public static readonly Dictionary En = new() + { + ["title"] = "Earth model", + ["view.rotation"] = "Rotation", + ["view.revolution"] = "Revolution", + ["play"] = "Play", + ["pause"] = "Pause", + ["speed"] = "Speed", + ["reset"] = "Reset", + ["labels"] = "Labels", + ["orbit"] = "Orbit", + ["grid"] = "Graticule", + ["tilt"] = "Exaggerate tilt", + ["lessons"] = "Teaching notes", + ["seasons"] = "Solstices & equinoxes", + ["close"] = "Close window", + ["hint"] = "Pinch or scroll to zoom · drag to turn the Earth", + ["shortcutHint"] = "Space play/pause · ←→ step · 1–4 solstices & equinoxes · F fullscreen", + ["classroom"] = "Classroom", + ["directPoint"] = "Subsolar", + ["frozen"] = "Frozen", + ["running"] = "Playing", + ["step"] = "Step", + ["closeup"] = "Earth close-up", + ["overhead"] = "Top view", + ["sideview"] = "Side view", + ["zoom"] = "Zoom", + ["orbitTeach"] = "The subsolar point travels between the tropics, producing the seasons.", + ["lat.equator"] = "Equator", + ["lat.tropicN"] = "Tropic of Cancer 23.5°N", + ["lat.tropicS"] = "Tropic of Capricorn 23.5°S", + ["lat.polarN"] = "Arctic Circle 66.5°N", + ["lat.polarS"] = "Antarctic Circle 66.5°S", + ["loading"] = "Preparing scene…", + ["subsolar"] = "Subsolar point", + ["north"] = "North pole", + ["south"] = "South pole", + ["northShort"] = "N", + ["southShort"] = "S", + ["sun"] = "Sun", + ["earth"] = "Earth", + ["spinInfo"] = "Rotation {0}° · period {1} h", + ["orbitInfo"] = "Orbit {0}°", + ["declinationInfo"] = "Subsolar {0}", + ["dateInfo"] = "Date {0}", + ["season.springEquinox"] = "Spring equinox", + ["season.summerSolstice"] = "Summer solstice", + ["season.autumnEquinox"] = "Autumn equinox", + ["season.winterSolstice"] = "Winter solstice" + }; +} diff --git a/model/_engine/src/PlanetScene.cs b/model/_engine/src/PlanetScene.cs new file mode 100644 index 0000000..9f7c91b --- /dev/null +++ b/model/_engine/src/PlanetScene.cs @@ -0,0 +1,74 @@ +using System.Collections.Generic; + +namespace NeoRF.EarthModels; + +/// <id>.model/scene.json —— 模型数据(可视化场景描述)。 +public sealed class SceneDefinition +{ + public int SchemaVersion { get; set; } = 1; + public string Type { get; set; } = "planet"; + /// rotation | revolution + public string DefaultView { get; set; } = "rotation"; + /// 模型支持的视图;为空表示只有 defaultView。 + public List Views { get; set; } = new(); + public Dictionary? NameI18n { get; set; } + public Dictionary? DescriptionI18n { get; set; } + public StarDefinition Star { get; set; } = new(); + public PlanetDefinition Planet { get; set; } = new(); + public OrbitDefinition Orbit { get; set; } = new(); + public List Lessons { get; set; } = new(); +} + +public sealed class StarDefinition +{ + public string Name { get; set; } = "Sun"; + public Dictionary? NameI18n { get; set; } + public string Color { get; set; } = "#FFC24B"; + /// 相对行星半径的视觉倍率 + public double RadiusScale { get; set; } = 0.5; +} + +public sealed class PlanetDefinition +{ + public string Name { get; set; } = "Earth"; + public Dictionary? NameI18n { get; set; } + /// 黄赤交角:教材值 23.5°(23°26′),决定南北回归线纬度。 + public double AxialTiltDeg { get; set; } = 23.5; + /// 回归线纬度,默认与黄赤交角一致;极圈 = 90 − 回归线。 + public double TropicDeg { get; set; } = 23.5; + public double RotationHours { get; set; } = 23.93; + public double OrbitDays { get; set; } = 365.26; + public string OceanColor { get; set; } = "#1B5FA8"; + public string LandColor { get; set; } = "#4F8C4C"; + public string? IceColor { get; set; } = "#E8EEF4"; + public string? LandFile { get; set; } = "land.json"; + public bool ShowGraticule { get; set; } = true; +} + +public sealed class OrbitDefinition +{ + public double SemiMajorAxis { get; set; } = 4.0; + public double Eccentricity { get; set; } = 0.0167; + public bool Show { get; set; } = true; + public List Seasons { get; set; } = new(); +} + +public sealed class SeasonPoint +{ + /// 0=春分 90=夏至 180=秋分 270=冬至 + public double AngleDeg { get; set; } + public string Key { get; set; } = ""; + public string? Date { get; set; } + /// 该节气的太阳直射纬度:春分/秋分 0,夏至 +23.5,冬至 −23.5。 + public double? DeclinationDeg { get; set; } + /// 课堂现象说明(写在模型数据里,启动器不参与)。 + public Dictionary? TeachingI18n { get; set; } +} + +public sealed class Lesson +{ + public Dictionary? TitleI18n { get; set; } + public Dictionary? BodyI18n { get; set; } + public string? View { get; set; } + public double? AngleDeg { get; set; } +} diff --git a/model/_engine/src/PlanetSceneRuntime.cs b/model/_engine/src/PlanetSceneRuntime.cs new file mode 100644 index 0000000..59fa9be --- /dev/null +++ b/model/_engine/src/PlanetSceneRuntime.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Avalonia.Media; + +namespace NeoRF.EarthModels; + +/// +/// 模型自己的场景运行时:场景描述 + 预烘焙地表纹理 + 调色板。 +/// 数据来自模型数据目录,不依赖启动器。 +/// +public sealed class SceneRuntime +{ + public SceneDefinition Scene { get; init; } = new(); + public PlanetTexture? Texture { get; init; } + public Color Ocean { get; init; } = Color.Parse("#1B5FA8"); + public Color Land { get; init; } = Color.Parse("#4F8C4C"); + public Color Ice { get; init; } = Color.Parse("#E6EDF4"); + public Color Star { get; init; } = Color.Parse("#FFC24B"); + + public long MemoryBytes => Texture?.ByteSize ?? 0; + + public static SceneRuntime Load(string dataDirectory, int memoryBudgetMb, + Action? progress = null) + { + progress?.Invoke(0.06, "读取场景数据"); + var scenePath = Path.Combine(dataDirectory, "scene.json"); + var scene = ModelJson.Read(scenePath) ?? new SceneDefinition(); + + var ocean = Parse(scene.Planet.OceanColor, "#1B5FA8"); + var land = Parse(scene.Planet.LandColor, "#4F8C4C"); + var ice = Parse(scene.Planet.IceColor, "#E6EDF4"); + + LandData? landData = null; + var landFile = scene.Planet.LandFile; + if (!string.IsNullOrWhiteSpace(landFile)) + { + var path = Path.IsPathRooted(landFile!) ? landFile! : Path.Combine(dataDirectory, landFile!); + progress?.Invoke(0.12, "读取地表轮廓"); + landData = LandData.Load(path); + } + + // 内存预算决定纹理分辨率(1024 宽约 3 MB) + var width = memoryBudgetMb >= 1024 ? PlanetTexture.DefaultWidth + : memoryBudgetMb >= 512 ? 768 + : 512; + + progress?.Invoke(0.16, "生成地表纹理"); + var texture = PlanetTexture.Build(landData, width, ocean, land, ice, + t => progress?.Invoke(0.16 + t * 0.48, "生成地表纹理")); + + progress?.Invoke(0.68, "场景就绪"); + return new SceneRuntime + { + Scene = scene, + Texture = texture, + Ocean = ocean, + Land = land, + Ice = ice, + Star = Parse(scene.Star.Color, "#FFC24B") + }; + } + + private static Color Parse(string? value, string fallback) + => Color.TryParse(string.IsNullOrWhiteSpace(value) ? fallback : value, out var c) ? c : Color.Parse(fallback); +} diff --git a/model/_engine/src/PlanetTexture.cs b/model/_engine/src/PlanetTexture.cs new file mode 100644 index 0000000..9de4ddc --- /dev/null +++ b/model/_engine/src/PlanetTexture.cs @@ -0,0 +1,476 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Avalonia.Media; + +namespace NeoRF.EarthModels; + +/// +/// 预烘焙的等经纬度地表贴图:反照率 + 高度 + 冰盖 + 云层 + 夜间灯光。 +/// 只在模型加载时算一次,之后每帧只做采样 —— 比逐像素跑噪声快一个数量级, +/// 而且能画出「真实一点」的地表:海洋深度、沙漠/雨林/针叶林带、山脉阴影、极地冰盖。 +/// +public sealed class PlanetTexture +{ + public const int DefaultWidth = 1024; + + public int Width { get; } + public int Height { get; } + + /// 打包的反照率(0xRRGGBB),每像素一次双线性即可拿三通道。 + public uint[] Albedo { get; } + /// 地形高度(0=海平面,255=高山) + public byte[] Elevation { get; } + /// 云量 + public byte[] Cloud { get; } + /// 夜间灯光 + public byte[] Lights { get; } + /// 预烘焙的地形坡度:东向 / 北向高度梯度(加载时算一次,每帧直接采样)。 + public float[] SlopeEast { get; } + public float[] SlopeNorth { get; } + + public long ByteSize => (long)(Albedo.Length * 4 + Elevation.Length + Cloud.Length + Lights.Length + + SlopeEast.Length * 4 + SlopeNorth.Length * 4); + + private PlanetTexture(int width, int height) + { + Width = width; + Height = height; + var count = width * height; + Albedo = new uint[count]; + Elevation = new byte[count]; + Cloud = new byte[count]; + Lights = new byte[count]; + SlopeEast = new float[count]; + SlopeNorth = new float[count]; + } + + public static PlanetTexture Build(LandData? landData, int width, Color ocean, Color land, Color ice, + Action? progress = null) + { + width = Math.Clamp(width, 256, 2048); + var height = width / 2; + var texture = new PlanetTexture(width, height); + + progress?.Invoke(0.08); + var mask = landData == null ? null : LandMask.Build(landData, width, height); + progress?.Invoke(0.28); + + // 到海岸的距离:海里用来做深度,陆地上用来做大陆性(内陆更干) + var landDistance = new float[width * height]; + var oceanDistance = new float[width * height]; + ComputeDistances(mask, width, height, landDistance, oceanDistance); + progress?.Invoke(0.42); + + Parallel.For(0, height, y => + { + var lat = 90.0 - (y + 0.5) * 180.0 / height; + var latAbs = MathF.Abs((float)lat); + var rowBase = y * width; + for (var x = 0; x < width; x++) + { + var lon = (x + 0.5) * 360.0 / width - 180.0; + var index = rowBase + x; + var isLand = mask == null || mask.Bits[index] > 127; + + var elevation = Fbm(lon * 2.1, lat * 2.1, 4, 0x51A3); + var moisture = Fbm(lon * 1.35 + 40, lat * 1.35 - 20, 3, 0x9E2B); + var detail = Fbm(lon * 0.85, lat * 0.85, 3, 0x2C77); + + if (isLand) + { + // 内陆更干,靠海更湿 + var inland = Math.Clamp(landDistance[index] / (width * 0.06f), 0f, 1f); + var wet = Math.Clamp(moisture * 0.78f + (1f - inland) * 0.16f + - MathF.Max(0f, latAbs - 45f) / 90f, 0f, 1f); + + var (r, g, b) = LandPalette(latAbs, wet, inland, elevation, detail, land, ice); + texture.Albedo[index] = Pack(r, g, b); + texture.Elevation[index] = (byte)Math.Clamp(elevation * 235f + detail * 20f, 0, 255); + + // 夜间灯光:沿海平原、中低纬,稀疏分布 + // 夜间灯光:低频的城市群辉光(高频点会在小尺寸球面上变成噪点) + var cityGlow = Smooth(0.55f, 0.92f, Fbm(lon * 1.7, lat * 1.7, 3, 0x7A31)); + if (latAbs < 60 && inland < 0.55f && elevation < 0.75f) + texture.Lights[index] = ToByte(cityGlow * 0.55f); + } + else + { + // 海洋:按离岸距离做深浅 + var depth = Math.Clamp(oceanDistance[index] / (width * 0.09f), 0f, 1f); + depth = (float)Math.Pow(depth, 0.65); + var shallowR = Math.Min(1f, ocean.R / 255f + 0.16f); + var shallowG = Math.Min(1f, ocean.G / 255f + 0.22f); + var shallowB = Math.Min(1f, ocean.B / 255f + 0.16f); + var deepR = ocean.R / 255f * 0.32f; + var deepG = ocean.G / 255f * 0.40f; + var deepB = ocean.B / 255f * 0.52f; + var wave = (detail - 0.5f) * 0.035f; + + texture.Albedo[index] = Pack( + ToByte(shallowR + (deepR - shallowR) * depth + wave), + ToByte(shallowG + (deepG - shallowG) * depth + wave), + ToByte(shallowB + (deepB - shallowB) * depth + wave)); + texture.Elevation[index] = 0; + } + + // 极地冰盖:纬度 + 噪声边界,海洋也能结冰 + var iceEdge = 62f + (detail - 0.5f) * 9f; + var iceAmt = Smooth(iceEdge - 7f, iceEdge + 6f, latAbs); + if (iceAmt > 0.001f) + { + var iceR = ice.R / 255f; + var iceG = ice.G / 255f; + var iceB = ice.B / 255f; + var packed = texture.Albedo[index]; + texture.Albedo[index] = Pack( + ToByte(Lerp(((packed >> 16) & 0xFF) / 255f, iceR, iceAmt)), + ToByte(Lerp(((packed >> 8) & 0xFF) / 255f, iceG, iceAmt)), + ToByte(Lerp((packed & 0xFF) / 255f, iceB, iceAmt))); + } + + // 云:多个尺度的 fbm,赤道与中纬多云 + var cloudBase = Fbm(lon * 0.55, lat * 0.7, 3, 0x1144); + var band = 0.5f + 0.5f * MathF.Cos(latAbs / 90f * MathF.PI * 3.1f); + var cloud = Smooth(0.48f, 0.84f, cloudBase * 0.86f + band * 0.14f); + texture.Cloud[index] = ToByte(cloud * 0.72f); + } + }); + + // 云层做一次模糊,避免小尺寸球面上采样出噪点 + Blur(texture.Cloud, width, height, 2); + + // 预烘焙地形坡度:渲染时不必每像素再取 4 次高度 + BakeSlopes(texture, width, height); + progress?.Invoke(0.62); + return texture; + } + + private static (byte R, byte G, byte B) LandPalette(float latAbs, float wet, float inland, float elevation, + float detail, Color landBase, Color ice) + { + // 基色随纬度:赤道雨林 -> 温带 -> 针叶林 -> 苔原 + float r, g, b; + var tropical = (1f - Smooth(8f, 24f, latAbs)); + var temperate = Smooth(20f, 34f, latAbs) * (1f - Smooth(46f, 60f, latAbs)); + var boreal = Smooth(46f, 60f, latAbs) * (1f - Smooth(62f, 70f, latAbs)); + var tundra = Smooth(60f, 72f, latAbs); + + r = 0.13f; g = 0.36f; b = 0.17f; // 温带草原绿 + r = Lerp(r, 0.10f, tropical); g = Lerp(g, 0.42f, tropical); b = Lerp(b, 0.19f, tropical); + r = Lerp(r, 0.17f, boreal); g = Lerp(g, 0.28f, boreal); b = Lerp(b, 0.17f, boreal); + r = Lerp(r, 0.34f, tundra); g = Lerp(g, 0.36f, tundra); b = Lerp(b, 0.31f, tundra); + + // 湿润度:干 -> 沙漠/草原 + var dry = Math.Clamp(1f - wet * 0.95f, 0f, 1f); + var desertBand = Math.Clamp(1f - MathF.Abs(latAbs - 24f) / 13f, 0f, 1f); + var desert = Math.Clamp(dry * 0.72f + desertBand * 0.62f, 0f, 1f); + r = Lerp(r, 0.72f, desert * 0.85f); + g = Lerp(g, 0.60f, desert * 0.85f); + b = Lerp(b, 0.38f, desert * 0.85f); + + // 高原/山地:岩石和雪 + var rock = Smooth(0.62f, 0.86f, elevation); + r = Lerp(r, 0.44f, rock * 0.7f); + g = Lerp(g, 0.40f, rock * 0.7f); + b = Lerp(b, 0.34f, rock * 0.7f); + + var snow = Smooth(0.86f, 0.97f, elevation + (latAbs - 40f) / 220f); + r = Lerp(r, ice.R / 255f, snow); + g = Lerp(g, ice.G / 255f, snow); + b = Lerp(b, ice.B / 255f, snow); + + // 细节扰动,避免大面积纯色 + var grain = (detail - 0.5f) * 0.07f; + var baseMix = 0.25f; + return ( + ToByte(Math.Clamp(r + grain + (landBase.R / 255f - 0.3f) * baseMix * 0.2f, 0f, 1f)), + ToByte(Math.Clamp(g + grain + (landBase.G / 255f - 0.45f) * baseMix * 0.2f, 0f, 1f)), + ToByte(Math.Clamp(b + grain + (landBase.B / 255f - 0.3f) * baseMix * 0.2f, 0f, 1f))); + } + + /// 可分离盒式模糊(原地),用于软化云层。 + private static void Blur(byte[] data, int width, int height, int radius) + { + var temp = new byte[data.Length]; + for (var y = 0; y < height; y++) + { + var row = y * width; + for (var x = 0; x < width; x++) + { + var sum = 0; + var count = 0; + for (var k = -radius; k <= radius; k++) + { + var sx = (x + k + width) % width; + sum += data[row + sx]; + count++; + } + temp[row + x] = (byte)(sum / count); + } + } + for (var x = 0; x < width; x++) + { + for (var y = 0; y < height; y++) + { + var sum = 0; + var count = 0; + for (var k = -radius; k <= radius; k++) + { + var sy = Math.Clamp(y + k, 0, height - 1); + sum += temp[sy * width + x]; + count++; + } + data[y * width + x] = (byte)(sum / count); + } + } + } + + /// 由高度图算东西/南北梯度,供球面光照直接使用。 + private static void BakeSlopes(PlanetTexture t, int width, int height) + { + const float relief = 0.055f * 90f; + for (var y = 0; y < height; y++) + { + var row = y * width; + var up = Math.Max(0, y - 1) * width; + var down = Math.Min(height - 1, y + 1) * width; + for (var x = 0; x < width; x++) + { + var left = (x - 1 + width) % width; + var right = (x + 1) % width; + t.SlopeEast[row + x] = (t.Elevation[row + right] - t.Elevation[row + left]) / 255f * relief; + t.SlopeNorth[row + x] = (t.Elevation[up + x] - t.Elevation[down + x]) / 255f * relief; + } + } + } + + // ---------------------------------------------------------------- 距离场 + private static void ComputeDistances(LandMask? mask, int width, int height, float[] landDistance, float[] oceanDistance) + { + var count = width * height; + const float big = 1e6f; + for (var i = 0; i < count; i++) + { + var isLand = mask != null && mask.Bits[i] > 127; + landDistance[i] = isLand ? big : -big; + oceanDistance[i] = isLand ? -big : big; + } + + // 两遍 chamfer:陆地到海洋的距离 / 海洋到陆地的距离 + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var i = y * width + x; + if (mask != null && mask.Bits[i] > 127) + { + var best = big; + if (x > 0 && mask.Bits[i - 1] <= 127) best = 0.5f; + if (x < width - 1 && mask.Bits[i + 1] <= 127) best = Math.Min(best, 0.5f); + if (y > 0 && mask.Bits[i - width] <= 127) best = Math.Min(best, 0.5f); + if (y < height - 1 && mask.Bits[i + width] <= 127) best = Math.Min(best, 0.5f); + if (best < big) landDistance[i] = best; + } + if (mask != null && mask.Bits[i] <= 127) + { + var best = big; + if (x > 0 && mask.Bits[i - 1] > 127) best = 0.5f; + if (x < width - 1 && mask.Bits[i + 1] > 127) best = Math.Min(best, 0.5f); + if (y > 0 && mask.Bits[i - width] > 127) best = Math.Min(best, 0.5f); + if (y < height - 1 && mask.Bits[i + width] > 127) best = Math.Min(best, 0.5f); + if (best < big) oceanDistance[i] = best; + } + } + } + + // 正向传递 + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var i = y * width + x; + Propagate(landDistance, i, width, height, x, y, -1, 0, 1.4142f); + Propagate(oceanDistance, i, width, height, x, y, -1, 0, 1.4142f); + if (x > 0) + { + landDistance[i] = Math.Min(landDistance[i], landDistance[i - 1] + 1f); + oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - 1] + 1f); + } + if (y > 0) + { + landDistance[i] = Math.Min(landDistance[i], landDistance[i - width] + 1f); + oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width] + 1f); + if (x > 0) + { + landDistance[i] = Math.Min(landDistance[i], landDistance[i - width - 1] + 1.4142f); + oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width - 1] + 1.4142f); + } + if (x < width - 1) + { + landDistance[i] = Math.Min(landDistance[i], landDistance[i - width + 1] + 1.4142f); + oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width + 1] + 1.4142f); + } + } + } + } + // 反向传递 + for (var y = height - 1; y >= 0; y--) + { + for (var x = width - 1; x >= 0; x--) + { + var i = y * width + x; + if (x < width - 1) + { + landDistance[i] = Math.Min(landDistance[i], landDistance[i + 1] + 1f); + oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + 1] + 1f); + } + if (y < height - 1) + { + landDistance[i] = Math.Min(landDistance[i], landDistance[i + width] + 1f); + oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width] + 1f); + if (x < width - 1) + { + landDistance[i] = Math.Min(landDistance[i], landDistance[i + width + 1] + 1.4142f); + oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width + 1] + 1.4142f); + } + if (x > 0) + { + landDistance[i] = Math.Min(landDistance[i], landDistance[i + width - 1] + 1.4142f); + oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width - 1] + 1.4142f); + } + } + } + } + + for (var i = 0; i < count; i++) + { + landDistance[i] = MathF.Max(0f, landDistance[i]); + oceanDistance[i] = MathF.Max(0f, oceanDistance[i]); + } + } + + private static void Propagate(float[] map, int index, int width, int height, int x, int y, int dx, int dy, float w) + { + var nx = x + dx; + var ny = y + dy; + if (nx < 0 || nx >= width || ny < 0 || ny >= height) return; + var other = ny * width + nx; + map[index] = Math.Min(map[index], map[other] + w); + } + + // ---------------------------------------------------------------- 噪声 + /// 值噪声 + 分形叠加(确定性,跨平台一致)。 + public static float Fbm(double x, double y, int octaves, int seed) + { + var amplitude = 1.0; + var frequency = 1.0; + var sum = 0.0; + var norm = 0.0; + for (var i = 0; i < octaves; i++) + { + sum += amplitude * ValueNoise(x * frequency, y * frequency, seed + i * 101); + norm += amplitude; + amplitude *= 0.5; + frequency *= 2.07; + } + return (float)(sum / norm); + } + + private static double ValueNoise(double x, double y, int seed) + { + var xi = (int)Math.Floor(x); + var yi = (int)Math.Floor(y); + var xf = x - xi; + var yf = y - yi; + var u = xf * xf * (3 - 2 * xf); + var v = yf * yf * (3 - 2 * yf); + var a = Hash(xi, yi, seed); + var b = Hash(xi + 1, yi, seed); + var c = Hash(xi, yi + 1, seed); + var d = Hash(xi + 1, yi + 1, seed); + return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v; + } + + private static double Hash(int x, int y, int seed) + { + var h = (uint)(x * 374761393 + y * 668265263 + seed * 1442695041); + h = (h ^ (h >> 13)) * 1274126177u; + h ^= h >> 16; + return (h & 0xFFFFFF) / (double)0xFFFFFF; + } + + // ---------------------------------------------------------------- 采样 + public void Sample(double lon, double lat, out float r, out float g, out float b, + out float elevation, out float cloud, out float lights, + out float slopeEast, out float slopeNorth) + { + var u = (lon + 180.0) / 360.0 * Width - 0.5; + var v = (90.0 - lat) / 180.0 * Height - 0.5; + + var x0 = (int)Math.Floor(u); + var y0 = (int)Math.Floor(v); + var fx = (float)(u - x0); + var fy = (float)(v - y0); + + var x1 = x0 + 1; + var y1 = y0 + 1; + if (x0 < 0) x0 += Width; if (x1 < 0) x1 += Width; + if (x0 >= Width) x0 -= Width; if (x1 >= Width) x1 -= Width; + y0 = Math.Clamp(y0, 0, Height - 1); + y1 = Math.Clamp(y1, 0, Height - 1); + + var i00 = y0 * Width + x0; + var i10 = y0 * Width + x1; + var i01 = y1 * Width + x0; + var i11 = y1 * Width + x1; + + float w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy), w01 = (1 - fx) * fy, w11 = fx * fy; + + var p00 = Albedo[i00]; + var p10 = Albedo[i10]; + var p01 = Albedo[i01]; + var p11 = Albedo[i11]; + var rr = ((p00 >> 16) & 0xFF) * w00 + ((p10 >> 16) & 0xFF) * w10 + ((p01 >> 16) & 0xFF) * w01 + ((p11 >> 16) & 0xFF) * w11; + var gg = ((p00 >> 8) & 0xFF) * w00 + ((p10 >> 8) & 0xFF) * w10 + ((p01 >> 8) & 0xFF) * w01 + ((p11 >> 8) & 0xFF) * w11; + var bb = (p00 & 0xFF) * w00 + (p10 & 0xFF) * w10 + (p01 & 0xFF) * w01 + (p11 & 0xFF) * w11; + r = rr / 255f; + g = gg / 255f; + b = bb / 255f; + + elevation = (Elevation[i00] * w00 + Elevation[i10] * w10 + Elevation[i01] * w01 + Elevation[i11] * w11) / 255f; + cloud = (Cloud[i00] * w00 + Cloud[i10] * w10 + Cloud[i01] * w01 + Cloud[i11] * w11) / 255f; + lights = Lights[i00] / 255f; + slopeEast = SlopeEast[i00] * w00 + SlopeEast[i10] * w10 + SlopeEast[i01] * w01 + SlopeEast[i11] * w11; + slopeNorth = SlopeNorth[i00] * w00 + SlopeNorth[i10] * w10 + SlopeNorth[i01] * w01 + SlopeNorth[i11] * w11; + } + + /// 只采样高度(法线扰动用)。 + public float SampleHeight(double lon, double lat) + { + var u = (lon + 180.0) / 360.0 * Width - 0.5; + var v = (90.0 - lat) / 180.0 * Height - 0.5; + var x = Math.Clamp((int)Math.Round(u), 0, Width - 1); + var y = Math.Clamp((int)Math.Round(v), 0, Height - 1); + return Elevation[y * Width + x] / 255f; + } + + public float SampleCloud(double lon, double lat) + { + var u = (lon + 180.0) / 360.0 * Width - 0.5; + var v = (90.0 - lat) / 180.0 * Height - 0.5; + var x = Math.Clamp((int)Math.Round(u), 0, Width - 1); + var y = Math.Clamp((int)Math.Round(v), 0, Height - 1); + return Cloud[y * Width + x] / 255f; + } + + public static byte ToByte(float v) => (byte)Math.Clamp((int)(v * 255f + 0.5f), 0, 255); + private static uint Pack(byte r, byte g, byte b) => ((uint)r << 16) | ((uint)g << 8) | b; + private static float Lerp(float a, float b, float t) => a + (b - a) * Math.Clamp(t, 0f, 1f); + private static float Smooth(float edge0, float edge1, float x) + { + if (edge1 <= edge0) return x >= edge1 ? 1f : 0f; + var t = Math.Clamp((x - edge0) / (edge1 - edge0), 0f, 1f); + return t * t * (3f - 2f * t); + } +} diff --git a/model/_engine/src/SphereRaster.cs b/model/_engine/src/SphereRaster.cs new file mode 100644 index 0000000..8b7bb8b --- /dev/null +++ b/model/_engine/src/SphereRaster.cs @@ -0,0 +1,172 @@ +using System; +using System.Numerics; +using System.Threading.Tasks; +using Avalonia.Media.Imaging; + +namespace NeoRF.EarthModels; + +/// +/// 球体像素级渲染:正交投影 + 预烘焙地表纹理 + 地形光照 + 云层 + 夜灯 + 大气边缘光。 +/// 纯 CPU 光栅、按行并行,不依赖 GPU,三平台效果一致。 +/// +public static unsafe class SphereRaster +{ + /// 把球体画进 WriteableBitmap(整张位图会被覆盖)。 + public static void Draw(WriteableBitmap bitmap, int size, Matrix4x4 cam, Matrix4x4 planet, + Vector3 light, PlanetTexture texture, double cloudShift, bool showClouds) + { + using var framebuffer = bitmap.Lock(); + var stride = framebuffer.RowBytes / 4; + Render((uint*)framebuffer.Address, stride, size, cam, planet, light, texture, cloudShift, showClouds); + } + + public static void Render(uint* dst, int stride, int size, Matrix4x4 cam, Matrix4x4 planet, + Vector3 light, PlanetTexture texture, double cloudShift, bool showClouds) + { + var radius = size * 0.5f - 1.0f; + var center = size * 0.5f; + var inv = 1f / radius; + + // 相机空间法线 -> 行星本地法线 + var combined = Matrix4x4.Multiply(planet, cam); + var mt = Matrix4x4.Transpose(combined); + float m11 = mt.M11, m12 = mt.M12, m13 = mt.M13; + float m21 = mt.M21, m22 = mt.M22, m23 = mt.M23; + float m31 = mt.M31, m32 = mt.M32, m33 = mt.M33; + + var lx = light.X; var ly = light.Y; var lz = light.Z; + + Parallel.For(0, size, y => + { + var ny = (center - y - 0.5f) * inv; + var row = dst + (long)y * stride; + for (var x = 0; x < size; x++) + { + var nx = (x + 0.5f - center) * inv; + var r2 = nx * nx + ny * ny; + if (r2 >= 1f) + { + row[x] = 0; + continue; + } + + var nz = MathF.Sqrt(1f - r2); + + // 本地法线(用于取经纬度) + var ux = nx * m11 + ny * m21 + nz * m31; + var uy = nx * m12 + ny * m22 + nz * m32; + var uz = nx * m13 + ny * m23 + nz * m33; + + var lat = MathF.Asin(Math.Clamp(uy, -1f, 1f)) * 57.2957795f; + var lon = MathF.Atan2(ux, uz) * 57.2957795f; + + var cloudLon = lon + cloudShift; + if (cloudLon > 180) cloudLon -= 360; + if (cloudLon < -180) cloudLon += 360; + + texture.Sample(lon, lat, out var ar, out var ag, out var ab, + out var elevation, out var cloud, out var lights, + out var dEast, out var dNorth); + + // ---- 地形法线:局部基向量可由球面法线直接推出,不必再算 6 次三角函数 + // 点 P=(cosLat·sinLon, sinLat, cosLat·cosLon) = (ux,uy,uz) + // 东向 = (cosLon,0,-sinLon),北向 = (-sinLat·sinLon, cosLat, -sinLat·cosLon) + var cosLat = MathF.Sqrt(MathF.Max(ux * ux + uz * uz, 1e-6f)); + var invCos = 1f / cosLat; + var eastX = uz * invCos; + var eastZ = -ux * invCos; + var northX = -uy * ux * invCos; + var northY = cosLat; + var northZ = -uy * uz * invCos; + + var nLocalX = ux + eastX * dEast + northX * dNorth; + var nLocalY = uy + northY * dNorth; + var nLocalZ = uz + eastZ * dEast + northZ * dNorth; + var nLen = MathF.Sqrt(nLocalX * nLocalX + nLocalY * nLocalY + nLocalZ * nLocalZ); + if (nLen > 0.0001f) { nLocalX /= nLen; nLocalY /= nLen; nLocalZ /= nLen; } + + var nCamX = nLocalX * combined.M11 + nLocalY * combined.M21 + nLocalZ * combined.M31; + var nCamY = nLocalX * combined.M12 + nLocalY * combined.M22 + nLocalZ * combined.M32; + var nCamZ = nLocalX * combined.M13 + nLocalY * combined.M23 + nLocalZ * combined.M33; + + var lam = nx * lx + ny * ly + nz * lz; // 几何光照(晨昏线) + var bump = nCamX * lx + nCamY * ly + nCamZ * lz; // 地形光照 + var day = Smooth(-0.18f, 0.22f, lam); + var terrainLight = 0.82f + 0.42f * MathF.Max(0f, bump - lam); + + var shade = (0.055f + 0.945f * day) * terrainLight; + + var br = ar * shade; + var bg = ag * shade; + var bb = ab * shade; + + // 海面高光(高度为 0 视为水面) + if (elevation < 0.02f) + { + var t2 = MathF.Max(0f, lam); + var t4 = t2 * t2 * t2 * t2; + var t8 = t4 * t4; + var t16 = t8 * t8; + var spec = t16 * t8 * t4 * t2 * t2 * 0.62f; + br += spec * 0.95f; + bg += spec * 0.98f; + bb += spec; + } + + // 云层(随经度缓慢漂移) + if (showClouds && cloud > 0.02f) + { + var cloudLight = 0.10f + 0.90f * day; + var c = Math.Clamp(cloud * 0.92f, 0f, 1f); + var cloudR = 0.98f * cloudLight; + var cloudG = 0.985f * cloudLight; + var cloudB = 1.0f * cloudLight; + br += (cloudR - br) * c; + bg += (cloudG - bg) * c; + bb += (cloudB - bb) * c; + } + + // 夜间灯光 + if (lights > 0.01f) + { + var night = 1f - day; + var glow = lights * night * 0.35f; + br += glow * 0.95f; + bg += glow * 0.72f; + bb += glow * 0.38f; + } + + // 大气边缘散射 + var rim = 1f - nz; + rim *= rim; + var litRim = rim * MathF.Max(0f, lam) * 0.98f; + br += 0.30f * litRim; + bg += 0.55f * litRim; + bb += 1.00f * litRim; + + // 夜面极淡反照 + var nightSide = 1f - day; + br += 0.008f * nightSide; + bg += 0.013f * nightSide; + bb += 0.028f * nightSide; + + var coverage = 1f; + var edge = (1f - MathF.Sqrt(r2)) * radius; + if (edge < 1f) coverage = MathF.Max(0f, edge); + + var a = (uint)(coverage * 255f); + var r8 = (uint)(Math.Clamp(br, 0f, 1f) * 255f * coverage); + var g8 = (uint)(Math.Clamp(bg, 0f, 1f) * 255f * coverage); + var b8 = (uint)(Math.Clamp(bb, 0f, 1f) * 255f * coverage); + row[x] = (a << 24) | (r8 << 16) | (g8 << 8) | b8; + } + }); + } + + private static float Smooth(float edge0, float edge1, float x) + { + if (edge1 <= edge0) return x >= edge1 ? 1f : 0f; + var t = Math.Clamp((x - edge0) / (edge1 - edge0), 0f, 1f); + return t * t * (3f - 2f * t); + } +} diff --git a/model/_sdk/EarthModelStudio.ModelSdk/EarthModelStudio.ModelSdk.csproj b/model/_sdk/EarthModelStudio.ModelSdk/EarthModelStudio.ModelSdk.csproj new file mode 100644 index 0000000..6905f6a --- /dev/null +++ b/model/_sdk/EarthModelStudio.ModelSdk/EarthModelStudio.ModelSdk.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + disable + EarthModelStudio.ModelSdk + EarthModelStudio.ModelSdk + false + Earth Model 模型契约:启动器与模型之间唯一的编译期依赖。 + + + + + + + diff --git a/model/_sdk/EarthModelStudio.ModelSdk/IModelContracts.cs b/model/_sdk/EarthModelStudio.ModelSdk/IModelContracts.cs new file mode 100644 index 0000000..73039a8 --- /dev/null +++ b/model/_sdk/EarthModelStudio.ModelSdk/IModelContracts.cs @@ -0,0 +1,68 @@ +using System; +using Avalonia.Controls; + +namespace EarthModelStudio.ModelSdk; + +/// +/// 模型入口契约。模型程序集里必须有一个公开、无参构造的 实现, +/// 启动器按模型清单里的 assembly + type 定位并创建它。 +/// +public interface IModelFactory +{ + /// 契约版本。启动器目前支持 1。 + int ApiVersion { get; } + + /// 创建一个模型运行时实例(每个窗口一个实例)。 + IModelRuntime Create(); +} + +/// +/// 模型运行时:负责把模型自己的界面交给启动器。 +/// 启动器只负责开窗口,**不参与任何渲染**。 +/// +public interface IModelRuntime : IDisposable +{ + /// + /// 在**后台线程**准备数据(读文件、算纹理等),期间禁止创建或操作任何 UI 控件。 + /// 启动器的进度窗会显示 汇报的进度。 + /// 默认空实现:模型也可以把准备工作留到 CreateView 里(那样会占用 UI 线程)。 + /// + void Prepare(IModelContext context) { } + + /// + /// 在 UI 线程创建模型窗口的内容。模型可以自由组合控件、自己画图、自己管动画。 + /// 返回的控件会被直接放进窗口,铺满客户区。 + /// + Control CreateView(IModelContext context); +} + +/// 启动器提供给模型的环境信息与能力。 +public interface IModelContext +{ + /// 模型 id(即模型目录名)。 + string ModelId { get; } + + /// 模型目录:model/<id>。 + string ModelDirectory { get; } + + /// 模型数据目录:model/<id>/<id>.model,模型自己的场景数据、贴图、语言包都放这里。 + string DataDirectory { get; } + + /// 界面语言(zh-CN / en)。模型应按它选择自己的文案。 + string Language { get; } + + /// 用户在设置里分配的运行内存预算(MB),模型可据此控制缓存规模。 + int MemoryBudgetMb { get; } + + /// 请求关闭承载此模型的窗口。 + void RequestClose(); + + /// + /// 汇报加载进度(0–1)与当前阶段文案。启动器的加载进度条会实时显示, + /// 也可以在任何时候调用(例如切换数据集时)。 + /// + void ReportProgress(double value, string? message = null); + + /// 输出日志(启动器会写到控制台)。 + void Log(string message); +} diff --git a/model/earth-revolution/earth-revolution.json b/model/earth-revolution/earth-revolution.json new file mode 100644 index 0000000..b35a7cc --- /dev/null +++ b/model/earth-revolution/earth-revolution.json @@ -0,0 +1,28 @@ +{ + "schemaVersion": 1, + "id": "earth-revolution", + "name": "Earth Revolution", + "nameI18n": { + "zh-CN": "地球公转", + "en": "Earth Revolution" + }, + "version": "1.0.0", + "author": "NeoRF", + "description": "四季更替、黄赤交角与二分二至", + "descriptionI18n": { + "zh-CN": "地球绕太阳公转一年:地轴指向不变,太阳直射点南北往返,形成四季。", + "en": "One year around the Sun: the fixed axial direction moves the subsolar point and creates the seasons." + }, + "tags": [ + "astronomy", + "geography", + "revolution" + ], + "entry": "scene.json", + "license": "MIT", + "updatedAt": "2026-11-07", + "assembly": "EarthRevolutionModel.dll", + "type": "NeoRF.EarthModels.RevolutionModelFactory", + "preview": "preview.png", + "apiVersion": 1 +} diff --git a/model/earth-revolution/earth-revolution.model/EarthRevolutionModel.dll b/model/earth-revolution/earth-revolution.model/EarthRevolutionModel.dll new file mode 100644 index 0000000..9b3e6b4 Binary files /dev/null and b/model/earth-revolution/earth-revolution.model/EarthRevolutionModel.dll differ diff --git a/model/earth-revolution/earth-revolution.model/i18n/en.json b/model/earth-revolution/earth-revolution.model/i18n/en.json new file mode 100644 index 0000000..145bcb0 --- /dev/null +++ b/model/earth-revolution/earth-revolution.model/i18n/en.json @@ -0,0 +1,33 @@ +{ + "title": "Earth Revolution", + "view.rotation": "Rotation", + "view.revolution": "Revolution", + "play": "Play", + "pause": "Pause", + "speed": "Speed", + "reset": "Reset", + "labels": "Labels", + "orbit": "Orbit", + "grid": "Graticule", + "tilt": "Exaggerate tilt", + "lessons": "Teaching notes", + "seasons": "Solstices & equinoxes", + "close": "Close window", + "loading": "Preparing scene…", + "subsolar": "Subsolar point", + "north": "North pole", + "south": "South pole", + "northShort": "N", + "southShort": "S", + "sun": "Sun", + "earth": "Earth", + "spinInfo": "Rotation {0}° · period {1} h", + "orbitInfo": "Orbit {0}°", + "declinationInfo": "Subsolar {0}", + "dateInfo": "Date {0}", + "season.springEquinox": "Spring equinox", + "season.summerSolstice": "Summer solstice", + "season.autumnEquinox": "Autumn equinox", + "season.winterSolstice": "Winter solstice", + "hint": "Pinch or scroll to zoom · drag to turn the Earth" +} \ No newline at end of file diff --git a/model/earth-revolution/earth-revolution.model/i18n/zh-CN.json b/model/earth-revolution/earth-revolution.model/i18n/zh-CN.json new file mode 100644 index 0000000..b6817af --- /dev/null +++ b/model/earth-revolution/earth-revolution.model/i18n/zh-CN.json @@ -0,0 +1,33 @@ +{ + "title": "地球自转", + "view.rotation": "自转", + "view.revolution": "公转", + "play": "播放", + "pause": "暂停", + "speed": "速度", + "reset": "重置", + "labels": "标注", + "orbit": "轨道", + "grid": "经纬网", + "tilt": "夸张倾角", + "lessons": "教学要点", + "seasons": "节气定位", + "close": "关闭窗口", + "loading": "正在准备场景…", + "subsolar": "太阳直射点", + "north": "北极", + "south": "南极", + "northShort": "N", + "southShort": "S", + "sun": "太阳", + "earth": "地球", + "spinInfo": "自转 {0}° · 周期 {1} 小时", + "orbitInfo": "公转 {0}°", + "declinationInfo": "太阳直射 {0}", + "dateInfo": "日期 {0}", + "season.springEquinox": "春分", + "season.summerSolstice": "夏至", + "season.autumnEquinox": "秋分", + "season.winterSolstice": "冬至", + "hint": "双指捏合或滚轮缩放 · 拖动可转动地球" +} \ No newline at end of file diff --git a/model/earth-revolution/earth-revolution.model/land.json b/model/earth-revolution/earth-revolution.model/land.json new file mode 100644 index 0000000..972210e --- /dev/null +++ b/model/earth-revolution/earth-revolution.model/land.json @@ -0,0 +1,98 @@ +{ + "schema": 1, + "note": "简化大陆轮廓(经度,纬度),用于教学演示,非测绘精度", + "polygons": [ + { + "name": "north-america", + "points": [[-168,66],[-164,70],[-155,71],[-145,70],[-133,69],[-120,69],[-110,68],[-100,69],[-92,68],[-85,70],[-80,73],[-72,71],[-64,66],[-60,60],[-56,52],[-60,47],[-66,45],[-70,42],[-74,40],[-76,35],[-81,31],[-80,25],[-83,29],[-88,30],[-94,29],[-97,26],[-97,21],[-92,19],[-87,21],[-88,16],[-83,9],[-78,9],[-84,14],[-90,14],[-96,16],[-105,20],[-112,25],[-117,32],[-122,37],[-124,42],[-125,48],[-131,54],[-140,59],[-150,59],[-158,56],[-165,60],[-166,64]] + }, + { + "name": "greenland", + "points": [[-45,60],[-52,64],[-55,68],[-60,72],[-63,76],[-56,80],[-42,82],[-28,80],[-21,74],[-23,70],[-31,66],[-38,62]] + }, + { + "name": "south-america", + "points": [[-78,8],[-72,11],[-64,10],[-60,8],[-52,5],[-50,0],[-44,-2],[-38,-5],[-35,-8],[-39,-13],[-41,-22],[-48,-25],[-53,-34],[-57,-38],[-62,-40],[-65,-45],[-68,-50],[-70,-55],[-75,-52],[-74,-45],[-73,-37],[-71,-30],[-70,-23],[-70,-18],[-76,-14],[-81,-6],[-80,-2],[-79,2],[-77,6]] + }, + { + "name": "africa", + "points": [[-17,15],[-16,20],[-13,28],[-9,32],[-5,36],[10,37],[20,32],[32,31],[35,28],[39,15],[43,11],[51,12],[48,2],[41,-2],[40,-10],[35,-18],[32,-25],[27,-33],[20,-35],[15,-28],[12,-17],[9,-1],[5,4],[-4,5],[-8,4],[-13,8],[-16,12]] + }, + { + "name": "europe", + "points": [[-9,38],[-9,43],[-2,44],[0,48],[2,51],[5,53],[8,54],[9,57],[12,56],[13,54],[20,54],[21,57],[24,58],[28,60],[30,60],[29,64],[25,66],[22,69],[30,70],[40,68],[46,66],[55,68],[60,70],[68,68],[62,62],[58,56],[52,50],[48,46],[40,45],[36,44],[30,45],[28,41],[24,40],[23,37],[19,40],[16,41],[12,44],[7,44],[3,42],[-2,37]] + }, + { + "name": "asia", + "points": [[60,70],[75,73],[90,75],[105,77],[115,74],[130,73],[145,72],[160,70],[170,68],[180,65],[172,62],[163,58],[155,52],[143,54],[137,50],[130,43],[126,40],[122,40],[120,36],[122,31],[118,25],[110,21],[105,10],[100,13],[98,8],[95,17],[90,22],[88,21],[80,16],[77,8],[73,18],[68,23],[62,25],[57,24],[52,28],[48,30],[44,13],[43,17],[39,21],[35,28],[34,31],[36,36],[30,41],[28,41],[30,45],[34,45],[40,45],[48,46],[52,50],[58,56],[62,62],[68,68]] + }, + { + "name": "australia", + "points": [[113,-22],[114,-27],[116,-35],[129,-32],[138,-35],[146,-39],[150,-37],[153,-28],[146,-19],[142,-11],[132,-11],[126,-14],[122,-18]] + }, + { + "name": "antarctica", + "points": [[-180,-72],[-150,-76],[-120,-74],[-90,-73],[-60,-64],[-30,-70],[0,-70],[30,-69],[60,-67],[90,-66],[120,-66],[150,-70],[180,-72],[180,-90],[-180,-90]] + }, + { + "name": "madagascar", + "points": [[43,-12],[50,-15],[50,-25],[45,-25],[43,-20]] + }, + { + "name": "japan", + "points": [[130,32],[136,35],[141,40],[145,44],[142,39],[137,34],[133,33]] + }, + { + "name": "britain", + "points": [[-6,50],[-2,53],[-2,58],[-5,58],[-6,54]] + }, + { + "name": "ireland", + "points": [[-10,52],[-6,53],[-6,55],[-10,55]] + }, + { + "name": "iceland", + "points": [[-24,65],[-14,66],[-14,64],[-22,63]] + }, + { + "name": "new-zealand", + "points": [[166,-46],[170,-44],[174,-41],[177,-38],[174,-35],[170,-38],[167,-42]] + }, + { + "name": "sumatra", + "points": [[95,5],[100,1],[105,-6],[100,-4],[96,2]] + }, + { + "name": "java", + "points": [[105,-6],[114,-8],[114,-9],[106,-7]] + }, + { + "name": "borneo", + "points": [[109,2],[117,4],[119,-2],[115,-4],[110,-2]] + }, + { + "name": "sulawesi", + "points": [[119,1],[125,1],[123,-5],[120,-3]] + }, + { + "name": "new-guinea", + "points": [[131,-1],[141,-3],[150,-6],[147,-9],[140,-9],[134,-5]] + }, + { + "name": "sri-lanka", + "points": [[80,9],[82,7],[81,6],[79,7]] + }, + { + "name": "philippines", + "points": [[120,18],[124,13],[126,8],[122,6],[120,12]] + }, + { + "name": "cuba", + "points": [[-85,22],[-77,20],[-74,20],[-80,23]] + }, + { + "name": "taiwan", + "points": [[120,25],[122,24],[121,22],[120,23]] + } + ] +} diff --git a/model/earth-revolution/earth-revolution.model/preview.png b/model/earth-revolution/earth-revolution.model/preview.png new file mode 100644 index 0000000..2fef741 Binary files /dev/null and b/model/earth-revolution/earth-revolution.model/preview.png differ diff --git a/model/earth-revolution/earth-revolution.model/scene.json b/model/earth-revolution/earth-revolution.model/scene.json new file mode 100644 index 0000000..d51ff40 --- /dev/null +++ b/model/earth-revolution/earth-revolution.model/scene.json @@ -0,0 +1,138 @@ +{ + "schemaVersion": 1, + "type": "planet", + "defaultView": "revolution", + "views": [ + "revolution" + ], + "nameI18n": { + "zh-CN": "地球公转", + "en": "Earth Revolution" + }, + "descriptionI18n": { + "zh-CN": "地球绕太阳公转一年:地轴指向不变,太阳直射点南北往返,形成四季。", + "en": "One year around the Sun: the fixed axial direction moves the subsolar point and creates the seasons." + }, + "star": { + "name": "Sun", + "nameI18n": { + "zh-CN": "太阳", + "en": "Sun" + }, + "color": "#FFC24B", + "radiusScale": 0.5 + }, + "planet": { + "name": "Earth", + "nameI18n": { + "zh-CN": "地球", + "en": "Earth" + }, + "axialTiltDeg": 23.5, + "tropicDeg": 23.5, + "rotationHours": 23.93, + "orbitDays": 365.26, + "oceanColor": "#1C5FA8", + "landColor": "#4E8C4C", + "iceColor": "#E9EFF6", + "landFile": "land.json", + "showGraticule": false + }, + "orbit": { + "semiMajorAxis": 4.0, + "eccentricity": 0.0167, + "show": true, + "seasons": [ + { + "angleDeg": 0, + "key": "season.springEquinox", + "date": "3/21", + "declinationDeg": 0, + "teachingI18n": { + "zh-CN": "太阳直射赤道,全球昼夜平分。此后直射点由赤道向北移动。", + "en": "The Sun is overhead at the equator and day equals night everywhere. The subsolar point now moves north." + } + }, + { + "angleDeg": 90, + "key": "season.summerSolstice", + "date": "6/22", + "declinationDeg": 23.5, + "teachingI18n": { + "zh-CN": "太阳直射北回归线 23.5°N。北半球昼最长、夜最短,北极圈内出现极昼。", + "en": "The Sun is overhead at the Tropic of Cancer (23.5°N). The northern hemisphere has its longest day." + } + }, + { + "angleDeg": 180, + "key": "season.autumnEquinox", + "date": "9/23", + "declinationDeg": 0, + "teachingI18n": { + "zh-CN": "太阳再次直射赤道,全球昼夜平分。此后直射点向南移动。", + "en": "The Sun is overhead at the equator again. The subsolar point now moves south." + } + }, + { + "angleDeg": 270, + "key": "season.winterSolstice", + "date": "12/22", + "declinationDeg": -23.5, + "teachingI18n": { + "zh-CN": "太阳直射南回归线 23.5°S。北半球昼最短、夜最长,北极圈内出现极夜。", + "en": "The Sun is overhead at the Tropic of Capricorn (23.5°S). The northern hemisphere has its shortest day." + } + } + ] + }, + "lessons": [ + { + "titleI18n": { + "zh-CN": "一年绕太阳一圈", + "en": "One lap per year" + }, + "bodyI18n": { + "zh-CN": "公转方向与自转相同,周期约 365.26 天;轨道接近圆形。", + "en": "The orbit takes about 365.26 days and runs the same direction as the spin." + }, + "view": "revolution", + "angleDeg": 0 + }, + { + "titleI18n": { + "zh-CN": "地轴指向不变", + "en": "The axis keeps its direction" + }, + "bodyI18n": { + "zh-CN": "公转过程中地轴始终指向北极星附近,黄赤交角 23.5° 保持不变。", + "en": "During the whole orbit the axis keeps pointing near Polaris, so the 23.5° tilt stays fixed in space." + }, + "view": "revolution", + "angleDeg": 90 + }, + { + "titleI18n": { + "zh-CN": "夏至与冬至", + "en": "Solstices" + }, + "bodyI18n": { + "zh-CN": "夏至太阳直射北回归线 23.5°N,北半球昼最长;冬至直射南回归线 23.5°S。", + "en": "At the June solstice the Sun is overhead at 23.5°N; at the December solstice at 23.5°S." + }, + "view": "revolution", + "angleDeg": 90 + }, + { + "titleI18n": { + "zh-CN": "春分与秋分", + "en": "Equinoxes" + }, + "bodyI18n": { + "zh-CN": "春分、秋分太阳直射赤道,全球昼夜平分,是四季的转折点。", + "en": "At the equinoxes the Sun is overhead at the equator and day equals night everywhere." + }, + "view": "revolution", + "angleDeg": 180 + } + ] +} diff --git a/model/earth-revolution/src/EarthRevolutionModel.csproj b/model/earth-revolution/src/EarthRevolutionModel.csproj new file mode 100644 index 0000000..ced296f --- /dev/null +++ b/model/earth-revolution/src/EarthRevolutionModel.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + disable + NeoRF.EarthModels + EarthRevolutionModel + true + false + + + + + + + + + + + + + + false + + + + diff --git a/model/earth-revolution/src/RevolutionModelFactory.cs b/model/earth-revolution/src/RevolutionModelFactory.cs new file mode 100644 index 0000000..ea0da18 --- /dev/null +++ b/model/earth-revolution/src/RevolutionModelFactory.cs @@ -0,0 +1,11 @@ +using EarthModelStudio.ModelSdk; + +namespace NeoRF.EarthModels; + +/// 地球公转模型入口(清单里的 type 指向这里)。 +public sealed class RevolutionModelFactory : IModelFactory +{ + public int ApiVersion => EarthModelRuntime.SupportedApiVersion; + + public IModelRuntime Create() => new EarthModelRuntime(); +} diff --git a/model/earth-rotation/earth-rotation.json b/model/earth-rotation/earth-rotation.json new file mode 100644 index 0000000..fd9fa53 --- /dev/null +++ b/model/earth-rotation/earth-rotation.json @@ -0,0 +1,28 @@ +{ + "schemaVersion": 1, + "id": "earth-rotation", + "name": "Earth Rotation", + "nameI18n": { + "zh-CN": "地球自转", + "en": "Earth Rotation" + }, + "version": "1.0.0", + "author": "NeoRF", + "description": "昼夜交替、晨昏线与太阳直射点", + "descriptionI18n": { + "zh-CN": "观察自转中的地球:昼夜半球、晨昏线与太阳直射点位置。", + "en": "Watch a rotating Earth: day/night hemispheres, terminator and the subsolar point." + }, + "tags": [ + "astronomy", + "geography", + "rotation" + ], + "entry": "scene.json", + "license": "MIT", + "updatedAt": "2026-11-07", + "assembly": "EarthRotationModel.dll", + "type": "NeoRF.EarthModels.RotationModelFactory", + "preview": "preview.png", + "apiVersion": 1 +} diff --git a/model/earth-rotation/earth-rotation.model/EarthRotationModel.dll b/model/earth-rotation/earth-rotation.model/EarthRotationModel.dll new file mode 100644 index 0000000..6b66d9b Binary files /dev/null and b/model/earth-rotation/earth-rotation.model/EarthRotationModel.dll differ diff --git a/model/earth-rotation/earth-rotation.model/i18n/en.json b/model/earth-rotation/earth-rotation.model/i18n/en.json new file mode 100644 index 0000000..536b37a --- /dev/null +++ b/model/earth-rotation/earth-rotation.model/i18n/en.json @@ -0,0 +1,33 @@ +{ + "title": "Earth Rotation", + "view.rotation": "Rotation", + "view.revolution": "Revolution", + "play": "Play", + "pause": "Pause", + "speed": "Speed", + "reset": "Reset", + "labels": "Labels", + "orbit": "Orbit", + "grid": "Graticule", + "tilt": "Exaggerate tilt", + "lessons": "Teaching notes", + "seasons": "Solstices & equinoxes", + "close": "Close window", + "loading": "Preparing scene…", + "subsolar": "Subsolar point", + "north": "North pole", + "south": "South pole", + "northShort": "N", + "southShort": "S", + "sun": "Sun", + "earth": "Earth", + "spinInfo": "Rotation {0}° · period {1} h", + "orbitInfo": "Orbit {0}°", + "declinationInfo": "Subsolar {0}", + "dateInfo": "Date {0}", + "season.springEquinox": "Spring equinox", + "season.summerSolstice": "Summer solstice", + "season.autumnEquinox": "Autumn equinox", + "season.winterSolstice": "Winter solstice", + "hint": "Pinch or scroll to zoom · drag to turn the Earth" +} \ No newline at end of file diff --git a/model/earth-rotation/earth-rotation.model/i18n/zh-CN.json b/model/earth-rotation/earth-rotation.model/i18n/zh-CN.json new file mode 100644 index 0000000..b6817af --- /dev/null +++ b/model/earth-rotation/earth-rotation.model/i18n/zh-CN.json @@ -0,0 +1,33 @@ +{ + "title": "地球自转", + "view.rotation": "自转", + "view.revolution": "公转", + "play": "播放", + "pause": "暂停", + "speed": "速度", + "reset": "重置", + "labels": "标注", + "orbit": "轨道", + "grid": "经纬网", + "tilt": "夸张倾角", + "lessons": "教学要点", + "seasons": "节气定位", + "close": "关闭窗口", + "loading": "正在准备场景…", + "subsolar": "太阳直射点", + "north": "北极", + "south": "南极", + "northShort": "N", + "southShort": "S", + "sun": "太阳", + "earth": "地球", + "spinInfo": "自转 {0}° · 周期 {1} 小时", + "orbitInfo": "公转 {0}°", + "declinationInfo": "太阳直射 {0}", + "dateInfo": "日期 {0}", + "season.springEquinox": "春分", + "season.summerSolstice": "夏至", + "season.autumnEquinox": "秋分", + "season.winterSolstice": "冬至", + "hint": "双指捏合或滚轮缩放 · 拖动可转动地球" +} \ No newline at end of file diff --git a/model/earth-rotation/earth-rotation.model/land.json b/model/earth-rotation/earth-rotation.model/land.json new file mode 100644 index 0000000..972210e --- /dev/null +++ b/model/earth-rotation/earth-rotation.model/land.json @@ -0,0 +1,98 @@ +{ + "schema": 1, + "note": "简化大陆轮廓(经度,纬度),用于教学演示,非测绘精度", + "polygons": [ + { + "name": "north-america", + "points": [[-168,66],[-164,70],[-155,71],[-145,70],[-133,69],[-120,69],[-110,68],[-100,69],[-92,68],[-85,70],[-80,73],[-72,71],[-64,66],[-60,60],[-56,52],[-60,47],[-66,45],[-70,42],[-74,40],[-76,35],[-81,31],[-80,25],[-83,29],[-88,30],[-94,29],[-97,26],[-97,21],[-92,19],[-87,21],[-88,16],[-83,9],[-78,9],[-84,14],[-90,14],[-96,16],[-105,20],[-112,25],[-117,32],[-122,37],[-124,42],[-125,48],[-131,54],[-140,59],[-150,59],[-158,56],[-165,60],[-166,64]] + }, + { + "name": "greenland", + "points": [[-45,60],[-52,64],[-55,68],[-60,72],[-63,76],[-56,80],[-42,82],[-28,80],[-21,74],[-23,70],[-31,66],[-38,62]] + }, + { + "name": "south-america", + "points": [[-78,8],[-72,11],[-64,10],[-60,8],[-52,5],[-50,0],[-44,-2],[-38,-5],[-35,-8],[-39,-13],[-41,-22],[-48,-25],[-53,-34],[-57,-38],[-62,-40],[-65,-45],[-68,-50],[-70,-55],[-75,-52],[-74,-45],[-73,-37],[-71,-30],[-70,-23],[-70,-18],[-76,-14],[-81,-6],[-80,-2],[-79,2],[-77,6]] + }, + { + "name": "africa", + "points": [[-17,15],[-16,20],[-13,28],[-9,32],[-5,36],[10,37],[20,32],[32,31],[35,28],[39,15],[43,11],[51,12],[48,2],[41,-2],[40,-10],[35,-18],[32,-25],[27,-33],[20,-35],[15,-28],[12,-17],[9,-1],[5,4],[-4,5],[-8,4],[-13,8],[-16,12]] + }, + { + "name": "europe", + "points": [[-9,38],[-9,43],[-2,44],[0,48],[2,51],[5,53],[8,54],[9,57],[12,56],[13,54],[20,54],[21,57],[24,58],[28,60],[30,60],[29,64],[25,66],[22,69],[30,70],[40,68],[46,66],[55,68],[60,70],[68,68],[62,62],[58,56],[52,50],[48,46],[40,45],[36,44],[30,45],[28,41],[24,40],[23,37],[19,40],[16,41],[12,44],[7,44],[3,42],[-2,37]] + }, + { + "name": "asia", + "points": [[60,70],[75,73],[90,75],[105,77],[115,74],[130,73],[145,72],[160,70],[170,68],[180,65],[172,62],[163,58],[155,52],[143,54],[137,50],[130,43],[126,40],[122,40],[120,36],[122,31],[118,25],[110,21],[105,10],[100,13],[98,8],[95,17],[90,22],[88,21],[80,16],[77,8],[73,18],[68,23],[62,25],[57,24],[52,28],[48,30],[44,13],[43,17],[39,21],[35,28],[34,31],[36,36],[30,41],[28,41],[30,45],[34,45],[40,45],[48,46],[52,50],[58,56],[62,62],[68,68]] + }, + { + "name": "australia", + "points": [[113,-22],[114,-27],[116,-35],[129,-32],[138,-35],[146,-39],[150,-37],[153,-28],[146,-19],[142,-11],[132,-11],[126,-14],[122,-18]] + }, + { + "name": "antarctica", + "points": [[-180,-72],[-150,-76],[-120,-74],[-90,-73],[-60,-64],[-30,-70],[0,-70],[30,-69],[60,-67],[90,-66],[120,-66],[150,-70],[180,-72],[180,-90],[-180,-90]] + }, + { + "name": "madagascar", + "points": [[43,-12],[50,-15],[50,-25],[45,-25],[43,-20]] + }, + { + "name": "japan", + "points": [[130,32],[136,35],[141,40],[145,44],[142,39],[137,34],[133,33]] + }, + { + "name": "britain", + "points": [[-6,50],[-2,53],[-2,58],[-5,58],[-6,54]] + }, + { + "name": "ireland", + "points": [[-10,52],[-6,53],[-6,55],[-10,55]] + }, + { + "name": "iceland", + "points": [[-24,65],[-14,66],[-14,64],[-22,63]] + }, + { + "name": "new-zealand", + "points": [[166,-46],[170,-44],[174,-41],[177,-38],[174,-35],[170,-38],[167,-42]] + }, + { + "name": "sumatra", + "points": [[95,5],[100,1],[105,-6],[100,-4],[96,2]] + }, + { + "name": "java", + "points": [[105,-6],[114,-8],[114,-9],[106,-7]] + }, + { + "name": "borneo", + "points": [[109,2],[117,4],[119,-2],[115,-4],[110,-2]] + }, + { + "name": "sulawesi", + "points": [[119,1],[125,1],[123,-5],[120,-3]] + }, + { + "name": "new-guinea", + "points": [[131,-1],[141,-3],[150,-6],[147,-9],[140,-9],[134,-5]] + }, + { + "name": "sri-lanka", + "points": [[80,9],[82,7],[81,6],[79,7]] + }, + { + "name": "philippines", + "points": [[120,18],[124,13],[126,8],[122,6],[120,12]] + }, + { + "name": "cuba", + "points": [[-85,22],[-77,20],[-74,20],[-80,23]] + }, + { + "name": "taiwan", + "points": [[120,25],[122,24],[121,22],[120,23]] + } + ] +} diff --git a/model/earth-rotation/earth-rotation.model/preview.png b/model/earth-rotation/earth-rotation.model/preview.png new file mode 100644 index 0000000..bcc0438 Binary files /dev/null and b/model/earth-rotation/earth-rotation.model/preview.png differ diff --git a/model/earth-rotation/earth-rotation.model/scene.json b/model/earth-rotation/earth-rotation.model/scene.json new file mode 100644 index 0000000..fdb7a89 --- /dev/null +++ b/model/earth-rotation/earth-rotation.model/scene.json @@ -0,0 +1,138 @@ +{ + "schemaVersion": 1, + "type": "planet", + "defaultView": "rotation", + "views": [ + "rotation" + ], + "nameI18n": { + "zh-CN": "地球自转", + "en": "Earth Rotation" + }, + "descriptionI18n": { + "zh-CN": "观察自转中的地球:昼夜半球、晨昏线与太阳直射点位置。", + "en": "Watch a rotating Earth: day/night hemispheres, terminator and the subsolar point." + }, + "star": { + "name": "Sun", + "nameI18n": { + "zh-CN": "太阳", + "en": "Sun" + }, + "color": "#FFC24B", + "radiusScale": 0.5 + }, + "planet": { + "name": "Earth", + "nameI18n": { + "zh-CN": "地球", + "en": "Earth" + }, + "axialTiltDeg": 23.5, + "tropicDeg": 23.5, + "rotationHours": 23.93, + "orbitDays": 365.26, + "oceanColor": "#1C5FA8", + "landColor": "#4E8C4C", + "iceColor": "#E9EFF6", + "landFile": "land.json", + "showGraticule": true + }, + "orbit": { + "semiMajorAxis": 4.0, + "eccentricity": 0.0167, + "show": true, + "seasons": [ + { + "angleDeg": 0, + "key": "season.springEquinox", + "date": "3/21", + "declinationDeg": 0, + "teachingI18n": { + "zh-CN": "太阳直射赤道,全球昼夜平分。", + "en": "The Sun is overhead at the equator and day equals night everywhere." + } + }, + { + "angleDeg": 90, + "key": "season.summerSolstice", + "date": "6/22", + "declinationDeg": 23.5, + "teachingI18n": { + "zh-CN": "太阳直射北回归线 23.5°N,北半球昼最长。", + "en": "The Sun is overhead at 23.5°N; the northern hemisphere has its longest day." + } + }, + { + "angleDeg": 180, + "key": "season.autumnEquinox", + "date": "9/23", + "declinationDeg": 0, + "teachingI18n": { + "zh-CN": "太阳直射赤道,全球昼夜平分。", + "en": "The Sun is overhead at the equator and day equals night everywhere." + } + }, + { + "angleDeg": 270, + "key": "season.winterSolstice", + "date": "12/22", + "declinationDeg": -23.5, + "teachingI18n": { + "zh-CN": "太阳直射南回归线 23.5°S,北半球昼最短。", + "en": "The Sun is overhead at 23.5°S; the northern hemisphere has its shortest day." + } + } + ] + }, + "lessons": [ + { + "titleI18n": { + "zh-CN": "自西向东的自转", + "en": "Rotation from west to east" + }, + "bodyI18n": { + "zh-CN": "从北极上空看,地球逆时针转动;转一圈用 23 小时 56 分 4 秒。", + "en": "Seen from above the north pole the Earth turns counter-clockwise, once every 23 h 56 min." + }, + "view": "rotation", + "angleDeg": 0 + }, + { + "titleI18n": { + "zh-CN": "昼夜交替", + "en": "Day and night" + }, + "bodyI18n": { + "zh-CN": "晨昏线(白色虚线)把地球分成昼半球与夜半球,交替周期 24 小时。", + "en": "The terminator (white dashes) splits the lit and dark hemispheres; one cycle takes 24 h." + }, + "view": "rotation", + "angleDeg": 60 + }, + { + "titleI18n": { + "zh-CN": "太阳直射点", + "en": "Subsolar point" + }, + "bodyI18n": { + "zh-CN": "黄色圆环标出太阳光垂直照射的位置,它随季节在南北回归线之间往返。", + "en": "The yellow ring marks where sunlight strikes vertically — it drifts between the tropics over a year." + }, + "view": "rotation", + "angleDeg": 120 + }, + { + "titleI18n": { + "zh-CN": "地轴倾斜 23.5°", + "en": "Axial tilt 23.5°" + }, + "bodyI18n": { + "zh-CN": "地轴与黄道面法线成 23.5°,倾斜方向不变,这是四季与五带划分的根本原因。", + "en": "The axis is tilted 23.5° from the ecliptic normal and keeps its direction — the root cause of seasons." + }, + "view": "rotation", + "angleDeg": 200 + } + ] +} diff --git a/model/earth-rotation/src/EarthRotationModel.csproj b/model/earth-rotation/src/EarthRotationModel.csproj new file mode 100644 index 0000000..5a9d098 --- /dev/null +++ b/model/earth-rotation/src/EarthRotationModel.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + disable + NeoRF.EarthModels + EarthRotationModel + true + false + + + + + + + + + + + + + + false + + + + diff --git a/model/earth-rotation/src/RotationModelFactory.cs b/model/earth-rotation/src/RotationModelFactory.cs new file mode 100644 index 0000000..764eab5 --- /dev/null +++ b/model/earth-rotation/src/RotationModelFactory.cs @@ -0,0 +1,11 @@ +using EarthModelStudio.ModelSdk; + +namespace NeoRF.EarthModels; + +/// 地球自转模型入口(清单里的 type 指向这里)。 +public sealed class RotationModelFactory : IModelFactory +{ + public int ApiVersion => EarthModelRuntime.SupportedApiVersion; + + public IModelRuntime Create() => new EarthModelRuntime(); +} diff --git a/src/main/dotnet/EarthModelStudio/App.axaml b/src/main/dotnet/EarthModelStudio/App.axaml new file mode 100644 index 0000000..cec4f40 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/App.axaml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + #2F6BFF + + + + + + + diff --git a/src/main/dotnet/EarthModelStudio/App.axaml.cs b/src/main/dotnet/EarthModelStudio/App.axaml.cs new file mode 100644 index 0000000..b45c9c1 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/App.axaml.cs @@ -0,0 +1,70 @@ +using System; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using EarthModelStudio.Services; +using EarthModelStudio.ViewModels; +using EarthModelStudio.Views; + +namespace EarthModelStudio; + +public partial class App : Application +{ + public override void Initialize() => AvaloniaXamlLoader.Load(this); + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + var services = AppServices.Create(); + + // 诊断模式:只验证模型程序集能否加载(发布包里也用它做冒烟测试) + if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") + { + var code = SelfTest(services); + Avalonia.Threading.Dispatcher.UIThread.Post( + () => desktop.Shutdown(code), Avalonia.Threading.DispatcherPriority.Background); + return; + } + + var vm = new MainViewModel(services); + var window = new MainWindow { DataContext = vm }; + + vm.ConfirmHandler = async message => + { + var dialog = new ConfirmWindow(message); + return await dialog.ShowDialog(window); + }; + + desktop.MainWindow = window; + desktop.ShutdownMode = ShutdownMode.OnMainWindowClose; + } + + base.OnFrameworkInitializationCompleted(); + } + + /// 逐个加载模型,打印结果;返回退出码(0 = 全部成功)。 + private static int SelfTest(AppServices services) + { + var packages = services.Models.Scan(); + Console.WriteLine($"模型库: {services.Paths.ModelRoot}"); + Console.WriteLine($"模型数: {packages.Count}"); + var failed = 0; + foreach (var package in packages) + { + try + { + using var loaded = services.ModelHost.Load(package, () => { }); + Console.WriteLine($"OK {package.Id} -> {loaded.View.GetType().FullName}"); + } + catch (Exception ex) + { + failed++; + Console.WriteLine($"FAIL {package.Id}: {ex.Message}"); + } + } + return failed == 0 ? 0 : 1; + } +} diff --git a/src/main/dotnet/EarthModelStudio/Assets/i18n/en.json b/src/main/dotnet/EarthModelStudio/Assets/i18n/en.json new file mode 100644 index 0000000..1ced838 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Assets/i18n/en.json @@ -0,0 +1,139 @@ +{ + "app.name": "Earth Model Studio", + "app.tagline": "Astronomy teaching models · visual launcher", + "app.version": "Version", + "app.platform": "Platform", + "nav.home": "Home", + "nav.download": "Download", + "nav.settings": "Settings", + "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", + "home.download": "Get models", + "home.settings": "Settings", + "home.installed": "Installed models", + "home.count": "{0} models", + "home.empty": "No models yet", + "home.emptyHint": "Import a model source on the Download page, or drop a model folder into model/.", + "home.emptyAction": "Get models", + "home.open": "Open folder", + "home.delete": "Delete", + "home.deleteConfirm": "Delete the model \"{0}\"? Its files will be removed from the local library.", + "home.size": "Size", + "home.stats.models": "Installed", + "home.stats.sources": "Sources", + "home.stats.memory": "Memory budget", + "home.recent": "Select a model, then press Launch", + "home.getMore": "Get more models", + "home.launchHint": "Models open in their own window with play/pause, view controls and teaching notes.", + "dl.title": "Download", + "dl.subtitle": "Import a model source: git repository, zip archive or local folder. The model/ folder in the repo is the model list.", + "dl.import": "Import source", + "dl.importPlaceholder": "https://github.com/user/repo.git or /path/to/model-repo", + "dl.sources": "Sources", + "dl.refresh": "Refresh", + "dl.remove": "Remove", + "dl.noSource": "No sources yet", + "dl.pickSource": "Select a source to see available models", + "dl.available": "Available models", + "dl.download": "Download", + "dl.installed": "Installed", + "dl.reinstall": "Re-download", + "dl.background": "Background tasks", + "dl.bgEmpty": "No background tasks", + "dl.cancel": "Cancel", + "dl.retry": "Retry", + "dl.clearDone": "Clear finished", + "dl.removeTask": "Remove", + "dl.status.queued": "Queued", + "dl.status.downloading": "Downloading", + "dl.status.done": "Completed", + "dl.status.failed": "Failed", + "dl.status.canceled": "Canceled", + "dl.hint": "GitHub / GitLab / Gitee repository URLs, zip links and local folders are supported", + "dl.empty": "No models in this source", + "dl.emptyHint": "A source needs model//.json layout", + "dl.syncing": "Reading model source…", + "dl.ready": "{0} models", + "dl.fromCache": "cached", + "dl.imported": "Source imported", + "dl.importFailed": "Import failed: {0}", + "dl.error.emptyUrl": "Please enter a source URL", + "dl.error.canceled": "Canceled", + "dl.error.unreachable": "Cannot reach this source, check the URL or network", + "dl.sourceDefault": "Source", + "set.title": "Settings", + "set.subtitle": "Model sources, startup memory allocation and local storage.", + "set.general": "General", + "set.language": "Language", + "set.language.auto": "System", + "set.fps": "Render frame rate", + "set.fps.desc": "Higher is smoother but uses more CPU.", + "set.memory": "Startup memory allocation", + "set.memory.desc": "The launcher hands this budget to each model; models decide how much data to cache with it.", + "set.memory.current": "In use", + "set.memory.unit": "MB", + "set.memory.hint": "2048 MB or more is recommended; 1024 MB for low-end devices.", + "set.preallocate": "Preload land data at startup", + "set.preallocate.desc": "Faster first frame, slightly slower startup.", + "set.sources": "Model sources", + "set.sources.desc": "Disabled sources are hidden from the Download page.", + "set.sourceEnabled": "Enabled", + "set.addSource": "Add source", + "set.sourceName": "Name", + "set.storage": "Storage", + "set.modelDir": "Model library", + "set.dataDir": "Data folder", + "set.openFolder": "Open folder", + "set.clearCache": "Clear cache", + "set.cacheCleared": "Cache cleared", + "set.about": "About", + "set.version": "Version", + "set.platform": "Platform", + "set.license": "License", + "set.licenseValue": "MIT", + "set.checkUpdate": "Check for updates", + "set.checkUpdate.desc": "Offline build — update by replacing the app folder.", + "set.modelFormat": "Model format", + "set.modelFormat.desc": "model//.json + .model/ scene data", + "player.back": "Close window", + "player.view.rotation": "Rotation", + "player.view.revolution": "Revolution", + "player.play": "Play", + "player.pause": "Pause", + "player.speed": "Speed", + "player.reset": "Reset", + "player.labels": "Labels", + "player.orbit": "Orbit", + "player.grid": "Graticule", + "player.tilt": "Exaggerate tilt", + "player.lessons": "Teaching notes", + "player.seasons": "Solstices & equinoxes", + "player.loading": "Preparing scene…", + "player.subsolar": "Subsolar point", + "player.north": "North pole", + "player.south": "South pole", + "player.northShort": "N", + "player.southShort": "S", + "player.spinInfo": "Rotation {0}° · period {1} h", + "player.orbitInfo": "Orbit {0}°", + "player.declinationInfo": "Subsolar {0}", + "player.dateInfo": "Date {0}", + "player.paused": "Paused", + "star.sun": "Sun", + "planet.earth": "Earth", + "season.springEquinox": "Spring equinox", + "season.summerSolstice": "Summer solstice", + "season.autumnEquinox": "Autumn equinox", + "season.winterSolstice": "Winter solstice", + "common.cancel": "Cancel", + "common.confirm": "Confirm", + "common.delete": "Delete", + "common.close": "Close", + "common.open": "Open", + "common.applied": "Applied", + "common.confirmTitle": "Please confirm", + "player.windowHint": "The model runs in its own window; close it to exit", + "player.errorTitle": "Failed to launch \"{0}\"", + "player.errorHint": "The model package has no usable assembly. Make sure .model contains the model dll, or re-download it." +} diff --git a/src/main/dotnet/EarthModelStudio/Assets/i18n/zh-CN.json b/src/main/dotnet/EarthModelStudio/Assets/i18n/zh-CN.json new file mode 100644 index 0000000..9ae4799 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Assets/i18n/zh-CN.json @@ -0,0 +1,139 @@ +{ + "app.name": "地球模型工作室", + "app.tagline": "天文教学模型 · 可视化启动器", + "app.version": "版本", + "app.platform": "平台", + "nav.home": "主页", + "nav.download": "下载", + "nav.settings": "设置", + "home.title": "模型库", + "home.subtitle": "选择模型,用可交互的三维演示讲清自转、公转与四季成因。", + "home.launch": "启动模型", + "home.download": "下载模型", + "home.settings": "设置", + "home.installed": "已安装模型", + "home.count": "{0} 个模型", + "home.empty": "模型库还是空的", + "home.emptyHint": "在「下载」页从链接导入模型源,或把模型直接放进 model 目录。", + "home.emptyAction": "去下载模型", + "home.open": "打开目录", + "home.delete": "删除", + "home.deleteConfirm": "删除模型「{0}」?模型文件会从本地模型库移除。", + "home.size": "体积", + "home.stats.models": "已安装", + "home.stats.sources": "模型源", + "home.stats.memory": "内存预算", + "home.recent": "选择模型后点击「启动模型」", + "home.getMore": "获取更多模型", + "home.launchHint": "模型在自己的窗口里运行,可播放/暂停、切换视角并使用教学要点。", + "dl.title": "下载模型", + "dl.subtitle": "从链接导入模型源:git 仓库、zip 压缩包或本地目录。仓库里的 model/ 文件夹就是模型列表。", + "dl.import": "导入模型源", + "dl.importPlaceholder": "https://github.com/user/repo.git 或 /本地/模型仓库", + "dl.sources": "模型源", + "dl.refresh": "刷新", + "dl.remove": "移除", + "dl.noSource": "还没有模型源", + "dl.pickSource": "选择一个模型源,查看可下载的模型", + "dl.available": "可用模型", + "dl.download": "下载", + "dl.installed": "已安装", + "dl.reinstall": "重新下载", + "dl.background": "后台任务", + "dl.bgEmpty": "暂无后台任务", + "dl.cancel": "取消", + "dl.retry": "重试", + "dl.clearDone": "清除已完成", + "dl.removeTask": "移除", + "dl.status.queued": "排队中", + "dl.status.downloading": "下载中", + "dl.status.done": "已完成", + "dl.status.failed": "失败", + "dl.status.canceled": "已取消", + "dl.hint": "支持 GitHub / GitLab / Gitee 仓库地址、zip 直链、本地目录", + "dl.empty": "这个源里没有模型", + "dl.emptyHint": "仓库需要包含 model/<模型ID>/<模型ID>.json 结构", + "dl.syncing": "正在读取模型源…", + "dl.ready": "共 {0} 个模型", + "dl.fromCache": "本地缓存", + "dl.imported": "已导入模型源", + "dl.importFailed": "导入失败:{0}", + "dl.error.emptyUrl": "请填写模型源链接", + "dl.error.canceled": "已取消", + "dl.error.unreachable": "无法访问该模型源,请检查链接或网络", + "dl.sourceDefault": "模型源", + "set.title": "设置", + "set.subtitle": "模型源、启动时内存分配与本地存储。", + "set.general": "通用", + "set.language": "界面语言", + "set.language.auto": "跟随系统", + "set.fps": "渲染帧率", + "set.fps.desc": "越高越顺滑,CPU 占用也越高。", + "set.memory": "启动时运行内存分配", + "set.memory.desc": "启动器把这份预算交给模型:模型自己决定用它缓存多少数据(贴图分辨率、缓冲等)。", + "set.memory.current": "当前占用", + "set.memory.unit": "MB", + "set.memory.hint": "建议 2048 MB 以上,低配设备可选 1024 MB。", + "set.preallocate": "启动时预加载模型地表数据", + "set.preallocate.desc": "打开后首帧更快,启动耗时略增。", + "set.sources": "模型源", + "set.sources.desc": "停用的模型源不会出现在下载页。", + "set.sourceEnabled": "启用", + "set.addSource": "添加模型源", + "set.sourceName": "名称", + "set.storage": "存储", + "set.modelDir": "模型库目录", + "set.dataDir": "数据目录", + "set.openFolder": "打开文件夹", + "set.clearCache": "清理缓存", + "set.cacheCleared": "缓存已清理", + "set.about": "关于", + "set.version": "版本", + "set.platform": "平台", + "set.license": "许可", + "set.licenseValue": "MIT", + "set.checkUpdate": "检查更新", + "set.checkUpdate.desc": "当前为离线构建,更新请替换程序目录。", + "set.modelFormat": "模型格式", + "set.modelFormat.desc": "model/<模型ID>/<模型ID>.json + <模型ID>.model/ 场景数据", + "player.back": "关闭窗口", + "player.view.rotation": "自转", + "player.view.revolution": "公转", + "player.play": "播放", + "player.pause": "暂停", + "player.speed": "速度", + "player.reset": "重置", + "player.labels": "标注", + "player.orbit": "轨道", + "player.grid": "经纬网", + "player.tilt": "夸张倾角", + "player.lessons": "教学要点", + "player.seasons": "节气定位", + "player.loading": "正在准备场景…", + "player.subsolar": "太阳直射点", + "player.north": "北极", + "player.south": "南极", + "player.northShort": "N", + "player.southShort": "S", + "player.spinInfo": "自转 {0}° · 周期 {1} 小时", + "player.orbitInfo": "公转 {0}°", + "player.declinationInfo": "太阳直射 {0}", + "player.dateInfo": "日期 {0}", + "player.paused": "已暂停", + "star.sun": "太阳", + "planet.earth": "地球", + "season.springEquinox": "春分", + "season.summerSolstice": "夏至", + "season.autumnEquinox": "秋分", + "season.winterSolstice": "冬至", + "common.cancel": "取消", + "common.confirm": "确定", + "common.delete": "删除", + "common.close": "关闭", + "common.open": "打开", + "common.applied": "已应用", + "common.confirmTitle": "请确认", + "player.windowHint": "模型在独立窗口中运行,关闭窗口即退出模型", + "player.errorTitle": "模型「{0}」启动失败", + "player.errorHint": "模型包里没有可用的功能程序集。请确认 .model 目录内有模型 dll,或重新下载该模型。" +} diff --git a/src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj b/src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj new file mode 100644 index 0000000..84df85d --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj @@ -0,0 +1,31 @@ + + + + WinExe + enable + true + EarthModelStudio + EarthModelStudio + app.manifest + false + true + false + + + + + + + + + + + + + + + + + + + diff --git a/src/main/dotnet/EarthModelStudio/Models/AppSettings.cs b/src/main/dotnet/EarthModelStudio/Models/AppSettings.cs new file mode 100644 index 0000000..72701e1 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Models/AppSettings.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace EarthModelStudio.Models; + +/// 应用设置,持久化到 data/settings.json。 +public sealed class AppSettings +{ + /// auto | zh-CN | en + public string Language { get; set; } = "auto"; + + /// light | dark + public string Theme { get; set; } = "light"; + + /// 渲染帧率:24 / 30 / 60 + public int RenderFps { get; set; } = 30; + + /// 启动时运行内存分配(MB)——决定场景缓存/纹理预算。 + public int MemoryMb { get; set; } = 2048; + + /// 启动时检查模型源更新。 + public bool CheckSourceOnStartup { get; set; } + + /// 模型库目录覆盖(留空则自动探测)。 + public string? ModelRootOverride { get; set; } + + public List Sources { get; set; } = new(); + + public List RecentModels { get; set; } = new(); +} + +/// 模型源:一个满足 Earth Model 规范的 git 仓库 / zip / 本地目录。 +public sealed class ModelSource +{ + public string Id { get; set; } = Guid.NewGuid().ToString("N")[..8]; + public string Name { get; set; } = ""; + public string Url { get; set; } = ""; + public string? Branch { get; set; } + public bool Enabled { get; set; } = true; + public bool BuiltIn { get; set; } + public string? LastSynced { get; set; } + + [JsonIgnore] + public string DisplayHost + { + get + { + if (string.IsNullOrWhiteSpace(Url)) return ""; + if (Url.StartsWith("file:", StringComparison.OrdinalIgnoreCase) || System.IO.Path.IsPathRooted(Url)) + return "local"; + return Uri.TryCreate(Url, UriKind.Absolute, out var u) ? u.Host : Url; + } + } +} diff --git a/src/main/dotnet/EarthModelStudio/Models/ModelManifest.cs b/src/main/dotnet/EarthModelStudio/Models/ModelManifest.cs new file mode 100644 index 0000000..13bd7b5 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Models/ModelManifest.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace EarthModelStudio.Models; + +/// model/<id>/<id>.json 的内容。 +public sealed class ModelManifest +{ + public int SchemaVersion { get; set; } = 1; + public string Id { get; set; } = ""; + public string Name { get; set; } = ""; + public Dictionary? NameI18n { get; set; } + public string Version { get; set; } = "1.0.0"; + public string Author { get; set; } = ""; + public string Description { get; set; } = ""; + public Dictionary? DescriptionI18n { get; set; } + public List? Tags { get; set; } + /// 相对 <id>.model 目录的入口文件,默认 scene.json + public string? Entry { get; set; } + /// 模型自带的界面程序集(相对 <id>.model),默认 <id>.dll + public string? Assembly { get; set; } + /// 实现 IModelFactory 的类型全名;留空则自动查找 + public string? Type { get; set; } + /// 封面图文件名,默认 preview.png + public string? Preview { get; set; } + /// 模型契约版本 + public int ApiVersion { get; set; } = 1; + public string? License { get; set; } + public string? UpdatedAt { get; set; } + public string? MinAppVersion { get; set; } +} + +public sealed class ModelPackage +{ + public ModelManifest Manifest { get; init; } = new(); + public string Directory { get; init; } = ""; + public long SizeBytes { get; set; } + + public string Id => Manifest.Id; + public string DataDirectory => System.IO.Path.Combine(Directory, Id + ".model"); + public string ScenePath + { + get + { + var entry = string.IsNullOrWhiteSpace(Manifest.Entry) ? "scene.json" : Manifest.Entry!; + if (entry.StartsWith(Id + ".model")) return System.IO.Path.Combine(Directory, entry); + return System.IO.Path.Combine(DataDirectory, entry); + } + } + + /// 模型自带的界面程序集路径。 + public string AssemblyPath + { + get + { + var file = string.IsNullOrWhiteSpace(Manifest.Assembly) ? Id + ".dll" : Manifest.Assembly!; + return System.IO.Path.IsPathRooted(file) ? file : System.IO.Path.Combine(DataDirectory, file); + } + } + + /// 封面图路径(launcher 只显示,不渲染)。 + public string PreviewPath + { + get + { + var file = string.IsNullOrWhiteSpace(Manifest.Preview) ? "preview.png" : Manifest.Preview!; + return System.IO.Path.IsPathRooted(file) ? file : System.IO.Path.Combine(DataDirectory, file); + } + } + + public string LocalizedName => Services.L.I.Pick(Manifest.NameI18n, + string.IsNullOrWhiteSpace(Manifest.Name) ? Id : Manifest.Name); + + public string LocalizedDescription => Services.L.I.Pick(Manifest.DescriptionI18n, Manifest.Description); +} + +public sealed class RemoteModel +{ + public ModelManifest Manifest { get; init; } = new(); + public string Directory { get; init; } = ""; + public long SizeBytes { get; init; } + public string SourceId { get; init; } = ""; + + public string Id => Manifest.Id; + public string LocalizedName => Services.L.I.Pick(Manifest.NameI18n, + string.IsNullOrWhiteSpace(Manifest.Name) ? Id : Manifest.Name); + public string LocalizedDescription => Services.L.I.Pick(Manifest.DescriptionI18n, Manifest.Description); +} + +public sealed class SourceIndex +{ + public string SourceId { get; init; } = ""; + public string Root { get; init; } = ""; + public bool FromCache { get; init; } + public List Models { get; init; } = new(); + public string? Error { get; init; } + public string ResolvedFrom { get; init; } = ""; +} diff --git a/src/main/dotnet/EarthModelStudio/Program.cs b/src/main/dotnet/EarthModelStudio/Program.cs new file mode 100644 index 0000000..3c5c00f --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Program.cs @@ -0,0 +1,15 @@ +using System; +using Avalonia; + +namespace EarthModelStudio; + +internal static class Program +{ + [STAThread] + public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + + public static AppBuilder BuildAvaloniaApp() + => AppBuilder.Configure() + .UsePlatformDetect() + .LogToTrace(); +} diff --git a/src/main/dotnet/EarthModelStudio/Services/AppPaths.cs b/src/main/dotnet/EarthModelStudio/Services/AppPaths.cs new file mode 100644 index 0000000..0812a80 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/AppPaths.cs @@ -0,0 +1,93 @@ +using System; +using System.IO; + +namespace EarthModelStudio.Services; + +/// +/// 目录探测。启动器本身不含任何模型数据,模型一律从外部模型库目录读取: +/// 1) 开发态:从 bin 目录向上找到 EarthModelStudio.sln,模型库用仓库根 model/ +/// 2) 绿色态:可执行文件旁边有 model/ 目录(发布包默认只建空目录) +/// 3) 安装态:模型库放到用户数据目录 +/// 也可用环境变量 EMS_HOME / EMS_MODELS 显式指定。 +/// +public sealed class AppPaths +{ + public string AppRoot { get; private init; } = ""; + public string ModelRoot { get; private init; } = ""; + public string DataRoot { get; private init; } = ""; + public bool IsPortableModelRoot { get; private init; } + + public string CacheRoot => Path.Combine(DataRoot, "cache"); + public string SettingsFile => Path.Combine(DataRoot, "settings.json"); + + public static AppPaths Discover() + { + var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar); + var dataRoot = Environment.GetEnvironmentVariable("EMS_DATA") + ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "EarthModelStudio"); + + // 显式指定模型库(模型是外置数据,可放在任意磁盘/网络盘) + var envModels = Environment.GetEnvironmentVariable("EMS_MODELS"); + if (!string.IsNullOrWhiteSpace(envModels)) + { + return new AppPaths + { + AppRoot = baseDir, + ModelRoot = envModels!, + DataRoot = dataRoot, + IsPortableModelRoot = false + }; + } + + var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME"); + if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot)) + repoRoot = FindRepoRoot(baseDir); + + var exeModelDir = Path.Combine(baseDir, "model"); + string appRoot, modelRoot; + bool portable = false; + + if (!string.IsNullOrEmpty(repoRoot) && Directory.Exists(Path.Combine(repoRoot!, "model"))) + { + appRoot = repoRoot!; + modelRoot = Path.Combine(appRoot, "model"); + } + else if (Directory.Exists(exeModelDir)) + { + appRoot = baseDir; + modelRoot = exeModelDir; + portable = true; + } + else + { + appRoot = baseDir; + modelRoot = Path.Combine(dataRoot, "model"); + } + + return new AppPaths + { + AppRoot = appRoot, + ModelRoot = modelRoot, + DataRoot = dataRoot, + IsPortableModelRoot = portable + }; + } + + private static string? FindRepoRoot(string start) + { + 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; + } + return null; + } + + public void EnsureCreated() + { + Directory.CreateDirectory(DataRoot); + Directory.CreateDirectory(CacheRoot); + Directory.CreateDirectory(ModelRoot); + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/AppServices.cs b/src/main/dotnet/EarthModelStudio/Services/AppServices.cs new file mode 100644 index 0000000..feb254f --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/AppServices.cs @@ -0,0 +1,49 @@ +using System; + +namespace EarthModelStudio.Services; + +/// 组合根:一处初始化所有服务。 +public sealed class AppServices +{ + public static AppServices Current { get; private set; } = null!; + + public AppPaths Paths { get; } + public SettingsService Settings { get; } + public ModelRepository Models { get; } + public DownloadCenter Downloads { get; } + public MemoryBudget Memory { get; } + public ModelSourceClient Sources { get; } + /// 模型加载器:只负责把模型程序集跑起来,不渲染。 + public ModelHost ModelHost { get; } + + private AppServices(AppPaths paths) + { + Paths = paths; + Settings = new SettingsService(paths); + Models = new ModelRepository(paths); + Sources = new ModelSourceClient(paths); + Downloads = new DownloadCenter(paths, Models); + Memory = new MemoryBudget(); + ModelHost = new ModelHost(paths, Settings, Memory); + } + + public static AppServices Create() + { + var paths = AppPaths.Discover(); + paths.EnsureCreated(); + + var services = new AppServices(paths); + services.Settings.Load(); + L.I.Initialize(services.Settings.Current.Language); + services.Memory.Apply(services.Settings.Current.MemoryMb); + + Current = services; + return services; + } + + public static AppServices Ensure() + { + if (Current == null) Create(); + return Current; + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/DownloadCenter.cs b/src/main/dotnet/EarthModelStudio/Services/DownloadCenter.cs new file mode 100644 index 0000000..df5434a --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/DownloadCenter.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using EarthModelStudio.Models; + +namespace EarthModelStudio.Services; + +public enum DownloadState +{ + Queued, + Running, + Completed, + Failed, + Canceled +} + +/// 一条下载任务(进入后台列表后一直保留,直到用户清除)。 +public sealed partial class DownloadJob : ObservableObject +{ + public RemoteModel Model { get; } + public string Id => Model.Id; + public string Name => Model.LocalizedName; + public string Version => Model.Manifest.Version; + public CancellationTokenSource Cts { get; } = new(); + + [ObservableProperty] private DownloadState _state = DownloadState.Queued; + [ObservableProperty] private double _progress; + [ObservableProperty] private string _statusText = ""; + [ObservableProperty] private string _detailText = ""; + [ObservableProperty] private string? _error; + + public DownloadJob(RemoteModel model) + { + Model = model; + RefreshText(); + } + + public bool IsActive => State is DownloadState.Queued or DownloadState.Running; + public bool CanRetry => State is DownloadState.Failed or DownloadState.Canceled; + public bool IsDone => State == DownloadState.Completed; + + public void RefreshText() + { + StatusText = State switch + { + DownloadState.Queued => L.I["dl.status.queued"], + DownloadState.Running => L.I["dl.status.downloading"], + DownloadState.Completed => L.I["dl.status.done"], + DownloadState.Failed => L.I["dl.status.failed"], + _ => L.I["dl.status.canceled"] + }; + DetailText = State == DownloadState.Failed && !string.IsNullOrEmpty(Error) + ? Error! + : ModelScanner.HumanSize(Model.SizeBytes); + OnPropertyChanged(nameof(IsActive)); + OnPropertyChanged(nameof(CanRetry)); + OnPropertyChanged(nameof(IsDone)); + } + + partial void OnStateChanged(DownloadState value) => RefreshText(); + partial void OnErrorChanged(string? value) => RefreshText(); +} + +/// 下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。 +public sealed class DownloadCenter +{ + private readonly ModelRepository _repository; + private readonly AppPaths _paths; + private readonly SemaphoreSlim _slots = new(2); + + public ObservableCollection Jobs { get; } = new(); + public event Action? Installed; + + public DownloadCenter(AppPaths paths, ModelRepository repository) + { + _paths = paths; + _repository = repository; + } + + public DownloadJob Enqueue(RemoteModel model) + { + var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive); + if (running != null) return running; + + var job = new DownloadJob(model); + Jobs.Insert(0, job); + _ = RunAsync(job); + return job; + } + + private async Task RunAsync(DownloadJob job) + { + // 在 UI 线程构造,回调自动回到 UI 线程 + var progress = new Progress<(long Done, long Total)>(p => + { + job.Progress = p.Total > 0 ? Math.Clamp((double)p.Done / p.Total, 0, 1) : 0; + }); + + try + { + await _slots.WaitAsync(job.Cts.Token).ConfigureAwait(true); + } + catch (OperationCanceledException) + { + job.State = DownloadState.Canceled; + return; + } + + try + { + job.State = DownloadState.Running; + await ModelInstaller.InstallAsync(job.Model, _paths.ModelRoot, progress, job.Cts.Token) + .ConfigureAwait(true); + job.Progress = 1; + job.State = DownloadState.Completed; + _repository.NotifyChanged(); + Installed?.Invoke(); + } + catch (OperationCanceledException) + { + job.State = DownloadState.Canceled; + } + catch (Exception ex) + { + job.Error = ex.Message; + job.State = DownloadState.Failed; + } + finally + { + _slots.Release(); + } + } + + public void Cancel(DownloadJob job) + { + try { job.Cts.Cancel(); } catch { } + if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled; + } + + public void Retry(DownloadJob job) + { + if (job.IsActive) return; + Jobs.Remove(job); + Enqueue(job.Model); + } + + public void Remove(DownloadJob job) + { + Cancel(job); + Jobs.Remove(job); + } + + public void ClearFinished() + { + for (var i = Jobs.Count - 1; i >= 0; i--) + { + if (Jobs[i].State is DownloadState.Completed or DownloadState.Canceled) + Jobs.RemoveAt(i); + } + } + + public int ActiveCount => Jobs.Count(j => j.IsActive); +} diff --git a/src/main/dotnet/EarthModelStudio/Services/Json.cs b/src/main/dotnet/EarthModelStudio/Services/Json.cs new file mode 100644 index 0000000..3264bd7 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/Json.cs @@ -0,0 +1,34 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace EarthModelStudio.Services; + +public static class Json +{ + public static readonly JsonSerializerOptions Options = new() + { + PropertyNameCaseInsensitive = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip + }; + + public static T? Read(string path) + { + if (!System.IO.File.Exists(path)) return default; + return JsonSerializer.Deserialize(System.IO.File.ReadAllText(path), Options); + } + + public static void Write(string path, T value) + { + var dir = System.IO.Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir); + var tmp = path + ".tmp"; + System.IO.File.WriteAllText(tmp, JsonSerializer.Serialize(value, Options)); + System.IO.File.Move(tmp, path, true); + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/Localization.cs b/src/main/dotnet/EarthModelStudio/Services/Localization.cs new file mode 100644 index 0000000..bb391b9 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/Localization.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.IO; +using System.Text.Json; +using Avalonia.Markup.Xaml; +using Avalonia.Data; +using Avalonia.Platform; + +namespace EarthModelStudio.Services; + +/// 轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。 +public sealed class L : INotifyPropertyChanged +{ + private static readonly L _instance = new(); + public static L I => _instance; + + private Dictionary _map = new(StringComparer.OrdinalIgnoreCase); + private readonly List> _watchers = new(); + + public string Language { get; private set; } = "zh-CN"; + public event PropertyChangedEventHandler? PropertyChanged; + public event Action? LanguageChanged; + + public static readonly (string Code, string Label)[] Supported = + { + ("zh-CN", "简体中文"), + ("en", "English") + }; + + public void Initialize(string? preference) + { + var code = Resolve(preference); + LoadLanguage(code, force: true); + } + + public static string Resolve(string? pref) + { + if (!string.IsNullOrWhiteSpace(pref) && !pref.Equals("auto", StringComparison.OrdinalIgnoreCase)) + return pref!.StartsWith("en", StringComparison.OrdinalIgnoreCase) ? "en" : "zh-CN"; + var ui = CultureInfo.CurrentUICulture; + return ui.TwoLetterISOLanguageName.Equals("zh", StringComparison.OrdinalIgnoreCase) ? "zh-CN" : "en"; + } + + public void SetLanguage(string code) + { + code = Resolve(code); + if (code == Language) return; + LoadLanguage(code, force: false); + } + + private void LoadLanguage(string code, bool force) + { + var loaded = ReadTable(code) ?? ReadTable("en") ?? new Dictionary(); + if (code != "zh-CN") + { + // 中文兜底,避免缺键出现空白 + foreach (var kv in ReadTable("zh-CN") ?? new Dictionary()) + loaded.TryAdd(kv.Key, kv.Value); + } + _map = loaded; + if (!force && code == Language) return; + Language = code; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]")); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language))); + foreach (var w in _watchers) + if (w.TryGetTarget(out var ls)) ls.Refresh(); + LanguageChanged?.Invoke(); + } + + private static Dictionary? ReadTable(string code) + { + try + { + var uri = new Uri($"avares://EarthModelStudio/Assets/i18n/{code}.json"); + using var stream = AssetLoader.Open(uri); + using var reader = new StreamReader(stream); + return JsonSerializer.Deserialize>(reader.ReadToEnd(), + new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); + } + catch + { + return null; + } + } + + public string this[string key] + { + get + { + if (string.IsNullOrEmpty(key)) return ""; + return _map.TryGetValue(key, out var v) ? v : key; + } + } + + public string F(string key, params object?[] args) + { + var fmt = this[key]; + try { return string.Format(fmt, args); } + catch (FormatException) { return fmt; } + } + + public LocalizedString For(string key) + { + var ls = new LocalizedString(key); + _watchers.Add(new WeakReference(ls)); + return ls; + } + + /// 按 i18n 字典取值:当前语言 -> 英文 -> zh-CN -> 默认名。 + public string Pick(Dictionary? dict, string fallback) + { + if (dict == null || dict.Count == 0) return fallback; + if (dict.TryGetValue(Language, out var v) && !string.IsNullOrWhiteSpace(v)) return v; + if (Language != "en" && dict.TryGetValue("en", out var en) && !string.IsNullOrWhiteSpace(en)) return en; + if (dict.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh; + foreach (var kv in dict) if (!string.IsNullOrWhiteSpace(kv.Value)) return kv.Value; + return fallback; + } +} + +public sealed class LocalizedString : INotifyPropertyChanged +{ + public string Key { get; } + public LocalizedString(string key) => Key = key; + public string Value => L.I[Key]; + public event PropertyChangedEventHandler? PropertyChanged; + internal void Refresh() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value))); +} + +/// XAML 用法:Text="{loc:Loc nav.home}" +public sealed class LocExtension : MarkupExtension +{ + public LocExtension() { } + public LocExtension(string key) => Key = key; + public string Key { get; set; } = ""; + + public override object ProvideValue(IServiceProvider serviceProvider) + => new Binding(nameof(LocalizedString.Value)) { Source = L.I.For(Key) }; +} diff --git a/src/main/dotnet/EarthModelStudio/Services/MemoryBudget.cs b/src/main/dotnet/EarthModelStudio/Services/MemoryBudget.cs new file mode 100644 index 0000000..b9512fd --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/MemoryBudget.cs @@ -0,0 +1,30 @@ +using System; + +namespace EarthModelStudio.Services; + +/// +/// 启动时运行内存分配(类似启动器的 -Xmx)。 +/// 启动器只负责把这份预算通过 IModelContext.MemoryBudgetMb 交给模型, +/// 具体怎么用(贴图分辨率、缓存大小)由模型自己决定。 +/// +public sealed class MemoryBudget +{ + public int BudgetMb { get; private set; } = 2048; + public long BudgetBytes => (long)BudgetMb * 1024L * 1024L; + public long ManagedBytes => GC.GetTotalMemory(false); + + public event Action? Changed; + + public void Apply(int mb) + { + BudgetMb = Math.Clamp(mb, 256, 16384); + Changed?.Invoke(); + } + + /// 内存情况变化(例如模型窗口开关)时刷新展示。 + public void Refresh() => Changed?.Invoke(); + + public double UsageRatio => BudgetBytes <= 0 ? 0 : Math.Clamp((double)ManagedBytes / BudgetBytes, 0, 1); + + public string UsageText => $"{ModelScanner.HumanSize(ManagedBytes)} / {BudgetMb} MB"; +} diff --git a/src/main/dotnet/EarthModelStudio/Services/ModelHost.cs b/src/main/dotnet/EarthModelStudio/Services/ModelHost.cs new file mode 100644 index 0000000..2508940 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/ModelHost.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.Loader; +using System.Threading.Tasks; +using Avalonia.Controls; +using EarthModelStudio.Models; +using EarthModelStudio.ModelSdk; + +namespace EarthModelStudio.Services; + +/// +/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。 +/// 启动器对“场景 / 行星 / 节气”一无所知,只认契约。 +/// +public sealed class ModelHost +{ + public const int SupportedApiVersion = 1; + + private readonly AppPaths _paths; + private readonly SettingsService _settings; + private readonly MemoryBudget _memory; + + public ModelHost(AppPaths paths, SettingsService settings, MemoryBudget memory) + { + _paths = paths; + _settings = settings; + _memory = memory; + } + + /// 同步加载(全部在 UI 线程,用于自检 / 命令行)。 + public LoadedModel Load(ModelPackage package, Action requestClose, Action? progress = null) + { + var session = CreateSession(package, requestClose, progress); + try + { + session.Runtime.Prepare(session.Context); + var view = session.Runtime.CreateView(session.Context) + ?? throw new InvalidOperationException("模型没有返回界面"); + return session.Complete(view); + } + catch + { + session.Dispose(); + throw; + } + } + + /// + /// 异步加载:数据准备放在后台线程(), + /// 界面构建回到 UI 线程,进度通过 实时汇报。 + /// + public async Task LoadAsync(ModelPackage package, Action requestClose, + Action? progress = null) + { + var session = CreateSession(package, requestClose, progress); + try + { + await Task.Run(() => session.Runtime.Prepare(session.Context)).ConfigureAwait(true); + var view = session.Runtime.CreateView(session.Context) + ?? throw new InvalidOperationException("模型没有返回界面"); + return session.Complete(view); + } + catch + { + session.Dispose(); + throw; + } + } + + private Session CreateSession(ModelPackage package, Action requestClose, Action? progress) + { + var assemblyPath = package.AssemblyPath; + if (!File.Exists(assemblyPath)) + throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath); + + var directory = Path.GetDirectoryName(assemblyPath)!; + var context = new ModelLoadContext(directory); + try + { + var assembly = context.LoadFromAssemblyPath(assemblyPath); + var type = ResolveFactoryType(assembly, package.Manifest.Type); + if (type == null) + throw new InvalidOperationException("模型程序集里没有找到 IModelFactory 实现"); + + if (Activator.CreateInstance(type) is not IModelFactory factory) + throw new InvalidOperationException($"无法创建模型入口:{type.FullName}"); + + if (factory.ApiVersion != SupportedApiVersion) + throw new InvalidOperationException( + $"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致"); + + var runtime = factory.Create(); + var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress); + return new Session(context, runtime, modelContext); + } + catch + { + context.Unload(); + throw; + } + } + + private static Type? ResolveFactoryType(Assembly assembly, string? typeName) + { + if (!string.IsNullOrWhiteSpace(typeName)) + { + var exact = assembly.GetType(typeName!, throwOnError: false); + if (exact != null) return exact; + } + + foreach (var type in assembly.GetTypes()) + { + if (type.IsAbstract || type.IsInterface) continue; + if (typeof(IModelFactory).IsAssignableFrom(type)) return type; + } + return null; + } + + private sealed class Session : IDisposable + { + private readonly ModelLoadContext _context; + + public Session(ModelLoadContext context, IModelRuntime runtime, ModelContext modelContext) + { + _context = context; + Runtime = runtime; + Context = modelContext; + } + + public IModelRuntime Runtime { get; } + public ModelContext Context { get; } + + public LoadedModel Complete(Control view) => new(_context, Runtime, view); + + public void Dispose() + { + try { Runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); } + try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); } + } + } +} + +/// 一次性模型实例:窗口关闭后释放视图、卸载程序集。 +public sealed class LoadedModel : IDisposable +{ + private readonly ModelLoadContext _context; + private readonly IModelRuntime _runtime; + private bool _disposed; + + public LoadedModel(ModelLoadContext context, IModelRuntime runtime, Control view) + { + _context = context; + _runtime = runtime; + View = view; + } + + public Control View { get; } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); } + try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); } + } +} + +/// 模型程序集加载上下文:契约与 Avalonia 一律回到默认上下文,保证类型一致。 +public sealed class ModelLoadContext : AssemblyLoadContext +{ + private static readonly HashSet Shared = new(StringComparer.OrdinalIgnoreCase) + { + "EarthModelStudio.ModelSdk", + "Avalonia", + "Avalonia.Base", + "Avalonia.Controls", + "Avalonia.Desktop", + "Avalonia.Skia", + "Avalonia.Themes.Fluent", + "SkiaSharp", + "HarfBuzzSharp" + }; + + private readonly string _directory; + + public ModelLoadContext(string directory) : base("model:" + Path.GetFileName(directory), isCollectible: true) + => _directory = directory; + + protected override Assembly? Load(AssemblyName assemblyName) + { + var name = assemblyName.Name; + if (string.IsNullOrEmpty(name)) return null; + if (Shared.Contains(name)) return null; // 用启动器已加载的那份 + if (name.StartsWith("System.", StringComparison.OrdinalIgnoreCase)) return null; + if (name is "System" or "netstandard" or "mscorlib") return null; + + var candidate = Path.Combine(_directory, name + ".dll"); + return File.Exists(candidate) ? LoadFromAssemblyPath(candidate) : null; + } +} + +/// 启动器提供给模型的环境。 +public sealed class ModelContext : IModelContext +{ + private readonly Action _requestClose; + private readonly Action? _progress; + + public ModelContext(ModelPackage package, string language, int memoryMb, Action requestClose, + Action? progress) + { + _progress = progress; + ModelId = package.Id; + ModelDirectory = package.Directory; + DataDirectory = package.DataDirectory; + Language = language; + MemoryBudgetMb = memoryMb; + _requestClose = requestClose; + } + + public string ModelId { get; } + public string ModelDirectory { get; } + public string DataDirectory { get; } + public string Language { get; } + public int MemoryBudgetMb { get; } + + public void RequestClose() => _requestClose(); + + public void ReportProgress(double value, string? message = null) => _progress?.Invoke(value, message); + + public void Log(string message) => Console.WriteLine(message); +} diff --git a/src/main/dotnet/EarthModelStudio/Services/ModelInstaller.cs b/src/main/dotnet/EarthModelStudio/Services/ModelInstaller.cs new file mode 100644 index 0000000..11d9c69 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/ModelInstaller.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using EarthModelStudio.Models; + +namespace EarthModelStudio.Services; + +public static class ModelInstaller +{ + /// 把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。 + public static async Task InstallAsync(RemoteModel model, string modelRoot, + IProgress<(long Done, long Total)>? progress, CancellationToken ct) + { + var target = Path.Combine(modelRoot, model.Id); + var staging = target + ".installing"; + if (Directory.Exists(staging)) Directory.Delete(staging, true); + Directory.CreateDirectory(staging); + + long total = 0; + var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories); + foreach (var file in files) + { + try { total += new FileInfo(file).Length; } catch { } + } + + long done = 0; + try + { + foreach (var file in files) + { + ct.ThrowIfCancellationRequested(); + var relative = Path.GetRelativePath(model.Directory, file); + var dest = Path.Combine(staging, relative); + var destDir = Path.GetDirectoryName(dest); + if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir); + + await using (var src = File.OpenRead(file)) + await using (var dst = File.Create(dest)) + { + await src.CopyToAsync(dst, 81920, ct); + } + long length = 0; + try { length = new FileInfo(dest).Length; } catch { } + done += length; + progress?.Report((done, total <= 0 ? done : total)); + } + + if (Directory.Exists(target)) + { + var backup = target + ".old"; + if (Directory.Exists(backup)) Directory.Delete(backup, true); + Directory.Move(target, backup); + Directory.Move(staging, target); + try { Directory.Delete(backup, true); } catch { } + } + else + { + Directory.Move(staging, target); + } + + progress?.Report((total, total)); + return target; + } + catch + { + try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { } + throw; + } + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/ModelRepository.cs b/src/main/dotnet/EarthModelStudio/Services/ModelRepository.cs new file mode 100644 index 0000000..29af023 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/ModelRepository.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using EarthModelStudio.Models; + +namespace EarthModelStudio.Services; + +/// +/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 —— +/// 场景、贴图、界面都由模型自己的程序集负责。 +/// +public sealed class ModelRepository +{ + private readonly AppPaths _paths; + + public ModelRepository(AppPaths paths) => _paths = paths; + + public event Action? Changed; + + public IReadOnlyList Scan() + { + var result = new List(); + foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot)) + { + result.Add(new ModelPackage + { + Manifest = manifest, + Directory = dir, + SizeBytes = ModelScanner.DirectorySize(dir) + }); + } + return result; + } + + public ModelPackage? Find(string id) => Scan().FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + + public bool Delete(string id) + { + var package = Find(id); + if (package == null) return false; + try + { + Directory.Delete(package.Directory, true); + Changed?.Invoke(); + return true; + } + catch (Exception ex) + { + Console.Error.WriteLine($"删除模型失败: {ex.Message}"); + return false; + } + } + + public void NotifyChanged() => Changed?.Invoke(); +} diff --git a/src/main/dotnet/EarthModelStudio/Services/ModelScanner.cs b/src/main/dotnet/EarthModelStudio/Services/ModelScanner.cs new file mode 100644 index 0000000..3f88f66 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/ModelScanner.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.IO; +using EarthModelStudio.Models; + +namespace EarthModelStudio.Services; + +public static class ModelScanner +{ + /// 扫描模型库:model/<id>/<id>.json + <id>.model/ + public static List<(ModelManifest Manifest, string Dir)> Scan(string modelRoot) + { + var list = new List<(ModelManifest, string)>(); + if (!Directory.Exists(modelRoot)) return list; + + foreach (var dir in Directory.GetDirectories(modelRoot)) + { + var folder = Path.GetFileName(dir); + if (folder.StartsWith(".")) continue; + + var manifestPath = Path.Combine(dir, folder + ".json"); + if (!File.Exists(manifestPath)) + { + var candidates = Directory.GetFiles(dir, "*.json", SearchOption.TopDirectoryOnly); + if (candidates.Length == 0) continue; + manifestPath = candidates[0]; + } + + ModelManifest? manifest; + try { manifest = Json.Read(manifestPath); } + catch (Exception ex) + { + Console.Error.WriteLine($"模型清单解析失败 {manifestPath}: {ex.Message}"); + continue; + } + + if (manifest == null) continue; + if (string.IsNullOrWhiteSpace(manifest.Id)) manifest.Id = folder; + list.Add((manifest, dir)); + } + + list.Sort((a, b) => string.Compare(a.Item1.Id, b.Item1.Id, StringComparison.OrdinalIgnoreCase)); + return list; + } + + public static long DirectorySize(string dir) + { + if (!Directory.Exists(dir)) return 0; + long total = 0; + try + { + foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)) + { + try { total += new FileInfo(file).Length; } + catch { /* 忽略被占用的文件 */ } + } + } + catch { /* 忽略权限问题 */ } + return total; + } + + public static string HumanSize(long bytes) + { + string[] units = { "B", "KB", "MB", "GB" }; + double value = bytes; + var unit = 0; + while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; } + return unit == 0 ? $"{bytes} B" : $"{value:0.#} {units[unit]}"; + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/ModelSourceClient.cs b/src/main/dotnet/EarthModelStudio/Services/ModelSourceClient.cs new file mode 100644 index 0000000..b0e2fc8 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/ModelSourceClient.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using EarthModelStudio.Models; + +namespace EarthModelStudio.Services; + +/// +/// 从链接导入模型源。 +/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。 +/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/<id>。 +/// +public sealed class ModelSourceClient +{ + private readonly AppPaths _paths; + private static readonly HttpClient Http = CreateHttp(); + + public ModelSourceClient(AppPaths paths) => _paths = paths; + + private static HttpClient CreateHttp() + { + var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; + client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0 (+model-source)"); + return client; + } + + public async Task FetchAsync(ModelSource source, bool force, IProgress? log, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(source.Url)) + return new SourceIndex { SourceId = source.Id, Error = "dl.error.emptyUrl" }; + + try + { + var (root, fromCache) = await ResolveRootAsync(source, force, log, ct); + var models = new List(); + foreach (var (manifest, dir) in ModelScanner.Scan(Path.Combine(root, "model"))) + { + models.Add(new RemoteModel + { + Manifest = manifest, + Directory = dir, + SizeBytes = ModelScanner.DirectorySize(dir), + SourceId = source.Id + }); + } + + return new SourceIndex + { + SourceId = source.Id, + Root = root, + Models = models, + FromCache = fromCache, + ResolvedFrom = root + }; + } + catch (OperationCanceledException) + { + return new SourceIndex { SourceId = source.Id, Error = "dl.error.canceled" }; + } + catch (Exception ex) + { + return new SourceIndex { SourceId = source.Id, Error = ex.Message }; + } + } + + private async Task<(string Root, bool FromCache)> ResolveRootAsync(ModelSource source, bool force, + IProgress? log, CancellationToken ct) + { + var raw = source.Url.Trim(); + + // 1) 本地目录(开发模型源最方便) + var localPath = raw.StartsWith("file://", StringComparison.OrdinalIgnoreCase) + ? new Uri(raw).LocalPath + : raw; + if (Directory.Exists(localPath)) + { + log?.Report("local"); + return (localPath, true); + } + + var cacheDir = Path.Combine(_paths.CacheRoot, "sources", source.Id); + if (!force && Directory.Exists(Path.Combine(cacheDir, "model"))) + { + log?.Report("cache"); + return (cacheDir, true); + } + + if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true); + Directory.CreateDirectory(cacheDir); + + // 2) zip 直链 / 托管平台归档 + foreach (var url in ArchiveCandidates(raw, source.Branch)) + { + ct.ThrowIfCancellationRequested(); + try + { + log?.Report("zip:" + url); + await DownloadZipAsync(url, cacheDir, ct); + if (Directory.Exists(Path.Combine(cacheDir, "model"))) + return (cacheDir, false); + } + catch (OperationCanceledException) { throw; } + catch (Exception ex) + { + log?.Report("zip-failed:" + ex.Message); + } + } + + // 3) git clone(需要本机安装 git) + log?.Report("git"); + if (await TryGitCloneAsync(raw, cacheDir, source.Branch, ct)) + return (cacheDir, false); + + throw new InvalidOperationException("dl.error.unreachable"); + } + + private static IEnumerable ArchiveCandidates(string url, string? branch) + { + if (url.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) + { + yield return url; + yield break; + } + + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) yield break; + var segments = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries); + if (segments.Length < 2) yield break; + + var owner = segments[0]; + var repo = segments[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase) + ? segments[1][..^4] + : segments[1]; + var host = uri.Host.ToLowerInvariant(); + + var branches = new List(); + if (!string.IsNullOrWhiteSpace(branch)) branches.Add(branch!); + else if (host.Contains("gitee")) { branches.Add("master"); branches.Add("main"); } + else { branches.Add("main"); branches.Add("master"); } + + foreach (var b in branches) + { + if (host.Contains("github.com")) + yield return $"https://codeload.github.com/{owner}/{repo}/zip/refs/heads/{b}"; + else if (host.Contains("gitlab")) + yield return $"https://gitlab.com/{owner}/{repo}/-/archive/{b}/{repo}-{b}.zip"; + else if (host.Contains("gitee.com")) + yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip"; + else + yield break; + } + } + + private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct) + { + var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tmpRoot); + var zipPath = Path.Combine(tmpRoot, "source.zip"); + try + { + using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct)) + { + response.EnsureSuccessStatusCode(); + await using var input = await response.Content.ReadAsStreamAsync(ct); + await using var output = File.Create(zipPath); + await input.CopyToAsync(output, 81920, ct); + } + + var extractDir = Path.Combine(tmpRoot, "extract"); + Directory.CreateDirectory(extractDir); + ZipFile.ExtractToDirectory(zipPath, extractDir, true); + + var root = FindModelRoot(extractDir) ?? extractDir; + foreach (var entry in Directory.GetFileSystemEntries(root)) + { + var name = Path.GetFileName(entry); + var dest = Path.Combine(cacheDir, 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); + } + } + finally + { + try { if (Directory.Exists(tmpRoot)) Directory.Delete(tmpRoot, true); } catch { } + } + } + + private static string? FindModelRoot(string dir, int depth = 0) + { + if (Directory.Exists(Path.Combine(dir, "model"))) return dir; + if (depth >= 2) return null; + foreach (var child in Directory.GetDirectories(dir)) + { + var found = FindModelRoot(child, depth + 1); + if (found != null) return found; + } + return null; + } + + private static async Task TryGitCloneAsync(string url, string cacheDir, string? branch, CancellationToken ct) + { + if (cacheDir.Length > 0 && Directory.Exists(cacheDir)) + { + foreach (var f in Directory.GetFileSystemEntries(cacheDir)) + { + if (Directory.Exists(f)) Directory.Delete(f, true); + else File.Delete(f); + } + } + + var args = new List { "clone", "--depth", "1" }; + if (!string.IsNullOrWhiteSpace(branch)) { args.Add("--branch"); args.Add(branch!); } + args.Add(url); + args.Add(cacheDir); + + try + { + var psi = new ProcessStartInfo("git") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }; + foreach (var a in args) psi.ArgumentList.Add(a); + + using var process = Process.Start(psi); + if (process == null) return false; + var stderrTask = process.StandardError.ReadToEndAsync(ct); + await process.WaitForExitAsync(ct); + var stderr = await stderrTask; + if (process.ExitCode != 0) + { + Console.Error.WriteLine($"git clone 失败: {stderr}"); + return false; + } + return Directory.Exists(Path.Combine(cacheDir, "model")) || Directory.Exists(cacheDir); + } + catch (Exception ex) + { + Console.Error.WriteLine($"git clone 异常: {ex.Message}"); + return false; + } + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/SettingsService.cs b/src/main/dotnet/EarthModelStudio/Services/SettingsService.cs new file mode 100644 index 0000000..f2e757b --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/SettingsService.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.IO; +using EarthModelStudio.Models; + +namespace EarthModelStudio.Services; + +public sealed class SettingsService +{ + private readonly AppPaths _paths; + + public AppSettings Current { get; private set; } = new(); + public event Action? Changed; + + public SettingsService(AppPaths paths) => _paths = paths; + + public void Load() + { + Current = Json.Read(_paths.SettingsFile) ?? new AppSettings(); + if (Current.Sources.Count == 0) SeedSources(); + if (Current.MemoryMb < 256) Current.MemoryMb = 2048; + } + + /// + /// 首次启动不预置任何模型源:启动器只做适配,模型内容由用户从链接导入。 + /// 这里只给一条空的自定义源占位。 + /// + private void SeedSources() + { + Current.Sources.Add(new ModelSource + { + Id = "custom", + Name = "自定义源", + Url = "", + Enabled = false + }); + Save(); + } + + public void Save() + { + try + { + Json.Write(_paths.SettingsFile, Current); + } + catch (Exception ex) + { + Console.Error.WriteLine($"保存设置失败: {ex.Message}"); + } + } + + public void Apply(Action mutate) + { + mutate(Current); + Save(); + Changed?.Invoke(); + } + + public void Notify() + { + Save(); + Changed?.Invoke(); + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/Shell.cs b/src/main/dotnet/EarthModelStudio/Services/Shell.cs new file mode 100644 index 0000000..e0304f4 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/Shell.cs @@ -0,0 +1,30 @@ +using System; +using System.Diagnostics; +using System.IO; + +namespace EarthModelStudio.Services; + +public static class Shell +{ + public static void OpenFolder(string path) + { + if (string.IsNullOrWhiteSpace(path)) return; + 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); + } + catch (Exception ex) + { + Console.Error.WriteLine($"打开目录失败: {ex.Message}"); + } + } +} diff --git a/src/main/dotnet/EarthModelStudio/Styles/AppTheme.axaml b/src/main/dotnet/EarthModelStudio/Styles/AppTheme.axaml new file mode 100644 index 0000000..51fa5c1 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Styles/AppTheme.axaml @@ -0,0 +1,249 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs b/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs new file mode 100644 index 0000000..7928908 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs @@ -0,0 +1,372 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Input; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using EarthModelStudio.Models; +using EarthModelStudio.Services; + +namespace EarthModelStudio.ViewModels; + +public partial class DownloadViewModel : ObservableObject +{ + private readonly AppServices _services; + private readonly MainViewModel _main; + private bool _initialized; + + public ObservableCollection Sources { get; } = new(); + public ObservableCollection Models { get; } = new(); + public ObservableCollection Jobs => _services.Downloads.Jobs; + + [ObservableProperty] private SourceItemViewModel? _selectedSource; + [ObservableProperty] private string _importUrl = ""; + [ObservableProperty] private bool _isBusy; + [ObservableProperty] private string _statusMessage = ""; + [ObservableProperty] private bool _hasModels; + [ObservableProperty] private bool _isBackgroundOpen = true; + [ObservableProperty] private string _jobSummary = ""; + [ObservableProperty] private bool _hasJobs; + [ObservableProperty] private bool _isSourceEmpty; + + public DownloadViewModel(AppServices services, MainViewModel main) + { + _services = services; + _main = main; + Jobs.CollectionChanged += OnJobsChanged; + foreach (var job in Jobs) job.PropertyChanged += OnJobPropertyChanged; + L.I.LanguageChanged += RefreshLanguage; + RebuildSources(); + UpdateJobState(); + } + + public string BackgroundTitle => L.I["dl.background"]; + public string ImportHint => L.I["dl.hint"]; + + // ------------------------------------------------------------ 页面生命周期 + public void OnShown() + { + if (_initialized) return; + _initialized = true; + if (SelectedSource == null) + SelectedSource = Sources.FirstOrDefault(s => s.Model.Enabled && !string.IsNullOrWhiteSpace(s.Model.Url)) + ?? Sources.FirstOrDefault(); + } + + // ------------------------------------------------------------ 模型源 + private void RebuildSources() + { + var keepId = SelectedSource?.Model.Id; + Sources.Clear(); + foreach (var source in _services.Settings.Current.Sources) + Sources.Add(new SourceItemViewModel(source, this, _services)); + + SelectedSource = Sources.FirstOrDefault(s => s.Model.Id == keepId) ?? SelectedSource; + } + + partial void OnSelectedSourceChanged(SourceItemViewModel? value) + { + if (value == null) return; + if (string.IsNullOrWhiteSpace(value.Model.Url)) + { + Models.Clear(); + HasModels = false; + IsSourceEmpty = true; + StatusMessage = L.I["dl.pickSource"]; + return; + } + _ = LoadAsync(value, force: false); + } + + internal void OnSourceEnabledChanged(SourceItemViewModel source) + { + if (!source.Model.Enabled && SelectedSource == source) Models.Clear(); + } + + internal void RemoveSource(SourceItemViewModel source) + { + _services.Settings.Current.Sources.Remove(source.Model); + _services.Settings.Save(); + var wasSelected = SelectedSource == source; + Sources.Remove(source); + if (wasSelected) + { + SelectedSource = Sources.FirstOrDefault(); + if (SelectedSource == null) + { + Models.Clear(); + HasModels = false; + } + } + } + + [RelayCommand] + private async Task ImportAsync() + { + var url = ImportUrl.Trim(); + if (string.IsNullOrWhiteSpace(url)) + { + StatusMessage = L.I["dl.error.emptyUrl"]; + return; + } + + var source = new ModelSource + { + Name = DeriveName(url), + Url = url, + Enabled = true + }; + _services.Settings.Current.Sources.Add(source); + _services.Settings.Save(); + + var item = new SourceItemViewModel(source, this, _services); + Sources.Add(item); + ImportUrl = ""; + SelectedSource = item; + await LoadAsync(item, force: true); + } + + private static string DeriveName(string url) + { + var trimmed = url.TrimEnd('/', '\\'); + var slash = trimmed.LastIndexOfAny(new[] { '/', '\\' }); + var name = slash >= 0 ? trimmed[(slash + 1)..] : trimmed; + if (name.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) name = name[..^4]; + if (name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) name = name[..^4]; + return string.IsNullOrWhiteSpace(name) ? url : name; + } + + [RelayCommand] + private async Task RefreshAsync() + { + if (SelectedSource == null) return; + await LoadAsync(SelectedSource, force: true); + } + + internal async Task RefreshFromSource(SourceItemViewModel source) + { + SelectedSource = source; + await LoadAsync(source, force: true); + } + + private async Task LoadAsync(SourceItemViewModel source, bool force) + { + if (!source.Model.Enabled) return; + IsBusy = true; + StatusMessage = L.I["dl.syncing"]; + try + { + var index = await _services.Sources.FetchAsync(source.Model, force, null, CancellationToken.None); + if (SelectedSource != source) return; + + if (index.Error != null) + { + Models.Clear(); + HasModels = false; + IsSourceEmpty = true; + StatusMessage = DescribeError(index.Error); + return; + } + + var installedIds = new HashSet( + _services.Models.Scan().Select(p => p.Id), StringComparer.OrdinalIgnoreCase); + + Models.Clear(); + foreach (var model in index.Models) + { + Models.Add(new RemoteModelRowViewModel(model, source, + installedIds.Contains(model.Id), DownloadCommand)); + } + + HasModels = Models.Count > 0; + IsSourceEmpty = Models.Count == 0; + StatusMessage = index.FromCache + ? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}" + : L.I.F("dl.ready", Models.Count); + } + catch (Exception ex) + { + StatusMessage = ex.Message; + } + finally + { + IsBusy = false; + } + } + + private static string DescribeError(string error) + { + if (error.StartsWith("dl.", StringComparison.Ordinal)) + { + var text = L.I[error]; + return text == error ? error : text; + } + return error; + } + + // ------------------------------------------------------------ 下载 + [RelayCommand] + private async Task DownloadAsync(RemoteModelRowViewModel row) + { + if (row == null) return; + row.RowOpacity = 0; + row.RowHeight = 0; + IsBackgroundOpen = true; + + _services.Downloads.Enqueue(row.Model); + + await Task.Delay(240); + Models.Remove(row); + HasModels = Models.Count > 0; + IsSourceEmpty = Models.Count == 0; + } + + [RelayCommand] + private void CancelJob(DownloadJob? job) + { + if (job != null) _services.Downloads.Cancel(job); + } + + [RelayCommand] + private void RetryJob(DownloadJob? job) + { + if (job != null) _services.Downloads.Retry(job); + } + + [RelayCommand] + private void RemoveJob(DownloadJob? job) + { + if (job != null) _services.Downloads.Remove(job); + } + + [RelayCommand] + private void ClearFinished() => _services.Downloads.ClearFinished(); + + [RelayCommand] + private void ToggleBackground() => IsBackgroundOpen = !IsBackgroundOpen; + + // ------------------------------------------------------------ 任务展示 + private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e) + { + if (e.NewItems != null) + foreach (DownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged; + if (e.OldItems != null) + foreach (DownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged; + UpdateJobState(); + } + + private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(DownloadJob.State)) + { + if (sender is DownloadJob { State: DownloadState.Completed }) + _services.Models.NotifyChanged(); + } + UpdateJobState(); + } + + private void UpdateJobState() + { + HasJobs = Jobs.Count > 0; + JobSummary = $"{L.I["dl.background"]} ({Jobs.Count})"; + OnPropertyChanged(nameof(JobSummary)); + } + + private void RefreshLanguage() + { + foreach (var source in Sources) source.RefreshLanguage(); + foreach (var model in Models) model.RefreshLanguage(); + foreach (var job in Jobs) job.RefreshText(); + OnPropertyChanged(nameof(BackgroundTitle)); + OnPropertyChanged(nameof(ImportHint)); + UpdateJobState(); + } +} + +public partial class SourceItemViewModel : ObservableObject +{ + private readonly DownloadViewModel _owner; + private readonly AppServices _services; + + public ModelSource Model { get; } + + public SourceItemViewModel(ModelSource model, DownloadViewModel owner, AppServices services) + { + Model = model; + _owner = owner; + _services = services; + RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this)); + RefreshCommand = new AsyncRelayCommand(async () => await _owner.RefreshFromSource(this)); + } + + public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name; + public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost; + public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url); + + public bool Enabled + { + get => Model.Enabled; + set + { + if (Model.Enabled == value) return; + Model.Enabled = value; + _services.Settings.Save(); + OnPropertyChanged(); + _owner.OnSourceEnabledChanged(this); + } + } + + public ICommand RemoveCommand { get; } + public ICommand RefreshCommand { get; } + + public void RefreshLanguage() + { + OnPropertyChanged(nameof(Name)); + OnPropertyChanged(nameof(HostText)); + } +} + +public partial class RemoteModelRowViewModel : ObservableObject +{ + public RemoteModel Model { get; } + public SourceItemViewModel Source { get; } + + public RemoteModelRowViewModel(RemoteModel model, SourceItemViewModel source, bool installed, ICommand downloadCommand) + { + Model = model; + Source = source; + Installed = installed; + DownloadCommand = downloadCommand; + } + + public string Name => Model.LocalizedName; + public string Description => Model.LocalizedDescription; + public string VersionText => "v" + Model.Manifest.Version; + public string SizeText => ModelScanner.HumanSize(Model.SizeBytes); + public string MetaText => $"{VersionText} · {SizeText}"; + public string TagsText => string.Join(" · ", Model.Manifest.Tags ?? new List()); + public bool HasTags => !string.IsNullOrWhiteSpace(TagsText); + + [ObservableProperty] private bool _installed; + [ObservableProperty] private double _rowHeight = 92; + [ObservableProperty] private double _rowOpacity = 1; + + public string ButtonText => Installed ? L.I["dl.reinstall"] : L.I["dl.download"]; + public ICommand DownloadCommand { get; } + + partial void OnInstalledChanged(bool value) => OnPropertyChanged(nameof(ButtonText)); + + public void RefreshLanguage() + { + OnPropertyChanged(nameof(Name)); + OnPropertyChanged(nameof(Description)); + OnPropertyChanged(nameof(MetaText)); + OnPropertyChanged(nameof(TagsText)); + OnPropertyChanged(nameof(ButtonText)); + } +} diff --git a/src/main/dotnet/EarthModelStudio/ViewModels/HomeViewModel.cs b/src/main/dotnet/EarthModelStudio/ViewModels/HomeViewModel.cs new file mode 100644 index 0000000..40b9688 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/ViewModels/HomeViewModel.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.ObjectModel; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Input; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using EarthModelStudio.Models; +using Avalonia.Media.Imaging; +using EarthModelStudio.Services; + +namespace EarthModelStudio.ViewModels; + +public partial class HomeViewModel : ObservableObject +{ + private readonly AppServices _services; + private readonly MainViewModel _main; + + public ObservableCollection Models { get; } = new(); + + [ObservableProperty] private ModelCardViewModel? _selected; + [ObservableProperty] private bool _isEmpty; + + public string CountText => L.I.F("home.count", Models.Count); + public string SourceCountText => _services.Settings.Current.Sources + .Count(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url)).ToString(); + public string MemoryText => $"{_services.Memory.BudgetMb} MB"; + public string SelectedHint => Selected == null ? L.I["home.recent"] : L.I["home.launchHint"]; + + public HomeViewModel(AppServices services, MainViewModel main) + { + _services = services; + _main = main; + _services.Models.Changed += Refresh; + L.I.LanguageChanged += RefreshLanguage; + Refresh(); + } + + public void Refresh() + { + var keepId = Selected?.Package.Id; + Models.Clear(); + foreach (var package in _services.Models.Scan()) + Models.Add(new ModelCardViewModel(package, _services, this)); + + Selected = Models.FirstOrDefault(m => m.Package.Id == keepId) ?? Models.FirstOrDefault(); + IsEmpty = Models.Count == 0; + RefreshLanguage(); + } + + private void RefreshLanguage() + { + OnPropertyChanged(nameof(CountText)); + OnPropertyChanged(nameof(SourceCountText)); + OnPropertyChanged(nameof(MemoryText)); + OnPropertyChanged(nameof(SelectedHint)); + foreach (var model in Models) model.RefreshLanguage(); + } + + public void LaunchModel(ModelCardViewModel card) + { + Selected = card; + _main.PlayModel(card.Package); + } + + public async Task DeleteAsync(ModelCardViewModel card) + { + if (!await _main.ConfirmAsync(L.I.F("home.deleteConfirm", card.Name))) return; + _services.Models.Delete(card.Package.Id); + _services.Models.NotifyChanged(); + Refresh(); + } + + [RelayCommand] + private void Launch() + { + var card = Selected ?? Models.FirstOrDefault(); + if (card != null) _main.PlayModel(card.Package); + } + + [RelayCommand] + private void OpenDownload() => _main.GoDownload(); + + [RelayCommand] + private void OpenSettings() => _main.GoSettings(); + + [RelayCommand] + private void OpenFolder() => Shell.OpenFolder(_services.Paths.ModelRoot); +} + +public partial class ModelCardViewModel : ObservableObject +{ + private readonly AppServices _services; + private Bitmap? _preview; + + public ModelPackage Package { get; } + + public ModelCardViewModel(ModelPackage package, AppServices services, HomeViewModel home) + { + Package = package; + _services = services; + LaunchCommand = new RelayCommand(() => home.LaunchModel(this)); + DeleteCommand = new AsyncRelayCommand(() => home.DeleteAsync(this)); + OpenFolderCommand = new RelayCommand(() => Shell.OpenFolder(package.Directory)); + } + + public string Name => Package.LocalizedName; + public string Description => Package.LocalizedDescription; + public string VersionText => "v" + Package.Manifest.Version; + public string SizeText => ModelScanner.HumanSize(Package.SizeBytes); + public string MetaText => $"{VersionText} · {SizeText}"; + public string TagsText => string.Join(" · ", Package.Manifest.Tags ?? new()); + public bool HasTags => !string.IsNullOrWhiteSpace(TagsText); + public string AuthorText => string.IsNullOrWhiteSpace(Package.Manifest.Author) ? "" : Package.Manifest.Author; + + /// 封面图来自模型包自带的 preview.png —— 启动器只显示,不渲染。 + public Bitmap? Preview + { + get + { + if (_preview != null) return _preview; + try + { + if (File.Exists(Package.PreviewPath)) _preview = new Bitmap(Package.PreviewPath); + } + catch (Exception ex) + { + Console.Error.WriteLine($"读取模型封面失败 {Package.Id}: {ex.Message}"); + } + return _preview; + } + } + + public bool HasPreview => Preview != null; + + public ICommand LaunchCommand { get; } + public ICommand DeleteCommand { get; } + public ICommand OpenFolderCommand { get; } + + public void RefreshLanguage() + { + OnPropertyChanged(nameof(Name)); + OnPropertyChanged(nameof(Description)); + OnPropertyChanged(nameof(MetaText)); + OnPropertyChanged(nameof(TagsText)); + } +} diff --git a/src/main/dotnet/EarthModelStudio/ViewModels/MainViewModel.cs b/src/main/dotnet/EarthModelStudio/ViewModels/MainViewModel.cs new file mode 100644 index 0000000..e951396 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/ViewModels/MainViewModel.cs @@ -0,0 +1,87 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using EarthModelStudio.Models; +using EarthModelStudio.Services; +using EarthModelStudio.ViewModels; + +namespace EarthModelStudio.ViewModels; + +public partial class MainViewModel : ObservableObject +{ + private readonly AppServices _services; + + public HomeViewModel Home { get; } + public DownloadViewModel Download { get; } + public SettingsViewModel Settings { get; } + + /// 模型宿主:按清单加载模型自带的功能程序集。 + public ModelHost Models { get; } + + [ObservableProperty] private ObservableObject _current = null!; + [ObservableProperty] private bool _isHomeActive = true; + [ObservableProperty] private bool _isDownloadActive; + [ObservableProperty] private bool _isSettingsActive; + + /// 由主窗口注入的确认对话框。 + public Func>? ConfirmHandler { get; set; } + + /// + /// 请求为新模型开一个独立窗口。真正创建窗口的是主窗口, + /// 因此同一个模型可以同时开多份,主界面也不会被替换。 + /// + public event Action? PlayerRequested; + + public string VersionText => "v1.0.0"; + public string PlatformText => RuntimeInformation.RuntimeIdentifier; + + public MainViewModel(AppServices services) + { + _services = services; + Models = services.ModelHost; + Home = new HomeViewModel(services, this); + Download = new DownloadViewModel(services, this); + Settings = new SettingsViewModel(services); + Current = Home; + } + + partial void OnCurrentChanged(ObservableObject value) + { + IsHomeActive = value is HomeViewModel; + IsDownloadActive = value is DownloadViewModel; + IsSettingsActive = value is SettingsViewModel; + } + + [RelayCommand] + public void GoHome() + { + Home.Refresh(); + Current = Home; + } + + [RelayCommand] + public void GoDownload() + { + Current = Download; + Download.OnShown(); + } + + [RelayCommand] + public void GoSettings() + { + Settings.Refresh(); + Current = Settings; + } + + /// 启动模型:交给模型自己的程序集,在独立窗口中运行。 + public void PlayModel(ModelPackage package) + { + _services.Memory.Refresh(); + PlayerRequested?.Invoke(package); + } + + public async Task ConfirmAsync(string message) + => ConfirmHandler == null || await ConfirmHandler(message); +} diff --git a/src/main/dotnet/EarthModelStudio/ViewModels/SettingsViewModel.cs b/src/main/dotnet/EarthModelStudio/ViewModels/SettingsViewModel.cs new file mode 100644 index 0000000..468c928 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/ViewModels/SettingsViewModel.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Runtime.InteropServices; +using System.Windows.Input; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using EarthModelStudio.Models; +using EarthModelStudio.Services; + +namespace EarthModelStudio.ViewModels; + +public sealed class LanguageOption +{ + public string Code { get; init; } = "auto"; + public string Label { get; set; } = ""; + public override string ToString() => Label; +} + +public partial class SettingsViewModel : ObservableObject +{ + private readonly AppServices _services; + private bool _loading = true; + + public ObservableCollection Sources { get; } = new(); + public ObservableCollection Languages { get; } = new(); + public int[] FrameRates { get; } = { 24, 30, 60 }; + + [ObservableProperty] private LanguageOption? _selectedLanguage; + [ObservableProperty] private int _selectedFps = 30; + [ObservableProperty] private double _memoryValue = 2048; + [ObservableProperty] private string _statusMessage = ""; + + public string MemoryValueText => $"{(int)Math.Round(MemoryValue)} MB"; + public string UsageText => _services.Memory.UsageText; + public string ModelRoot => _services.Paths.ModelRoot; + public string DataRoot => _services.Paths.DataRoot; + public string PlatformText => $"{RuntimeInformation.OSDescription} · {RuntimeInformation.RuntimeIdentifier}"; + public string VersionText => "v1.0.0"; + public string MemoryHint => L.I["set.memory.hint"]; + + public SettingsViewModel(AppServices services) + { + _services = services; + L.I.LanguageChanged += OnLanguageChanged; + Refresh(); + _loading = false; + } + + public void Refresh() + { + _loading = true; + BuildLanguages(); + var settings = _services.Settings.Current; + SelectedFps = settings.RenderFps; + MemoryValue = settings.MemoryMb; + + Sources.Clear(); + foreach (var source in settings.Sources) + Sources.Add(new SettingsSourceViewModel(source, _services, this)); + + _loading = false; + OnPropertyChanged(nameof(UsageText)); + OnPropertyChanged(nameof(MemoryValueText)); + OnPropertyChanged(nameof(MemoryHint)); + OnPropertyChanged(nameof(ModelRoot)); + OnPropertyChanged(nameof(DataRoot)); + } + + private void BuildLanguages() + { + var current = _services.Settings.Current.Language; + Languages.Clear(); + Languages.Add(new LanguageOption { Code = "auto", Label = L.I["set.language.auto"] }); + foreach (var (code, label) in L.Supported) + Languages.Add(new LanguageOption { Code = code, Label = label }); + SelectedLanguage = Languages.FirstOrDefault(l => l.Code == current) ?? Languages[0]; + } + + private void OnLanguageChanged() + { + _loading = true; + BuildLanguages(); + _loading = false; + Refresh(); + } + + partial void OnSelectedLanguageChanged(LanguageOption? value) + { + if (_loading || value == null) return; + _services.Settings.Apply(s => s.Language = value.Code); + L.I.SetLanguage(value.Code); + } + + partial void OnSelectedFpsChanged(int value) + { + if (_loading) return; + _services.Settings.Apply(s => s.RenderFps = Math.Clamp(value, 12, 120)); + } + + partial void OnMemoryValueChanged(double value) + { + if (_loading) return; + var mb = (int)Math.Round(value); + _services.Settings.Apply(s => s.MemoryMb = mb); + _services.Memory.Apply(mb); + OnPropertyChanged(nameof(MemoryValueText)); + OnPropertyChanged(nameof(UsageText)); + } + + [RelayCommand] + private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot); + + [RelayCommand] + private void OpenDataFolder() => Shell.OpenFolder(_services.Paths.DataRoot); + + [RelayCommand] + private void ClearCache() + { + // 模型数据由模型自己管理;这里只回收启动器侧托管内存 + GC.Collect(); + GC.WaitForPendingFinalizers(); + _services.Memory.Refresh(); + StatusMessage = L.I["set.cacheCleared"]; + OnPropertyChanged(nameof(UsageText)); + } + + [RelayCommand] + private void ApplyMemory() + { + _services.Memory.Apply((int)Math.Round(MemoryValue)); + StatusMessage = L.I["common.applied"]; + OnPropertyChanged(nameof(UsageText)); + } + + internal void RemoveSource(SettingsSourceViewModel source) + { + _services.Settings.Current.Sources.Remove(source.Model); + _services.Settings.Save(); + Sources.Remove(source); + _services.Settings.Notify(); + } +} + +public partial class SettingsSourceViewModel : ObservableObject +{ + private readonly AppServices _services; + private readonly SettingsViewModel _owner; + + public ModelSource Model { get; } + + public SettingsSourceViewModel(ModelSource model, AppServices services, SettingsViewModel owner) + { + Model = model; + _services = services; + _owner = owner; + RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this)); + } + + public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name; + public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url; + + public bool Enabled + { + get => Model.Enabled; + set + { + if (Model.Enabled == value) return; + Model.Enabled = value; + _services.Settings.Save(); + OnPropertyChanged(); + } + } + + public ICommand RemoveCommand { get; } +} diff --git a/src/main/dotnet/EarthModelStudio/Views/ConfirmWindow.axaml b/src/main/dotnet/EarthModelStudio/Views/ConfirmWindow.axaml new file mode 100644 index 0000000..15f3ce2 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Views/ConfirmWindow.axaml @@ -0,0 +1,19 @@ + + + + + + +