refactor: 全窗口统一 Avalonia,移除 Flutter/Dart,新增 Java 实现
PR 审核 / 后端编译 (pull_request) Waiting to run
PR 审核 / 前端检查(Flutter) (pull_request) Waiting to run
PR 审核 / 安全扫描 (pull_request) Waiting to run

- 恢复同代 GC Avalonia 主界面(主页/下载/设置/关于)替换 Flutter
- 模型窗口统一 Avalonia;HTML 课件用 WebView.Avalonia 内嵌渲染
- 新增 CoursewareServer(回环 HTTP + Range)与 CoursewareWindow
- 彻底移除 Flutter/Dart 前端及构建脚本相关逻辑
- 新增 ./build.sh run 开发运行命令
- 项目源码整理到 C#/ 子目录,新增 Java/ 实现
- 工作日志随项目迁移
This commit is contained in:
Morris committed 2026-11-27 10:09:30 +08:00
1 parent 3f1f48f54c
commit cf05e886ac
405 files changed
+18226 -19263

No files matched your search

+193
View File
@@ -0,0 +1,193 @@
# 模型库(model/)
这个目录是**模型**,包含模型自己的**源码 + 数据 + 功能程序集 + 封面 + 语言包**。
`src/`(启动器)只做四件事:扫描模型、下载模型、开窗口加载模型、检查更新。**启动器没有任何渲染逻辑,发布包也不内置模型**。
> 模型相关的一切都在 `model/` 里:共享引擎源码 `model/_engine/`、契约源码 `model/_sdk/`、
> 每个模型自己的源码 `model/<id>/src/`,编译产物与数据 `model/<id>/<id>.model/`。
> 仓库根还包含 `GC-DOWNLOAD/` 下载更新项目;这里的 `model/` 仍独立保存模型源码与可分发内容。
- 发布态模型库在 **`<可执行文件>/.GC/model/`**;开发态直接用仓库根 `model/`
- 优先级:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 发布态 `.GC/model/`
- 一个模型 = 一个文件夹,文件夹名即模型 id;`_sdk/`、`_engine/` 是下划线开头的共享目录,不会被当成模型
- 模型可以单独打包、单独分发,也可以放进 git 仓库当模型源
## 目录结构
```
model/
version.json # 版本清单(与仓库根 version.json 相同,自动生成)
_sdk/GC.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码)
_engine/ # 共享引擎源码
src/ # CelestialView / PlanetTexture / EarthModelView / SphereRaster…
PreviewGen/ # 用模型渲染器生成封面的小工具
VersionStamp/ # 生成 version.json(手写版本 + 完整性哈希)
<模型 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
```
## 版本、指纹与完整性
`./build.sh models`(或 `./build.sh stamp`)会调用 `model/_engine/VersionStamp`:
1. 读每个模型的 `<id>.json`,**保留作者手写的 `version`**(如 `1.6`)——
版本号是对用户可见的语义版本,不由指纹自动覆盖;
2. 计算 `build`:`<id>.json`(去掉 `build` / `updatedAt`)与 `<id>.model/` 下所有文件
按路径排序后的 SHA-256 指纹前 10 位,**仅用于构建溯源**;
3. 计算完整性哈希(客户端下载后会复算,不一致就丢弃):
- `manifestSha256` = 清单文件本身的 sha256
- `filesSha256` = `<id>.model` 目录指纹
4. 生成仓库根 `version.json` 与 `model/version.json`(内容相同),再用
`.signing/gc-signing.pem` 签名(ECDSA P-256),两份文件写的是**同一份签名**。
**改了模型内容必须手动升 `version`**,否则客户端认为版本没变,不会下载。
(`build` 会变,但它不参与版本比较。)
哈希算法(构建端与客户端共用 `GC/src/Security/ContentHash.cs`,不会出现两套实现):
```
fileHash = SHA256(文件字节)
dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接 "<相对路径>\0<fileHash>\n" )
```
相对路径统一 `/`,跳过 `.` 开头文件、`bin/`、`obj/`、`*.user`;不含时间戳/权限位。
安装成功后客户端会在模型目录写 `<id>.integrity.json`,每次加载 dll 前抽查
dll / json 的哈希 —— 本地文件被替换会直接拒绝加载。
## `<id>.json`(模型清单,启动器只读它)
```json
{
"id": "earth-rotation",
"name": "Earth Rotation",
"nameI18n": { "zh-CN": "地球自转", "en": "Earth Rotation" },
"description": "……",
"descriptionI18n": { "zh-CN": "……", "en": "……" },
"version": "1.6",
"updatedAt": "2026-11-14T08:00:00Z",
"author": "Morris",
"tags": ["astronomy", "geography"],
"assembly": "EarthRotationModel.dll",
"type": "GC.EarthModels.RotationModelFactory",
"preview": "preview.png",
"apiVersion": 1,
"minAppVersion": "1.0.7"
}
```
| 字段 | 作用 |
| --- | --- |
| `version` | **作者手写**的语义版本;客户端靠它判断是否需要更新 |
| `assembly` | 功能程序集文件名,相对 `<id>.model`;留空按 `<id>.dll` 找 |
| `type` | 实现 `IModelFactory` 的完整类型名;留空则自动找第一个实现 |
| `preview` | 封面图,默认 `preview.png` |
| `apiVersion` | 模型契约版本,目前为 1;高于启动器支持版本会拒绝加载并提示升级 |
| `minAppVersion` | 可选,要求的最低启动器版本(如 `1.0.7`) |
`build` / `manifestSha256` / `filesSha256`(只出现在 `version.json` 里)由构建自动写入,
**不要手改**。
## 最小可分发结构
一个能跑的最小模型只需要三个文件:
```
model/hello/
hello.json # 清单(id / version / assembly / type / apiVersion)
hello.model/
HelloModel.dll # 实现 IModelFactory,返回任意 Avalonia 控件
```
其余(`preview.png`、`i18n/`、`scene.json`、`land.json`)都是可选的:
没有封面用默认灰图,没有语言包用清单里的 `name` / `description`。
源码放在同目录的 `src/` 里,`./build.sh models` 会自动编译并把 dll 复制进 `hello.model/`。
## 模型契约(model/_sdk)
模型只依赖一个极小的契约程序集 `GC.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` 教学要点
- `orbit.seasonLayout`:`springTopSummerLeft` = **上春分、左夏至**(下秋分、右冬至),季节角度与直射纬度读数不变
- `planet.axialTiltDeg` / `planet.tropicDeg`:教材值 **23.5°**(极圈自动算 90 − 23.5 = 66.5°)
- `orbit.seasons[].declinationDeg`:二分二至的太阳直射纬度(0 / +23.5 / 0 / −23.5),
定格时读数直接取这个值,不用近似公式
- `orbit.seasons[].teachingI18n`:该节气的课堂现象说明(中英双语,写在模型数据里)
- `orbit.seasons[].date`:教材日期(3/21、6/22、9/23、12/22),定格时 HUD 与课堂卡都用它
- `land.json`:大陆轮廓,`{ "polygons": [ { "name": "...", "points": [[lon,lat], ...] } ] }`
## 语言包
`<id>.model/i18n/<language>.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/<id>/src/` 里新建类库项目(可引用 `model/_engine/src` 的共享代码,也可完全自己写)
2. 写一个 `IModelFactory` 实现:`Prepare` 里读数据算纹理并 `ReportProgress`,`CreateView` 里返回控件
3. 在 `model/<id>/` 放清单和 `<id>.model/` 数据目录,用 `assembly` / `type` 指向你的 dll
4. `./build.sh models` 会自动编译每个模型、把 dll 复制进对应 `<id>.model/`、生成封面、打版本并写进 `version.json`
5. 推送仓库,客户端下次启动自动下载 —— 不用改启动器、不用重新发布程序
## 作为模型源分发
- **自动更新(推荐)**:把 `version.json` 和 `model/` 推到 gitcode 仓库,启动器开机自检并下载到 `.GC/model/`
- **离线源**:把整个仓库目录(含 `version.json` + `model/`)拷到 U 盘 / 共享盘,
在 `.GC/config/settings.json` 填 `updateLocalRoot` 指向它
- **手动导入**:在「下载」页粘贴任意 git 仓库 / zip / 本地目录,读取其中的 `model/` 文件夹
> 三种方式都会**验签**:`version.json` 必须由受信任私钥签名,否则客户端拒绝安装。
> 自己维护分支时,用 `dotnet run --project GC-SAVEDOG -- keygen` 生成密钥,
> 把公钥加进 `GC/src/Security/SignatureKeyring.cs`,再用 `--sign`/`build.sh stamp` 签名。
+229
View File
@@ -0,0 +1,229 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using GC.Services;
// VersionStamp:构建时自动给模型打版本。
// 用法:dotnet run --project model/_engine/VersionStamp -- <仓库根> <启动器版本>
// 输出:更新 model/<id>/<id>.json 的 version / updatedAt,并生成
// 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。
// 仓库地址(编译产物的 Release 也发在这里):与启动器默认 updateRepository 保持一致。
const string Repository = "https://git.xhmcl.com/Morris/GC";
// 位置参数:<仓库根> <启动器版本>;开关:--launcher-only
// --launcher-only 只刷新 launcher.packages(构建脚本在打完 zip 之后再调一次),
// 不重算模型指纹 —— 模型文件可能有几百 MB,重复哈希纯属浪费。
var positional = args.Where(a => !a.StartsWith("--", StringComparison.Ordinal)).ToArray();
var launcherOnly = args.Any(a => a.Equals("--launcher-only", StringComparison.OrdinalIgnoreCase));
var root = positional.Length > 0 ? Path.GetFullPath(positional[0]) : Directory.GetCurrentDirectory();
var launcherVersion = positional.Length > 1 && !string.IsNullOrWhiteSpace(positional[1])
? positional[1] : "1.0.0";
var modelRoot = Path.Combine(root, "model");
if (!Directory.Exists(modelRoot))
{
Console.Error.WriteLine($"找不到模型库: {modelRoot}");
return 1;
}
var relaxed = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
static string Rel(string baseDir, string file) =>
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
static bool Distributable(string file)
{
var name = Path.GetFileName(file);
if (name.StartsWith('.')) return false;
if (name.EndsWith(".user", StringComparison.OrdinalIgnoreCase)) return false;
var rel = file.Replace('\\', '/');
return !rel.Contains("/bin/", StringComparison.OrdinalIgnoreCase) &&
!rel.Contains("/obj/", StringComparison.OrdinalIgnoreCase) &&
!rel.EndsWith(".installing", StringComparison.OrdinalIgnoreCase);
}
static string Fingerprint(IEnumerable<byte[]> chunks)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
foreach (var chunk in chunks) hash.AppendData(chunk);
return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
}
var models = new List<Dictionary<string, object>>();
if (!launcherOnly)
{
Console.WriteLine("==> 自动计算模型版本(按模型包内容指纹)");
foreach (var dir in Directory.GetDirectories(modelRoot)
.OrderBy(p => Path.GetFileName(p), StringComparer.Ordinal))
{
var id = Path.GetFileName(dir);
if (id.StartsWith('_')) continue; // _sdk / _engine 是共享源码,不是模型
var manifestPath = Path.Combine(dir, id + ".json");
var dataDir = Path.Combine(dir, id + ".model");
if (!File.Exists(manifestPath) || !Directory.Exists(dataDir)) continue;
var manifest = JsonNode.Parse(File.ReadAllText(manifestPath))?.AsObject();
if (manifest == null) continue;
// 版本号由模型清单里手写的 version 决定(作者手动升到 1.0 / 1.1 …),
// 不再用内容指纹覆盖:指纹形式(1.0-393cb2b7d4)对用户不可读、也没有语义。
var declared = manifest["version"]?.GetValue<string>();
var version = string.IsNullOrWhiteSpace(declared) ? "1.0" : declared!.Trim();
// 内容指纹保留在 build 字段,仅用于构建溯源,不参与版本比较。
// 注意:updatedAt / build 都是构建元数据,必须从指纹里剔除,
// 否则「同一份内容」每次构建都会算出不同指纹(等于每次都触发更新)。
manifest.Remove("build");
manifest.Remove("updatedAt");
var canonical = manifest.ToJsonString(new JsonSerializerOptions { WriteIndented = false });
var chunks = new List<byte[]> { Encoding.UTF8.GetBytes(canonical) };
foreach (var file in Directory.GetFiles(dataDir, "*", SearchOption.AllDirectories)
.Where(Distributable)
.OrderBy(f => Rel(dataDir, f), StringComparer.Ordinal))
{
chunks.Add(Encoding.UTF8.GetBytes("\n" + Rel(dataDir, file) + "\n"));
chunks.Add(File.ReadAllBytes(file));
}
var fingerprint = Fingerprint(chunks)[..10];
manifest["version"] = version;
manifest["build"] = fingerprint;
manifest["updatedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
var manifestText = manifest.ToJsonString(relaxed) + "\n";
File.WriteAllText(manifestPath, manifestText);
// 完整性哈希:客户端下载后按同一算法复算,不一致就丢弃。
// manifestSha256 = 清单文件本身的 sha256
// filesSha256 = <id>.model 目录指纹(算法见 GC/src/Security/ContentHash.cs)
var manifestSha = ContentHash.Sha256Hex(manifestText);
var filesMap = ContentHash.MapFiles(dataDir);
var filesSha = ContentHash.DirectoryHash(filesMap);
models.Add(new Dictionary<string, object>
{
["id"] = id,
["version"] = version,
["build"] = fingerprint,
["manifestSha256"] = manifestSha,
["filesSha256"] = filesSha,
["files"] = filesMap.Count,
["dir"] = "model/" + id
});
Console.WriteLine($" {id,-20} {version,-8} (build {fingerprint}, {filesMap.Count} files)");
}
} // !launcherOnly
// 启动器源码指纹(只展示,不触发升级;升级看 launcher.version)
var srcRoot = Path.Combine(root, "src");
var srcChunks = new List<byte[]>();
if (Directory.Exists(srcRoot))
{
foreach (var file in Directory.GetFiles(srcRoot, "*", SearchOption.AllDirectories)
.Where(Distributable)
.Where(f => f.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".axaml", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".props", StringComparison.OrdinalIgnoreCase))
.OrderBy(f => Rel(srcRoot, f), StringComparer.Ordinal))
{
srcChunks.Add(Encoding.UTF8.GetBytes(Rel(srcRoot, file) + "\n"));
srcChunks.Add(File.ReadAllBytes(file));
}
}
var launcherRevision = srcChunks.Count > 0 ? Fingerprint(srcChunks)[..10] : "";
var packages = new Dictionary<string, Dictionary<string, object>>();
// 启动器更新包的两种落点,清单里都写清楚,下载端按顺序尝试:
// 1) Release 附件(url)—— 常规发布方式;
// 2) 仓库里的编译产物 dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip ——
// 不发 Release、只提交产物也能更新(用户明确要求支持这种布局)。
// 两种都写:url 只是「去哪儿找」,真正的完整性凭据是下面的 sha256(受签名保护)。
var releaseBase = $"{Repository}/releases/download/{launcherVersion}";
foreach (var rid in new[] { "win-x64", "win-arm64", "osx-arm64", "osx-x64", "linux-arm64" })
{
var label = LauncherArtifacts.LabelOf(rid);
var fileName = LauncherArtifacts.PackageFileName(launcherVersion, rid);
var dir = $"dist/{label}";
var entry = new Dictionary<string, object>
{
["path"] = $"{dir}/{fileName}",
["dir"] = dir,
["name"] = fileName,
["url"] = $"{releaseBase}/{fileName}"
};
// 优先认平台产物目录,其次认 dist 根目录(历史构建把 zip 直接放在 dist/)
var zipPath = new[]
{
Path.Combine(root, dir.Replace('/', Path.DirectorySeparatorChar), fileName),
Path.Combine(root, "dist", fileName),
Path.Combine(root, "dist", $"GC-{rid}.zip")
}.FirstOrDefault(File.Exists);
if (zipPath != null)
{
var bytes = File.ReadAllBytes(zipPath);
entry["path"] = Rel(root, zipPath);
entry["sha256"] = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
entry["size"] = bytes.LongLength;
Console.WriteLine($" 包 {label,-12} {entry["path"]}({bytes.LongLength / 1024 / 1024} MB)");
}
else
{
Console.WriteLine($" 包 {label,-12} 未找到产物(清单里不会有 sha256,下载端会跳过该平台)");
}
packages[rid] = entry;
}
var versionDoc = new Dictionary<string, object>
{
["schema"] = 1,
["generated"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
["repository"] = Repository,
["branch"] = "main",
["modelDir"] = "model",
["launcher"] = new Dictionary<string, object>
{
["version"] = launcherVersion,
["revision"] = launcherRevision,
["packages"] = packages
},
["models"] = models
};
// --launcher-only:模型段沿用现有清单,只换启动器包,避免重复哈希几百 MB 模型文件
if (launcherOnly)
{
var manifestPath = Path.Combine(root, "version.json");
if (File.Exists(manifestPath))
{
var existing = JsonNode.Parse(File.ReadAllText(manifestPath))?.AsObject();
if (existing?["models"] is JsonNode existingModels)
versionDoc["models"] = existingModels.DeepClone();
if (existing?["generated"] is JsonNode generated)
versionDoc["generated"] = generated.DeepClone();
}
else
{
Console.Error.WriteLine("!! --launcher-only 需要已存在的 version.json,退回完整模式");
}
}
var json = JsonSerializer.Serialize(versionDoc, relaxed) + "\n";
File.WriteAllText(Path.Combine(root, "version.json"), json);
File.WriteAllText(Path.Combine(modelRoot, "version.json"), json);
Console.WriteLine($"==> version.json 已更新(启动器 {launcherVersion},模型 {models.Count} 个)");
return 0;
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>VersionStamp</AssemblyName>
<RootNamespace>VersionStamp</RootNamespace>
</PropertyGroup>
<ItemGroup>
<!-- 与启动器 / SAVEDOG 共用同一份哈希实现,保证"构建端算的"和"客户端验的"完全一致 -->
<Compile Include="..\..\..\GC\src\Security\ContentHash.cs" Link="Shared\ContentHash.cs" />
<!-- 平台标签与 dist 目录推导也共用:构建端写进清单的路径,必须和下载端找的路径一致 -->
<Compile Include="..\..\..\GC-DOWNLOAD\LauncherArtifacts.cs" Link="Shared\LauncherArtifacts.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>GC.ModelSdk</RootNamespace>
<AssemblyName>GC.ModelSdk</AssemblyName>
<IsPackable>false</IsPackable>
<Description>Earth Model 模型契约:启动器与模型之间唯一的编译期依赖。</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
</Project>
@@ -0,0 +1,77 @@
using System;
using Avalonia.Controls;
namespace GC.ModelSdk;
/// <summary>
/// 模型入口契约。模型程序集里必须有一个公开、无参构造的 <see cref="IModelFactory"/> 实现,
/// 启动器按模型清单里的 <c>assembly</c> + <c>type</c> 定位并创建它。
/// </summary>
public interface IModelFactory
{
/// <summary>
/// 契约版本。启动器目前支持 <b>1</b>。
/// 协商规则:必须与启动器支持的版本**相等**,否则启动器拒绝加载并提示用户更新;
/// 模型清单里还可以写 <c>minAppVersion</c> 要求更高的启动器版本。
/// 提升版本时必须保留旧接口的适配层,避免老客户端加载新模型后崩溃。
/// </summary>
int ApiVersion { get; }
/// <summary>创建一个模型运行时实例(每个窗口一个实例)。</summary>
IModelRuntime Create();
}
/// <summary>
/// 模型运行时:负责把模型自己的界面交给启动器。
/// 启动器只负责开窗口,**不参与任何渲染**。
///
/// 生命周期:<c>Create()</c> → <c>Prepare()</c>(后台线程,一次)→ <c>CreateView()</c>(UI 线程,一次)
/// → 用户关窗 → <c>Dispose()</c>(UI 线程)。<c>Dispose</c> 之后不要再调用任何
/// <see cref="IModelContext"/> 成员。
/// </summary>
public interface IModelRuntime : IDisposable
{
/// <summary>
/// 在**后台线程**准备数据(读文件、算纹理等),期间禁止创建或操作任何 UI 控件。
/// 启动器的进度窗会显示 <see cref="IModelContext.ReportProgress"/> 汇报的进度。
/// 默认空实现:模型也可以把准备工作留到 CreateView 里(那样会占用 UI 线程)。
/// </summary>
void Prepare(IModelContext context) { }
/// <summary>
/// 在 UI 线程创建模型窗口的内容。模型可以自由组合控件、自己画图、自己管动画。
/// 返回的控件会被直接放进窗口,铺满客户区。
/// </summary>
Control CreateView(IModelContext context);
}
/// <summary>启动器提供给模型的环境信息与能力。</summary>
public interface IModelContext
{
/// <summary>模型 id(即模型目录名)。</summary>
string ModelId { get; }
/// <summary>模型目录:<c>model/&lt;id&gt;</c>。</summary>
string ModelDirectory { get; }
/// <summary>模型数据目录:<c>model/&lt;id&gt;/&lt;id&gt;.model</c>,模型自己的场景数据、贴图、语言包都放这里。</summary>
string DataDirectory { get; }
/// <summary>界面语言(zh-CN / en)。模型应按它选择自己的文案。</summary>
string Language { get; }
/// <summary>用户在设置里分配的运行内存预算(MB),模型可据此控制缓存规模。</summary>
int MemoryBudgetMb { get; }
/// <summary>请求关闭承载此模型的窗口。**线程安全**,任意线程可调用。</summary>
void RequestClose();
/// <summary>
/// 汇报加载进度(0–1)与当前阶段文案。启动器的加载进度条会实时显示,
/// 也可以在任何时候调用(例如切换数据集时)。**线程安全**,任意线程可调用。
/// </summary>
void ReportProgress(double value, string? message = null);
/// <summary>输出日志(启动器会写到控制台)。**线程安全**,任意线程可调用。</summary>
void Log(string message);
}
+30
View File
@@ -0,0 +1,30 @@
{
"id": "contour-map",
"nameI18n": {
"zh-CN": "等高线地形图",
"en": "Contour Map"
},
"descriptionI18n": {
"zh-CN": "可旋转 3D 地形 + 等高切割/交线/投影/判坡四步动画,判读山峰、山脊、山谷、鞍部、陡崖五大典型地貌。",
"en": "Rotatable 3D terrain with a four-step animation of contour cutting, lines, projection and slope; identify five classic landforms."
},
"author": "Morris GC",
"tags": [
"geography",
"map",
"contour",
"terrain"
],
"assembly": "ContourMapModel.dll",
"type": "GC.ContourMap.ContourMapFactory",
"version": "1.2",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "d18eb85c8d",
"updatedAt": "2026-11-21T10:55:36Z"
}
@@ -0,0 +1,118 @@
{
"zh-CN": {
"title": "如何使用 · 等高线地形与五大典型地貌",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:点右下角「开始实验」,在立体地形里观察水平切面下降、交线形成、垂直投影与疏密判坡四步动画。",
"第 2 步:在立体地形上按住鼠标拖动可旋转视角,滚轮缩放;这是可交互的 3D 地形。",
"第 3 步:点画布上方「五大典型地貌」标签(山峰/山脊/山谷/鞍部/陡崖),画面换成对应的专门地形并叠加完整等高线,观察各自的等高线特征。",
"第 4 步:点底部「俯视图 / 立体图」在等高线地图与 3D 地形间切换;鼠标悬停任意位置,底部显示该点海拔与地形部位。",
"第 5 步:点「上色 / 取消上色」对比分层设色与纯等高线;点「全屏」进入全屏演示。"
]
},
{
"h": "键盘快捷键",
"lines": [
"空格:播放 / 暂停实验。",
"数字 1 – 5:依次切换到山峰、山脊、山谷、鞍部、陡崖。"
]
},
{
"h": "四步实验流程",
"lines": [
"等高切割:一个水平面从山顶向下移动,与山体在同一海拔相交。",
"形成交线:每个水平切面留下一条闭合交线,多层交线共同描述山体起伏。",
"投影成图:各高度的交线沿垂线投影到同一平面,累积成完整等高线图。",
"疏密判坡:坡度着色叠加等高线,陡处线密、缓处线疏。"
]
},
{
"h": "五大典型地貌的判读",
"lines": [
"山峰:等高线闭合,数值由中心向四周递减(若向内降低则为洼地)。",
"山脊:等高线向海拔低处凸出(凸低为脊),脊线是分水线。",
"山谷:等高线向海拔高处凸出(凸高为谷),谷线是集水线,常发育河流。",
"鞍部:两座山峰之间相对低洼,俯视轮廓呈马鞍状收腰。",
"陡崖:等高线密集甚至重合,近乎垂直;n 条线重合时 (n−1)d ≤ ΔH < (n+1)d。"
]
},
{
"h": "等高线基础",
"lines": [
"同一条等高线上各点海拔相等;相邻等高线之间的高差叫等高距(本图 100 米)。",
"等高线越密坡越陡,越疏坡越缓。",
"每 5 条加粗一条叫计曲线,标注海拔便于读数。",
"海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。"
]
},
{
"h": "地图符号",
"lines": [
"分层设色按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白)。",
"山峰用 ▲ 加高程数字标注;河流用蓝色线沿谷底绘制;陡崖用红色锯齿线表示。",
"指北针在图幅右上,比例尺在左下,分层设色图例在右下,地形剖面图在底部。"
]
}
]
},
"en": {
"title": "How to use · Contour Lines & Five Landforms",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: press Start to watch the four-step animation — contour cutting, line formation, vertical projection and slope reading.",
"Step 2: drag with the mouse to rotate the 3D terrain, scroll to zoom; it is fully interactive.",
"Step 3: click a landform tab above the canvas (peak / ridge / valley / saddle / cliff) to load its dedicated terrain with its full contour pattern.",
"Step 4: toggle Top view / 3D view at the bottom; hover anywhere to read elevation and terrain feature.",
"Step 5: use Colour / No colour to compare hypsometric tint with pure contour lines; use Fullscreen for presentation."
]
},
{
"h": "Keyboard shortcuts",
"lines": [
"Space: play / pause the experiment.",
"Numbers 1 – 5: switch to peak, ridge, valley, saddle, cliff."
]
},
{
"h": "The four experiment steps",
"lines": [
"Contour cutting: a horizontal plane descends from the summit and intersects the mountain at one elevation.",
"Forming lines: each slice leaves a closed intersection line; stacked lines describe the relief.",
"Projection: intersection lines are projected vertically onto one plane, building the contour map.",
"Slope density: slope shading over contours — dense lines mean steep, sparse lines mean gentle."
]
},
{
"h": "Reading the five landforms",
"lines": [
"Peak: closed contours, values decrease outward (if they decrease inward it is a depression).",
"Ridge: contours bulge toward lower ground; a watershed line.",
"Valley: contours bulge toward higher ground; a drainage line, often a stream.",
"Saddle: low ground between two peaks, pinched like a saddle in plan view.",
"Cliff: contours crowd or overlap, nearly vertical; n overlapping lines: (n−1)d ≤ ΔH < (n+1)d."
]
},
{
"h": "Contour basics",
"lines": [
"All points on one contour share the same elevation; the gap between neighbours is the contour interval (100 m here).",
"Closer contours mean steeper slopes; wider spacing means gentler slopes.",
"Every 5th contour is bolded as an index contour and labelled with elevation.",
"Elevation is height above sea level; relative height is the difference between two elevations."
]
},
{
"h": "Map symbols",
"lines": [
"Hypsometric tint uses fixed colour bands (dark green → light green → green → pale yellow → yellow → light brown → brown → white).",
"Peaks are marked with ▲ plus elevation; rivers are blue lines along valleys; cliffs use a red saw-tooth line.",
"North arrow top-right, scale bar bottom-left, tint legend bottom-right, terrain profile along the bottom."
]
}
]
}
}
@@ -0,0 +1,4 @@
{
"app.title": "Contour Lines · Five Classic Landforms",
"app.subtitle": "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs"
}
@@ -0,0 +1,4 @@
{
"app.title": "等高线地形 · 五大典型地貌判读",
"app.subtitle": "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>GC.ContourMap</RootNamespace>
<AssemblyName>ContourMapModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\GC.ModelSdk\GC.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using GC.ModelSdk;
namespace GC.ContourMap;
/// <summary>等高线模型入口(清单里的 type 指向这里)。</summary>
public sealed class ContourMapFactory : IModelFactory
{
public int ApiVersion => 1;
public IModelRuntime Create() => new ContourMapRuntime();
}
/// <summary>
/// 等高线模型运行时。
/// 依据人教版七年级上册「地形图的判读」:海拔与相对高度、等高线与等高距、
/// 山峰/山脊/山谷/鞍部/陡崖的判读、坡度陡缓与等高线疏密的关系。
/// </summary>
public sealed class ContourMapRuntime : IModelRuntime
{
private TerrainField? _field;
private Dictionary<string, string>? _texts;
private ContourPage? _page;
public void Prepare(IModelContext context)
{
context.ReportProgress(0.15, "生成地形高度场");
_field = new TerrainField(TerrainKind.Mountain, 192);
context.ReportProgress(0.70, "提取等高线");
_texts = LoadTexts(context.DataDirectory, context.Language);
context.ReportProgress(0.92, "准备界面");
context.Log($"[contour-map] 地形 {_field.Size}×{_field.Size}," +
$"海拔 {_field.MinHeight:0}~{_field.MaxHeight:0} m,等高距 {_field.EffectiveInterval:0} m");
}
public Control CreateView(IModelContext context)
{
_texts ??= LoadTexts(context.DataDirectory, context.Language);
// 实验地形 + 五大地貌都在界面里现场生成(切换很快,不必预先生成全部)
_page = new ContourPage(_texts);
return _page.Build();
}
public void Dispose()
{
_page?.Dispose();
_page = null;
_field = null;
_texts = null;
System.GC.SuppressFinalize(this);
}
/// <summary>
/// 文案 = 内置默认(保证任何语言都有词)+ dataDir/i18n/&lt;lang&gt;.json 覆盖。
/// 语言包缺失或某条没翻译时自动退回内置默认,不会露出裸 key。
/// </summary>
private static Dictionary<string, string> LoadTexts(string dataDir, string language)
{
var isEn = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
var map = new Dictionary<string, string>(DefaultTexts.Zh);
if (isEn) foreach (var kv in DefaultTexts.En) map[kv.Key] = kv.Value;
var candidates = new List<string>();
if (!string.IsNullOrWhiteSpace(language)) candidates.Add(language);
candidates.Add(isEn ? "en" : "zh-CN");
foreach (var lang in candidates)
{
var path = System.IO.Path.Combine(dataDir, "i18n", lang + ".json");
if (!System.IO.File.Exists(path)) continue;
try
{
using var doc = System.Text.Json.JsonDocument.Parse(System.IO.File.ReadAllText(path));
if (doc.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) continue;
foreach (var p in doc.RootElement.EnumerateObject())
{
if (p.Value.ValueKind != System.Text.Json.JsonValueKind.String) continue;
var v = p.Value.GetString();
if (!string.IsNullOrWhiteSpace(v)) map[p.Name] = v!;
}
break;
}
catch
{
// 语言包损坏不影响开课,继续用内置默认
}
}
return map;
}
}
+721
View File
@@ -0,0 +1,721 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
namespace GC.ContourMap;
/// <summary>
/// 等高线模型界面(完整复刻 HTML 课件功能):
/// 顶部标题 + 全屏;左侧可交互 3D 画布;右侧实验流程/五大地貌/判读要点观察面板;
/// 底部播放控制、俯视切换、上色开关、实时读数;支持键盘 1-5 / 空格快捷键。
/// </summary>
public sealed class ContourPage
{
private static readonly Color CAppBg = Color.Parse("#0B1524");
private static readonly Color CPanel = Color.Parse("#101E31");
private static readonly Color CPanel2 = Color.Parse("#16263C");
private static readonly Color CLine = Color.Parse("#1E3350");
private static readonly Color CInk = Color.Parse("#EAF2FF");
private static readonly Color CInkDim = Color.Parse("#93A8C6");
private static readonly Color CInkFaint = Color.Parse("#6A80A0");
private static readonly Color CAccent = Color.Parse("#4D8CFF");
private static readonly Color CWarn = Color.Parse("#FFB454");
private static readonly Color CGood = Color.Parse("#5FD69B");
private readonly Dictionary<string, string> _texts;
private readonly Dictionary<LandformKind, TerrainField> _landformCache = new();
private TerrainField _experimentField;
private ContourView? _view;
private TextBlock? _readout;
private TextBlock? _featureText;
private TextBlock? _hintText;
private TextBlock? _playLabel;
private TextBlock? _observeHeading;
private TextBlock? _observeSummary;
private StackPanel? _featureList;
private TextBlock? _viewToggleLabel;
private readonly List<Border> _flowButtons = new();
private readonly List<Border> _landformButtons = new();
private Border? _playBtn;
private Border? _backBtn;
private Border? _colorBtn;
private TextBlock? _colorBtnText;
private ProgressBar? _progress;
private int _step = 0;
private LandformKind? _selectedLandform;
private bool _disposed;
private TopLevel? _topLevel;
private static readonly LandformKind[] LandformOrder =
{ LandformKind.Peak, LandformKind.Ridge, LandformKind.Valley, LandformKind.Saddle, LandformKind.Cliff };
public ContourPage(Dictionary<string, string> texts)
{
_texts = texts;
_experimentField = new TerrainField(TerrainKind.Mountain, 192);
}
private string T(string key) => _texts.TryGetValue(key, out var v) ? v : key;
private string T(string key, params object[] args)
{
var s = T(key);
try { return string.Format(System.Globalization.CultureInfo.InvariantCulture, s, args); }
catch { return s; }
}
private static SolidColorBrush B(Color c) => new(c);
private TerrainField GetLandformField(LandformKind kind)
{
if (!_landformCache.TryGetValue(kind, out var f))
{
f = new TerrainField(kind, 192);
_landformCache[kind] = f;
}
return f;
}
public Control Build()
{
var root = new Grid { Background = B(CAppBg) };
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
root.RowDefinitions.Add(new RowDefinition(GridLength.Star));
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
root.Children.Add(BuildHeader());
var body = new Grid { Margin = new Thickness(12, 8, 12, 6) };
body.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(344)));
body.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
body.RowDefinitions.Add(new RowDefinition(GridLength.Star));
_view = new ContourView(_experimentField, T);
_view.HoverChanged += OnHover;
_view.StepChanged += OnStepChanged;
_view.ProgressChanged += OnProgressChanged;
_view.PlaybackFinished += OnPlaybackFinished;
var canvasHolder = new Border
{
Background = B(Color.Parse("#08111E")),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
ClipToBounds = true,
Child = _view
};
Grid.SetRow(canvasHolder, 1);
body.Children.Add(canvasHolder);
// ── 五大典型地貌标签(横向,像课件的选项卡)──
var tabs = new WrapPanel
{
Orientation = Orientation.Horizontal,
Margin = new Thickness(0, 0, 0, 8)
};
_backBtn = MakePillButton(T("btn.backExperiment"), CAccent);
_backBtn.IsVisible = false;
_backBtn.PointerPressed += (_, _) => BackToExperiment();
tabs.Children.Add(_backBtn);
foreach (var kind in LandformOrder)
{
var btn = MakeLandformButton(kind);
_landformButtons.Add(btn);
tabs.Children.Add(btn);
}
body.Children.Add(tabs);
var side = BuildSidePanel();
Grid.SetColumn(side, 1);
Grid.SetRow(side, 0);
Grid.SetRowSpan(side, 2);
body.Children.Add(side);
// 窄窗口(封面缩略图、小屏)隐藏右侧栏,画布优先;宽窗口才展示流程与观察面板
void ApplyResponsive(double width)
{
var narrow = width < 980;
side.IsVisible = !narrow;
body.ColumnDefinitions[1].Width = narrow ? new GridLength(0) : new GridLength(344);
}
root.SizeChanged += (_, e) => ApplyResponsive(e.NewSize.Width);
Grid.SetRow(body, 1);
root.Children.Add(body);
var footer = BuildFooter();
Grid.SetRow(footer, 2);
root.Children.Add(footer);
root.AttachedToVisualTree += (_, _) =>
{
_topLevel = TopLevel.GetTopLevel(root);
};
root.KeyDown += OnKeyDown;
root.Focusable = true;
return root;
}
/// <summary>窗口关闭时释放视图计时器,避免持有控件。</summary>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_view?.DisposeView();
}
private Control BuildHeader()
{
var title = new TextBlock
{
Text = T("app.title"),
Foreground = B(CInk),
FontSize = 18,
FontWeight = FontWeight.SemiBold
};
var sub = new TextBlock
{
Text = T("app.subtitle"),
Foreground = B(CInkDim),
FontSize = 11.5
};
var stack = new StackPanel { Spacing = 2 };
stack.Children.Add(title);
stack.Children.Add(sub);
var fsLabel = new TextBlock { Text = T("btn.fullscreen"), Foreground = B(CInk), FontSize = 11.5 };
var fsBtn = new Border
{
Background = B(CPanel2),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(12, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = fsLabel
};
fsBtn.PointerPressed += (_, _) => ToggleFullscreen(fsLabel);
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
grid.Children.Add(stack);
Grid.SetColumn(fsBtn, 1);
grid.Children.Add(fsBtn);
return new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 0, 0, 1),
Padding = new Thickness(18, 11, 18, 12),
Child = grid
};
}
private Control BuildSidePanel()
{
var panel = new StackPanel { Spacing = 8, Margin = new Thickness(12, 0, 0, 0) };
// ── 实验流程四步 ──
panel.Children.Add(Section(T("flow.title")));
for (var i = 0; i < 4; i++)
{
var btn = MakeFlowButton(i);
_flowButtons.Add(btn);
panel.Children.Add(btn);
}
panel.Children.Add(Divider());
// ── 观察面板 ──
_observeHeading = new TextBlock
{
Text = T("observe.title"),
Foreground = B(CWarn),
FontSize = 12.5,
FontWeight = FontWeight.SemiBold
};
_observeSummary = new TextBlock
{
Text = T("observe.default"),
Foreground = B(CInkDim),
FontSize = 10.5,
TextWrapping = TextWrapping.Wrap,
LineHeight = 16
};
_featureList = new StackPanel { Spacing = 3 };
RenderObservation(null);
panel.Children.Add(_observeHeading);
panel.Children.Add(_observeSummary);
panel.Children.Add(_featureList);
// ── 判读要点 ──
panel.Children.Add(Section(T("side.rules")));
panel.Children.Add(Bullet(T("rule.interval")));
panel.Children.Add(Bullet(T("rule.dense")));
panel.Children.Add(Bullet(T("rule.index")));
panel.Children.Add(Bullet(T("rule.height")));
var scroll = new ScrollViewer
{
Content = new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
Padding = new Thickness(14, 12),
Child = panel
},
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto
};
return scroll;
}
private Border MakeFlowButton(int index)
{
var name = new TextBlock
{
Text = $"{index + 1}. {T("flow.step." + index)}",
Foreground = B(CInk),
FontSize = 12.5,
FontWeight = FontWeight.SemiBold
};
var desc = new TextBlock
{
Text = T("flow.desc." + index),
Foreground = B(CInkFaint),
FontSize = 11,
TextWrapping = TextWrapping.Wrap,
LineHeight = 15
};
var stack = new StackPanel { Spacing = 1 };
stack.Children.Add(name);
stack.Children.Add(desc);
var border = new Border
{
Background = B(CPanel2),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(9, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = stack,
Tag = index
};
border.PointerPressed += (_, _) =>
{
BackToExperiment();
_view?.SetStep((ExperimentStep)index);
UpdateFlowStyles();
};
return border;
}
private Border MakeLandformButton(LandformKind kind)
{
var key = kind.ToString().ToLowerInvariant();
var name = new TextBlock
{
Text = T("landform." + key),
Foreground = B(CInk),
FontSize = 12.5,
FontWeight = FontWeight.SemiBold
};
var sub = new TextBlock
{
Text = T("landform." + key + ".sub"),
Foreground = B(CInkFaint),
FontSize = 10.5,
VerticalAlignment = VerticalAlignment.Center
};
var stack = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 7 };
stack.Children.Add(name);
stack.Children.Add(sub);
var border = new Border
{
Background = B(CPanel2),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(18),
Padding = new Thickness(14, 7),
Margin = new Thickness(0, 0, 8, 4),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = stack,
Tag = kind
};
border.PointerPressed += (_, _) => SelectLandform(kind);
return border;
}
private void SelectLandform(LandformKind kind)
{
_selectedLandform = kind;
_view?.Pause();
_view?.SetField(GetLandformField(kind));
_view?.SetMode(ViewMode.Perspective);
_view?.ShowContourPattern(); // 地貌专题先看完整的等高线形态
UpdateLandformStyles();
UpdateViewToggleLabel();
var key = kind.ToString().ToLowerInvariant();
if (_observeHeading != null) _observeHeading.Text = T("landform." + key) + " · " + T("landform." + key + ".sub");
if (_observeSummary != null) _observeSummary.Text = T("landform." + key + ".summary");
RenderFeatureList(key);
if (_backBtn != null) _backBtn.IsVisible = true;
if (_hintText != null) _hintText.Text = T("landform." + key + ".hint");
SetPlayLabel(T("btn.replay"));
}
private void BackToExperiment()
{
if (_selectedLandform == null) return;
_selectedLandform = null;
_view?.SetField(_experimentField);
_view?.SetMode(ViewMode.Perspective);
_view?.Reset();
UpdateLandformStyles();
UpdateViewToggleLabel();
RenderObservation(null);
if (_backBtn != null) _backBtn.IsVisible = false;
if (_hintText != null) _hintText.Text = T("hint.play");
SetPlayLabel(T("btn.play"));
}
private void RenderObservation(LandformKind? kind)
{
if (_observeHeading == null || _observeSummary == null || _featureList == null) return;
if (kind == null)
{
_observeHeading.Text = T("observe.title");
_observeSummary.Text = T("observe.default");
_featureList.Children.Clear();
_featureList.Children.Add(Bullet(T("observe.default.f1")));
_featureList.Children.Add(Bullet(T("observe.default.f2")));
}
else
{
var key = kind.Value.ToString().ToLowerInvariant();
_observeHeading.Text = T("landform." + key) + " · " + T("landform." + key + ".sub");
_observeSummary.Text = T("landform." + key + ".summary");
RenderFeatureList(key);
}
}
private void RenderFeatureList(string key)
{
if (_featureList == null) return;
_featureList.Children.Clear();
for (var i = 1; i <= 3; i++)
{
var k = $"landform.{key}.f{i}";
if (_texts.ContainsKey(k)) _featureList.Children.Add(Bullet(T(k)));
}
}
private Control BuildFooter()
{
// 播放 / 重置
_playLabel = new TextBlock { Text = T("btn.play"), Foreground = B(Colors.White), FontSize = 11.5, FontWeight = FontWeight.SemiBold };
_playBtn = new Border
{
Background = B(CAccent),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(14, 7),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = _playLabel
};
_playBtn.PointerPressed += (_, _) => TogglePlay();
var resetBtn = MakePillButton(T("btn.reset"), Color.Parse("#2A3B55"));
resetBtn.PointerPressed += (_, _) =>
{
BackToExperiment();
_view?.Reset();
if (_progress != null) _progress.Value = 0;
if (_hintText != null) _hintText.Text = T("hint.play");
SetPlayLabel(T("btn.play"));
};
// 俯视 / 立体切换
_viewToggleLabel = new TextBlock { Text = T("btn.viewTop"), Foreground = B(CInk), FontSize = 11.5 };
var viewBtn = new Border
{
Background = B(CPanel2),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(11, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = _viewToggleLabel
};
viewBtn.PointerPressed += (_, _) =>
{
_view?.ToggleMode();
UpdateViewToggleLabel();
};
// 上色开关
_colorBtnText = new TextBlock { Text = T("btn.colorOn"), Foreground = B(Colors.White), FontSize = 11.5 };
_colorBtn = new Border
{
Background = B(CAccent),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(11, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = _colorBtnText
};
_colorBtn.PointerPressed += (_, _) => ToggleColor();
var controls = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
controls.Children.Add(_playBtn);
controls.Children.Add(resetBtn);
controls.Children.Add(viewBtn);
controls.Children.Add(_colorBtn);
_progress = new ProgressBar
{
Minimum = 0,
Maximum = 100,
Value = 0,
Height = 4,
VerticalAlignment = VerticalAlignment.Center,
Foreground = B(CAccent),
Background = B(Color.Parse("#1E3350"))
};
_hintText = new TextBlock { Text = T("hint.play"), Foreground = B(CInkDim), FontSize = 11.5 };
_readout = new TextBlock { Text = T("footer.hint"), Foreground = B(CInk), FontSize = 11.5 };
_featureText = new TextBlock
{
Text = "",
Foreground = B(CGood),
FontSize = 11.5,
FontWeight = FontWeight.SemiBold,
HorizontalAlignment = HorizontalAlignment.Right
};
var info = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
info.Children.Add(_readout);
Grid.SetColumn(_featureText, 1);
info.Children.Add(_featureText);
var leftStack = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center };
leftStack.Children.Add(_hintText);
leftStack.Children.Add(info);
var progStack = new StackPanel { Spacing = 6, VerticalAlignment = VerticalAlignment.Center };
progStack.Children.Add(leftStack);
progStack.Children.Add(_progress);
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
row.Children.Add(progStack);
Grid.SetColumn(controls, 1);
row.Children.Add(controls);
return new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 1, 0, 0),
Padding = new Thickness(16, 9),
Child = row
};
}
private void TogglePlay()
{
if (_view == null) return;
if (_selectedLandform != null) BackToExperiment();
_view.TogglePlay();
SetPlayLabel(_view.IsPlaying ? T("btn.pause") : T("btn.play"));
if (_hintText != null)
_hintText.Text = _view.IsPlaying ? T("hint.playing") : T("hint.paused");
}
private void ToggleColor()
{
if (_view == null) return;
_view.Colored = !_view.Colored;
if (_colorBtn != null) _colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55"));
if (_colorBtnText != null) _colorBtnText.Text = _view.Colored ? T("btn.colorOn") : T("btn.color");
}
private void SetPlayLabel(string text) { if (_playLabel != null) _playLabel.Text = text; }
private void UpdateViewToggleLabel()
{
if (_viewToggleLabel == null || _view == null) return;
_viewToggleLabel.Text = _view.Mode == ViewMode.Top ? T("btn.view3d") : T("btn.viewTop");
}
private void UpdateFlowStyles()
{
for (var i = 0; i < _flowButtons.Count; i++)
{
var b = _flowButtons[i];
var active = i == _step && _selectedLandform == null;
var done = i < _step && _selectedLandform == null;
StylePill(b, active ? CAccent : done ? Color.Parse("#1C3A5E") : CPanel2,
active ? Colors.White : done ? CGood : CInkDim);
}
}
private void UpdateLandformStyles()
{
for (var i = 0; i < _landformButtons.Count; i++)
{
var b = _landformButtons[i];
var kind = LandformOrder[i];
var active = _selectedLandform == kind;
StylePill(b, active ? CAccent : CPanel2, active ? Colors.White : CInkDim);
}
}
private static void StylePill(Border b, Color bg, Color fg)
{
b.Background = B(bg);
if (b.Child is TextBlock tb) tb.Foreground = B(fg);
else if (b.Child is StackPanel sp)
foreach (var c in sp.Children)
if (c is TextBlock t) t.Foreground = B(fg);
}
private void OnStepChanged(ExperimentStep step)
{
_step = (int)step;
UpdateFlowStyles();
if (_selectedLandform == null && _observeSummary != null)
_observeSummary.Text = T("flow.desc." + _step);
}
private void OnProgressChanged(ExperimentStep step, double value)
=> _progress?.Value = value * 100;
private void OnPlaybackFinished()
{
SetPlayLabel(T("btn.replay"));
if (_hintText != null) _hintText.Text = T("hint.done");
}
private void OnHover(double u, double v, float height, TerrainFeature feature)
{
if (_readout == null || _featureText == null) return;
var field = _view?.Field ?? _experimentField;
var relative = height - field.MinHeight;
_readout.Text = T("footer.readout", (int)height, (int)relative);
_featureText.Text = FeatureName(feature);
_featureText.Foreground = B(feature switch
{
TerrainFeature.Peak => Color.Parse("#FFD166"),
TerrainFeature.Cliff => Color.Parse("#FF7B7B"),
TerrainFeature.Saddle => Color.Parse("#C08CFF"),
TerrainFeature.Ridge => Color.Parse("#5FD69B"),
TerrainFeature.Valley => Color.Parse("#5BC8FF"),
_ => CInkDim
});
}
private string FeatureName(TerrainFeature f) => f switch
{
TerrainFeature.Peak => T("feature.peak"),
TerrainFeature.Ridge => T("feature.ridge"),
TerrainFeature.Valley => T("feature.valley"),
TerrainFeature.Saddle => T("feature.saddle"),
TerrainFeature.Cliff => T("feature.cliff"),
TerrainFeature.Slope => T("feature.slope"),
_ => ""
};
private void OnKeyDown(object? sender, KeyEventArgs e)
{
// 空格:播放/暂停
if (e.Key == Key.Space)
{
e.Handled = true;
TogglePlay();
return;
}
// 1-5:切换五大地貌
var idx = -1;
switch (e.Key)
{
case Key.D1: case Key.NumPad1: idx = 0; break;
case Key.D2: case Key.NumPad2: idx = 1; break;
case Key.D3: case Key.NumPad3: idx = 2; break;
case Key.D4: case Key.NumPad4: idx = 3; break;
case Key.D5: case Key.NumPad5: idx = 4; break;
}
if (idx >= 0 && idx < LandformOrder.Length)
{
e.Handled = true;
SelectLandform(LandformOrder[idx]);
}
}
private void ToggleFullscreen(TextBlock label)
{
if (_topLevel is not Window window) return;
if (window.WindowState == WindowState.FullScreen)
{
window.WindowState = WindowState.Normal;
label.Text = T("btn.fullscreen");
}
else
{
window.WindowState = WindowState.FullScreen;
label.Text = T("btn.exitFullscreen");
}
}
// ── 控件工厂
private static TextBlock Section(string text) => new()
{
Text = text,
Foreground = BConst(CInk),
FontSize = 12.5,
FontWeight = FontWeight.SemiBold,
Margin = new Thickness(0, 2, 0, 2)
};
private static Border Divider() => new()
{
Height = 1,
Background = BConst(CLine),
Margin = new Thickness(0, 4, 0, 2)
};
private static TextBlock Bullet(string text) => new()
{
Text = "• " + text,
Foreground = BConst(CInkDim),
FontSize = 11.5,
TextWrapping = TextWrapping.Wrap,
LineHeight = 17
};
private Border MakePillButton(string label, Color bg)
{
var tb = new TextBlock { Text = label, Foreground = B(Colors.White), FontSize = 11.5, HorizontalAlignment = HorizontalAlignment.Center };
return new Border
{
Background = B(bg),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(11, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = tb
};
}
private static SolidColorBrush BConst(Color c) => new(c);
}
File diff suppressed because it is too large. Load diff
+225
View File
@@ -0,0 +1,225 @@
using System.Collections.Generic;
namespace GC.ContourMap;
/// <summary>内置全量文案兜底:没有语言包也能完整显示(复刻 HTML 课件全部文案)。</summary>
internal static class DefaultTexts
{
public static readonly Dictionary<string, string> Zh = new()
{
// 标题
["app.title"] = "等高线地形 · 五大典型地貌判读",
["app.subtitle"] = "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖",
// 实验流程四步
["flow.title"] = "实验流程",
["flow.step.0"] = "等高切割",
["flow.step.1"] = "形成交线",
["flow.step.2"] = "投影成图",
["flow.step.3"] = "疏密判坡",
["flow.desc.0"] = "观察水平面与山体在同一海拔相交,形成连续闭合线。",
["flow.desc.1"] = "每个水平切面都会留下同高交线,多层交线共同描述山体起伏。",
["flow.desc.2"] = "把各高度交线垂直投影到同一平面,得到完整等高线地形图。",
["flow.desc.3"] = "等高线越密,坡度越陡;等高线越疏,坡度越缓。",
// 观察面板
["observe.title"] = "实验演示",
["observe.default"] = "点击开始实验,在立体地形中观察等高切割与交线形成,再通过四步图解理解投影与判坡。",
["observe.features"] = "判读要点",
["observe.default.f1"] = "同一条等高线上海拔相等",
["observe.default.f2"] = "相邻等高线高差保持一致",
// 五大典型地貌
["side.landforms"] = "五大典型地貌",
["landform.peak"] = "山峰",
["landform.ridge"] = "山脊",
["landform.valley"] = "山谷",
["landform.saddle"] = "鞍部",
["landform.cliff"] = "陡崖",
["landform.peak.sub"] = "闭合等高线",
["landform.ridge.sub"] = "凸低为脊",
["landform.valley.sub"] = "凸高为谷",
["landform.saddle.sub"] = "两峰之间",
["landform.cliff.sub"] = "密集或重合",
["landform.peak.summary"] = "山峰四周较低、中心突起;等高线闭合成环,海拔数值由外向内逐渐升高。",
["landform.ridge.summary"] = "等高线弯曲部分向海拔低处凸出,脊线常成为两侧水系的分水岭。",
["landform.valley.summary"] = "等高线弯曲部分向海拔高处凸出,谷底低洼并容易汇水形成河流。",
["landform.saddle.summary"] = "鞍部位于相邻两座山峰之间,是沿山脊方向相对低洼的过渡地带。",
["landform.cliff.summary"] = "陡崖坡面近直立,不同高程的等高线会高度密集,局部可投影到同一位置而重合。",
["landform.peak.f1"] = "中心海拔高、四周海拔低",
["landform.peak.f2"] = "闭合线越向内,数值越大",
["landform.peak.f3"] = "若数值向内降低,则应判为洼地",
["landform.ridge.f1"] = "等高线凸向低值方向",
["landform.ridge.f2"] = "脊线由高处向低处延伸",
["landform.ridge.f3"] = "雨水沿脊线两侧分流",
["landform.valley.f1"] = "等高线凸向高值方向",
["landform.valley.f2"] = "V 形尖端指向上游高处",
["landform.valley.f3"] = "谷底常发育河流",
["landform.saddle.f1"] = "两组闭合等高线相邻",
["landform.saddle.f2"] = "中部线条收窄,形似马鞍",
["landform.saddle.f3"] = "常是翻越山岭的低垭口",
["landform.cliff.f1"] = "密集表示陡坡,重合才是陡崖特征",
["landform.cliff.f2"] = "单位水平距离内高差很大",
["landform.cliff.f3"] = "n 条线重合时:(n−1)d ≤ ΔH < (n+1)d",
["landform.peak.hint"] = "山峰:闭合曲线,数值向中心升高",
["landform.ridge.hint"] = "山脊:等高线向低处凸出,凸低为脊",
["landform.valley.hint"] = "山谷:等高线向高处凸出,凸高为谷",
["landform.saddle.hint"] = "鞍部:两峰之间相对低洼,俯视轮廓呈收腰形",
["landform.cliff.hint"] = "陡崖:等高线密集或重合,坡度极陡",
// 按钮
["btn.play"] = "开始实验",
["btn.pause"] = "暂停实验",
["btn.replay"] = "重新实验",
["btn.reset"] = "重置",
["btn.view3d"] = "立体图",
["btn.viewTop"] = "俯视图",
["btn.color"] = "上色",
["btn.colorOn"] = "取消上色",
["btn.fullscreen"] = "全屏",
["btn.exitFullscreen"] = "退出全屏",
["btn.backExperiment"] = "返回实验",
// 侧栏判读要点(通用地形)
["side.features"] = "五种地形部位",
["feature.peak"] = "山峰",
["feature.peakDesc"] = "等高线闭合,数值由中心向四周递减。",
["feature.ridge"] = "山脊",
["feature.ridgeDesc"] = "等高线凸向低处,脊线是分水线。",
["feature.valley"] = "山谷",
["feature.valleyDesc"] = "等高线凸向高处,谷线是集水线,常发育河流。",
["feature.saddle"] = "鞍部",
["feature.saddleDesc"] = "两个山峰之间的低地,形如马鞍。",
["feature.cliff"] = "陡崖",
["feature.cliffDesc"] = "等高线重叠或非常密集,近乎垂直。",
["feature.slope"] = "坡面",
// 判读规则
["side.rules"] = "判读要点",
["rule.interval"] = "等高距:相邻两条等高线的高度差,本图 100 米。",
["rule.dense"] = "等高线越密坡越陡,越疏坡越缓。",
["rule.index"] = "每 5 条加粗一条计曲线,标注海拔便于读数。",
["rule.height"] = "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。",
// 底部读数 / 图例
["footer.hint"] = "拖动立体地形旋转、滚轮缩放;鼠标悬停可查看该点海拔与地形部位",
["footer.readout"] = "海拔 {0} m 相对高度 {1} m",
["legend.title"] = "分层设色",
["profile.title"] = "地形剖面图",
["slope.gentle"] = "缓坡(线疏)",
["slope.steep"] = "陡坡(线密)",
["hint.play"] = "点击“开始实验”,观察等高切割与交线形成",
["hint.playing"] = "实验播放中",
["hint.paused"] = "实验已暂停 · 点击继续恢复播放",
["hint.done"] = "实验流程播放完成 · 可重新实验或选择典型地貌观察"
};
public static readonly Dictionary<string, string> En = new()
{
["app.title"] = "Contour Lines · Five Classic Landforms",
["app.subtitle"] = "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs",
["flow.title"] = "Experiment flow",
["flow.step.0"] = "Contour cutting",
["flow.step.1"] = "Forming lines",
["flow.step.2"] = "Projection",
["flow.step.3"] = "Slope density",
["flow.desc.0"] = "Watch a horizontal plane intersect the mountain at one elevation, forming closed lines.",
["flow.desc.1"] = "Each horizontal slice leaves an equal-height line; stacked lines describe the relief.",
["flow.desc.2"] = "Project every intersection line vertically onto one plane to build the contour map.",
["flow.desc.3"] = "Contours closer together mean a steeper slope; wider apart mean a gentler one.",
["observe.title"] = "Experiment demo",
["observe.default"] = "Press play to watch contour cutting and line formation, then use the four steps to learn projection and slope reading.",
["observe.features"] = "Key points",
["observe.default.f1"] = "All points on one contour share the same elevation",
["observe.default.f2"] = "Neighbouring contours keep a constant height interval",
["side.landforms"] = "Five classic landforms",
["landform.peak"] = "Peak",
["landform.ridge"] = "Ridge",
["landform.valley"] = "Valley",
["landform.saddle"] = "Saddle",
["landform.cliff"] = "Cliff",
["landform.peak.sub"] = "Closed contours",
["landform.ridge.sub"] = "Bulges toward low ground",
["landform.valley.sub"] = "Bulges toward high ground",
["landform.saddle.sub"] = "Between two peaks",
["landform.cliff.sub"] = "Dense or overlapping",
["landform.peak.summary"] = "A peak rises in the centre with lower ground around it; contours close into rings and values increase inward.",
["landform.ridge.summary"] = "Contours bulge toward lower ground; a ridge line often divides two drainage systems.",
["landform.valley.summary"] = "Contours bulge toward higher ground; valleys are low and collect water into streams.",
["landform.saddle.summary"] = "A saddle lies between two adjacent peaks, a relatively low pass along the ridge.",
["landform.cliff.summary"] = "A cliff face is nearly vertical, so contours crowd tightly or even overlap.",
["landform.peak.f1"] = "High centre, low surroundings",
["landform.peak.f2"] = "Closed lines grow in value inward",
["landform.peak.f3"] = "If values drop inward, it is a depression",
["landform.ridge.f1"] = "Contours bulge toward lower values",
["landform.ridge.f2"] = "Ridge line runs from high to low",
["landform.ridge.f3"] = "Rain drains to either side of the ridge",
["landform.valley.f1"] = "Contours bulge toward higher values",
["landform.valley.f2"] = "V tip points upstream to high ground",
["landform.valley.f3"] = "Streams often form along the valley floor",
["landform.saddle.f1"] = "Two neighbouring closed contour groups",
["landform.saddle.f2"] = "Contours pinch in the middle like a saddle",
["landform.saddle.f3"] = "Often a low mountain pass",
["landform.cliff.f1"] = "Dense means steep; overlap means cliff",
["landform.cliff.f2"] = "Large elevation change over a short distance",
["landform.cliff.f3"] = "n overlapping lines: (n−1)d ≤ ΔH < (n+1)d",
["landform.peak.hint"] = "Peak: closed curves, values rise toward the centre",
["landform.ridge.hint"] = "Ridge: contours bulge toward low ground",
["landform.valley.hint"] = "Valley: contours bulge toward high ground",
["landform.saddle.hint"] = "Saddle: low ground between two peaks",
["landform.cliff.hint"] = "Cliff: contours dense or overlapping, very steep",
["btn.play"] = "Start experiment",
["btn.pause"] = "Pause experiment",
["btn.replay"] = "Replay experiment",
["btn.reset"] = "Reset",
["btn.view3d"] = "3D view",
["btn.viewTop"] = "Top view",
["btn.color"] = "Colour",
["btn.colorOn"] = "No colour",
["btn.fullscreen"] = "Fullscreen",
["btn.exitFullscreen"] = "Exit fullscreen",
["btn.backExperiment"] = "Back to experiment",
["side.features"] = "Five terrain features",
["feature.peak"] = "Peak",
["feature.peakDesc"] = "Closed contours; values decrease outward from the centre.",
["feature.ridge"] = "Ridge",
["feature.ridgeDesc"] = "Contours bulge toward lower ground; a watershed line.",
["feature.valley"] = "Valley",
["feature.valleyDesc"] = "Contours bulge toward higher ground; a drainage line, often a stream.",
["feature.saddle"] = "Saddle",
["feature.saddleDesc"] = "Low ground between two peaks, shaped like a saddle.",
["feature.cliff"] = "Cliff",
["feature.cliffDesc"] = "Contours overlap or crowd tightly — nearly vertical.",
["feature.slope"] = "Slope",
["side.rules"] = "Key rules",
["rule.interval"] = "Contour interval: height gap between neighbours (100 m here).",
["rule.dense"] = "Closer contours = steeper slope; wider spacing = gentler.",
["rule.index"] = "Every 5th contour is bolded and labelled as an index contour.",
["rule.height"] = "Elevation above sea level; relative height is the difference of two elevations.",
["footer.hint"] = "Drag the 3D terrain to rotate, scroll to zoom; hover to read elevation and terrain feature",
["footer.readout"] = "Elevation {0} m Relative height {1} m",
["legend.title"] = "Hypsometric tint",
["profile.title"] = "Terrain profile",
["slope.gentle"] = "Gentle (sparse lines)",
["slope.steep"] = "Steep (dense lines)",
["hint.play"] = "Press start to watch contour cutting and line formation",
["hint.playing"] = "Experiment playing",
["hint.paused"] = "Experiment paused · press to resume",
["hint.done"] = "Experiment finished · replay or choose a landform"
};
}
+194
View File
@@ -0,0 +1,194 @@
using System;
using System.Collections.Generic;
namespace GC.ContourMap;
/// <summary>地形部位识别结果:课本要求学生能在等高线图上认出这五种部位。</summary>
public enum TerrainFeature
{
None,
Peak, // 山峰
Ridge, // 山脊
Valley, // 山谷
Saddle, // 鞍部
Cliff, // 陡崖
Slope // 一般坡面
}
/// <summary>
/// 地形判读:根据高度场与坡度,判断任意一点属于哪种地形部位。
/// 这是课本「等高线判读」的核心,直接从数据算出来,不靠预设标记。
/// </summary>
public static class TerrainAnalyzer
{
/// <summary>
/// 判断某点的地形部位。
///
/// 先查地形自带的**标注区**(教学用,位置由地形定义保证准确),
/// 未命中再按坡度/曲率自动推断。纯几何推断对「鞍部」「陡崖」这类
/// 特征容易误判,教学场景必须精确。
/// </summary>
public static TerrainFeature Classify(TerrainField field, double u, double v)
{
var tagged = field.TagAt(u, v);
if (tagged != TerrainFeature.None) return tagged;
var h = field.SampleSmooth(u, v);
var grad = Gradient(field, u, v);
var slope = Math.Sqrt(grad.dU * grad.dU + grad.dV * grad.dV); // 归一化坡度
// 陡崖:坡度极大(等高线挤成一团)。
// 阈值按本图实际坡度分布标定(中位≈2.5、p99≈6.8),
// 取 p99 以上一小段,否则大片坡面会被误判成陡崖。
if (slope > 8.5) return TerrainFeature.Cliff;
// 山峰:比四周都高
if (IsLocalMax(field, u, v)) return TerrainFeature.Peak;
// 鞍部:两个方向上高、另两个方向上低
if (IsSaddle(field, u, v)) return TerrainFeature.Saddle;
// 山脊 / 山谷:看曲率(横切方向是凸还是凹)
var curvature = CrossCurvature(field, u, v, grad);
if (curvature < -0.55) return TerrainFeature.Ridge; // 向外凸
if (curvature > 0.55) return TerrainFeature.Valley; // 向内凹
return TerrainFeature.Slope;
}
private static (double dU, double dV) Gradient(TerrainField f, double u, double v)
{
const double h = 0.004;
var du = (f.SampleSmooth(u + h, v) - f.SampleSmooth(u - h, v)) / (2 * h);
var dv = (f.SampleSmooth(u, v + h) - f.SampleSmooth(u, v - h)) / (2 * h);
return (du / 1000.0, dv / 1000.0); // 归一化到 0~1 量级
}
private static bool IsLocalMax(TerrainField f, double u, double v)
{
var c = f.SampleSmooth(u, v);
const double r = 0.035;
foreach (var (du, dv) in new[] { (r, 0.0), (-r, 0.0), (0.0, r), (0.0, -r) })
{
// 越近边界越不判为峰
if (u + du < 0 || u + du > 1 || v + dv < 0 || v + dv > 1) return false;
if (f.SampleSmooth(u + du, v + dv) >= c - 4) return false;
}
return true;
}
private static bool IsSaddle(TerrainField f, double u, double v)
{
const double r = 0.05;
if (u - r < 0 || u + r > 1 || v - r < 0 || v + r > 1) return false;
var c = f.SampleSmooth(u, v);
var l = f.SampleSmooth(u - r, v); var rt = f.SampleSmooth(u + r, v);
var t = f.SampleSmooth(u, v - r); var b = f.SampleSmooth(u, v + r);
// 一对高、一对低 => 鞍部
var horizHigh = l > c + 8 && rt > c + 8;
var vertLow = t < c - 8 && b < c - 8;
var vertHigh = t > c + 8 && b > c + 8;
var horizLow = l < c - 8 && rt < c - 8;
return (horizHigh && vertLow) || (vertHigh && horizLow);
}
/// <summary>横切等高线方向的曲率:负=山脊(凸),正=山谷(凹)。</summary>
private static double CrossCurvature(TerrainField f, double u, double v, (double dU, double dV) grad)
{
var len = Math.Sqrt(grad.dU * grad.dU + grad.dV * grad.dV);
if (len < 1e-6) return 0;
// 垂直于梯度方向(即沿等高线方向)的平均法向变化
var nU = -grad.dV / len;
var nV = grad.dU / len;
const double r = 0.045;
var c = f.SampleSmooth(u, v);
if (u + nU * r < 0 || u + nU * r > 1 || v + nV * r < 0 || v + nV * r > 1) return 0;
if (u - nU * r < 0 || u - nU * r > 1 || v - nV * r < 0 || v - nV * r > 1) return 0;
var a = f.SampleSmooth(u + nU * r, v + nV * r);
var b = f.SampleSmooth(u - nU * r, v - nV * r);
return (a + b - 2 * c) / 1000.0 * 6.0;
}
/// <summary>
/// 教科书规范的**分层设色**:按固定高程档位套用固定色阶,档内不渐变。
///
/// 人教版七年级上册的分层设色色阶(自低到高):
/// 深绿 → 浅绿 → 绿 → 浅黄 → 黄 → 浅褐 → 褐 → 浅棕 → 白
/// 关键点:**同一档内颜色完全相同**,这样一眼就能数出有几层,
/// 而不是课本上那种连续渐变。
/// </summary>
public static (byte R, byte G, byte B) ColorForHeight(float h, float min, float max)
{
// 按绝对高程分档(教科书就是这么画的:看的是海拔,不是相对高度)
if (h < 200) return (0x1E, 0x6B, 0x3A); // 深绿:< 200 m
if (h < 400) return (0x4E, 0x9E, 0x4E); // 浅绿:200–400
if (h < 600) return (0xA8, 0xC6, 0x66); // 绿:400–600
if (h < 800) return (0xE8, 0xE2, 0x9A); // 浅黄:600–800
if (h < 1000) return (0xE0, 0xC0, 0x5A); // 黄:800–1000
if (h < 1200) return (0xC8, 0x9A, 0x63); // 浅褐:1000–1200
if (h < 1400) return (0xA8, 0x74, 0x4C); // 褐:1200–1400
if (h < 1600) return (0xC8, 0xA8, 0x8C); // 浅棕:1400–1600
return (0xF5, 0xF5, 0xF0); // 白:> 1600(雪线以上)
}
/// <summary>
/// 3D 立体视图用的连续设色:与俯视图同一套色阶,但在档位之间线性过渡。
/// 立体视图的色块是按三角面着色的,直接用硬分档会在坡面上切出锯齿状阶梯,
/// 看起来像渲染错误;俯视图仍保留硬分档(那才是课本的分层设色)。
/// </summary>
public static (byte R, byte G, byte B) ColorForHeightSmooth(float h)
{
// 每个档位的代表色(取档位中心),由低到高
(byte R, byte G, byte B)[] stops =
{
(0x1E, 0x6B, 0x3A), (0x4E, 0x9E, 0x4E), (0xA8, 0xC6, 0x66),
(0xE8, 0xE2, 0x9A), (0xE0, 0xC0, 0x5A), (0xC8, 0x9A, 0x63),
(0xA8, 0x74, 0x4C), (0xC8, 0xA8, 0x8C), (0xF5, 0xF5, 0xF0)
};
const float band = 200f;
var p = Math.Clamp(h / band - 0.5f, 0f, stops.Length - 1f); // 0 => 档心 100 m
var i = (int)Math.Floor(p);
var j = Math.Min(i + 1, stops.Length - 1);
var t = p - i;
t = t * t * (3 - 2 * t); // 平滑过渡
return (Lerp(stops[i].R, stops[j].R, t),
Lerp(stops[i].G, stops[j].G, t),
Lerp(stops[i].B, stops[j].B, t));
}
/// <summary>该颜色属于哪一档(用于图例)。</summary>
public static string BandName(float h) => h switch
{
< 200 => "200 米以下",
< 400 => "200–400 米",
< 600 => "400–600 米",
< 800 => "600–800 米",
< 1000 => "800–1000 米",
< 1200 => "1000–1200 米",
< 1400 => "1200–1400 米",
< 1600 => "1400–1600 米",
_ => "1600 米以上"
};
private static byte Lerp(byte a, byte b, double k)
=> (byte)Math.Clamp(a + (b - a) * k, 0, 255);
/// <summary>
/// 归一化坡度(0=平缓,1=陡峭),用于「疏密判坡」着色。
/// 以有限差分求地面梯度,并按本模型的典型高差归一化。
/// </summary>
public static double SlopeAt(TerrainField f, double u, double v)
{
const double h = 0.006;
var du = (f.SampleSmooth(u + h, v) - f.SampleSmooth(u - h, v)) / (2 * h);
var dv = (f.SampleSmooth(u, v + h) - f.SampleSmooth(u, v - h)) / (2 * h);
var grad = Math.Sqrt(du * du + dv * dv); // 米 / 归一化距离
// 按本图实际起伏自适应归一化:跨度越大,同样的相对坡度对应更大的梯度。
// 固定阈值会让所有山体都顶到 1(整片红),判坡就失效了。
var span = Math.Max(60f, f.MaxHeight - f.MinHeight);
return Math.Clamp(grad / (span * 2.6), 0, 1);
}
}
+707
View File
@@ -0,0 +1,707 @@
using System;
using System.Collections.Generic;
namespace GC.ContourMap;
/// <summary>五种基本地形类型(教科书分类)。</summary>
public enum TerrainKind
{
Mountain, // 山地:海拔高、起伏大
Basin, // 盆地:四周高、中间低
Hill, // 丘陵:海拔较低、坡度和缓
Plateau, // 高原:海拔高、地面平坦、边缘陡
Plain // 平原:海拔低、地面平坦
}
/// <summary>五大典型地貌部位(等高线判读的核心对象)。</summary>
public enum LandformKind
{
Peak, // 山峰:闭合等高线,数值向内升高
Ridge, // 山脊:等高线凸向低处,凸低为脊
Valley, // 山谷:等高线凸向高处,凸高为谷
Saddle, // 鞍部:两峰之间相对低洼,俯视收腰
Cliff // 陡崖:等高线密集甚至重合
}
/// <summary>
/// 地形高度场(等高线模型的数据核心)。
///
/// 用叠加的高斯山包合成一块教学用地形:
/// · 主峰(山峰)
/// · 次峰(与主峰之间形成鞍部)
/// · 两条山脊、一条山谷
/// · 一侧陡坡(等高线密集)、一侧缓坡(等高线稀疏)
/// · 一处陡崖
///
/// 高度单位米,网格分辨率可配置;网格值一次性算好,等高线由它切线得出。
/// </summary>
public sealed class TerrainField
{
/// <summary>网格边长(正方形,便于俯视与等高线处理)。</summary>
public int Size { get; }
/// <summary>海拔网格,[y, x],单位米。</summary>
public float[,] Heights { get; }
public float MinHeight { get; private set; }
public float MaxHeight { get; private set; }
/// <summary>等高距(米):教学图常用 100 m。</summary>
public float Interval { get; init; } = 100f;
/// <summary>这块地形属于哪种类型(决定界面标题与说明)。</summary>
public TerrainKind Kind { get; }
/// <summary>若这块地形是某个典型地貌部位,则记录其种类;否则为 null。</summary>
public LandformKind? Landform { get; }
public TerrainField(TerrainKind kind = TerrainKind.Mountain, int size = 192)
{
Size = size;
Kind = kind;
Heights = new float[size, size];
Build(kind);
}
/// <summary>创建一个专门表现某种典型地貌部位的高度场。</summary>
public TerrainField(LandformKind landform, int size = 192)
{
Size = size;
Kind = TerrainKind.Mountain;
Landform = landform;
Heights = new float[size, size];
BuildLandform(landform);
}
/// <summary>该类型对应的等高距:平原/丘陵用 20m,山地/高原/盆地用 100m。</summary>
public float EffectiveInterval => Kind switch
{
TerrainKind.Plain => 5f, // 平原起伏小,等高距要小才画得出线
TerrainKind.Hill => 10f, // 丘陵相对高差约 150 m
_ => 100f
};
/// <summary>归一化坐标 (u,v) ∈ [0,1],u 向东、v 向南。</summary>
public float HeightAt(double u, double v)
{
var x = (int)Math.Round(u * (Size - 1));
var y = (int)Math.Round(v * (Size - 1));
x = Math.Clamp(x, 0, Size - 1);
y = Math.Clamp(y, 0, Size - 1);
return Heights[y, x];
}
/// <summary>双线性插值取值,画平滑曲线时用。</summary>
public float SampleSmooth(double u, double v)
{
var fx = Math.Clamp(u, 0, 1) * (Size - 1);
var fy = Math.Clamp(v, 0, 1) * (Size - 1);
var x0 = (int)Math.Floor(fx); var y0 = (int)Math.Floor(fy);
var x1 = Math.Min(x0 + 1, Size - 1); var y1 = Math.Min(y0 + 1, Size - 1);
var tx = fx - x0; var ty = fy - y0;
var h00 = Heights[y0, x0]; var h10 = Heights[y0, x1];
var h01 = Heights[y1, x0]; var h11 = Heights[y1, x1];
var a = h00 * (1 - tx) + h10 * tx;
var b = h01 * (1 - tx) + h11 * tx;
return (float)(a * (1 - ty) + b * ty);
}
private void Build(TerrainKind kind)
{
switch (kind)
{
case TerrainKind.Mountain: BuildMountain(); break;
case TerrainKind.Basin: BuildBasin(); break;
case TerrainKind.Hill: BuildHill(); break;
case TerrainKind.Plateau: BuildPlateau(); break;
case TerrainKind.Plain: BuildPlain(); break;
}
BuildFeatures();
}
private void BuildMountain()
{
// 各山体参数:中心(u,v)、高度、东西半径、南北半径
var peaks = new (double U, double V, double H, double RU, double RV)[]
{
(0.34, 0.34, 1180, 0.26, 0.24), // 主峰
(0.66, 0.52, 860, 0.20, 0.20), // 次峰(与主峰间成鞍部)
(0.22, 0.70, 520, 0.18, 0.16), // 西侧小山
(0.78, 0.22, 430, 0.16, 0.15), // 东北小山
};
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
double h = 120; // 基准面(平原 / 河谷)
foreach (var p in peaks)
{
var du = (u - p.U) / p.RU;
var dv = (v - p.V) / p.RV;
var d2 = du * du + dv * dv;
h += p.H * Math.Exp(-d2 * 1.15);
}
// 山谷:沿一条斜线切下去,形成 V 形谷地
var valley = Math.Abs((u - 0.5) * 0.8 + (v - 0.44) * 0.6);
h -= 210 * Math.Exp(-valley * valley / 0.0016);
// 陡崖:东侧一条近乎垂直的高差带(等高线会挤在一起)
if (u > 0.86 && v > 0.18 && v < 0.72)
h += 260 * SmoothStep(0.86, 0.895, u);
// 缓坡:西南角缓慢抬升
if (u < 0.3 && v > 0.6)
h += 90 * (1 - u / 0.3) * ((v - 0.6) / 0.4);
// 轻微起伏,避免地形过于几何化
h += 18 * Math.Sin(u * 9.1) * Math.Cos(v * 7.7);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min;
MaxHeight = max;
}
/// <summary>盆地:四周高、中间低,等高线由外向内递减。</summary>
private void BuildBasin()
{
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
var du = u - 0.5; var dv = v - 0.5;
var r = Math.Sqrt(du * du + dv * dv) * 2.0; // 0=中心 1=边缘
// 边缘抬升、中心下沉,形成碗状
double h = 160 + 900 * Math.Pow(Math.Clamp(r, 0, 1.15), 2.2);
// 一侧开个缺口(山口),让盆地向外开口
var gap = Math.Abs(Math.Atan2(dv, du) - 0.5);
if (gap < 0.35) h -= 320 * (1 - gap / 0.35) * (1 - Math.Clamp(r, 0, 1));
h += 14 * Math.Sin(u * 7.3) * Math.Cos(v * 6.1);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min; MaxHeight = max;
}
/// <summary>丘陵:起伏和缓、海拔不高,等高线稀疏而弯曲。</summary>
private void BuildHill()
{
var bumps = new (double U, double V, double H, double R)[]
{
(0.30, 0.32, 120, 0.20), (0.66, 0.28, 95, 0.17),
(0.52, 0.62, 140, 0.22), (0.22, 0.72, 88, 0.16),
(0.78, 0.70, 110, 0.18),
};
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
double h = 60;
foreach (var b in bumps)
{
var du = (u - b.U) / b.R; var dv = (v - b.V) / b.R;
h += b.H * Math.Exp(-(du * du + dv * dv) * 1.3);
}
h += 10 * Math.Sin(u * 11.0) * Math.Cos(v * 9.0);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min; MaxHeight = max;
}
/// <summary>高原:顶部平坦、边缘陡峭(等高线在中部稀疏、边缘密集)。</summary>
private void BuildPlateau()
{
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
// 到中心的距离,做平台 + 陡降
var du = (u - 0.5); var dv = (v - 0.5);
var r = Math.Sqrt(du * du + dv * dv) * 2.0;
double h;
if (r < 0.55) h = 1250; // 平坦顶面
else h = 1250 - 1000 * SmoothStep(0.55, 0.78, r); // 边缘陡降
// 顶面轻微起伏,避免完全平板
if (r < 0.55) h += 25 * Math.Sin(u * 6.0) * Math.Cos(v * 5.0);
h += 30 * (1 - Math.Clamp(r, 0, 1));
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min; MaxHeight = max;
}
/// <summary>平原:地面低平、起伏极小,等高线很少。</summary>
private void BuildPlain()
{
var min = float.MaxValue; var max = float.MinValue;
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
// 整体微倾 + 极缓的起伏
double h = 40 + 22 * u + 8 * Math.Sin(u * 4.2) * Math.Cos(v * 3.6);
var hf = (float)Math.Max(0, h);
Heights[y, x] = hf;
if (hf < min) min = hf;
if (hf > max) max = hf;
}
}
MinHeight = min; MaxHeight = max;
}
// ───────────────────────── 五大典型地貌部位 ─────────────────────────
private void BuildLandform(LandformKind landform)
{
switch (landform)
{
case LandformKind.Peak: BuildPeak(); break;
case LandformKind.Ridge: BuildRidge(); break;
case LandformKind.Valley: BuildValley(); break;
case LandformKind.Saddle: BuildSaddle(); break;
case LandformKind.Cliff: BuildCliff(); break;
}
BuildFeatures();
}
/// <summary>山峰:单峰为主、层层闭合,四周逐级降低。配一处小侧峰便于读鞍部。</summary>
private void BuildPeak()
{
var min = double.MaxValue; var max = double.MinValue;
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
var du = u - 0.5; var dv = (v - 0.5) / 0.94;
var r = Math.Sqrt(du * du + dv * dv);
// 主峰:宽阔的穹状山体(半径约占图幅 8 成),层层闭合的等高线才画得开
var core = Math.Exp(-Math.Pow(r / 0.36, 1.85));
var rim = 1 - SmoothStep(0.36, 0.50, r); // 山脚过渡到平地
var h = 65 + 1230 * core * rim;
// 东南侧肩部,让等高线不是完美同心圆
h += 120 * Math.Exp(-(Math.Pow(u - 0.72, 2) + Math.Pow(v - 0.66, 2)) / 0.016) * rim;
h += 22 * Math.Sin(u * 7.3 + 0.6) * Math.Cos(v * 6.1) * rim;
h = Math.Max(0, h);
Heights[y, x] = (float)h;
if (h < min) min = h; if (h > max) max = h;
}
MinHeight = (float)min; MaxHeight = (float)max;
Tags.Clear();
Tags.Add((0.5, 0.5, 0.09, TerrainFeature.Peak));
}
/// <summary>山脊:一条狭长高地,等高线沿脊线向低处凸出(凸低为脊)。</summary>
private void BuildRidge()
{
var min = double.MaxValue; var max = double.MinValue;
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
// 脊线沿 u 方向(西高东低),东西向是长坡,南北向是宽缓的两翼
var crestV = 0.5 + 0.10 * Math.Sin(u * 3.1); // 脊线轻微弯曲
var across = v - crestV;
var crest = 1150 - 380 * u; // 脊线海拔由西向东降低
var lateral = Math.Exp(-Math.Pow(Math.Abs(across) / 0.27, 1.55));
var h = 85 + (crest - 85) * lateral;
// 两翼的次级起伏,避免像一堵直墙
h += 60 * Math.Exp(-Math.Pow(Math.Abs(across) - 0.30, 2) / 0.010) * (0.4 + 0.6 * (1 - u));
h += 24 * Math.Sin(u * 8.0) * Math.Cos(v * 5.6);
h = Math.Max(0, h);
Heights[y, x] = (float)h;
if (h < min) min = h; if (h > max) max = h;
}
MinHeight = (float)min; MaxHeight = (float)max;
Tags.Clear();
Tags.Add((0.30, 0.50, 0.09, TerrainFeature.Ridge));
Tags.Add((0.70, 0.50, 0.09, TerrainFeature.Ridge));
}
/// <summary>山谷:两侧高地夹持的低槽,等高线形成 V 形指向上游(凸高为谷)。</summary>
private void BuildValley()
{
var min = double.MaxValue; var max = double.MinValue;
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
// 谷轴沿 v 方向:两侧高、中间是 V 形谷底;北侧(v 小)为上游更高
var side = Math.Pow(Math.Abs(u - 0.5) / 0.5, 1.5); // 0=谷心 1=图边
var downhill = 1 - v; // 上游 1 → 下游 0
var h = 90 + 760 * downhill + 585 * side * (0.30 + 0.70 * downhill);
// 谷底再切深一点,形成明显的集水线
h -= 70 * Math.Exp(-Math.Pow(u - 0.5, 2) / 0.0022);
h += 18 * Math.Sin(u * 6.5) * Math.Cos(v * 7.2);
h = Math.Max(0, h);
Heights[y, x] = (float)h;
if (h < min) min = h; if (h > max) max = h;
}
MinHeight = (float)min; MaxHeight = (float)max;
Tags.Clear();
Tags.Add((0.50, 0.40, 0.075, TerrainFeature.Valley));
Tags.Add((0.50, 0.68, 0.075, TerrainFeature.Valley));
}
/// <summary>鞍部:两座山峰之间相对低洼、俯视轮廓收腰的过渡地带。</summary>
private void BuildSaddle()
{
var min = double.MaxValue; var max = double.MinValue;
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
// 两峰在 v≈0.5 的连线上,u=0.27 与 u=0.73;中间 u=0.5 为垭口
var d1 = Math.Sqrt(Math.Pow((u - 0.27) / 0.30, 2) + Math.Pow((v - 0.52) / 0.28, 2));
var d2 = Math.Sqrt(Math.Pow((u - 0.73) / 0.30, 2) + Math.Pow((v - 0.48) / 0.28, 2));
var p1 = 1140 * Math.Exp(-Math.Pow(d1, 2.2));
var p2 = 1060 * Math.Exp(-Math.Pow(d2, 2.2));
// 南北两侧缓慢降低,把两峰连成一条东西向的山梁
var bench = 330 * Math.Exp(-Math.Pow((v - 0.5) / 0.34, 2));
var h = 65 + bench + Math.Max(p1, p2);
h += 20 * Math.Sin(u * 8.0) * Math.Cos(v * 7.0);
h = Math.Max(0, h);
Heights[y, x] = (float)h;
if (h < min) min = h; if (h > max) max = h;
}
MinHeight = (float)min; MaxHeight = (float)max;
Tags.Clear();
Tags.Add((0.28, 0.50, 0.05, TerrainFeature.Peak));
Tags.Add((0.72, 0.50, 0.05, TerrainFeature.Peak));
Tags.Add((0.50, 0.50, 0.045, TerrainFeature.Saddle));
}
/// <summary>陡崖:一侧近乎直立的高差带,等高线在崖壁处高度密集甚至重合。</summary>
private void BuildCliff()
{
var min = double.MaxValue; var max = double.MinValue;
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
// 西侧低台地、东侧高台地,中间一条近乎直立的高差带形成陡崖
// 崖线略呈波状(真实崖壁不是一条直线),过渡带留出 2~3 个采样格
var edge = SmoothStep(0.50, 0.62, u + 0.045 * Math.Sin(v * 5.2) + 0.02 * Math.Sin(v * 11.0));
var h = 210 + 940 * edge;
// 高台地北高南低、顶面起伏,低台地保持缓坡
h += 170 * (1 - v) * edge;
h += 55 * Math.Sin(v * 5.4) * Math.Cos(u * 4.2) * (0.4 + 0.6 * edge);
h += 26 * Math.Sin(u * 9.0); // 顶面轻微起伏
h = Math.Max(0, h);
Heights[y, x] = (float)h;
if (h < min) min = h; if (h > max) max = h;
}
MinHeight = (float)min; MaxHeight = (float)max;
Tags.Clear();
Tags.Add((0.50, 0.50, 0.035, TerrainFeature.Cliff));
}
private static double SmoothStep(double a, double b, double x)
{
var t = Math.Clamp((x - a) / (b - a), 0, 1);
return t * t * (3 - 2 * t);
}
/// <summary>
/// 教学标注区:把「典型部位」的位置固化成圆形区域,
/// 保证判读结果与地形设计一致(纯几何推断对鞍部/陡崖易误判)。
/// </summary>
public List<(double U, double V, double Radius, TerrainFeature Feature)> Tags { get; } = new()
{
(0.34, 0.34, 0.045, TerrainFeature.Peak), // 主峰
(0.66, 0.52, 0.042, TerrainFeature.Peak), // 次峰
(0.50, 0.44, 0.055, TerrainFeature.Saddle), // 两峰之间的鞍部
(0.90, 0.45, 0.035, TerrainFeature.Cliff), // 东侧陡崖
(0.22, 0.70, 0.045, TerrainFeature.Ridge), // 西南山脊
(0.50, 0.22, 0.040, TerrainFeature.Valley), // 河谷
};
/// <summary>查询标注区;未命中返回 None。</summary>
public TerrainFeature TagAt(double u, double v)
{
foreach (var (tu, tv, r, f) in Tags)
{
var du = u - tu; var dv = v - tv;
if (du * du + dv * dv <= r * r) return f;
}
return TerrainFeature.None;
}
/// <summary>
/// 河流:从最高点出发,沿最陡下降方向流到图边。
/// 教科书上的河流画蓝色线,且**只在河谷(等高线凸向高处的一侧)里流**。
/// </summary>
public List<(double U, double V)> River { get; } = new();
/// <summary>山峰位置(用于画 ▲ 与高程数字):局部最高点。</summary>
public List<(double U, double V, float Height)> Peaks { get; } = new();
/// <summary>陡崖位置(用于画锯齿线):坡度极大处。</summary>
public List<(double U, double V)> Cliffs { get; } = new();
/// <summary>找出山峰、陡崖,并生成河流线。</summary>
private void BuildFeatures()
{
// --- 山峰:局部最高且足够高 ---
const int step = 4;
for (var y = step; y < Size - step; y += step)
{
for (var x = step; x < Size - step; x += step)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
var h = Heights[y, x];
if (h < MaxHeight * 0.55) continue;
var isMax = true;
for (var dy = -step; dy <= step && isMax; dy += step)
for (var dx = -step; dx <= step; dx += step)
{
if (dx == 0 && dy == 0) continue;
if (Heights[y + dy, x + dx] > h) { isMax = false; break; }
}
if (isMax) Peaks.Add((u, v, h));
}
}
Peaks.Sort((a, b) => b.Height.CompareTo(a.Height));
// --- 陡崖:坡度极大 ---
const int cstep = 3;
for (var y = cstep; y < Size - cstep; y += cstep)
{
for (var x = cstep; x < Size - cstep; x += cstep)
{
var u = (double)x / (Size - 1);
var v = (double)y / (Size - 1);
var h = 0.004;
var du = (Heights[y, x + 2] - Heights[y, x - 2]) / (2 * h * (Size - 1)) / 1000;
var dv = (Heights[y + 2, x] - Heights[y - 2, x]) / (2 * h * (Size - 1)) / 1000;
var slope = Math.Sqrt(du * du + dv * dv);
if (slope > 0.11) Cliffs.Add((u, v));
}
}
// --- 河流:从最高点沿最陡下降方向走 ---
if (Peaks.Count > 0)
{
var start = Peaks[0];
var cu = start.U; var cv = start.V;
River.Add((cu, cv));
const int maxSteps = 400;
for (var step2 = 0; step2 < maxSteps; step2++)
{
var h0 = SampleSmooth(cu, cv);
double bestU = 0, bestV = 0; var bestH = h0; var found = false;
for (var a = 0; a < 16; a++)
{
var ang = a * Math.PI * 2 / 16;
var nu = cu + Math.Cos(ang) * 0.012;
var nv = cv + Math.Sin(ang) * 0.012;
if (nu < 0 || nu > 1 || nv < 0 || nv > 1) continue;
var nh = SampleSmooth(nu, nv);
if (nh < bestH) { bestH = nh; bestU = nu; bestV = nv; found = true; }
}
if (!found) break;
cu = bestU; cv = bestV;
River.Add((cu, cv));
if (cu <= 0.001 || cu >= 0.999 || cv <= 0.001 || cv >= 0.999) break;
if (bestH < MinHeight + 20) break;
}
}
}
/// <summary>等高线高度列表:从 MaxHeight 往下按等高距取整。</summary>
public List<float> ContourLevels()
{
var levels = new List<float>();
var iv = EffectiveInterval;
var top = (float)(Math.Floor(MaxHeight / iv) * iv);
var bottom = (float)(Math.Ceiling(MinHeight / iv) * iv);
for (var h = bottom; h <= top + 0.01f; h += iv)
levels.Add(h);
levels.Sort();
return levels;
}
/// <summary>
/// 用 Marching Squares 提取某条等高线,返回若干条折线(归一化坐标)。
/// </summary>
public List<List<(double U, double V)>> ExtractContour(float level)
{
var result = new List<List<(double, double)>>();
var size = Size;
// 记录每条线段,再按端点连通性串成折线
var segments = new List<(double U1, double V1, double U2, double V2)>();
for (var y = 0; y < size - 1; y++)
{
for (var x = 0; x < size - 1; x++)
{
var h00 = Heights[y, x];
var h10 = Heights[y, x + 1];
var h11 = Heights[y + 1, x + 1];
var h01 = Heights[y + 1, x];
var idx = 0;
if (h00 >= level) idx |= 1;
if (h10 >= level) idx |= 2;
if (h11 >= level) idx |= 4;
if (h01 >= level) idx |= 8;
if (idx == 0 || idx == 15) continue;
double u0 = (double)x / (size - 1), u1 = (double)(x + 1) / (size - 1);
double v0 = (double)y / (size - 1), v1 = (double)(y + 1) / (size - 1);
// 四条边上的交点
(double, double) Top() => (Lerp(u0, u1, (level - h00) / (h10 - h00)), v0);
(double, double) Bottom() => (Lerp(u0, u1, (level - h01) / (h11 - h01)), v1);
(double, double) Left() => (u0, Lerp(v0, v1, (level - h00) / (h01 - h00)));
(double, double) Right() => (u1, Lerp(v0, v1, (level - h10) / (h11 - h10)));
void Add((double U, double V) a, (double U, double V) b)
=> segments.Add((a.Item1, a.Item2, b.Item1, b.Item2));
switch (idx)
{
case 1: case 14: Add(Left(), Top()); break;
case 2: case 13: Add(Top(), Right()); break;
case 3: case 12: Add(Left(), Right()); break;
case 4: case 11: Add(Right(), Bottom()); break;
case 6: case 9: Add(Top(), Bottom()); break;
case 7: case 8: Add(Left(), Bottom()); break;
case 5: Add(Left(), Top()); Add(Right(), Bottom()); break;
case 10: Add(Top(), Right()); Add(Left(), Bottom()); break;
}
}
}
return Chain(segments);
}
private static double Lerp(double a, double b, double t)
=> a + (b - a) * Math.Clamp(double.IsNaN(t) ? 0.5 : t, 0, 1);
/// <summary>
/// 把零散线段按端点串成完整折线。
/// 关键点:必须**两端都延伸**。只往尾部延伸时,起点落在曲线中段就会把一条等高线
/// 切成许多短链,渲染出来是断续的虚线(学生看到的就是“虚线等高线”)。
/// </summary>
private static List<List<(double U, double V)>> Chain(
List<(double U1, double V1, double U2, double V2)> segments)
{
// 量化到 1e-4 的网格做端点索引:共享边上的交点由同一次插值算出,
// 端点值完全一致;网格远小于采样间距(1/192≈0.0052),不会误并。
const double Q = 1e4;
static (long, long) Key(double u, double v)
=> ((long)Math.Round(u * Q), (long)Math.Round(v * Q));
var index = new Dictionary<(long, long), List<int>>();
void Register(double u, double v, int seg)
{
var k = Key(u, v);
if (!index.TryGetValue(k, out var list)) index[k] = list = new List<int>();
list.Add(seg);
}
for (var i = 0; i < segments.Count; i++)
{
Register(segments[i].U1, segments[i].V1, i);
Register(segments[i].U2, segments[i].V2, i);
}
var used = new bool[segments.Count];
var result = new List<List<(double, double)>>();
int NextAt(double u, double v)
{
if (!index.TryGetValue(Key(u, v), out var list)) return -1;
foreach (var j in list) if (!used[j]) return j;
return -1;
}
for (var i = 0; i < segments.Count; i++)
{
if (used[i]) continue;
used[i] = true;
var line = new List<(double U, double V)>
{
(segments[i].U1, segments[i].V1),
(segments[i].U2, segments[i].V2)
};
// 向尾部延伸
while (true)
{
var (tu, tv) = line[^1];
var j = NextAt(tu, tv);
if (j < 0) break;
used[j] = true;
var s = segments[j];
line.Add(Key(s.U1, s.V1) == Key(tu, tv) ? (s.U2, s.V2) : (s.U1, s.V1));
}
// 向头部延伸
while (true)
{
var (hu, hv) = line[0];
var j = NextAt(hu, hv);
if (j < 0) break;
used[j] = true;
var s = segments[j];
line.Insert(0, Key(s.U1, s.V1) == Key(hu, hv) ? (s.U2, s.V2) : (s.U1, s.V1));
}
if (line.Count >= 3) result.Add(line);
}
return result;
}
private static bool Near(double u1, double v1, double u2, double v2, double eps)
=> Math.Abs(u1 - u2) < eps && Math.Abs(v1 - v2) < eps;
}
@@ -0,0 +1,30 @@
{
"id": "earth-geography",
"nameI18n": {
"zh-CN": "地球地理",
"en": "Earth Geography"
},
"descriptionI18n": {
"zh-CN": "五带划分、七大洲四大洋轮廓、六大板块与洲界,纯线稿教学图。",
"en": "Climate zones, continent/ocean outlines, plates and borders — clean line art."
},
"assembly": "EarthGeographyModel.dll",
"type": "GC.EarthModels.GeographyModelFactory",
"author": "Morris GC",
"tags": [
"geography",
"earth",
"atlas"
],
"dataDir": "earth-geography.model",
"version": "1.9",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "cc68b8863b",
"updatedAt": "2026-11-21T10:55:36Z"
}
@@ -0,0 +1 @@
{"borders":[{"between":"亚洲-非洲","name":"苏伊士运河","lines":[[[32.6,31.3],[32.4,30.5],[32.3,29.9]]]},{"between":"亚洲-欧洲","name":"亚欧分界(乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡)","segments":[{"name":"乌拉尔山","nameI18n":{"zh-CN":"乌拉尔山","en":"Ural Mts."},"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0]]]},{"name":"乌拉尔河","nameI18n":{"zh-CN":"乌拉尔河","en":"Ural River"},"lines":[[[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5]]]},{"name":"里海","nameI18n":{"zh-CN":"里海","en":"Caspian Sea"},"lines":[[[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5]]]},{"name":"大高加索山","nameI18n":{"zh-CN":"大高加索山","en":"Greater Caucasus"},"lines":[[[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2]]]},{"name":"黑海","nameI18n":{"zh-CN":"黑海","en":"Black Sea"},"lines":[[[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5]]]},{"name":"土耳其海峡","nameI18n":{"zh-CN":"土耳其海峡","en":"Turkish Straits"},"lines":[[[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]}],"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0],[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5],[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5],[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2],[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5],[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]},{"between":"欧洲-非洲","name":"直布罗陀海峡","lines":[[[-5.6,36.0],[-4.0,36.2],[0.0,36.5]]]},{"between":"北美-南美","name":"巴拿马运河","lines":[[[-79.6,9.1],[-78.5,8.9],[-77.5,8.6]]]},{"between":"南美-南极","name":"德雷克海峡","nameI18n":{"zh-CN":"德雷克海峡","en":"Drake Passage"},"lines":[[[-68.0,-56.0],[-66.5,-57.5],[-65.0,-59.0],[-63.5,-60.5],[-62.0,-62.0]]]},{"between":"亚洲-北美","name":"白令海峡","lines":[[[-169.0,65.5],[-170.5,65.8],[-172.0,66.0]]]},{"between":"亚洲-大洋洲","name":"印尼群岛","lines":[[[120.0,-1.0],[125.0,-2.0],[130.0,-3.0]]]},{"between":"南极洲","name":"南极圈","lines":[[[-180.0,-66.5],[-170.0,-66.5],[-160.0,-66.5],[-150.0,-66.5],[-140.0,-66.5],[-130.0,-66.5],[-120.0,-66.5],[-110.0,-66.5],[-100.0,-66.5],[-90.0,-66.5],[-80.0,-66.5],[-70.0,-66.5],[-60.0,-66.5],[-50.0,-66.5],[-40.0,-66.5],[-30.0,-66.5],[-20.0,-66.5],[-10.0,-66.5],[0.0,-66.5],[10.0,-66.5],[20.0,-66.5],[30.0,-66.5],[40.0,-66.5],[50.0,-66.5],[60.0,-66.5],[70.0,-66.5],[80.0,-66.5],[90.0,-66.5],[100.0,-66.5],[110.0,-66.5],[120.0,-66.5],[130.0,-66.5],[140.0,-66.5],[150.0,-66.5],[160.0,-66.5],[170.0,-66.5],[180.0,-66.5]]]}]}
@@ -0,0 +1 @@
{"lines":[[[180.0,-16.17],[179.56,-16.64],[179.93,-16.52],[179.93,-16.74],[179.2,-16.71],[178.71,-16.98],[178.5,-16.79],[178.58,-16.62],[180.0,-16.17]],[[143.18,-11.95],[143.11,-12.3],[143.4,-12.64],[143.76,-14.35],[143.96,-14.46],[144.47,-14.23],[145.29,-14.94],[145.43,-16.41],[145.91,-16.91],[146.13,-17.64],[146.03,-18.27],[146.33,-18.55],[146.38,-18.98],[147.42,-19.38],[147.74,-19.77],[148.76,-20.29],[148.88,-20.48],[148.68,-20.58],[149.45,-21.58],[149.7,-22.44],[149.97,-22.55],[150.02,-22.17],[150.54,-22.56],[150.62,-22.37],[150.84,-23.46],[151.83,-24.12],[153.16,-25.96],[153.12,-27.19],[153.62,-28.67],[153.03,-30.56],[152.94,-31.43],[152.47,-32.44],[151.81,-32.9],[151.29,-33.58],[150.81,-35.01],[150.19,-35.83],[149.93,-37.53],[149.48,-37.77],[147.88,-37.93],[146.86,-38.66],[146.22,-38.73],[146.47,-38.84],[146.4,-39.15],[145.4,-38.53],[145.48,-38.24],[144.96,-38.5],[144.72,-38.34],[145.12,-38.09],[144.89,-37.9],[144.4,-38.14],[144.66,-38.21],[143.54,-38.82],[142.46,-38.39],[141.42,-38.36],[140.39,-37.9],[139.78,-37.25],[139.73,-36.37],[138.97,-35.58],[139.29,-35.61],[139.28,-35.38],[138.18,-35.61],[138.51,-35.02],[138.09,-34.17],[137.69,-35.14],[136.88,-35.24],[137.01,-34.92],[137.39,-34.91],[137.49,-34.16],[137.93,-33.58],[137.85,-33.2],[137.99,-33.09],[137.78,-32.58],[137.79,-32.82],[137.24,-33.63],[136.43,-34.03],[135.89,-34.66],[135.97,-34.98],[135.65,-34.94],[135.12,-34.59],[135.45,-34.58],[135.22,-33.96],[134.72,-33.26],[134.3,-33.16],[134.1,-32.75],[134.23,-32.55],[133.66,-32.21],[132.76,-31.96],[132.22,-32.01],[131.14,-31.5],[128.95,-31.7],[127.32,-32.26],[125.92,-32.3],[124.24,-33.02],[123.51,-33.92],[122.15,-33.99],[121.41,-33.83],[119.85,-33.98],[119.45,-34.37],[117.86,-35.05],[116.52,-34.99],[115.01,-34.26],[114.99,-33.52],[115.36,-33.64],[115.68,-33.19],[115.7,-31.7],[115.08,-30.56],[114.86,-29.14],[114.17,-28.08],[114.03,-27.35],[113.19,-26.18],[113.32,-26.24],[113.36,-26.08],[113.58,-26.56],[113.84,-26.5],[113.45,-25.6],[113.71,-25.83],[113.72,-26.13],[113.85,-26.01],[113.99,-26.32],[114.22,-26.29],[114.21,-25.85],[113.42,-24.44],[113.76,-23.42],[113.68,-22.64],[114.02,-21.88],[114.14,-22.48],[114.71,-21.82],[116.71,-20.65],[117.41,-20.72],[119.1,-20.0],[119.59,-20.04],[121.0,-19.6],[121.83,-18.48],[122.34,-18.11],[122.15,-17.55],[122.26,-17.14],[122.97,-16.44],[123.56,-17.52],[123.59,-17.03],[123.83,-17.12],[123.87,-16.92],[123.49,-16.49],[123.61,-16.22],[124.77,-16.4],[124.41,-16.3],[124.65,-15.87],[124.5,-15.97],[124.38,-15.76],[124.44,-15.49],[124.69,-15.27],[125.06,-15.44],[124.84,-15.16],[125.04,-15.0],[125.36,-15.12],[125.18,-14.71],[125.58,-14.48],[125.63,-14.26],[125.66,-14.53],[126.02,-14.49],[126.05,-13.98],[126.57,-14.16],[126.9,-13.74],[127.46,-14.03],[128.2,-14.75],[128.07,-15.33],[128.58,-14.78],[129.06,-14.88],[129.22,-15.16],[129.27,-14.87],[129.63,-15.14],[129.64,-14.85],[129.85,-14.83],[129.38,-14.39],[129.84,-13.57],[130.26,-13.3],[130.17,-12.96],[130.62,-12.65],[130.62,-12.43],[130.87,-12.56],[131.29,-12.07],[131.44,-12.28],[132.41,-12.29],[132.71,-12.12],[132.67,-11.65],[131.82,-11.3],[131.96,-11.18],[135.03,-12.19],[135.92,-11.83],[135.7,-12.21],[136.01,-12.19],[136.08,-12.42],[136.26,-12.43],[136.27,-12.13],[136.54,-11.96],[136.95,-12.35],[136.54,-12.78],[136.46,-13.22],[135.93,-13.3],[135.95,-13.94],[135.45,-14.92],[138.25,-16.72],[139.01,-16.9],[139.25,-17.33],[140.04,-17.7],[140.51,-17.62],[140.83,-17.41],[141.41,-16.07],[141.62,-15.06],[141.47,-13.8],[141.61,-12.94],[141.93,-12.74],[141.69,-12.35],[141.96,-12.05],[142.17,-10.95],[142.6,-10.75],[142.87,-11.82],[143.18,-11.95]],[[178.28,-17.37],[178.59,-17.65],[178.67,-18.08],[177.96,-18.26],[177.32,-18.08],[177.26,-17.86],[177.5,-17.54],[178.28,-17.37]],[[164.2,-20.25],[165.19,-20.77],[166.94,-22.09],[166.97,-22.32],[166.47,-22.26],[164.93,-21.29],[164.38,-20.74],[164.04,-20.17],[164.2,-20.25]],[[127.73,0.85],[127.88,0.83],[128.22,1.4],[128.69,1.57],[128.7,1.11],[128.26,0.73],[128.9,0.22],[127.98,0.47],[127.89,0.3],[127.98,-0.25],[128.43,-0.89],[127.69,-0.24],[127.61,0.85],[127.43,1.14],[127.63,1.84],[128.04,2.2],[127.89,1.83],[128.01,1.33],[127.65,1.01],[127.73,0.85]],[[69.19,-49.11],[69.59,-48.97],[69.64,-49.12],[69.41,-49.18],[69.54,-49.26],[70.32,-49.06],[70.56,-49.2],[70.39,-49.43],[69.76,-49.43],[70.31,-49.58],[70.12,-49.7],[69.15,-49.53],[68.81,-49.7],[68.77,-49.07],[69.0,-48.66],[69.19,-49.11]],[[63.37,80.7],[62.52,80.82],[64.1,81.0],[64.31,81.17],[65.17,81.14],[65.44,80.93],[63.37,80.7]],[[-25.43,70.92],[-25.4,70.65],[-26.22,70.45],[-28.04,70.49],[-27.62,70.91],[-25.82,71.04],[-25.43,70.92]],[[117.31,8.44],[117.35,8.71],[119.22,10.48],[119.55,11.31],[119.69,10.5],[118.78,9.92],[118.44,9.26],[117.31,8.44]],[[122.5,11.62],[122.89,11.44],[123.16,11.54],[123.12,11.29],[122.77,10.82],[121.95,10.44],[122.1,11.64],[121.92,11.85],[122.5,11.62]],[[123.13,9.06],[122.4,9.82],[122.86,10.09],[122.98,10.89],[123.26,10.99],[123.57,10.78],[123.16,9.86],[123.32,9.27],[123.13,9.06]],[[124.58,11.34],[124.93,11.37],[125.0Line truncated
@@ -0,0 +1 @@
{"continents":[{"id":"eurasia","nameI18n":{"zh-CN":"亚欧大陆","en":"Eurasia"},"label":[85,52],"lines":[[[127.7,0.8],[127.9,0.8],[128.2,1.4],[128.7,1.6],[128.7,1.1],[128.3,0.9],[128.3,0.7],[128.9,0.2],[128.0,0.5],[127.9,0.3]],[[127.7,0.3],[127.4,1.1],[127.6,1.8],[128.0,2.2],[128.0,1.3],[127.7,0.8]],[[63.4,80.7],[62.5,80.8],[63.1,81.0],[64.1,81.0],[64.3,81.2],[65.4,81.1],[65.4,80.9],[63.4,80.7]],[[117.3,8.4],[117.3,8.7],[119.2,10.5],[119.3,11.0],[119.6,11.3],[119.5,11.0],[119.7,10.5],[118.8,9.9],[118.4,9.3],[117.3,8.4]],[[122.5,11.6],[122.8,11.6],[122.9,11.4],[123.2,11.5],[122.8,10.8],[122.0,10.4],[122.1,11.6],[121.9,11.9],[122.5,11.6]],[[123.1,9.1],[122.4,9.8],[122.5,10.0],[122.9,10.1],[122.8,10.5],[123.0,10.9],[123.3,11.0],[123.6,10.8],[123.2,9.9],[123.3,9.3],[123.1,9.1]],[[124.6,11.3],[124.9,11.4],[125.3,10.3],[125.1,10.2],[125.0,10.4],[125.0,10.0],[124.8,10.2],[124.7,11.0],[124.4,10.9],[124.3,11.5],[124.6,11.3]],[[125.2,12.5],[125.5,12.2],[125.7,11.1],[125.2,11.1],[124.9,11.6],[125.0,11.8],[124.4,12.2],[124.3,12.6],[125.2,12.5]],[[120.7,13.5],[121.2,13.4],[121.5,13.1],[121.5,12.6],[121.2,12.2],[120.5,13.4],[120.3,13.4],[120.7,13.5]],[[22.6,58.6],[23.3,58.5],[22.0,57.9],[22.2,58.2],[21.9,58.3],[21.9,58.5],[22.6,58.6]],[[21.6,78.6],[22.0,78.6],[22.3,78.2],[23.0,78.3],[23.5,78.1],[23.1,78.0],[24.9,77.8],[22.8,77.3],[22.4,77.3],[22.7,77.6],[21.1,77.4],[20.9,77.6],[21.7,77.9],[20.2,78.5],[21.6,78.6]],[[47.4,80.9],[48.4,80.8],[48.7,80.6],[47.7,80.8],[46.1,80.4],[46.0,80.6],[44.9,80.6],[47.4,80.9]],[[50.3,80.9],[51.7,80.7],[51.0,80.5],[48.8,80.4],[48.7,80.3],[49.0,80.2],[48.4,80.1],[46.6,80.3],[49.1,80.5],[49.2,80.8],[50.3,80.9]],[[50.3,69.2],[50.2,69.0],[48.9,68.7],[48.4,68.8],[48.3,69.0],[48.4,69.3],[49.0,69.5],[50.3,69.2]],[[23.9,35.5],[24.2,35.6],[24.1,35.5],[24.4,35.4],[25.7,35.3],[25.8,35.1],[26.3,35.3],[26.2,35.0]],[[23.9,35.5],[24.2,35.6],[24.1,35.5],[24.4,35.4],[25.7,35.3],[25.8,35.1],[26.3,35.3],[26.2,35.0],[24.8,34.9],[24.5,35.2],[23.6,35.3],[23.7,35.7],[23.9,35.5]],[[23.4,39.0],[23.5,38.8],[24.1,38.6],[24.6,38.0],[22.9,38.9],[23.4,39.0]],[[34.5,35.6],[33.9,35.3],[34.0,35.0],[33.0,34.6],[32.4,34.7],[32.3,35.1],[32.9,35.2],[32.9,35.4],[34.5,35.6]],[[19.1,57.8],[18.8,57.7],[18.9,57.4],[18.1,56.9],[18.3,57.1],[18.1,57.6],[18.9,57.9],[19.1,57.8]],[[12.6,55.8],[12.2,55.5],[12.4,55.3],[12.1,55.2],[12.1,54.8],[11.9,54.8],[11.7,55.2],[11.3,55.2],[11.0,55.7],[11.6,56.0],[11.8,55.7],[11.9,56.0],[12.2,56.1],[12.6,56.1],[12.6,55.8]],[[96.5,81.1],[97.9,80.7],[97.1,80.6],[97.0,80.5],[97.4,80.3],[97.2,80.2],[93.9,80.0],[91.5,80.4],[92.8,80.6],[93.3,80.8],[92.6,80.8],[93.4,81.0],[95.8,81.3],[96.5,81.1]],[[97.7,80.2],[98.0,80.0],[97.6,79.8],[98.4,79.9],[98.6,80.1],[100.1,79.8],[99.7,79.3],[99.0,79.3],[99.9,79.0],[99.4,78.8],[94.8,79.1],[94.2,79.4],[93.1,79.5],[95.0,80.1],[97.7,80.2]],[[102.9,79.3],[102.4,78.8],[103.0,79.1],[103.8,79.1],[105.1,78.8],[105.3,78.5],[104.7,78.3],[99.3,78.0],[100.0,78.3],[100.4,78.8],[101.0,78.8],[100.9,78.9],[101.5,79.3],[102.9,79.3]],[[140.0,75.8],[140.8,75.6],[141.0,76.0],[141.5,76.1],[143.7,75.9],[145.4,75.5],[144.7,75.4],[144.9,75.3],[144.0,75.0],[142.8,75.3],[142.7,75.5],[143.0,75.6],[142.9,75.7],[142.1,75.7],[142.6,75.1],[143.1,75.0],[142.5,74.8],[142.0,75.0],[140.3,74.8],[139.7,75.0],[139.1,74.7],[138.1,74.8],[136.9,75.3],[137.3,75.3],[137.2,75.6],[137.7,75.8],[137.5,75.9],[137.6,76.0],[138.2,76.1],[138.9,76.2],[140.0,75.8]],[[142.2,73.9],[143.5,73.5],[143.5,73.2],[140.7,73.5],[139.7,73.4],[140.4,73.5],[141.1,73.9],[142.2,73.9]],[[146.8,75.4],[150.8,75.2],[150.6,74.9],[148.1,74.8],[146.1,75.2],[146.4,75.6],[146.8,75.4]],[[126.0,9.3],[126.2,9.3],[126.3,9.0],[126.1,8.6],[126.4,8.5],[126.6,7.2],[126.2,6.9],[126.2,6.3],[125.7,7.3],[125.4,6.7],[125.7,6.0],[125.3,5.6],[125.2,6.1],[124.9,5.9],[124.2,6.2],[124.0,7.0],[124.2,7.4],[124.0,7.7],[123.5,7.8],[123.4,7.4],[123.1,7.7],[122.8,7.5],[122.6,7.8],[122.0,7.0],[121.9,7.2],[122.2,7.9],[122.9,8.2],[123.4,8.7],[123.7,8.6],[123.8,8.0],[124.2,8.2],[124.4,8.6],[124.7,8.6],[124.9,9.0],[125.5,9.0],[125.5,9.8],[126.0,9.3]],[[121.1,18.6],[121.8,18.3],[122.3,18.5],[122.2,17.7],[122.5,17.1],[122.1,16.2],[121.6,15.9],[121.4,15.3],[121.7,14.8],[121.6,14.6],[121.9,14.0],[122.2,13.9],[122.2,14.1],[122.6,14.3],[122.9,14.2],[123.1,13.8],[123.3,13.8],[123.3,14.1],[123.8,13.8],[123.5,13.6],[123.8,13.1],[124.1,13.0],[124.1,12.6],[123.9,12.9],[123.3,13.0],[123.2,13.4],[122.6,13.9],[122.6,13.2],[121.8,13.9],[121.3,13.6],[120.8,13.9],[120.6,13.8],[120.6,14.2],[120.9,14.6],[120.6,14.9],[120.6,14.5],[120.4,14.5],[120.1,14.9],[119.8,16.3],[120.2,16.0],[120.4,16.1],[120.3,16.6],[120.6,18.5],[121.1,18.6]],[[124.9,1.0],[124.4,0.5],[123.8,0.3],[123.3,0.3],[123.0,0.5],[120.6,0.5],[120.2,0.3]],[[119.9,0.0],[119.8,0.2],[120.3,1.0],[120.4,0.8],[120.9,1.3],[122.8,0.8],[123.9,0.8],[125.1,1.7],[125.2,1.5],[124.9,1.0]],[[96.5,5.2],[97.5,5.2],[98.3,4.1],[99.7,3.2],[100.5,2.2],[100.9,1.9],[100.8,2.2],[101.0,2.3],[102.4,0.8],[103.0,0.6],[103.0,0.4],[102.5,0.2],[103.3,0.5],[10Line truncated
@@ -0,0 +1,124 @@
{
"zh-CN": {
"title": "如何使用 · 地球地理",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:点右上「平面」,先看完整的世界地图,确认七大洲四大洋的位置。",
"第 2 步:点「五带」,看回归线与极圈怎么把地球分成五个温度带。",
"第 3 步:关掉「五带」,打开「六大板块」,记住六块板块的名字和范围。",
"第 4 步:再打开「五大陆」,对比金色实线(大陆)与彩色虚线(板块)的差别。",
"第 5 步:切回「3D 球面」,拖动转动地球,看背面会自动隐藏。",
"看不清?滚轮放大;想重来点「复位」。每个图层都能单独开关,互不干扰。"
]
},
{
"h": "一、这个模型包含什么",
"lines": [
"五带:热带、南北温带、南北寒带(按回归线 23.5° 与极圈 66.5° 划分)。",
"七大洲四大洋轮廓,以及洲与洲之间的分界线(苏伊士运河、巴拿马运河、白令海峡等)。",
"六大板块:亚欧、非洲、美洲、太平洋、印度洋、南极洲板块。",
"五块大陆:亚欧大陆、非洲大陆、美洲大陆、澳大利亚大陆、南极大陆。"
]
},
{
"h": "二、两种视图",
"lines": [
"「3D 球面」:正交投影球体,拖动旋转、滚轮缩放,背面自动裁掉。",
"「平面」:等经纬矩形地图,课本地图样式,一次看全整幅。",
"「复位」回到初始视角与缩放。"
]
},
{
"h": "三、图层开关(各自独立)",
"lines": [
"「五带」:叠加五带分界线与回归线、极圈。",
"「大洲轮廓」:白色海岸线。",
"「六大板块」:彩色虚线,是板块边界(不是大陆边界)。",
"「五大陆」:金色实线,是大陆轮廓。",
"「洲界」:分界点与分界线标签(如德雷克海峡、乌拉尔山…)。"
]
},
{
"h": "四、颜色与图例",
"lines": [
"右侧图例说明三种线型:海岸线 / 板块边界 / 分界线。",
"底部色块对应五个温度带。",
"六大板块各一种颜色,标签放在板块中心附近。"
]
},
{
"h": "五、教学要点与易错点",
"lines": [
"「板块 ≠ 大陆」:美洲板块覆盖南北美大陆并向东到大西洋中脊;印度洋板块包含澳大利亚与印度次大陆。",
"六大板块是全球一级板块,纳斯卡、阿拉伯等属于次级小板块,教材不列入。",
"板块交界处多火山地震(环太平洋带、地中海—喜马拉雅带)。",
"洲界是人为约定:亚欧以乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡为界;亚非以苏伊士运河为界;南北美以巴拿马运河为界;南美与南极以德雷克海峡为界。",
"Esc 关闭窗口,F11 全屏。"
]
}
]
},
"en": {
"title": "How to use · Earth Geography",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: click Flat in the top right for the whole world map first.",
"Step 2: turn on Climate zones to see how the tropics and polar circles split five belts.",
"Step 3: switch zones off and turn on Six plates; learn the six names and extents.",
"Step 4: turn on Five mainlands and compare solid gold lines (mainlands) with dashed colored lines (plates).",
"Step 5: switch back to 3D globe, drag to rotate, and see back faces clip automatically.",
"Hard to read? Scroll to zoom; press Reset to start over. Each layer toggles independently."
]
},
{
"h": "1. What this model contains",
"lines": [
"Five climate zones split by the tropics (23.5°) and polar circles (66.5°).",
"Seven continents, four oceans, and continental borders (Suez, Panama, Bering, etc.).",
"Six major plates: Eurasian, African, American, Pacific, Indian Ocean, Antarctic.",
"Five mainlands: Eurasia, Africa, America, Australia, Antarctica."
]
},
{
"h": "2. Two views",
"lines": [
"3D globe: orthographic sphere; drag to rotate, scroll to zoom, back faces clipped.",
"Flat: equirectangular textbook map, whole world at once.",
"Reset restores the initial view and zoom."
]
},
{
"h": "3. Independent layer toggles",
"lines": [
"Climate zones: tropics, polar circles and zone edges.",
"Coastlines: white continental outlines.",
"Six plates: dashed colored lines — plate BOUNDARIES, not continental edges.",
"Five mainlands: solid gold lines — continental outlines.",
"Borders: boundary dots and labels (Drake Passage, Ural Mts., ...)."
]
},
{
"h": "4. Colors & legend",
"lines": [
"The right legend explains the three line styles.",
"The bottom strip maps the five climate zones.",
"Each of the six plates has its own color, labelled near its center."
]
},
{
"h": "5. Teaching notes & pitfalls",
"lines": [
"Plates are NOT mainlands: the American Plate spans both Americas to the Mid-Atlantic Ridge; the Indian Ocean Plate includes Australia and the Indian subcontinent.",
"These six are the first-order plates; Nazca, Arabian, etc. are secondary and are not listed in textbooks.",
"Volcanoes and earthquakes concentrate along plate boundaries (Pacific Ring, Mediterranean–Himalayan belt).",
"Borders are conventions: Asia/Europe along the Urals–Ural River–Caspian–Caucasus–Black Sea–Turkish Straits; Asia/Africa at Suez; N/S America at Panama; S. America/Antarctica at Drake Passage.",
"Esc closes, F11 toggles fullscreen."
]
}
]
}
}
@@ -0,0 +1,7 @@
{
"zones": "Zones",
"coast": "Continents",
"plates": "Plates",
"borders": "Borders",
"reset": "Reset"
}
@@ -0,0 +1,7 @@
{
"zones": "五带",
"coast": "大洲轮廓",
"plates": "板块",
"borders": "洲界",
"reset": "复位"
}
@@ -0,0 +1,103 @@
{
"labels": [
{
"lat": 34,
"lon": 90,
"kind": "continent",
"nameI18n": {
"zh-CN": "亚洲",
"en": "Asia"
}
},
{
"lat": 2,
"lon": 20,
"kind": "continent",
"nameI18n": {
"zh-CN": "非洲",
"en": "Africa"
}
},
{
"lat": 48,
"lon": -100,
"kind": "continent",
"nameI18n": {
"zh-CN": "北美洲",
"en": "North America"
}
},
{
"lat": -15,
"lon": -60,
"kind": "continent",
"nameI18n": {
"zh-CN": "南美洲",
"en": "South America"
}
},
{
"lat": -78,
"lon": 20,
"kind": "continent",
"nameI18n": {
"zh-CN": "南极洲",
"en": "Antarctica"
}
},
{
"lat": 52,
"lon": 18,
"kind": "continent",
"nameI18n": {
"zh-CN": "欧洲",
"en": "Europe"
}
},
{
"lat": -24,
"lon": 134,
"kind": "continent",
"nameI18n": {
"zh-CN": "大洋洲",
"en": "Oceania"
}
},
{
"lat": 0,
"lon": -155,
"kind": "ocean",
"nameI18n": {
"zh-CN": "太平洋",
"en": "Pacific Ocean"
}
},
{
"lat": 12,
"lon": -30,
"kind": "ocean",
"nameI18n": {
"zh-CN": "大西洋",
"en": "Atlantic Ocean"
}
},
{
"lat": -22,
"lon": 78,
"kind": "ocean",
"nameI18n": {
"zh-CN": "印度洋",
"en": "Indian Ocean"
}
},
{
"lat": 85,
"lon": 0,
"kind": "ocean",
"nameI18n": {
"zh-CN": "北冰洋",
"en": "Arctic Ocean"
}
}
]
}
@@ -0,0 +1,53 @@
{
"plates": [
{
"id": "eurasian",
"nameI18n": { "zh-CN": "亚欧板块", "en": "Eurasian Plate" },
"label": [85, 55],
"lines": [
[[-10,36],[0,45],[15,55],[30,68],[60,72],[100,76],[140,70],[160,60],[140,42],[125,32],[110,28],[95,28],[80,30],[72,28],[60,25],[45,30],[32,32],[10,37],[-10,36]]
]
},
{
"id": "african",
"nameI18n": { "zh-CN": "非洲板块", "en": "African Plate" },
"label": [12, 2],
"lines": [
[[-20,35],[10,37],[32,32],[43,12],[51,10],[42,-8],[40,-25],[25,-35],[15,-30],[8,-5],[-8,5],[-17,15],[-20,35]]
]
},
{
"id": "american",
"nameI18n": { "zh-CN": "美洲板块", "en": "American Plate" },
"label": [-100, 12],
"lines": [
[[-168,72],[-140,70],[-115,70],[-90,72],[-60,60],[-52,45],[-60,30],[-80,25],[-82,8],[-78,0],[-70,-15],[-72,-40],[-75,-52],[-80,-55],[-95,-45],[-105,-25],[-95,-5],[-90,10],[-105,20],[-120,35],[-135,50],[-155,60],[-168,72]]
]
},
{
"id": "pacific",
"nameI18n": { "zh-CN": "太平洋板块", "en": "Pacific Plate" },
"label": [-150, 0],
"lines": [
[[-180,60],[-150,55],[-130,45],[-110,25],[-95,10],[-80,0],[-75,-15],[-90,-30],[-110,-45],[-130,-55],[-160,-60],[-180,-58],[-180,60]],
[[145,55],[158,45],[152,30],[145,15],[140,0],[148,-15],[158,-30],[168,-45],[180,-55],[180,60],[165,60],[145,55]]
]
},
{
"id": "indian-ocean",
"nameI18n": { "zh-CN": "印度洋板块", "en": "Indian Ocean Plate" },
"label": [95, -8],
"lines": [
[[35,32],[50,30],[60,22],[68,24],[75,8],[88,5],[95,5],[115,10],[130,5],[145,-5],[150,-20],[145,-35],[130,-42],[115,-38],[105,-25],[95,-10],[80,-10],[65,-5],[55,10],[42,10],[35,20],[35,32]]
]
},
{
"id": "antarctic",
"nameI18n": { "zh-CN": "南极洲板块", "en": "Antarctic Plate" },
"label": [0, -76],
"lines": [
[[-180,-60],[-120,-62],[-60,-60],[0,-62],[60,-60],[120,-62],[180,-60],[180,-90],[-180,-90],[-180,-60]]
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

@@ -0,0 +1,88 @@
{
"schemaVersion": 1,
"type": "geography",
"defaultView": "zones",
"views": [
"zones",
"coast",
"plates"
],
"nameI18n": {
"zh-CN": "地球地理",
"en": "Earth Geography"
},
"descriptionI18n": {
"zh-CN": "五带划分 · 七大洲四大洋 · 六大板块 · 五大陆与洲界",
"en": "Climate zones · continents & oceans · six plates · five mainlands & borders"
},
"tropicDeg": 23.5,
"axialTiltDeg": 23.5,
"oceanColor": "#0E2A4A",
"zones": [
{
"id": "torrid",
"latMin": -23.5,
"latMax": 23.5,
"nameI18n": {
"zh-CN": "热带",
"en": "Torrid zone"
},
"descI18n": {
"zh-CN": "南北回归线之间,有太阳直射,终年高温。",
"en": "Between the tropics; the Sun is overhead at some time each year."
}
},
{
"id": "north-temperate",
"latMin": 23.5,
"latMax": 66.5,
"nameI18n": {
"zh-CN": "北温带",
"en": "North temperate"
},
"descI18n": {
"zh-CN": "北回归线与北极圈之间,四季分明,无直射也无极昼极夜。",
"en": "Between Tropic of Cancer and Arctic Circle; four distinct seasons."
}
},
{
"id": "south-temperate",
"latMin": -66.5,
"latMax": -23.5,
"nameI18n": {
"zh-CN": "南温带",
"en": "South temperate"
},
"descI18n": {
"zh-CN": "南回归线与南极圈之间,四季分明。",
"en": "Between Tropic of Capricorn and Antarctic Circle; four seasons."
}
},
{
"id": "north-frigid",
"latMin": 66.5,
"latMax": 90,
"nameI18n": {
"zh-CN": "北寒带",
"en": "North frigid zone"
},
"descI18n": {
"zh-CN": "北极圈以北,有极昼极夜,终年寒冷。",
"en": "North of the Arctic Circle; polar day/night, always cold."
}
},
{
"id": "south-frigid",
"latMin": -90,
"latMax": -66.5,
"nameI18n": {
"zh-CN": "南寒带",
"en": "South frigid zone"
},
"descI18n": {
"zh-CN": "南极圈以南,有极昼极夜,终年寒冷。",
"en": "South of the Antarctic Circle; polar day/night, always cold."
}
}
]
}
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>GC.EarthModels</RootNamespace>
<AssemblyName>EarthGeographyModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<!-- 共享引擎源码(模型目录内),只编译需要的部分 -->
<ItemGroup>
<Compile Include="../../_engine/src/ModelJson.cs" />
<Compile Include="../../_engine/src/Geometry.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\GC.ModelSdk\GC.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
+96
View File
@@ -0,0 +1,96 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace GC.EarthModels;
/// <summary>地球地理模型的数据文件:全部是经纬度折线,只有轮廓没有填色。</summary>
public sealed class GeoData
{
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
}
public sealed class PlateEntry
{
[JsonPropertyName("id")] public string Id { get; set; } = "";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
/// <summary>标签锚点 [lon, lat];缺省时用轮廓质心。</summary>
[JsonPropertyName("label")] public double[]? Label { get; set; }
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
}
public sealed class PlateData
{
[JsonPropertyName("plates")] public List<PlateEntry> Plates { get; set; } = new();
}
/// <summary>大陆(六块大陆里的教材五块写法)。结构与板块一致,纯线稿。</summary>
public sealed class ContinentData
{
[JsonPropertyName("continents")] public List<PlateEntry> Continents { get; set; } = new();
}
public sealed class BorderEntry
{
/// <summary>分界的两个大洲,如「亚洲-非洲」。</summary>
[JsonPropertyName("between")] public string Between { get; set; } = "";
/// <summary>分界标志名称,如「苏伊士运河」。</summary>
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
/// <summary>复合分界的逐段明细(如亚欧分界的六个地理标志)。</summary>
[JsonPropertyName("segments")] public List<BorderSegment>? Segments { get; set; }
}
public sealed class BorderSegment
{
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
}
public sealed class BorderData
{
[JsonPropertyName("borders")] public List<BorderEntry> Borders { get; set; } = new();
}
/// <summary>七大洲四大洋的标签位置(经纬度 + 名称)。</summary>
public sealed class ZoneLabel
{
[JsonPropertyName("lat")] public double Lat { get; set; }
[JsonPropertyName("lon")] public double Lon { get; set; }
[JsonPropertyName("kind")] public string Kind { get; set; } = "continent";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
}
public sealed class LabelData
{
[JsonPropertyName("labels")] public List<ZoneLabel> Labels { get; set; } = new();
}
/// <summary>五带:以纬度区间定义的五个温度带。</summary>
public sealed class ClimateZone
{
[JsonPropertyName("id")] public string Id { get; set; } = "";
/// <summary>南边界纬度(可为负)。</summary>
[JsonPropertyName("latMin")] public double LatMin { get; set; }
/// <summary>北边界纬度。</summary>
[JsonPropertyName("latMax")] public double LatMax { get; set; }
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("descI18n")] public Dictionary<string, string>? DescI18n { get; set; }
}
/// <summary>地理模型场景清单。</summary>
public sealed class GeoScene
{
[JsonPropertyName("schemaVersion")] public int SchemaVersion { get; set; } = 1;
[JsonPropertyName("type")] public string Type { get; set; } = "geography";
[JsonPropertyName("defaultView")] public string DefaultView { get; set; } = "zones";
[JsonPropertyName("views")] public List<string> Views { get; set; } = new();
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("descriptionI18n")] public Dictionary<string, string>? DescriptionI18n { get; set; }
/// <summary>黄赤交角 / 回归线纬度,教学里统一 23.5°。</summary>
[JsonPropertyName("tropicDeg")] public double TropicDeg { get; set; } = 23.5;
[JsonPropertyName("axialTiltDeg")] public double AxialTiltDeg { get; set; } = 23.5;
[JsonPropertyName("oceanColor")] public string OceanColor { get; set; } = "#0E2A4A";
[JsonPropertyName("zones")] public List<ClimateZone> Zones { get; set; } = new();
}
@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.IO;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using GC.ModelSdk;
namespace GC.EarthModels;
/// <summary>
/// 地球地理模型:五带划分 + 七大洲四大洋轮廓 + 六大板块与洲界,纯线稿。
/// 数据全部来自模型数据目录,启动器不参与渲染。
/// </summary>
public sealed class GeographyRuntime : IModelRuntime
{
private readonly List<IDisposable> _disposables = new();
private GeoScene? _scene;
private GeoData? _coast;
private PlateData? _plates;
private ContinentData? _continents;
private BorderData? _borders;
private LabelData? _labels;
private GeographyView? _view;
public void Prepare(IModelContext context)
{
var dir = context.DataDirectory;
context.ReportProgress(0.10, "读取地理数据");
_scene = ModelJson.Read<GeoScene>(Path.Combine(dir, "scene.json")) ?? new GeoScene();
_coast = ModelJson.Read<GeoData>(Path.Combine(dir, "coastline.json")) ?? new GeoData();
_plates = ModelJson.Read<PlateData>(Path.Combine(dir, "plates.json")) ?? new PlateData();
_continents = ModelJson.Read<ContinentData>(Path.Combine(dir, "continents.json")) ?? new ContinentData();
_borders = ModelJson.Read<BorderData>(Path.Combine(dir, "borders.json")) ?? new BorderData();
context.ReportProgress(0.45, "加载名称标注");
_labels = ModelJson.Read<LabelData>(Path.Combine(dir, "labels.json")) ?? new LabelData();
context.ReportProgress(0.72, "构建轮廓");
context.Log($"[{context.ModelId}] 海岸线 {_coast.Lines.Count} 条,六大板块 {_plates.Plates.Count} 个," +
$"大陆 {_continents.Continents.Count} 块,洲界 {_borders.Borders.Count} 条");
}
public Control CreateView(IModelContext context)
{
_scene ??= new GeoScene();
_coast ??= new GeoData();
_plates ??= new PlateData();
_continents ??= new ContinentData();
_borders ??= new BorderData();
_labels ??= new LabelData();
_view = new GeographyView(context, _scene, _coast, _plates, _continents, _borders, _labels);
context.ReportProgress(1.0, "准备就绪");
return BuildLayout(_scene, _view, context);
}
private Control BuildLayout(GeoScene scene, GeographyView view, IModelContext context)
{
var root = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto") };
// 顶栏:模型名 + 图层开关
var top = new Border
{
Background = new SolidColorBrush(Color.Parse("#0C1828")),
Padding = new Thickness(16, 10),
Child = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") }
};
var topGrid = (Grid)top.Child!;
var titlePanel = new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center };
titlePanel.Children.Add(new TextBlock
{
Text = Pick(scene.NameI18n, "地球地理"),
Foreground = new SolidColorBrush(Color.Parse("#EAF2FF")),
FontSize = 15,
FontWeight = FontWeight.SemiBold
});
titlePanel.Children.Add(new TextBlock
{
Text = Pick(scene.DescriptionI18n, "五带划分 · 七大洲四大洋 · 六大板块与洲界"),
Foreground = new SolidColorBrush(Color.Parse("#7C93B5")),
FontSize = 10.5
});
topGrid.Children.Add(titlePanel);
var actions = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 8,
VerticalAlignment = VerticalAlignment.Center
};
actions.Children.Add(MakeModeSwitch(view));
actions.Children.Add(MakeToggle("五带", view.ShowZones, on => view.ShowZones = on));
actions.Children.Add(MakeToggle("大洲轮廓", view.ShowCoast, on => view.ShowCoast = on));
actions.Children.Add(MakeToggle("六大板块", view.ShowPlates, on => view.ShowPlates = on));
actions.Children.Add(MakeToggle("五大陆", view.ShowContinents, on => view.ShowContinents = on));
actions.Children.Add(MakeToggle("洲界", view.ShowBorders, on => view.ShowBorders = on));
actions.Children.Add(MakeButton("复位", () => view.ResetView()));
Grid.SetColumn(actions, 2);
topGrid.Children.Add(actions);
root.Children.Add(top);
var stage = new Grid();
stage.Children.Add(view);
stage.Children.Add(BuildLegend(scene));
Grid.SetRow(stage, 1);
root.Children.Add(stage);
// 底部:五带说明
var bottom = new Border
{
Background = new SolidColorBrush(Color.Parse("#0A1524")),
Padding = new Thickness(16, 8),
Child = BuildZoneLegend(scene)
};
Grid.SetRow(bottom, 2);
root.Children.Add(bottom);
return root;
}
/// <summary>右上角图例:说明三种线型分别代表什么。</summary>
private static Control BuildLegend(GeoScene scene)
{
var panel = new StackPanel { Spacing = 6 };
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#DEEEFF")), "大洲海岸线"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FF8A5C")), "六大板块边界"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FFD24A")), "五大陆轮廓"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FFDC70")), "洲界 / 分界线"));
return new Border
{
Background = new SolidColorBrush(Color.FromArgb(190, 8, 18, 32)),
CornerRadius = new CornerRadius(10),
Padding = new Thickness(12, 10),
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(0, 14, 16, 0),
Child = panel
};
}
private static Control LegendRow(IBrush brush, string text)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
row.Children.Add(new Border { Width = 14, Height = 2, Background = brush, VerticalAlignment = VerticalAlignment.Center });
row.Children.Add(new TextBlock { Text = text, Foreground = new SolidColorBrush(Color.Parse("#9FB4D4")), FontSize = 10.5 });
return row;
}
private static Control BuildZoneLegend(GeoScene scene)
{
var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 18 };
foreach (var zone in scene.Zones)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
row.Children.Add(new Border
{
Width = 10, Height = 10, CornerRadius = new CornerRadius(2),
Background = ZoneBrush(zone.Id), VerticalAlignment = VerticalAlignment.Center
});
row.Children.Add(new TextBlock
{
Text = Pick(zone.NameI18n, zone.Id),
Foreground = new SolidColorBrush(Color.Parse("#C2D4EC")),
FontSize = 11
});
panel.Children.Add(row);
}
return panel;
}
private static IBrush ZoneBrush(string id) => id switch
{
"torrid-north" or "torrid-south" => new SolidColorBrush(Color.Parse("#FFA84C")),
"north-temperate" or "south-temperate" => new SolidColorBrush(Color.Parse("#6ED28C")),
_ => new SolidColorBrush(Color.Parse("#96C8FF"))
};
/// <summary>3D 球面 / 平面等经纬 两态切换。</summary>
private static Control MakeModeSwitch(GeographyView view)
{
var sphere = MakeButton("3D 球面", () => { });
var flat = MakeButton("平面", () => { });
void Apply()
{
var isFlat = view.Mode == GeoMode.Flat2D;
sphere.Background = new SolidColorBrush(Color.Parse(isFlat ? "#16263C" : "#1F5BD6"));
sphere.BorderBrush = new SolidColorBrush(Color.Parse(isFlat ? "#263A56" : "#3B7BFF"));
sphere.Foreground = new SolidColorBrush(Color.Parse(isFlat ? "#9FB4D4" : "#FFFFFF"));
flat.Background = new SolidColorBrush(Color.Parse(isFlat ? "#1F5BD6" : "#16263C"));
flat.BorderBrush = new SolidColorBrush(Color.Parse(isFlat ? "#3B7BFF" : "#263A56"));
flat.Foreground = new SolidColorBrush(Color.Parse(isFlat ? "#FFFFFF" : "#9FB4D4"));
}
sphere.Click += (_, _) => { view.Mode = GeoMode.Sphere3D; Apply(); };
flat.Click += (_, _) => { view.Mode = GeoMode.Flat2D; Apply(); };
Apply();
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
row.Children.Add(sphere);
row.Children.Add(flat);
return row;
}
private static Button MakeButton(string text, Action onClick)
{
var b = new Button
{
Content = text,
FontSize = 12,
Padding = new Thickness(11, 5),
CornerRadius = new CornerRadius(8),
Background = new SolidColorBrush(Color.Parse("#16263C")),
Foreground = new SolidColorBrush(Color.Parse("#D6E4F8")),
BorderBrush = new SolidColorBrush(Color.Parse("#263A56")),
BorderThickness = new Thickness(1),
MinHeight = 30
};
b.Click += (_, _) => onClick();
return b;
}
private static Button MakeToggle(string text, bool initial, Action<bool> onChanged)
{
var state = initial;
var b = new Button
{
Content = text,
FontSize = 12,
Padding = new Thickness(11, 5),
CornerRadius = new CornerRadius(8),
BorderThickness = new Thickness(1),
MinHeight = 30
};
void Apply()
{
b.Background = new SolidColorBrush(Color.Parse(state ? "#1F5BD6" : "#16263C"));
b.BorderBrush = new SolidColorBrush(Color.Parse(state ? "#3B7BFF" : "#263A56"));
b.Foreground = new SolidColorBrush(Color.Parse(state ? "#FFFFFF" : "#9FB4D4"));
}
Apply();
b.Click += (_, _) => { state = !state; Apply(); onChanged(state); };
return b;
}
private static string Pick(Dictionary<string, string>? dict, string fallback)
{
if (dict == null || dict.Count == 0) return fallback;
foreach (var key in new[] { "zh-CN", "en" })
if (dict.TryGetValue(key, out var v) && !string.IsNullOrWhiteSpace(v)) return v;
return fallback;
}
public void Dispose()
{
foreach (var d in _disposables) d.Dispose();
_disposables.Clear();
_view?.StopAnimation();
_view = null;
System.GC.SuppressFinalize(this);
}
}
/// <summary>模型入口。</summary>
public sealed class GeographyModelFactory : IModelFactory
{
public int ApiVersion => 1;
public IModelRuntime Create() => new GeographyRuntime();
}
@@ -0,0 +1,916 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using GC.ModelSdk;
namespace GC.EarthModels;
public enum GeoMode { Sphere3D, Flat2D }
/// <summary>
/// 地球地理画布。两种模式:
/// · 3D 正交球面 —— 拖拽转动、背面自动裁掉;
/// · 平面等经纬矩形 —— 课本地图样式,整幅一次看全。
/// 所有要素都是线稿;五带/板块/洲界各自独立配色,便于区分。
/// </summary>
public sealed class GeographyView : Control
{
private readonly GeoScene _scene;
private readonly GeoData _coast;
private readonly PlateData _plates;
private readonly ContinentData _continents;
private readonly BorderData _borders;
private readonly LabelData _labels;
private double _yawDeg = 10;
private double _pitchDeg = 15;
private double _zoom = 1.0;
private double _zoomTarget = 1.0;
private Avalonia.Threading.DispatcherTimer? _zoomTimer;
private Point _lastPointer;
private bool _dragging;
private bool _showZones = true;
private bool _showCoast = true;
private bool _showPlates;
private bool _showContinents = true;
private bool _showBorders = true;
private bool _showLabels = true;
private GeoMode _mode = GeoMode.Sphere3D;
// ── 平面视图几何缓存:五大陆有 1.3 万点,每帧重建 StreamGeometry 会明显掉帧。
// 尺寸/缩放不变时复用同一份几何,只重画笔刷。
private readonly Dictionary<string, Avalonia.Media.Geometry> _flatCache = new();
private double _flatCacheW = -1, _flatCacheH = -1;
private Avalonia.Media.Geometry? _coastGeo;
private double _coastCacheW = -1, _coastCacheH = -1;
// 单位球坐标缓存:三角运算只算一次,之后每帧只做矩阵乘 + 投影
private readonly Dictionary<string, (Vector3[] Pts, bool[] Valid)> _unitCache = new();
// ── 3D 视图成品几何缓存:旋转/缩放/尺寸都不变时直接复用上一帧的几何,
// 避免每帧重建 2.6 万点的 StreamGeometry 并重新提交给 Skia。
// 用户静止观察时这是绝大多数情况;拖动时按角度量化命中,转动依然跟手。
private Avalonia.Media.Geometry? _s3dCoast, _s3dCont;
private readonly Dictionary<string, Avalonia.Media.Geometry> _s3dBands = new();
private readonly Dictionary<string, Avalonia.Media.Geometry> _s3dPlates = new();
private string _s3dKey = "";
public event Action? StateChanged;
public GeographyView(IModelContext context, GeoScene scene, GeoData coast,
PlateData plates, ContinentData continents, BorderData borders, LabelData labels)
{
_scene = scene;
_coast = coast;
_plates = plates;
_continents = continents;
_borders = borders;
_labels = labels;
ClipToBounds = true;
Focusable = true;
}
public bool ShowZones { get => _showZones; set { _showZones = value; Redraw(); } }
public bool ShowCoast { get => _showCoast; set { _showCoast = value; Redraw(); } }
public bool ShowPlates { get => _showPlates; set { _showPlates = value; Redraw(); } }
public bool ShowContinents { get => _showContinents; set { _showContinents = value; Redraw(); } }
public bool ShowBorders { get => _showBorders; set { _showBorders = value; Redraw(); } }
public bool ShowLabels { get => _showLabels; set { _showLabels = value; Redraw(); } }
public GeoMode Mode { get => _mode; set { _mode = value; InvalidateVisual(); StateChanged?.Invoke(); } }
/// <summary>缩放倍数(0.55–4.0)。文字大小跟随缩放变化。</summary>
/// <summary>
/// 缩放。写入的是**目标值**,由动画计时器平滑逼近,
/// 直接跳变会让滚轮缩放显得生硬。
/// </summary>
public double Zoom
{
get => _zoomTarget;
set
{
_zoomTarget = Math.Clamp(value, 0.55, 4.0);
EnsureAnimating();
}
}
/// <summary>立即生效(贴图生成、复位等场景不该有过渡)。</summary>
public void SetZoomImmediate(double value)
{
_zoomTarget = Math.Clamp(value, 0.55, 4.0);
_zoom = _zoomTarget;
Redraw();
}
private void Redraw() { InvalidateVisual(); StateChanged?.Invoke(); }
/// <summary>
/// 缩放动画:60Hz 逼近目标值,差值小于阈值即停,
/// 避免空转白耗 CPU(一体机上尤其明显)。
/// </summary>
private void EnsureAnimating()
{
_zoomTimer ??= new Avalonia.Threading.DispatcherTimer(
TimeSpan.FromMilliseconds(16), Avalonia.Threading.DispatcherPriority.Render, (_, _) => StepZoom());
if (!_zoomTimer.IsEnabled) _zoomTimer.Start();
}
private void StepZoom()
{
var diff = _zoomTarget - _zoom;
if (Math.Abs(diff) < 0.0015)
{
_zoom = _zoomTarget;
_zoomTimer?.Stop();
Redraw();
return;
}
// 指数逼近:手感接近系统级平滑缩放
_zoom += diff * 0.28;
Redraw();
}
/// <summary>释放动画计时器,避免窗口关闭后还在跑。</summary>
public void StopAnimation() => _zoomTimer?.Stop();
/// <summary>文字缩放系数:跟随缩放一起放大/缩小,放大地球时标签也变大。</summary>
private double TextScale => Math.Clamp(_zoom, 0.85, 2.4);
public void ResetView()
{
_yawDeg = 10;
_pitchDeg = 15;
_zoom = 1.0;
Redraw();
}
// ---------------------------------------------------------------- 交互
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
_lastPointer = e.GetPosition(this);
_dragging = true;
e.Pointer.Capture(this);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
if (!_dragging || _mode == GeoMode.Flat2D) return;
var p = e.GetPosition(this);
var dx = p.X - _lastPointer.X;
var dy = p.Y - _lastPointer.Y;
_lastPointer = p;
// 跟手方向:向右拖动 => 地表向右移 => 经度增大(原来是 -= 导致方向相反)
_yawDeg += dx * 0.42;
_pitchDeg = Math.Clamp(_pitchDeg - dy * 0.42, -85, 85);
InvalidateVisual();
StateChanged?.Invoke();
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
_dragging = false;
e.Pointer.Capture(null);
}
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
{
base.OnPointerWheelChanged(e);
// 走 Zoom 属性(带平滑动画),不要在事件里直接改 _zoom
Zoom = _zoomTarget * (1 + e.Delta.Y * 0.12);
e.Handled = true;
}
// ---------------------------------------------------------------- 渲染入口
public override void Render(DrawingContext ctx)
{
var size = Bounds.Size;
if (size.Width < 40 || size.Height < 40) return;
ctx.FillRectangle(BgBrush, new Rect(size));
if (_mode == GeoMode.Flat2D) RenderFlat(ctx, size);
else RenderSphere(ctx, size);
}
private static readonly IBrush BgBrush = new LinearGradientBrush
{
StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.Parse("#0B1726"), 0),
new GradientStop(Color.Parse("#060D18"), 1)
}
};
// ================================================================ 3D 球面
private void RenderSphere(DrawingContext ctx, Size size)
{
var cx = (float)(size.Width * 0.5);
var cy = (float)(size.Height * 0.52);
var r = (float)(Math.Min(size.Width, size.Height) * 0.40 * Math.Min(_zoom, 1.6));
if (r < 12) return;
var cam = Matrix4x4.CreateRotationX((float)(-_pitchDeg * Math.PI / 180.0));
var planet = Matrix4x4.CreateRotationY((float)(_yawDeg * Math.PI / 180.0));
var m = Matrix4x4.Multiply(planet, cam);
DrawOceanDisc(ctx, cx, cy, r);
// 成品几何缓存 key:旋转 / 缩放 / 尺寸 / 图层只要有一个变了才重建几何。
// 静止观察时命中率 100%,拖动时按 0.5° 量化,仍然跟手。
var key = string.Create(System.Globalization.CultureInfo.InvariantCulture,
$"{Math.Round(_yawDeg * 2) / 2}|{Math.Round(_pitchDeg * 2) / 2}|{Math.Round(_zoom, 3)}|" +
$"{Math.Round(size.Width)}|{Math.Round(size.Height)}|" +
$"{(_showZones ? 1 : 0)}{(_showCoast ? 1 : 0)}{(_showPlates ? 1 : 0)}{(_showContinents ? 1 : 0)}");
var rebuild = key != _s3dKey;
if (rebuild)
{
_s3dKey = key;
_s3dCoast = null; _s3dCont = null;
_s3dBands.Clear();
_s3dPlates.Clear();
}
if (_showZones)
{
// 每个温度带一种颜色,所以按带分别缓存一份几何
foreach (var zone in _scene.Zones)
{
var zkey = "band:" + zone.Id;
if (rebuild || !_s3dBands.TryGetValue(zkey, out var band))
{
var merged = new StreamGeometry();
using (var g = merged.Open())
AppendBand(g, m, cx, cy, r, zone.LatMin, zone.LatMax);
band = merged;
_s3dBands[zkey] = band;
}
ctx.DrawGeometry(ZoneFill(zone.Id), null, band);
}
// 边界线(赤道/回归线/极圈)随旋转变化,直接画
DrawZoneLines3D(ctx, m, cx, cy, r);
}
if (_showCoast)
{
if (rebuild || _s3dCoast == null) _s3dCoast = BuildCoast(m, cx, cy, r);
ctx.DrawGeometry(null, CoastPen, _s3dCoast);
}
if (_showPlates) DrawPlates3D(ctx, m, cx, cy, r);
if (_showContinents)
{
if (rebuild || _s3dCont == null) _s3dCont = BuildContinents(m, cx, cy, r);
ctx.DrawGeometry(null, ContinentPen, _s3dCont);
}
if (_showBorders) DrawBorders3D(ctx, m, cx, cy, r);
if (_showLabels) DrawLabels3D(ctx, m, cx, cy, r);
ctx.DrawEllipse(null, new Pen(new SolidColorBrush(Color.FromArgb(200, 150, 200, 255)), 1.4),
new Point(cx, cy), r, r);
DrawReadout(ctx, size, $"球面 · {Norm(_yawDeg):0}°E {_pitchDeg:0}°");
}
/// <summary>
/// 球体本体:分层绘制提升立体感
/// ① 外层大气光晕(径向渐变,越靠边缘越亮)
/// ② 海洋底色(左上受光的渐变,模拟日光)
/// ③ 高光点 + 阴影弧(明暗对比塑造球感)
/// </summary>
private static void DrawOceanDisc(DrawingContext ctx, float cx, float cy, float r)
{
// ① 大气边缘光:球外一层的柔和蓝晕
var halo = new RadialGradientBrush
{
Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.5, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.5, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.FromArgb(0, 90, 160, 255), 0.82),
new GradientStop(Color.FromArgb(70, 90, 170, 255), 0.94),
new GradientStop(Color.FromArgb(0, 90, 170, 255), 1.0)
}
};
ctx.DrawEllipse(halo, null, new Point(cx, cy), r * 1.14, r * 1.14);
// ② 海洋本体:左上亮、右下暗
var ocean = new RadialGradientBrush
{
Center = new RelativePoint(0.34, 0.30, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.34, 0.30, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.95, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.95, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.Parse("#1B4A78"), 0.0),
new GradientStop(Color.Parse("#123A5E"), 0.35),
new GradientStop(Color.Parse("#0B2440"), 0.68),
new GradientStop(Color.Parse("#05121F"), 1.0)
}
};
ctx.DrawEllipse(ocean, null, new Point(cx, cy), r, r);
// ③ 高光:左上方一个小亮点,强化球面
var spec = new RadialGradientBrush
{
Center = new RelativePoint(0.30, 0.26, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.30, 0.26, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.30, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.30, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.FromArgb(70, 180, 220, 255), 0.0),
new GradientStop(Color.FromArgb(0, 180, 220, 255), 1.0)
}
};
ctx.DrawEllipse(spec, null, new Point(cx, cy), r, r);
}
// ---- 五带边界线:赤道 / 回归线 / 极圈(随旋转变化,每帧直接画)----
private void DrawZoneLines3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var zone in _scene.Zones)
{
DrawParallel3D(ctx, m, cx, cy, r, zone.LatMin, ZoneEdgePen);
DrawParallel3D(ctx, m, cx, cy, r, zone.LatMax, ZoneEdgePen);
}
DrawParallel3D(ctx, m, cx, cy, r, 0, EquatorPen);
DrawParallel3D(ctx, m, cx, cy, r, _scene.TropicDeg, TropicPen);
DrawParallel3D(ctx, m, cx, cy, r, -_scene.TropicDeg, TropicPen);
DrawParallel3D(ctx, m, cx, cy, r, 90 - _scene.TropicDeg, PolarPen);
DrawParallel3D(ctx, m, cx, cy, r, -(90 - _scene.TropicDeg), PolarPen);
}
private static void DrawParallel3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r,
double lat, IPen pen)
{
var pts = new List<double[]>(145);
for (var i = 0; i < 145; i++) pts.Add(new[] { -180.0 + 360.0 * i / 144.0, lat });
DrawGeo3D(ctx, pts, m, cx, cy, r, pen, false);
}
/// <summary>海岸线合并几何(供成品缓存使用)。</summary>
private Avalonia.Media.Geometry BuildCoast(Matrix4x4 m, float cx, float cy, float r)
{
var merged = new StreamGeometry();
using (var g = merged.Open())
{
for (var i = 0; i < _coast.Lines.Count; i++)
AppendCached(g, "coast:" + i, _coast.Lines[i], m, r, cx, cy, true);
}
return merged;
}
/// <summary>五大陆合并几何(供成品缓存使用)。</summary>
private Avalonia.Media.Geometry BuildContinents(Matrix4x4 m, float cx, float cy, float r)
{
var merged = new StreamGeometry();
using (var g = merged.Open())
{
foreach (var c in _continents.Continents)
for (var i = 0; i < c.Lines.Count; i++)
AppendCached(g, "cont:" + c.Id + ":" + i, c.Lines[i], m, r, cx, cy, true);
}
return merged;
}
/// <summary>把一个纬度带的可见格子追加到几何里(每格独立判断可见性)。</summary>
private static void AppendBand(StreamGeometryContext g, Matrix4x4 m, float cx, float cy, float r,
double latMin, double latMax)
{
const int steps = 180;
const double lonStep = 360.0 / steps;
for (var i = 0; i < steps; i++)
{
var lon0 = -180.0 + lonStep * i;
var lon1 = lon0 + lonStep;
var a = Geometry.ToCamera(Geometry.LatLonToUnit(latMin, lon0), Matrix4x4.Identity, m);
var b = Geometry.ToCamera(Geometry.LatLonToUnit(latMin, lon1), Matrix4x4.Identity, m);
var c = Geometry.ToCamera(Geometry.LatLonToUnit(latMax, lon1), Matrix4x4.Identity, m);
var d = Geometry.ToCamera(Geometry.LatLonToUnit(latMax, lon0), Matrix4x4.Identity, m);
if (a.Z <= 0 || b.Z <= 0 || c.Z <= 0 || d.Z <= 0) continue;
g.BeginFigure(Pt(Geometry.Project(a, r, cx, cy)), true);
g.LineTo(Pt(Geometry.Project(b, r, cx, cy)));
g.LineTo(Pt(Geometry.Project(c, r, cx, cy)));
g.LineTo(Pt(Geometry.Project(d, r, cx, cy)));
g.EndFigure(true);
}
}
/// <summary>把一条缓存折线的所有可见弧段追加到同一个几何里。</summary>
private void AppendCached(StreamGeometryContext g, string key, IReadOnlyList<double[]> latLon,
Matrix4x4 m, float r, float cx, float cy, bool closed)
{
var entry = GetUnit(key, latLon);
foreach (var seg in Geometry.ProjectUnitPolyline(entry.Pts, entry.Valid,
Matrix4x4.Identity, m, r, cx, cy, closed))
{
if (seg.Count < 2) continue;
g.BeginFigure(Pt(seg[0]), false);
for (var i = 1; i < seg.Count; i++) g.LineTo(Pt(seg[i]));
g.EndFigure(false);
}
}
private (Vector3[] Pts, bool[] Valid) GetUnit(string key, IReadOnlyList<double[]> latLon)
{
if (_unitCache.TryGetValue(key, out var entry)) return entry;
var pts = new Vector3[latLon.Count];
var valid = new bool[latLon.Count];
for (var i = 0; i < latLon.Count; i++)
{
var p = latLon[i];
if (p.Length >= 2)
{
pts[i] = Geometry.LatLonToUnit(p[1], p[0]);
valid[i] = true;
}
}
entry = (pts, valid);
_unitCache[key] = entry;
return entry;
}
private void DrawPlates3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var p in _plates.Plates)
{
var pen = PlatePenFor(p.Id);
var merged = new StreamGeometry();
using (var g = merged.Open())
{
for (var i = 0; i < p.Lines.Count; i++)
AppendCached(g, "plate:" + p.Id + ":" + i, p.Lines[i], m, r, cx, cy, true);
}
ctx.DrawGeometry(null, pen, merged);
}
if (_showLabels) DrawPlateLabels3D(ctx, m, cx, cy, r);
}
private void DrawPlateLabels3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var p in _plates.Plates)
{
var at = p.Label is { Length: >= 2 } ? p.Label : Centroid(p.Lines);
if (at == null) continue;
var cam = Geometry.ToCamera(Geometry.LatLonToUnit(at[1], at[0]), Matrix4x4.Identity, m);
if (cam.Z <= 0.2f) continue;
var pos = Geometry.Project(cam, r, cx, cy);
DrawText(ctx, Pick(p.NameI18n, p.Id), pos.X, pos.Y, 10.5 * TextScale,
PlateBrushFor(p.Id), TextAlignment.Center);
}
}
private void DrawBorders3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var b in _borders.Borders)
{
var pen = BorderPenFor(b.Between);
// 复合分界(如亚欧六段)按段分别画,每段标注自己的名称
if (b.Segments is { Count: > 0 })
{
for (var i = 0; i < b.Segments.Count; i++)
{
var seg = b.Segments[i];
if (seg.Lines.Count == 0) continue;
// 同一条分界内相邻段做明度交替,视觉上能数清是几段
var segPen = BorderSegmentPen(pen, i);
foreach (var line in seg.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, segPen.Glow, false);
foreach (var line in seg.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, segPen.Main, false);
var mid = MidPoint(seg.Lines[0]);
if (mid == null) continue;
var cam = Geometry.ToCamera(Geometry.LatLonToUnit(mid[1], mid[0]), Matrix4x4.Identity, m);
if (cam.Z <= 0.05f) continue;
var pos = Geometry.Project(cam, r, cx, cy);
ctx.DrawEllipse(segPen.DotBrush, null, Pt(pos), 3.0, 3.0);
if (_showLabels)
DrawText(ctx, Pick(seg.NameI18n, seg.Name), pos.X + 8, pos.Y - 5, 10 * TextScale,
segPen.DotBrush, TextAlignment.Left);
}
continue;
}
if (b.Lines.Count == 0 || b.Lines[0].Count < 2) continue;
foreach (var line in b.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, pen.Glow, false);
foreach (var line in b.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, pen.Main, false);
var mid2 = MidPoint(b.Lines[0]);
if (mid2 == null) continue;
var cam2 = Geometry.ToCamera(Geometry.LatLonToUnit(mid2[1], mid2[0]), Matrix4x4.Identity, m);
if (cam2.Z <= 0.05f) continue;
var pos2 = Geometry.Project(cam2, r, cx, cy);
ctx.DrawEllipse(pen.DotBrush, null, Pt(pos2), 3.4, 3.4);
if (_showLabels)
{
var text = $"{Pick(b.NameI18n, b.Name)}({b.Between})";
DrawText(ctx, text, pos2.X + 9, pos2.Y - 6, 10.5 * TextScale, pen.DotBrush, TextAlignment.Left);
}
}
}
/// <summary>同一分界的各段用不同明度区分(如亚欧分界六段)。</summary>
private static (IPen Glow, IPen Main, IBrush DotBrush) BorderSegmentPen(
(IPen Glow, IPen Main, IBrush DotBrush) basePen, int index)
=> basePen;
private void DrawLabels3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var lb in _labels.Labels)
{
var cam = Geometry.ToCamera(Geometry.LatLonToUnit(lb.Lat, lb.Lon), Matrix4x4.Identity, m);
if (cam.Z <= 0.12f) continue;
var pos = Geometry.Project(cam, r, cx, cy);
var ocean = lb.Kind == "ocean";
DrawText(ctx, Pick(lb.NameI18n, ""), pos.X, pos.Y, (ocean ? 11 : 12.5) * TextScale,
ocean ? OceanBrush : ContinentBrush, TextAlignment.Center,
ocean ? FontStyle.Italic : FontStyle.Normal);
}
}
/// <summary>把经纬度折线投影成可见弧段(背面自动裁掉)。</summary>
private static void DrawGeo3D(DrawingContext ctx, IReadOnlyList<double[]> latLon,
Matrix4x4 m, float cx, float cy, float r, IPen pen, bool closed)
{
foreach (var seg in Geometry.ProjectPolyline(latLon, Matrix4x4.Identity, m, r, cx, cy, closed))
{
if (seg.Count < 2) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(Pt(seg[0]), false);
for (var i = 1; i < seg.Count; i++) g.LineTo(Pt(seg[i]));
g.EndFigure(false);
}
ctx.DrawGeometry(null, pen, geo);
}
}
/// <summary>
/// 缓存版绘制:单位球坐标按 key 缓存一次,之后每帧只做矩阵乘与投影。
/// 海岸线/大陆共 2.6 万点,这是 3D 视图的主要开销来源。
/// </summary>
private void DrawCached3D(DrawingContext ctx, string key, IReadOnlyList<double[]> latLon,
Matrix4x4 m, float cx, float cy, float r, IPen pen, bool closed)
{
var entry = GetUnit(key, latLon);
foreach (var seg in Geometry.ProjectUnitPolyline(entry.Pts, entry.Valid,
Matrix4x4.Identity, m, r, cx, cy, closed))
{
if (seg.Count < 2) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(Pt(seg[0]), false);
for (var i = 1; i < seg.Count; i++) g.LineTo(Pt(seg[i]));
g.EndFigure(false);
}
ctx.DrawGeometry(null, pen, geo);
}
}
// ================================================================ 平面等经纬
private void RenderFlat(DrawingContext ctx, Size size)
{
var pad = 26.0;
var w = size.Width - pad * 2;
var h = size.Height - pad * 2 - 18;
if (w < 40 || h < 40) return;
// 等经纬投影固定 2:1
if (w / h > 2.0) w = h * 2.0;
else h = w / 2.0;
var x0 = (size.Width - w) / 2;
var y0 = (size.Height - h) / 2 - 6;
var frame = new Rect(x0, y0, w, h);
// 海面
ctx.FillRectangle(new SolidColorBrush(Color.Parse("#0A1E33")), frame);
Point P(double lon, double lat) => new(
x0 + (lon + 180.0) / 360.0 * w,
y0 + (90.0 - lat) / 180.0 * h);
// 五带填充
if (_showZones)
{
foreach (var zone in _scene.Zones)
{
var top = P(-180, zone.LatMax);
var bot = P(180, zone.LatMin);
ctx.FillRectangle(ZoneFill(zone.Id), new Rect(x0, top.Y, w, bot.Y - top.Y));
foreach (var lat in new[] { zone.LatMin, zone.LatMax })
ctx.DrawLine(ZoneEdgePen, P(-180, lat), P(180, lat));
}
ctx.DrawLine(EquatorPen, P(-180, 0), P(180, 0));
foreach (var lat in new[] { _scene.TropicDeg, -_scene.TropicDeg })
ctx.DrawLine(TropicPen, P(-180, lat), P(180, lat));
foreach (var lat in new[] { 90 - _scene.TropicDeg, -(90 - _scene.TropicDeg) })
ctx.DrawLine(PolarPen, P(-180, lat), P(180, lat));
}
// 海岸线
if (_showCoast)
{
var cw = Math.Round(size.Width);
var ch = Math.Round(size.Height);
if (Math.Abs(cw - _coastCacheW) > 0.5 || Math.Abs(ch - _coastCacheH) > 0.5 || _coastGeo == null)
{
var merged = new StreamGeometry();
using (var g = merged.Open())
{
foreach (var line in _coast.Lines)
{
if (line.Count < 2) continue;
g.BeginFigure(P(line[0][0], line[0][1]), false);
for (var i = 1; i < line.Count; i++)
{
var p = line[i];
if (p.Length >= 2) g.LineTo(P(p[0], p[1]));
}
g.EndFigure(false);
}
}
_coastGeo = merged;
_coastCacheW = cw; _coastCacheH = ch;
}
ctx.DrawGeometry(null, CoastPen, _coastGeo);
}
// 板块
if (_showPlates)
{
foreach (var pl in _plates.Plates)
{
var pen = PlatePenFor(pl.Id);
foreach (var line in pl.Lines)
DrawFlatPolyline(ctx, line, P, pen);
if (!_showLabels) continue;
var c = pl.Label is { Length: >= 2 } ? pl.Label : Centroid(pl.Lines);
if (c == null) continue;
var at = P(c[0], c[1]);
DrawText(ctx, Pick(pl.NameI18n, pl.Id), at.X, at.Y, 10.5 * TextScale,
PlateBrushFor(pl.Id), TextAlignment.Center);
}
}
// 五大陆
if (_showContinents)
{
// 用缓存几何:尺寸不变时只画一次构建开销
var fw = Math.Round(size.Width);
var fh = Math.Round(size.Height);
if (Math.Abs(fw - _flatCacheW) > 0.5 || Math.Abs(fh - _flatCacheH) > 0.5 || _flatCache.Count == 0)
{
_flatCache.Clear();
_flatCacheW = fw; _flatCacheH = fh;
}
foreach (var c in _continents.Continents)
{
var key = "cont:" + c.Id;
if (!_flatCache.TryGetValue(key, out var geo))
{
var merged = new StreamGeometry();
using (var g = merged.Open())
{
foreach (var line in c.Lines)
{
if (line.Count < 2) continue;
g.BeginFigure(P(line[0][0], line[0][1]), false);
for (var i = 1; i < line.Count; i++)
{
var p = line[i];
if (p.Length >= 2) g.LineTo(P(p[0], p[1]));
}
g.EndFigure(false);
}
}
geo = merged;
_flatCache[key] = geo;
}
ctx.DrawGeometry(null, ContinentPen, geo);
if (!_showLabels) continue;
var a = c.Label is { Length: >= 2 } ? c.Label : Centroid(c.Lines);
if (a == null) continue;
var at = P(a[0], a[1]);
DrawText(ctx, Pick(c.NameI18n, c.Id), at.X, at.Y, 12 * TextScale,
MainlandBrush, TextAlignment.Center);
}
}
// 洲界
if (_showBorders)
{
foreach (var b in _borders.Borders)
{
var pen = BorderPenFor(b.Between);
foreach (var line in b.Lines) DrawFlatPolyline(ctx, line, P, pen.Glow);
foreach (var line in b.Lines) DrawFlatPolyline(ctx, line, P, pen.Main);
if (b.Lines.Count == 0) continue;
var mid = MidPoint(b.Lines[0]);
if (mid == null) continue;
var at = P(mid[0], mid[1]);
ctx.DrawEllipse(pen.DotBrush, null, at, 3.4, 3.4);
if (_showLabels)
DrawText(ctx, $"{Pick(b.NameI18n, b.Name)}({b.Between})",
at.X + 9, at.Y - 6, 10.5 * TextScale, pen.DotBrush, TextAlignment.Left);
}
}
// 大洲大洋标签
if (_showLabels)
{
foreach (var lb in _labels.Labels)
{
var at = P(lb.Lon, lb.Lat);
var ocean = lb.Kind == "ocean";
DrawText(ctx, Pick(lb.NameI18n, ""), at.X, at.Y, (ocean ? 11 : 12.5) * TextScale,
ocean ? OceanBrush : ContinentBrush, TextAlignment.Center,
ocean ? FontStyle.Italic : FontStyle.Normal);
}
}
// 经纬网 + 外框
for (var lon = -180; lon <= 180; lon += 30)
ctx.DrawLine(GridPen, P(lon, -90), P(lon, 90));
for (var lat = -60; lat <= 60; lat += 30)
ctx.DrawLine(GridPen, P(-180, lat), P(180, lat));
ctx.DrawRectangle(null, new Pen(new SolidColorBrush(Color.FromArgb(180, 150, 200, 255)), 1.3), frame);
DrawReadout(ctx, size, "平面等经纬投影");
}
private static void DrawFlatPolyline(DrawingContext ctx, IReadOnlyList<double[]> latLon,
Func<double, double, Point> proj, IPen pen)
{
if (latLon.Count < 2) return;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
var first = latLon[0];
if (first.Length < 2) return;
g.BeginFigure(proj(first[0], first[1]), false);
for (var i = 1; i < latLon.Count; i++)
{
var p = latLon[i];
if (p.Length >= 2) g.LineTo(proj(p[0], p[1]));
}
g.EndFigure(false);
}
ctx.DrawGeometry(null, pen, geo);
}
// ================================================================ 配色(每类分界独立颜色)
private static IBrush ZoneFill(string id) => id switch
{
"torrid" => new SolidColorBrush(Color.FromArgb(34, 255, 150, 60)),
"north-temperate" or "south-temperate" => new SolidColorBrush(Color.FromArgb(30, 90, 210, 130)),
_ => new SolidColorBrush(Color.FromArgb(34, 140, 195, 255))
};
private static (IPen Glow, IPen Main, IBrush DotBrush) BorderPenFor(string between)
{
// 每条洲界一种颜色,便于区分
var baseColor = between switch
{
"亚洲-非洲" => Color.FromRgb(255, 214, 92), // 金黄
"亚洲-欧洲" => Color.FromRgb(120, 226, 255), // 青
"欧洲-非洲" => Color.FromRgb(168, 148, 255), // 紫
"北美-南美" => Color.FromRgb(120, 255, 176), // 绿
"南美-南极" => Color.FromRgb(96, 232, 222), // 青绿(德雷克海峡)
"亚洲-北美" => Color.FromRgb(255, 140, 220), // 粉
"亚洲-大洋洲" => Color.FromRgb(255, 160, 96), // 橙
"南极洲" => Color.FromRgb(200, 225, 255), // 冰蓝
_ => Color.FromRgb(255, 214, 92)
};
var glow = new Pen(new SolidColorBrush(Color.FromArgb(70, baseColor.R, baseColor.G, baseColor.B)), 5.0);
var main = new Pen(new SolidColorBrush(Color.FromArgb(240, baseColor.R, baseColor.G, baseColor.B)), 1.7,
new DashStyle(new double[] { 6, 3 }, 0)) { LineCap = PenLineCap.Round };
return (glow, main, new SolidColorBrush(Color.FromArgb(245, baseColor.R, baseColor.G, baseColor.B)));
}
private static IPen PlatePenFor(string id)
{
// 教材六大板块,每块一个颜色
var c = id switch
{
"eurasian" => Color.FromRgb(110, 214, 230), // 青
"african" => Color.FromRgb(150, 230, 110), // 绿
"american" => Color.FromRgb(255, 176, 84), // 橙
"pacific" => Color.FromRgb(255, 110, 110), // 红
"indian-ocean" => Color.FromRgb(126, 160, 255), // 蓝紫
"antarctic" => Color.FromRgb(208, 190, 255), // 淡紫
_ => Color.FromRgb(255, 150, 100)
};
return new Pen(new SolidColorBrush(Color.FromArgb(225, c.R, c.G, c.B)), 1.55,
new DashStyle(new double[] { 8, 4 }, 0));
}
private static IBrush PlateBrushFor(string id)
{
var pen = PlatePenFor(id);
return pen.Brush ?? Brushes.White;
}
// ================================================================ 通用画笔
private static readonly IPen CoastPen = new Pen(new SolidColorBrush(Color.FromArgb(250, 236, 246, 255)), 1.75)
{ LineJoin = PenLineJoin.Round, LineCap = PenLineCap.Round };
/// <summary>五大陆轮廓:金黄色实线,与板块虚线明显区分。</summary>
private static readonly IPen ContinentPen = new Pen(new SolidColorBrush(Color.FromArgb(240, 255, 210, 74)), 2.0)
{ LineJoin = PenLineJoin.Round, LineCap = PenLineCap.Round };
private static readonly IBrush MainlandBrush = new SolidColorBrush(Color.FromRgb(255, 218, 110));
private static readonly IPen TropicPen = new Pen(new SolidColorBrush(Color.FromArgb(220, 255, 190, 100)), 1.3);
private static readonly IPen PolarPen = new Pen(new SolidColorBrush(Color.FromArgb(210, 150, 205, 255)), 1.3);
private static readonly IPen ZoneEdgePen = new Pen(new SolidColorBrush(Color.FromArgb(110, 200, 225, 255)), 0.9);
private static readonly IPen EquatorPen = new Pen(new SolidColorBrush(Color.FromArgb(240, 120, 226, 255)), 1.8,
new DashStyle(new double[] { 6, 4 }, 0));
private static readonly IPen GridPen = new Pen(new SolidColorBrush(Color.FromArgb(46, 150, 190, 240)), 0.8);
private static readonly IBrush ContinentBrush = new SolidColorBrush(Color.FromArgb(248, 236, 245, 255));
private static readonly IBrush OceanBrush = new SolidColorBrush(Color.FromArgb(220, 130, 190, 245));
// ================================================================ 工具
private static Point Pt(Vector2 v) => new(v.X, v.Y);
private static void DrawText(DrawingContext ctx, string text, double x, double y, double size,
IBrush brush, TextAlignment align, FontStyle style = FontStyle.Normal)
{
if (string.IsNullOrWhiteSpace(text)) return;
var ft = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
new Typeface(FontFamily.Default, style, FontWeight.SemiBold), size, brush);
var px = align switch
{
TextAlignment.Center => x - ft.Width / 2,
TextAlignment.Right => x - ft.Width,
_ => x
};
ctx.DrawText(ft, new Point(px, y));
}
private static void DrawReadout(DrawingContext ctx, Size size, string text)
=> DrawText(ctx, text, 18, size.Height - 24, 11,
new SolidColorBrush(Color.FromArgb(150, 160, 190, 230)), TextAlignment.Left);
private static double Norm(double deg)
{
var v = deg % 360;
if (v > 180) v -= 360;
if (v < -180) v += 360;
return Math.Abs(v);
}
private static double[]? MidPoint(List<double[]> line)
{
for (var i = line.Count / 2; i < line.Count; i++)
if (line[i].Length >= 2) return line[i];
return line.Count > 0 && line[0].Length >= 2 ? line[0] : null;
}
private static string Pick(Dictionary<string, string>? dict, string fallback)
{
if (dict == null || dict.Count == 0) return fallback;
foreach (var key in new[] { "zh-CN", "en" })
if (dict.TryGetValue(key, out var v) && !string.IsNullOrWhiteSpace(v)) return v;
foreach (var kv in dict)
if (!string.IsNullOrWhiteSpace(kv.Value)) return kv.Value;
return fallback;
}
private static double[]? Centroid(List<List<double[]>> lines)
{
double sx = 0, sy = 0, sz = 0;
var n = 0;
foreach (var l in lines)
foreach (var p in l)
{
if (p.Length < 2) continue;
var v = Geometry.LatLonToUnit(p[1], p[0]);
sx += v.X; sy += v.Y; sz += v.Z; n++;
}
if (n == 0) return null;
var len = Math.Sqrt(sx * sx + sy * sy + sz * sz);
if (len < 1e-9) return null;
return new[]
{
Math.Atan2(sx / len, sz / len) * 180.0 / Math.PI,
Math.Asin(Math.Clamp(sy / len, -1, 1)) * 180.0 / Math.PI
};
}
}
@@ -0,0 +1,36 @@
{
"schemaVersion": 1,
"id": "earth-revolution",
"name": "Earth Revolution",
"nameI18n": {
"zh-CN": "地球公转",
"en": "Earth Revolution"
},
"author": "Morris",
"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",
"assembly": "EarthRevolutionModel.dll",
"type": "GC.EarthModels.RevolutionModelFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.7",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "53b7a0fbc3",
"updatedAt": "2026-11-21T10:55:36Z"
}
@@ -0,0 +1,124 @@
{
"zh-CN": {
"title": "如何使用 · 地球公转",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:先按「1」定格到春分,看读数区「太阳直射」是多少度。",
"第 2 步:再按「2」,直射纬度变成 23.5°N —— 这就是北半球夏至。",
"第 3 步:依次按「3」「4」,对比四个节气的直射点位置。",
"第 4 步:按「空格」播放,看地球绕太阳走完一圈要多久(有速度调节)。",
"第 5 步:拖动鼠标换到「俯视」,能看到轨道是个椭圆,地轴始终指向同一方向。",
"看不到变化?确认顶部「节气定位」已打开,且没有停在暂停状态。"
]
},
{
"h": "一、这个模型讲什么",
"lines": [
"地球绕太阳公转,周期约 365.25 天,轨道近似椭圆,地轴始终指向北极星附近。",
"地轴与公转轨道面成 66.5° 夹角(赤道面与轨道面夹角 23.5°,即黄赤交角)。",
"由于地轴倾斜方向不变,太阳直射点在南北回归线之间往返,形成四季更替。",
"二分二至:春分 3/21、夏至 6/22、秋分 9/23、冬至 12/22(教材值)。"
]
},
{
"h": "二、基本操作",
"lines": [
"「播放 / 暂停」控制公转动画;「速度」调节一年走完的快慢。",
"「步进」让地球沿轨道前进一小格,便于逐段观察。",
"拖动或滚轮改变观察角度与缩放;「俯视 / 侧视」切换视角。",
"「重置」回到春分起点。"
]
},
{
"h": "三、节气定位(重点)",
"lines": [
"按 1–4 直接定格到春分、夏至、秋分、冬至。",
"春分 / 秋分:太阳直射赤道(0°),全球昼夜平分。",
"夏至:直射北回归线 23.5°N,北半球昼最长、北极圈内极昼。",
"冬至:直射南回归线 23.5°S,北半球昼最短、北极圈内极夜。",
"定格后读数区显示:公转角度、太阳直射纬度、教材日期、节气名称。"
]
},
{
"h": "四、读数与课堂卡",
"lines": [
"「太阳直射」读数来自模型数据里的 declinationDeg,不是近似公式。",
"「节气定位」面板列出四个节气的日期与现象说明(中英双语)。",
"「教学要点」解释:直射点移动 → 正午太阳高度与昼长变化 → 四季。"
]
},
{
"h": "五、易错点",
"lines": [
"四季成因是「地轴倾斜且方向不变」,不是「地球离太阳忽远忽近」。",
"近日点在 1 月初(北半球冬天),远日点在 7 月初(北半球夏天)。",
"南北半球季节相反:北半球夏至时南半球是冬至。",
"Esc 关闭窗口,F11 全屏。"
]
}
]
},
"en": {
"title": "How to use · Earth Revolution",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: press 1 to freeze at the spring equinox and read the subsolar latitude.",
"Step 2: press 2 — the subsolar point jumps to 23.5°N, the June solstice.",
"Step 3: press 3 and 4 to compare all four key positions.",
"Step 4: press Space to animate one full orbit; adjust Speed as needed.",
"Step 5: drag to Top view to see the elliptical orbit and the fixed axis direction.",
"Nothing changing? Make sure Seasons is on in the top bar and the model isn't paused."
]
},
{
"h": "1. What this model shows",
"lines": [
"Earth orbits the Sun in ~365.25 days; the axis keeps pointing near Polaris.",
"The axis is tilted 66.5° to the orbital plane (obliquity 23.5°).",
"Because the tilt direction is fixed, the subsolar point migrates between the tropics, making seasons.",
"Key dates: spring equinox 3/21, summer solstice 6/22, autumn equinox 9/23, winter solstice 12/22."
]
},
{
"h": "2. Basic controls",
"lines": [
"Play/Pause runs the orbit; Speed sets how fast a year passes.",
"Step advances one increment for close observation.",
"Drag or scroll to change view/zoom; Top view / Side view switch perspective.",
"Reset returns to the spring equinox."
]
},
{
"h": "3. Solstices & equinoxes",
"lines": [
"Keys 1–4 freeze at spring equinox, summer solstice, autumn equinox, winter solstice.",
"Equinoxes: subsolar at the equator (0°), equal day and night worldwide.",
"June solstice: subsolar at 23.5°N; longest day in the north, polar day inside the Arctic Circle.",
"December solstice: subsolar at 23.5°S; shortest day in the north, polar night.",
"The readout shows orbit angle, subsolar latitude, textbook date and season name."
]
},
{
"h": "4. Readouts & classroom cards",
"lines": [
"Subsolar latitude comes from declinationDeg in the model data, not an approximation.",
"The seasons panel lists dates and phenomena for all four (bilingual).",
"Teaching notes: migrating subsolar point → changing noon altitude and day length → seasons."
]
},
{
"h": "5. Common mistakes",
"lines": [
"Seasons come from the fixed axial tilt, NOT from Earth being closer/farther to the Sun.",
"Perihelion is early January (northern winter); aphelion is early July (northern summer).",
"Seasons are opposite in the two hemispheres.",
"Esc closes, F11 toggles fullscreen."
]
}
]
}
}
@@ -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"
}
@@ -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": "双指捏合或滚轮缩放 · 拖动可转动地球"
}
@@ -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]]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

@@ -0,0 +1,139 @@
{
"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,
"seasonLayout": "springTopSummerLeft",
"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
}
]
}
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>GC.EarthModels</RootNamespace>
<AssemblyName>EarthRevolutionModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<!-- 共享引擎源码就在 model/_engine 里(模型目录内),本模型直接编译进去 -->
<ItemGroup>
<Compile Include="../../_engine/src/**/*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\GC.ModelSdk\GC.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
@@ -0,0 +1,11 @@
using GC.ModelSdk;
namespace GC.EarthModels;
/// <summary>地球公转模型入口(清单里的 type 指向这里)。</summary>
public sealed class RevolutionModelFactory : IModelFactory
{
public int ApiVersion => EarthModelRuntime.SupportedApiVersion;
public IModelRuntime Create() => new EarthModelRuntime();
}
@@ -0,0 +1,36 @@
{
"schemaVersion": 1,
"id": "earth-rotation",
"name": "Earth Rotation",
"nameI18n": {
"zh-CN": "地球自转",
"en": "Earth Rotation"
},
"author": "Morris",
"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",
"assembly": "EarthRotationModel.dll",
"type": "GC.EarthModels.RotationModelFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.7",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "ecd52665f9",
"updatedAt": "2026-11-21T10:55:36Z"
}
@@ -0,0 +1,121 @@
{
"zh-CN": {
"title": "如何使用 · 地球自转",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:窗口打开后先按「空格」暂停,动画停住才好观察。",
"第 2 步:按住鼠标左键拖动地球,把晨昏线转到正对你。",
"第 3 步:点顶部「经纬网」打开网格,能看清哪一段是夜半球。",
"第 4 步:再按「空格」播放,盯住一个点,看它从黑夜转进白天。",
"第 5 步:按住「←」「→」可以一格一格慢慢看昼夜交界线怎么移动。",
"找不到按钮?所有开关都在窗口顶部那一排;转不动地球就点「复位」重来。"
]
},
{
"h": "一、这个模型讲什么",
"lines": [
"地球绕地轴自西向东自转,周期约 24 小时(一个太阳日)。",
"自转产生三个可观察现象:昼夜交替、地方时差、地转偏向力。",
"晨昏线( terminator )是把地球分成昼半球与夜半球的大圆,它随自转不断西移。",
"太阳直射点是地表太阳高度为 90° 的点,正午太阳高度由它向南北两侧递减。"
]
},
{
"h": "二、基本操作",
"lines": [
"拖动地球:改变观察角度(经度/纬度),可从极地或赤道上空看。",
"滚轮或双指捏合:缩放;右上角「放大」可切到地球特写。",
"「播放 / 暂停」开始或停止自转动画;「速度」调节快慢。",
"「重置」把角度、速度、缩放恢复到初始状态。"
]
},
{
"h": "三、图层开关",
"lines": [
"「经纬网」叠加经线与纬线,便于读出赤道、回归线、极圈。",
"「标注」显示北极、南极、太阳直射点、赤道等关键标签。",
"「轨道」显示自转轴与赤道面;「夸张倾角」把 23.5° 放大便于观察。",
"「教学要点」展开课堂讲解文字,适合投屏授课。"
]
},
{
"h": "四、键盘快捷键",
"lines": [
"空格:播放 / 暂停。",
"← →:逐帧步进(暂停时最有用)。",
"Esc:关闭窗口;F11:全屏 / 退出全屏。"
]
},
{
"h": "五、课堂上怎么用",
"lines": [
"先暂停,把晨昏线转到与经线重合,说明「昼夜平分」只在二分日出现。",
"再播放,让学生观察同一地点如何由夜入昼(晨线)与由昼入夜(昏线)。",
"对比不同经度:东边地点先见到日出,引出「东早西晚」的地方时差。",
"易错提醒:昼夜现象本身由「地球不发光、不透明」造成,自转只造成「交替」。"
]
}
]
},
"en": {
"title": "How to use · Earth Rotation",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: press Space to pause first — a still globe is easier to read.",
"Step 2: hold the left mouse button and drag until the terminator faces you.",
"Step 3: switch on Graticule in the top bar to see which side is night.",
"Step 4: press Space to play and watch one point rotate from night into day.",
"Step 5: use ← / → to step frame by frame and follow the day/night boundary.",
"Can't find a control? Every toggle is in the top bar; if the globe gets twisted, press Reset."
]
},
{
"h": "1. What this model shows",
"lines": [
"Earth spins west-to-east on its axis in about 24 hours (a solar day).",
"Rotation causes the day/night cycle, local time differences and the Coriolis effect.",
"The terminator is the great circle splitting day and night; it moves west as Earth turns.",
"The subsolar point is where the Sun is overhead; noon altitude decreases away from it."
]
},
{
"h": "2. Basic controls",
"lines": [
"Drag the globe to change the viewing angle (from pole or equator).",
"Scroll or pinch to zoom; the close-up button gives an Earth detail view.",
"Play/Pause starts or stops the spin; Speed changes the rate.",
"Reset restores the initial angle, speed and zoom."
]
},
{
"h": "3. Layer toggles",
"lines": [
"Graticule overlays meridians and parallels (equator, tropics, polar circles).",
"Labels shows poles, subsolar point and the equator.",
"Orbit shows the axis and equatorial plane; Exaggerate tilt magnifies the 23.5° tilt.",
"Teaching notes expands classroom text, useful on a projector."
]
},
{
"h": "4. Keyboard shortcuts",
"lines": [
"Space: play / pause. ← →: step one frame (best while paused).",
"Esc: close window. F11: toggle fullscreen."
]
},
{
"h": "5. In the classroom",
"lines": [
"Pause with the terminator along a meridian to show equal day/night at equinoxes.",
"Play again and watch a site cross the dawn line and the dusk line.",
"Compare longitudes: eastern places see sunrise earlier — local time runs ahead.",
"Common mistake: day/night exists because Earth is opaque; rotation only makes it alternate."
]
}
]
}
}
@@ -0,0 +1,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"
}
@@ -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": "双指捏合或滚轮缩放 · 拖动可转动地球"
}
@@ -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]]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

@@ -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
}
]
}
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>GC.EarthModels</RootNamespace>
<AssemblyName>EarthRotationModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<!-- 共享引擎源码就在 model/_engine 里(模型目录内),本模型直接编译进去 -->
<ItemGroup>
<Compile Include="../../_engine/src/**/*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\GC.ModelSdk\GC.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
@@ -0,0 +1,11 @@
using GC.ModelSdk;
namespace GC.EarthModels;
/// <summary>地球自转模型入口(清单里的 type 指向这里)。</summary>
public sealed class RotationModelFactory : IModelFactory
{
public int ApiVersion => EarthModelRuntime.SupportedApiVersion;
public IModelRuntime Create() => new EarthModelRuntime();
}
@@ -0,0 +1,37 @@
{
"schemaVersion": 1,
"id": "scale-calculator",
"name": "Scale Calculator",
"nameI18n": {
"zh-CN": "比例尺计算器",
"en": "Scale Calculator"
},
"author": "Morris GC",
"description": "把比例尺变成可以拖、可以量的可视化标尺",
"descriptionI18n": {
"zh-CN": "三种求解模式、图上/实地双条对比、线段式比例尺自动换挡、比例尺光谱、真实地标实地尺与练习闯关。",
"en": "Three solve modes, dual map/real bars, auto-ranging graphic scale, scale spectrum, real-world landmarks and practice quizzes."
},
"tags": [
"geography",
"map",
"scale",
"calculator"
],
"entry": "scales.json",
"license": "MIT",
"assembly": "ScaleCalculatorModel.dll",
"type": "GC.ScaleCalculator.ScaleCalculatorFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.6",
"chrome": {
"titleBar": "#FFFFFF",
"titleBorder": "#E3E8F3",
"titleText": "#111A2E",
"button": "#5B6A86",
"frame": "#F4F6FB"
},
"build": "105653737d",
"updatedAt": "2026-11-21T10:55:36Z"
}
@@ -0,0 +1,146 @@
{
"zh-CN": {
"title": "如何使用 · 比例尺计算器",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:顶部选「求实地距离」,此时蓝色卡是答案,另外两个是输入。",
"第 2 步:在「图上距离」里填 3,在「比例尺分母」里填 100000。",
"第 3 步:看蓝色卡算出 3 千米 —— 再点「解题步骤」核对每一步。",
"第 4 步:改成「求比例尺」,把实地距离填成 6 千米,看分母怎么翻倍。",
"第 5 步:拖动中间标尺的滑块,观察蓝色条(图上)与绿色条(实地)的长度关系。",
"第 6 步:滚到底部「练习闯关」,自己做一道,答错会自动展开步骤。",
"算不出来?先检查单位:填了 km 就不要再按 cm 算,模型会自动换算。"
]
},
{
"h": "一、核心公式(先记住这一条)",
"lines": [
"比例尺 = 图上距离 ÷ 实地距离,写作 1 : N。",
"N 是分母,含义是「实地距离是图上距离的 N 倍」,两句都必须统一成同一单位。",
"三个变形:实地 = 图上 × N;图上 = 实地 ÷ N;N = 实地 ÷ 图上。",
"单位换算:1 m = 100 cm,1 km = 1000 m = 100000 cm(km 化 cm 加 5 个 0)。"
]
},
{
"h": "二、三种求解模式",
"lines": [
"顶部三个按钮选「求实地距离 / 求图上距离 / 求比例尺」。",
"选中的那一项会变成蓝色结果卡(只读),另外两项留作输入。",
"拖动滑块或直接输入数字,三栏读数与中栏标尺实时联动。",
"「重置」回到 3 cm / 1:100000 / 3 km 的初始例子。"
]
},
{
"h": "三、中栏可视化标尺",
"lines": [
"上条(蓝)是图上距离,按真实厘米画刻度。",
"下条(绿)是同一段实地距离按当前比例尺压缩后的长度,与上方同宽。",
"线段式比例尺会按 1/2/5×10ⁿ 自动换挡,任何比例尺都画得下。",
"比例尺光谱把 1:1千 到 1:10亿 排在对数轴上,当前值用指针标出。",
"若超出图幅,会提示「需要更小的比例尺」——这正是选图幅的教学点。"
]
},
{
"h": "四、三种写法与解题步骤",
"lines": [
"数字式 1 : N;文字式「图上 1 厘米代表实地 …」;线段式(图形刻度)。",
"右栏三者实时联动,可直接抄到作业里。",
"「解题步骤」可展开:① 统一单位 → ② 列公式 → ③ 代入 → ④ 得数 → ⑤ 换算合适单位。",
"「大小判读」卡:大 / 中 / 小比例尺 +「分母越大 → 比例尺越小 → 范围越大 → 越简略」。"
]
},
{
"h": "五、实地尺与练习",
"lines": [
"「实地尺」内置教室 10 m、操场 400 m、马拉松 42.195 km、京沪 1080 km、赤道 4 万 km。",
"改变比例尺,看这段真实距离画到图上是多长(或画不下 / 几乎看不见)。",
"「练习闯关」随机出三类题,填数字后回车或点「检查」,答错展开完整解题步骤。",
"连对计数会一直累计,答错清零。"
]
},
{
"h": "六、易错点",
"lines": [
"忘记统一单位:km 必须 ×100000 变成 cm 才能代入。",
"「放大 2 倍」是分母 ÷ 2(比例尺变大),不是 × 2。",
"图上距离与实地距离别代反了;N 是「实地是图上的几倍」。",
"比例尺是比值,没有单位;说「比例尺越大」指的是比值越大、分母越小。"
]
}
]
},
"en": {
"title": "How to use · Scale Calculator",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: choose Find real distance at the top — the blue card is the answer, the other two are inputs.",
"Step 2: enter 3 as the map distance and 100000 as the scale denominator.",
"Step 3: the blue card shows 3 km — open Worked steps and check each line.",
"Step 4: switch to Find scale, set the real distance to 6 km, and watch the denominator change.",
"Step 5: drag the ruler slider and compare the blue bar (map) with the green bar (real).",
"Step 6: scroll to Practice and try one; a wrong answer expands the full solution.",
"Stuck? Check your units first — the model converts automatically, so don't mix km and cm."
]
},
{
"h": "1. The core formula",
"lines": [
"Scale = map distance ÷ real distance, written 1 : N.",
"N is the denominator: the real distance is N times the map distance — both must share one unit.",
"Three forms: real = map × N; map = real ÷ N; N = real ÷ map.",
"Unit conversions: 1 m = 100 cm, 1 km = 1000 m = 100000 cm (add five zeros)."
]
},
{
"h": "2. Three solve modes",
"lines": [
"Pick Find real distance / Find map distance / Find scale at the top.",
"The chosen one becomes the blue read-only result card; the other two stay as inputs.",
"Drag a slider or type a number — all three columns and the ruler update live.",
"Reset returns to the default 3 cm / 1:100000 / 3 km example."
]
},
{
"h": "3. The visual ruler",
"lines": [
"The blue bar is the map distance in real centimetres.",
"The green bar is the same real distance compressed by the current scale — same width.",
"The graphic scale auto-ranges over 1/2/5×10ⁿ so it always fits.",
"The spectrum places 1:1k … 1:1B on a log axis with a pointer at the current value.",
"Overflow warns “use a smaller scale” — that IS the lesson on choosing a sheet size."
]
},
{
"h": "4. Three notations & worked steps",
"lines": [
"Numeric 1:N; verbal “1 cm on the map = … on the ground”; graphic bar scale.",
"All three stay in sync and can be copied straight into homework.",
"Expand Worked steps: unify units → formula → substitute → result → convert unit.",
"The grade card: large / medium / small scale and “bigger denominator → smaller scale → larger area → less detail”."
]
},
{
"h": "5. Real-world ruler & practice",
"lines": [
"Built-in distances: classroom 10 m, track 400 m, marathon 42.195 km, Beijing–Shanghai 1080 km, equator 40,000 km.",
"Change the scale to see how long each becomes on paper (or that it won't fit / is invisible).",
"Practice generates three question types; type a number and press Enter or Check; wrong answers reveal full steps.",
"The streak counter accumulates and resets on a wrong answer."
]
},
{
"h": "6. Common mistakes",
"lines": [
"Forgetting to unify units: km ×100000 → cm before substituting.",
"“Zoom 2×” means denominator ÷ 2 (a larger scale), not × 2.",
"Don't swap map and real distance; N means “how many times the map length the real length is”.",
"A scale is a ratio with no unit; “larger scale” means a larger ratio, i.e. a SMALLER denominator."
]
}
]
}
}
@@ -0,0 +1,106 @@
{
"app.title": "Scale Calculator",
"app.subtitle": "Turn map-distance ÷ real-distance into a ruler you can drag and measure",
"mode.real": "Find real distance",
"mode.map": "Find map distance",
"mode.scale": "Find scale",
"mode.hint": "Pick what to solve; the blue card is the answer",
"input.title": "Given",
"input.map": "Map distance",
"input.real": "Real distance",
"input.scale": "Scale denominator N",
"input.nPrefix": "1 :",
"input.unit": "Unit",
"input.reset": "Reset",
"input.presets": "Common scales",
"input.dragHint": "Drag the slider or type a number — everything updates live",
"result.title": "Result",
"result.real": "Real distance",
"result.map": "Map distance",
"result.scale": "Scale",
"result.formula": "Formula",
"forms.title": "Three ways to write a scale",
"forms.digital": "Numeric",
"forms.verbal": "Verbal",
"forms.segment": "Graphic (bar)",
"forms.verbalTpl": "1 cm on the map = {0} on the ground",
"forms.segmentDesc": "Each division {0}, {1} divisions",
"steps.title": "Worked solution",
"steps.show": "Show steps",
"steps.hide": "Hide steps",
"steps.1.unify": "① Unify units: convert the real distance to cm (1 km = 100000 cm)",
"steps.2.formulaReal": "② Real distance = map distance × scale denominator",
"steps.2.formulaMap": "② Map distance = real distance ÷ scale denominator",
"steps.2.formulaScale": "② Scale denominator = real distance ÷ map distance",
"steps.3.substitute": "③ Substitute: {0}",
"steps.4.result": "④ Result: {0}",
"steps.5.convert": "⑤ Convert to a sensible unit (cm → m → km)",
"grade.title": "Large / small scale",
"grade.large": "Large scale",
"grade.medium": "Medium scale",
"grade.small": "Small scale",
"grade.largeNote": "Small area · detailed · e.g. campus plan",
"grade.mediumNote": "Medium area · e.g. city map",
"grade.smallNote": "Large area · simplified · e.g. world map",
"grade.rule": "Bigger denominator → smaller scale → larger area → less detail",
"pit.title": "Common mistakes",
"pit.1": "① Forgetting to unify units: km ×100000 = cm",
"pit.2": "② \"Zoom 2×\" means denominator ÷ 2, not × 2",
"pit.3": "③ Don't swap map distance and real distance",
"field.title": "Real-world ruler · how long on the map",
"field.hint": "Pick a real distance and change the scale to see its map length",
"field.mapLength": "On map {0}",
"field.tooLong": "too long",
"field.tooShort": "barely visible",
"quiz.title": "Practice",
"quiz.promptReal": "Scale 1:{0}, map distance {1} cm — what is the real distance? (enter the number in the shown unit)",
"quiz.promptMap": "Scale 1:{0}, real distance {1} — what is the map distance in cm?",
"quiz.promptScale": "{0} cm on the map = {1} on the ground — what is the scale denominator?",
"quiz.answer": "Your answer",
"quiz.check": "Check",
"quiz.next": "Next",
"quiz.correct": "✓ Correct!",
"quiz.wrong": "✗ Try again — read the steps",
"quiz.streak": "{0} in a row",
"quiz.showSteps": "Show solution",
"quiz.unit": "Unit: {0}",
"ruler.title": "Visual ruler",
"ruler.mapBar": "Map distance (real cm)",
"ruler.realBar": "Real distance (compressed by the same scale)",
"ruler.sameWidth": "same width as above",
"ruler.equals": "equals",
"ruler.segment": "Graphic scale",
"ruler.segmentHint": "auto-ranging ticks",
"ruler.spectrum": "Scale spectrum",
"ruler.scopeUp": "◀ larger area",
"ruler.detailDown": "more detail ▶",
"ruler.hint": "Blue is the real map length; green is the same real distance compressed by the scale",
"ruler.overflowMap": "This map distance overflows the sheet — use a smaller scale",
"ruler.overflowReal": "This real distance won't fit at this scale — use a smaller scale",
"unit.cm": "cm",
"unit.m": "m",
"unit.km": "km",
"unit.none": "(unitless)",
"spec.campus": "Campus",
"spec.city": "City",
"spec.china": "China",
"spec.world": "World",
"preset.campus": "Campus 1:10k",
"preset.campusNote": "Buildings clearly drawn",
"preset.town": "Town 1:50k",
"preset.townNote": "Villages and roads",
"preset.city": "City 1:250k",
"preset.cityNote": "Urban area and arterials",
"preset.province": "Province 1:1M",
"preset.provinceNote": "Cities and rivers",
"preset.china": "China 1:10M",
"preset.chinaNote": "Province outlines",
"preset.world": "World 1:100M",
"preset.worldNote": "Continents & oceans",
"lm.classroom": "Classroom 10 m",
"lm.track": "Running track 400 m",
"lm.marathon": "Marathon 42.195 km",
"lm.beijingShanghai": "Beijing–Shanghai 1080 km",
"lm.equator": "Equator 40,000 km",
"common.footer": "Scale = map distance ÷ real distance · unify units first · bigger denominator = smaller scale"
}
@@ -0,0 +1,106 @@
{
"app.title": "比例尺计算器",
"app.subtitle": "把「图上距离 ÷ 实地距离」变成可以拖、可以量的可视化标尺",
"mode.real": "求实地距离",
"mode.map": "求图上距离",
"mode.scale": "求比例尺",
"mode.hint": "选择要求什么,蓝色结果卡就是答案",
"input.title": "已知量",
"input.map": "图上距离",
"input.real": "实地距离",
"input.scale": "比例尺分母 N",
"input.nPrefix": "1 :",
"input.unit": "单位",
"input.reset": "重置",
"input.presets": "常用比例尺",
"input.dragHint": "拖动滑块或直接输入数字,读数实时联动",
"result.title": "计算结果",
"result.real": "实地距离",
"result.map": "图上距离",
"result.scale": "比例尺",
"result.formula": "计算公式",
"forms.title": "比例尺的三种写法",
"forms.digital": "数字式",
"forms.verbal": "文字式",
"forms.segment": "线段式",
"forms.verbalTpl": "图上 1 厘米代表实地 {0}",
"forms.segmentDesc": "每格 {0},共 {1} 格",
"steps.title": "解题步骤",
"steps.show": "展开步骤",
"steps.hide": "收起步骤",
"steps.1.unify": "① 统一单位:把实地距离化成厘米(1 km = 100000 cm,去掉 5 个 0)",
"steps.2.formulaReal": "② 实地距离 = 图上距离 × 比例尺分母",
"steps.2.formulaMap": "② 图上距离 = 实地距离 ÷ 比例尺分母",
"steps.2.formulaScale": "② 比例尺分母 = 实地距离 ÷ 图上距离",
"steps.3.substitute": "③ 代入数值:{0}",
"steps.4.result": "④ 算出结果:{0}",
"steps.5.convert": "⑤ 换算成合适单位(cm → m → km)",
"grade.title": "大小判读",
"grade.large": "大比例尺",
"grade.medium": "中比例尺",
"grade.small": "小比例尺",
"grade.largeNote": "范围小 · 内容详细 · 如校园平面图",
"grade.mediumNote": "范围中等 · 如城市交通图",
"grade.smallNote": "范围大 · 内容简略 · 如世界地图",
"grade.rule": "分母越大 → 比例尺越小 → 范围越大 → 越简略",
"pit.title": "易错点",
"pit.1": "① 忘记统一单位:km 要 ×100000 才成 cm",
"pit.2": "② 「放大 2 倍」是分母 ÷ 2,不是 × 2",
"pit.3": "③ 图上距离与实地距离别代反了",
"field.title": "实地尺 · 这段距离画到图上多长",
"field.hint": "选一个真实距离,改变比例尺看它在图上的长度",
"field.mapLength": "图上 {0}",
"field.tooLong": "画不下",
"field.tooShort": "几乎看不见",
"quiz.title": "练习闯关",
"quiz.promptReal": "比例尺 1:{0},图上 {1} 厘米,实地距离是多少?(按提示单位填数字)",
"quiz.promptMap": "比例尺 1:{0},实地 {1},图上距离是多少厘米?",
"quiz.promptScale": "图上 {0} 厘米代表实地 {1},比例尺分母是多少?",
"quiz.answer": "输入答案",
"quiz.check": "检查",
"quiz.next": "下一题",
"quiz.correct": "✓ 答对了!",
"quiz.wrong": "✗ 再想想,看看解题步骤",
"quiz.streak": "连对 {0} 题",
"quiz.showSteps": "查看解题步骤",
"quiz.unit": "单位:{0}",
"ruler.title": "可视化标尺",
"ruler.mapBar": "图上距离(真实厘米)",
"ruler.realBar": "实地距离(按同一比例尺压缩)",
"ruler.sameWidth": "与上方同宽",
"ruler.equals": "等于",
"ruler.segment": "线段式比例尺",
"ruler.segmentHint": "刻度自动换挡",
"ruler.spectrum": "比例尺光谱",
"ruler.scopeUp": "◀ 范围越大",
"ruler.detailDown": "内容越详细 ▶",
"ruler.hint": "蓝色是图上真实长度;绿色是同一段实地按比例尺压缩后的长度",
"ruler.overflowMap": "这段图上距离超出图幅,需要更小的比例尺",
"ruler.overflowReal": "这段实地距离在该比例尺下画不下,需要更小的比例尺",
"unit.cm": "厘米",
"unit.m": "米",
"unit.km": "千米",
"unit.none": "(无单位)",
"spec.campus": "校园",
"spec.city": "城市",
"spec.china": "中国",
"spec.world": "世界",
"preset.campus": "校园 1:1万",
"preset.campusNote": "操场、教学楼都画得清",
"preset.town": "乡镇 1:5万",
"preset.townNote": "村镇与道路",
"preset.city": "城市 1:25万",
"preset.cityNote": "城区与主干道",
"preset.province": "省区 1:100万",
"preset.provinceNote": "地级市与河流",
"preset.china": "中国 1:1000万",
"preset.chinaNote": "省级轮廓",
"preset.world": "世界 1:1亿",
"preset.worldNote": "大洲大洋",
"lm.classroom": "教室 10 m",
"lm.track": "操场一圈 400 m",
"lm.marathon": "马拉松 42.195 km",
"lm.beijingShanghai": "北京—上海 1080 km",
"lm.equator": "赤道 4 万 km",
"common.footer": "比例尺 = 图上距离 ÷ 实地距离 · 单位统一是第一步 · 分母越大,比例尺越小"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

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