Compare commits
2
Commits
main
...
feat/user-system
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cfd6809714 | ||
|
|
38781c9807 |
No files matched your search
@@ -264,3 +264,56 @@ mingw-w64 14.0.0_3 携带 GCC 16.2,与 Flutter 插件(flutter_inappwebview_w
|
||||
### 修正(19:17)
|
||||
- 夜间构建 tag 改为 **`nightly`**(concurrency 组 `release-nightly`);
|
||||
`@build-bot` 手动触发仍是 **`ip-prerelease`**(组 `release-ip-prerelease`)。两个 tag 互不覆盖。
|
||||
|
||||
## 用户系统重做(20:30)
|
||||
分支 `feat/user-system`,提交 ecb71ad。GitHub 直接推 main,XHGit 开 PR #39。
|
||||
|
||||
### 存储
|
||||
- `.GC/user/<用户名>/pw.yaml`:username / pw_hash(sha512+salt) / points / last_sign_in / consecutive_days / theme_color / theme_paid / theme_paid_at
|
||||
- `.GC/user/user.yaml`:username + session_token,后端启动自动登录(前端不需要自己找 .GC)
|
||||
- 旧 `.GC/user/<用户名>.yaml` 启动时自动迁移
|
||||
|
||||
### 关键实现
|
||||
- 验证码:`_captchas` 内存字典,算术题 5 分钟、一次性(TryRemove)
|
||||
- 签到奖励:1-6:10 / 7:30 / 8-13:15 / 14:40 / 15-20:20 / 21:50 / 22-27:25 / 28:60 / 29:40 / 30:100
|
||||
- 主题色:ThemeCost() 服务端算价(默认蓝 0 / 预置 50 / 其它 150);1 小时内换色退 floor(theme_paid*0.8)
|
||||
- 前端:GcPalette.apply('#hex') 应用用户主题色;人品值纯客户端随机,不限次
|
||||
|
||||
### 踩坑
|
||||
- `flutter build macos` 没有 --no-codesign(iOS 才有),已从 flutter.sh 与两个 workflow 移除
|
||||
- `GcColors.appBg` 是 getter,不能放进 const Widget
|
||||
- CaptchaInfo 在 api_client.dart,user_page 需要单独 import
|
||||
|
||||
## 删百宝箱 + 设置页去主题色(20:47,提交 38781c9)
|
||||
- 删除 `pages/treasure.dart`、侧栏 `nav.treasure` 入口、`pages.dart` 导出、i18n 的 treasure.* 键
|
||||
- 侧栏索引变化:user 从 6 → 5(download=2 / settings=3 不受影响,home.dart 里的 goTo 无需改)
|
||||
- `settings.dart`:删掉主题色色板、自定义颜色对话、`_accentSwatch` / `_customAccentChip` / `_pickCustomAccent` / `_applyAccent`,以及 i18n 的 set.accent.*
|
||||
- 强调色唯一来源改为用户账号:`controller._applySettings` 不再用 `settings.accentColor`;
|
||||
启动 `_applyUserTheme()` 拉 `/api/user/me` 上色;退出登录回落 `GcPalette.defaultAccent`
|
||||
- 注意:后端 SettingsInfo 仍保留 accentColor 字段(未删,避免破坏旧配置与 API 兼容)
|
||||
|
||||
## 模型回退 Avalonia + 积分计费改造(21:05–21:35)
|
||||
|
||||
### 1. 模型从 Flutter 回退 Avalonia(方案 B)
|
||||
- 恢复源:5b62897(Flutter 重写前最后的 Avalonia 模型版本)→ `model/_sdk`、5 个模型的 `src/`、`GC-DRAW/PlayerWindow.cs`、`ModelHost.cs`、`AvaloniaHost.cs`
|
||||
- `FlutterShell.cs`:主线程跑 Avalonia 事件循环(`uiHost.RunOnCurrentThread()`),修复 1.1.1 的 AppKit 主线程崩溃
|
||||
- `BackendServer.cs`:`/api/models/{id}/launch` 走 `host.LaunchAsync(package)` 开 Avalonia 窗口
|
||||
- `GC.Core.csproj` 重新引用 Avalonia/MVVM/GC.ModelSdk;`Directory.Build.props` 加 AvaloniaVersion
|
||||
- 前端清理死代码:删 `pages/model_view.dart` + `lib/models/` 12 个 Flutter 模型文件(保留 user.dart),controller 删 `activeModelId/openModel/closeModel`
|
||||
- GC.sln 全量编译通过;flutter analyze 0 error
|
||||
|
||||
### 2. 积分精确到 0.01
|
||||
- `UserRecord.Points/ThemePaid`:int → decimal;pw.yaml 用 `ToString("0.##")` 写,decimal.TryParse 读(兼容旧整数)
|
||||
- 主题色退款改 `Math.Floor(paid * 0.8 * 100) / 100` 保 2 位
|
||||
- 前端 `points/themePaid` int → double,新增顶层 `formatPoints()`(整数不带小数、去尾零)
|
||||
|
||||
### 3. 人品值 / 二选一 后端计费(原先前端本地随机免费)
|
||||
- pw.yaml 新增 `fortune_date/fortune_count/pick_date/pick_count`(UTC 日期跨天清零)
|
||||
- 阶梯(按当日已付费次数):免费1次 → 0.1×5 → 0.2×5 → 0.5×15 → 1.0 起;二选一免费1次 → 0.5/次
|
||||
- 端点 `POST /api/user/fortune`、`POST /api/user/pick`(服务端随机数);FortuneComment 评语后端生成
|
||||
- 前端 `_rollFortune/_pickRandom` 改走 API,需登录,toast 显示本次消耗
|
||||
|
||||
### 端到端验证(GC_UI_PORT=18999)
|
||||
- 注册→签到(10分)→连摇27次:费用 0/0.1×5/0.2×5/0.5×15/1.0,余额始终精确到 0.01,10 分花到 0
|
||||
- 二选一首免、余额不足报「积分不足,本次需要 0.5 积分」(400)
|
||||
- 重启进程后 user.yaml 自动登录 + 当日计数持久化生效;测试账号 billtest 已删
|
||||
@@ -14,6 +14,10 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<MvvmVersion>8.2.2</MvvmVersion>
|
||||
<!-- 模型窗口仍由 Avalonia 承载(模型契约返回 Avalonia Control),
|
||||
界面本身是 Flutter。Avalonia.BuildServices 的遥测会向用户目录写日志,
|
||||
在只读目录 / CI 里会直接让编译失败,build.sh / build.ps1 已默认关闭。 -->
|
||||
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
||||
<Version>1.1.2</Version>
|
||||
<Company>Morris</Company>
|
||||
<Product>GC</Product>
|
||||
|
||||
+29
-5
@@ -54,6 +54,7 @@ internal static class FlutterShell
|
||||
Environment.SetEnvironmentVariable(Services.GcUiContract.TokenEnvVar, token);
|
||||
|
||||
var port = Port;
|
||||
AvaloniaHost? uiHost = null;
|
||||
|
||||
// 用户可能重复启动:只有当端口上已有一个「持有同一令牌」的后端时才复用。
|
||||
// 同机其他程序即便占端口并返回 200,也没有令牌,会被 IsHealthy 拒绝,
|
||||
@@ -67,13 +68,14 @@ internal static class FlutterShell
|
||||
|
||||
for (var candidate = start; candidate < start + Services.GcUiContract.PortScanRange; candidate++)
|
||||
{
|
||||
var app = TryStartBackend(args, candidate);
|
||||
var app = TryStartBackend(args, candidate, out var host);
|
||||
if (app == null) continue;
|
||||
|
||||
if (WaitHealthy(candidate, token, TimeSpan.FromSeconds(25)))
|
||||
{
|
||||
port = candidate;
|
||||
_backend = app;
|
||||
uiHost = host;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -93,9 +95,27 @@ internal static class FlutterShell
|
||||
return false;
|
||||
}
|
||||
|
||||
// 前端窗口已拉起。这里不再需要 AppKit 事件循环:模型已经全部在 Flutter 里渲染,
|
||||
// 后端只是纯 HTTP 服务,主线程阻塞等它退出即可。
|
||||
// 前端窗口已拉起。模型窗口由 Avalonia 承载,而 macOS 的 AppKit 要求
|
||||
// NSApplication 必须在**主线程**——所以事件循环要跑在这里(当前正是主线程),
|
||||
// 不能丢到副线程,否则一点「启动模型」就会把整个后端带崩。
|
||||
ui.EnableRaisingEvents = true;
|
||||
var closed = 0;
|
||||
void RequestClose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref closed, 1) == 1) return;
|
||||
uiHost?.Shutdown();
|
||||
}
|
||||
|
||||
ui.Exited += (_, _) => RequestClose();
|
||||
if (ui.HasExited) RequestClose();
|
||||
|
||||
if (!ui.HasExited && uiHost != null)
|
||||
{
|
||||
// 阻塞直到界面退出(或图形环境初始化失败)。
|
||||
uiHost.RunOnCurrentThread();
|
||||
}
|
||||
|
||||
// Avalonia 起不来(无桌面会话)时仍要等界面退出,避免后端被提前收掉。
|
||||
if (!ui.HasExited) ui.WaitForExit();
|
||||
|
||||
StopBackend(_backend);
|
||||
@@ -158,16 +178,20 @@ internal static class FlutterShell
|
||||
// ---------------------------------------------------------------- 进程管理
|
||||
|
||||
/// <summary>在本进程内启动后端;端口被占用等失败情况返回 null。</summary>
|
||||
private static WebApplication? TryStartBackend(string[] args, int port)
|
||||
/// <param name="uiHost">成功时交出模型窗口宿主,由调用方在主线程跑事件循环。</param>
|
||||
private static WebApplication? TryStartBackend(string[] args, int port, out AvaloniaHost? uiHost)
|
||||
{
|
||||
uiHost = null;
|
||||
try
|
||||
{
|
||||
var app = BackendServer.Start(args, port);
|
||||
var app = BackendServer.Start(args, port, out var host);
|
||||
uiHost = host;
|
||||
app.StartAsync().GetAwaiter().GetResult();
|
||||
return app;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
uiHost = null;
|
||||
Console.Error.WriteLine($"[shell] 后端启动失败(端口 {port}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,642 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using Avalonia;
|
||||
using Avalonia.Animation;
|
||||
using Avalonia.Animation.Easings;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Shapes = Avalonia.Controls.Shapes;
|
||||
using Avalonia.VisualTree;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 模型窗口:**只做窗口宿主**。
|
||||
/// 内容完全来自模型程序集(<see cref="LoadedModel.View"/>),启动器不渲染任何东西。
|
||||
/// 快捷键:Esc 关闭窗口,F11 全屏。
|
||||
/// </summary>
|
||||
public sealed class PlayerWindow : Window
|
||||
{
|
||||
private LoadedModel? _model;
|
||||
private bool _closing;
|
||||
private Button? _maximizeButton;
|
||||
private Border? _frame;
|
||||
private TextBlock? _titleText;
|
||||
private Border? _titleBar;
|
||||
private readonly List<Button> _titleButtons = new();
|
||||
private readonly List<Shapes.Path> _titleGlyphs = new();
|
||||
private Shapes.Path? _maximizeGlyph;
|
||||
private Shapes.Path? _restoreGlyph;
|
||||
private string _maxMaxPath = "";
|
||||
private string _maxRestorePath = "";
|
||||
private Button? _helpButton;
|
||||
/// <summary>基准尺寸(1240×820 时的标题栏高度与按钮尺寸)。</summary>
|
||||
private const double BaseWidth = 1240;
|
||||
private const double BaseTitleBarHeight = 34;
|
||||
private const double BaseButtonWidth = 38;
|
||||
private const double BaseButtonHeight = 28;
|
||||
private const double BaseTitleFont = 11.5;
|
||||
private const double BaseHelpFont = 11.5;
|
||||
|
||||
public PlayerWindow(ModelPackage package, LoadedModel model)
|
||||
{
|
||||
_model = model;
|
||||
Title = package.LocalizedName;
|
||||
Width = 1240;
|
||||
Height = 820;
|
||||
MinWidth = 1000;
|
||||
MinHeight = 680;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
// 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
|
||||
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
|
||||
|
||||
// 标题栏配色来自模型清单,跟随模型自己的界面风格:
|
||||
// 地球模型是深色舞台,比例尺计算器是浅色卡片,两者不能共用一套深色。
|
||||
var chrome = package.Manifest.Chrome;
|
||||
var barBg = ParseColor(chrome?.TitleBar, "#0C1828");
|
||||
var barBorder = ParseColor(chrome?.TitleBorder, "#1B2740");
|
||||
var barText = ParseColor(chrome?.TitleText, "#EAF2FF");
|
||||
var btnText = ParseColor(chrome?.Button, "#9FB4D4");
|
||||
var frameBg = ParseColor(chrome?.Frame, "#0A1524");
|
||||
|
||||
var titleText = new TextBlock
|
||||
{
|
||||
Text = package.LocalizedName,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 11.5,
|
||||
Margin = new Thickness(14, 0, 0, 0),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
[Grid.ColumnProperty] = 0
|
||||
};
|
||||
_titleText = titleText;
|
||||
|
||||
var helpButton = new Button
|
||||
{
|
||||
Content = IsEnglish() ? "How to use?" : "如何使用?",
|
||||
Height = 26,
|
||||
Padding = new Thickness(12, 0),
|
||||
Background = Brushes.Transparent,
|
||||
Foreground = new SolidColorBrush(btnText),
|
||||
BorderThickness = new Thickness(0),
|
||||
FontSize = 11.5,
|
||||
CornerRadius = new CornerRadius(7),
|
||||
Margin = new Thickness(0, 0, 6, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
[Grid.ColumnProperty] = 1
|
||||
};
|
||||
helpButton.Click += (_, _) => ShowHelp(package, barBg, barBorder, barText, btnText, frameBg);
|
||||
|
||||
// 标题栏三键:最小化 / 最大化 / 关闭 —— 卡通画风。
|
||||
// 每颗按钮 = 彩色实心圆底 + 粗圆头描边图标,像一颗小糖豆。
|
||||
(Button Btn, Shapes.Path Icon) MakeBadge(int column, string iconPath)
|
||||
{
|
||||
// 纯矢量图标,没有彩色圆圈
|
||||
var icon = new Shapes.Path
|
||||
{
|
||||
Data = Geometry.Parse(iconPath),
|
||||
Stroke = new SolidColorBrush(btnText),
|
||||
StrokeThickness = 1.5,
|
||||
StrokeLineCap = PenLineCap.Round,
|
||||
StrokeJoin = PenLineJoin.Round,
|
||||
Fill = null,
|
||||
Stretch = Stretch.None,
|
||||
Width = 10,
|
||||
Height = 10,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
var layer = new Grid
|
||||
{
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
layer.Children.Add(icon);
|
||||
|
||||
var b = new Button
|
||||
{
|
||||
Width = 38,
|
||||
Height = 28,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(2, 0, 0, 0),
|
||||
Content = layer,
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
[Grid.ColumnProperty] = column
|
||||
};
|
||||
var hoverBg = IsLight(barBg)
|
||||
? new SolidColorBrush(Color.Parse("#EEF1F7"))
|
||||
: new SolidColorBrush(Color.Parse("#1E2C46"));
|
||||
var isCloseBtn = column == 4;
|
||||
b.PointerEntered += (_, _) =>
|
||||
{
|
||||
b.Background = hoverBg;
|
||||
icon.Stroke = new SolidColorBrush(isCloseBtn ? Colors.White
|
||||
: IsLight(barBg) ? Color.Parse("#111A2E") : Colors.White);
|
||||
};
|
||||
b.PointerExited += (_, _) =>
|
||||
{
|
||||
b.Background = Brushes.Transparent;
|
||||
icon.Stroke = new SolidColorBrush(btnText);
|
||||
};
|
||||
b.Classes.Add("model-titlebtn");
|
||||
_titleButtons.Add(b);
|
||||
_titleGlyphs.Add(icon);
|
||||
return (b, icon);
|
||||
}
|
||||
|
||||
// 卡通配色:暖黄 / 薄荷绿 / 珊瑚红
|
||||
var minBadge = MakeBadge(2, "M1.5,5 L8.5,5");
|
||||
var maxBadge = MakeBadge(3, "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
|
||||
var closeBadge = MakeBadge(4, "M2,2 L8,8 M8,2 L2,8");
|
||||
|
||||
var minimizeButton = minBadge.Btn;
|
||||
var maximizeButton = maxBadge.Btn;
|
||||
var closeButton = closeBadge.Btn;
|
||||
|
||||
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
|
||||
maximizeButton.Click += (_, _) => ToggleMaximize();
|
||||
closeButton.Click += (_, _) => _ = CloseWithAnimationAsync();
|
||||
_maximizeGlyph = maxBadge.Icon;
|
||||
_restoreGlyph = maxBadge.Icon;
|
||||
_maxRestorePath = "M2.6,3.6 L7.4,3.6 L7.4,8.4 L2.6,8.4 Z M2.6,3.6 L2.6,1.6 L7.4,1.6 L7.4,6.4";
|
||||
_maxMaxPath = "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z";
|
||||
|
||||
var titleBar = new Border
|
||||
{
|
||||
Height = 34,
|
||||
Background = new SolidColorBrush(barBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Child = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto,Auto,Auto"),
|
||||
Margin = new Thickness(0, 0, 10, 0),
|
||||
Children = { titleText, helpButton, minimizeButton, maximizeButton, closeButton }
|
||||
}
|
||||
};
|
||||
titleBar.PointerPressed += OnTitleBarPointerPressed;
|
||||
// 双击标题栏 = 最大化 / 还原(与系统标题栏一致)
|
||||
titleBar.DoubleTapped += (_, e) =>
|
||||
{
|
||||
if (e.Source is Button) return;
|
||||
ToggleMaximize();
|
||||
};
|
||||
_maximizeButton = maximizeButton;
|
||||
_titleBar = titleBar;
|
||||
_helpButton = helpButton;
|
||||
_titleButtons.Add(minimizeButton);
|
||||
_titleButtons.Add(maximizeButton);
|
||||
_titleButtons.Add(closeButton);
|
||||
|
||||
var dock = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(titleBar, Dock.Top);
|
||||
dock.Children.Add(titleBar);
|
||||
dock.Children.Add(model.View);
|
||||
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(frameBg),
|
||||
ClipToBounds = true,
|
||||
Child = dock
|
||||
};
|
||||
_frame = (Border)Content;
|
||||
|
||||
// 最大化 / 还原时同步圆角与按钮图标
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == WindowStateProperty) UpdateMaximizeVisual();
|
||||
};
|
||||
|
||||
// 窗口随心拉大 / 拉小时,标题栏文字与按钮同比缩放。
|
||||
// 同时监听 Bounds 属性(不只是 SizeChanged),保证最大化/还原也立刻生效。
|
||||
SizeChanged += (_, _) => ApplyChromeScale();
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == BoundsProperty) ApplyChromeScale();
|
||||
};
|
||||
ApplyChromeScale();
|
||||
|
||||
KeyDown += OnKeyDown;
|
||||
Closed += OnClosed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 让标题栏的文字与按钮尺寸跟随窗口大小。
|
||||
/// 以 1240px 宽为基准线性缩放,限制在 0.85–1.9 倍,
|
||||
/// 避免最大化到 4K 时按钮大得离谱、缩到最小又点不中。
|
||||
/// </summary>
|
||||
private void ApplyChromeScale()
|
||||
{
|
||||
if (Bounds.Width < 100) return;
|
||||
var scale = Math.Clamp(Bounds.Width / BaseWidth, 0.85, 1.9);
|
||||
|
||||
if (_titleBar != null) _titleBar.Height = Math.Round(BaseTitleBarHeight * scale);
|
||||
foreach (var b in _titleButtons)
|
||||
{
|
||||
b.Width = Math.Round(BaseButtonWidth * scale);
|
||||
b.Height = Math.Round(BaseButtonHeight * scale);
|
||||
b.FontSize = Math.Round(13 * scale, 1);
|
||||
b.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
|
||||
}
|
||||
if (_helpButton != null)
|
||||
{
|
||||
_helpButton.Height = Math.Round(26 * scale);
|
||||
_helpButton.FontSize = Math.Round(BaseHelpFont * scale, 1);
|
||||
_helpButton.Padding = new Thickness(Math.Round(12 * scale), 0);
|
||||
_helpButton.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
|
||||
}
|
||||
foreach (var g in _titleGlyphs)
|
||||
{
|
||||
g.Width = Math.Round(10 * scale, 1);
|
||||
g.Height = Math.Round(10 * scale, 1);
|
||||
g.StrokeThickness = Math.Round(1.5 * scale, 2);
|
||||
}
|
||||
if (_titleText != null)
|
||||
{
|
||||
_titleText.FontSize = Math.Round(BaseTitleFont * scale, 1);
|
||||
_titleText.Margin = new Thickness(Math.Round(14 * scale), 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>判断颜色是否属于浅色系(用于决定悬停用深色还是浅色)。</summary>
|
||||
private static bool IsLight(Color c)
|
||||
{
|
||||
// 相对亮度(sRGB 近似)
|
||||
var lum = (0.299 * c.R + 0.587 * c.G + 0.114 * c.B) / 255.0;
|
||||
return lum > 0.6;
|
||||
}
|
||||
|
||||
private void ToggleMaximize()
|
||||
{
|
||||
WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
}
|
||||
|
||||
private void UpdateMaximizeVisual()
|
||||
{
|
||||
var max = WindowState == WindowState.Maximized || WindowState == WindowState.FullScreen;
|
||||
if (_maximizeGlyph != null)
|
||||
{
|
||||
// 只换 Data,不换控件对象(换对象会触发 "already has a parent")
|
||||
_maximizeGlyph.Data = Geometry.Parse(max ? _maxRestorePath : _maxMaxPath);
|
||||
}
|
||||
if (_maximizeButton != null)
|
||||
{
|
||||
Avalonia.Controls.ToolTip.SetTip(_maximizeButton, max
|
||||
? (IsEnglish() ? "Restore" : "还原")
|
||||
: (IsEnglish() ? "Maximize" : "最大化"));
|
||||
}
|
||||
// 最大化后同样保留圆角(用户要求:任何状态都要圆角)
|
||||
if (_frame != null) _frame.CornerRadius = new CornerRadius(16);
|
||||
}
|
||||
|
||||
private static Color ParseColor(string? hex, string fallback)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(hex))
|
||||
{
|
||||
try { return Color.Parse(hex!); }
|
||||
catch { /* 模型写错颜色时退回默认 */ }
|
||||
}
|
||||
return Color.Parse(fallback);
|
||||
}
|
||||
|
||||
private static bool IsEnglish() => L.I.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 「如何使用?」:读取模型自带数据目录里的 help.json(中英双语),
|
||||
/// 用与标题栏一致的配色弹出一个独立小窗。说明内容完全由模型提供,启动器不内置文案。
|
||||
/// </summary>
|
||||
private void ShowHelp(ModelPackage package, Color barBg, Color barBorder, Color barText,
|
||||
Color btnText, Color frameBg)
|
||||
{
|
||||
var lang = IsEnglish() ? "en" : "zh-CN";
|
||||
var file = Path.Combine(package.DataDirectory, "help.json");
|
||||
string title = IsEnglish() ? "How to use" : "如何使用";
|
||||
// 分节内容:每节一个标题 + 若干条说明;兼容旧的扁平 lines 格式
|
||||
var sections = new List<(string Heading, List<string> Lines)>();
|
||||
|
||||
if (File.Exists(file))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var root = doc.RootElement;
|
||||
var node = root.TryGetProperty(lang, out var exact) ? exact
|
||||
: root.TryGetProperty("zh-CN", out var zh) ? zh : root;
|
||||
if (node.TryGetProperty("title", out var t)) title = t.GetString() ?? title;
|
||||
|
||||
if (node.TryGetProperty("sections", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var sec in arr.EnumerateArray())
|
||||
{
|
||||
var heading = sec.TryGetProperty("h", out var h) ? h.GetString() ?? "" : "";
|
||||
var items = new List<string>();
|
||||
if (sec.TryGetProperty("lines", out var ls) && ls.ValueKind == JsonValueKind.Array)
|
||||
foreach (var item in ls.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
|
||||
if (items.Count > 0) sections.Add((heading, items));
|
||||
}
|
||||
}
|
||||
else if (node.TryGetProperty("lines", out var flat) && flat.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
var items = new List<string>();
|
||||
foreach (var item in flat.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
|
||||
if (items.Count > 0) sections.Add(("", items));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取模型帮助失败 {file}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
if (sections.Count == 0)
|
||||
sections.Add(("", new List<string>
|
||||
{
|
||||
IsEnglish() ? "This model has no usage notes yet." : "该模型暂未提供使用说明。"
|
||||
}));
|
||||
|
||||
var body = new StackPanel { Spacing = 6 };
|
||||
foreach (var (heading, items) in sections)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(heading))
|
||||
body.Children.Add(new TextBlock
|
||||
{
|
||||
Text = heading,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 13.5,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
Margin = new Thickness(0, 12, 0, 2)
|
||||
});
|
||||
foreach (var line in items)
|
||||
body.Children.Add(new TextBlock
|
||||
{
|
||||
Text = "• " + line,
|
||||
Foreground = new SolidColorBrush(btnText),
|
||||
FontSize = 12.5,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 19
|
||||
});
|
||||
}
|
||||
|
||||
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
|
||||
// 纯矢量图标,无彩色圆底(与三个窗口按钮保持一致)
|
||||
var helpCross = new Shapes.Path
|
||||
{
|
||||
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
|
||||
Stroke = new SolidColorBrush(btnText),
|
||||
StrokeThickness = 1.5,
|
||||
StrokeLineCap = PenLineCap.Round,
|
||||
Fill = null,
|
||||
Stretch = Stretch.None,
|
||||
Width = 10, Height = 10,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var helpClose = new Button
|
||||
{
|
||||
Content = helpCross,
|
||||
Width = 34,
|
||||
Height = 26,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(6, 0, 0, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
helpClose.PointerEntered += (_, _) =>
|
||||
{
|
||||
helpClose.Background = new SolidColorBrush(IsLight(frameBg)
|
||||
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
|
||||
helpCross.Stroke = new SolidColorBrush(Colors.White);
|
||||
};
|
||||
helpClose.PointerExited += (_, _) =>
|
||||
{
|
||||
helpClose.Background = Brushes.Transparent;
|
||||
helpCross.Stroke = new SolidColorBrush(btnText);
|
||||
};
|
||||
|
||||
var helpTitle = new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var helpBarGrid = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
|
||||
Margin = new Thickness(22, 0, 14, 0)
|
||||
};
|
||||
helpBarGrid.Children.Add(helpTitle);
|
||||
Grid.SetColumn(helpClose, 1);
|
||||
helpBarGrid.Children.Add(helpClose);
|
||||
|
||||
var helpTitleBar = new Border
|
||||
{
|
||||
Height = 48,
|
||||
Background = new SolidColorBrush(barBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Child = helpBarGrid
|
||||
};
|
||||
helpTitleBar.PointerPressed += (_, e) =>
|
||||
{
|
||||
if (e.GetCurrentPoint(helpTitleBar).Properties.IsLeftButtonPressed)
|
||||
helpClose.FindAncestorOfType<Window>()?.BeginMoveDrag(e);
|
||||
};
|
||||
|
||||
// ── 底部固定操作条:无论正文多长,「知道了」始终可见 ──
|
||||
var ok = new Button
|
||||
{
|
||||
Content = IsEnglish() ? "Got it" : "知道了",
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Padding = new Thickness(20, 8),
|
||||
Background = new SolidColorBrush(Color.Parse("#2F6BFF")),
|
||||
Foreground = new SolidColorBrush(Colors.White),
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
var footer = new Border
|
||||
{
|
||||
Padding = new Thickness(24, 10, 24, 14),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 1, 0, 0),
|
||||
Child = ok
|
||||
};
|
||||
|
||||
// 标题栏(顶) + 正文(中,滚动) + 操作条(底,固定)
|
||||
var rootPanel = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(helpTitleBar, Dock.Top);
|
||||
rootPanel.Children.Add(helpTitleBar);
|
||||
DockPanel.SetDock(footer, Dock.Bottom);
|
||||
rootPanel.Children.Add(footer);
|
||||
var scroll = new ScrollViewer
|
||||
{
|
||||
Content = new Border
|
||||
{
|
||||
Margin = new Thickness(24, 14, 24, 10),
|
||||
Child = body
|
||||
},
|
||||
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
|
||||
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled
|
||||
};
|
||||
rootPanel.Children.Add(scroll);
|
||||
|
||||
var win = new Window
|
||||
{
|
||||
Title = title,
|
||||
Width = 660,
|
||||
Height = Math.Min(760, 230 + sections.Sum(s => s.Lines.Count * 24 + 40)),
|
||||
MinWidth = 480,
|
||||
MinHeight = 320,
|
||||
Background = Brushes.Transparent,
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent },
|
||||
SystemDecorations = SystemDecorations.None,
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(frameBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(1),
|
||||
ClipToBounds = true,
|
||||
Child = rootPanel
|
||||
}
|
||||
};
|
||||
ok.Click += (_, _) => win.Close();
|
||||
helpClose.Click += (_, _) => win.Close();
|
||||
win.Show(this);
|
||||
}
|
||||
|
||||
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Escape:
|
||||
_ = CloseWithAnimationAsync();
|
||||
e.Handled = true;
|
||||
break;
|
||||
case Key.F11:
|
||||
WindowState = WindowState == WindowState.FullScreen
|
||||
? WindowState.Normal
|
||||
: WindowState.FullScreen;
|
||||
e.Handled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 关闭动画:淡出 + 轻微缩小,动画结束后再真正关闭窗口。
|
||||
/// 与主窗口的关闭动画保持同一节奏(180ms)。
|
||||
/// </summary>
|
||||
private async Task CloseWithAnimationAsync()
|
||||
{
|
||||
if (_closing) return;
|
||||
_closing = true;
|
||||
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = OpacityProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(180),
|
||||
Easing = new CubicEaseIn()
|
||||
}
|
||||
};
|
||||
Opacity = 0;
|
||||
|
||||
await Task.Delay(190);
|
||||
Close();
|
||||
}
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e)
|
||||
{
|
||||
Content = null;
|
||||
_model?.Dispose();
|
||||
_model = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型加载失败时显示的提示窗口(不含任何渲染逻辑)。</summary>
|
||||
public sealed class ModelErrorWindow : Window
|
||||
{
|
||||
public ModelErrorWindow(string title, string message)
|
||||
{
|
||||
Title = title;
|
||||
Width = 560;
|
||||
Height = 340;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
|
||||
var lines = new List<Control>
|
||||
{
|
||||
new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
},
|
||||
new TextBlock
|
||||
{
|
||||
Text = message,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12,
|
||||
TextWrapping = TextWrapping.Wrap
|
||||
},
|
||||
new Button
|
||||
{
|
||||
Content = "确定",
|
||||
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
|
||||
Padding = new Thickness(18, 6)
|
||||
}
|
||||
};
|
||||
|
||||
var panel = new StackPanel
|
||||
{
|
||||
Margin = new Thickness(24),
|
||||
Spacing = 14
|
||||
};
|
||||
foreach (var line in lines) panel.Children.Add(line);
|
||||
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(12),
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226")),
|
||||
Child = panel
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -135,6 +135,9 @@ public sealed record LoginRequest(string Username, string Password);
|
||||
/// <summary>换主题色:只传颜色,价格由服务端按预置/自定义判定。</summary>
|
||||
public sealed record ThemeRequest(string Color, int? Cost = null);
|
||||
|
||||
/// <summary>二选一:两个候选选项,服务端随机挑一个并计费。</summary>
|
||||
public sealed record PickRequest(string OptionA, string OptionB);
|
||||
|
||||
public sealed record CaptchaDto(string Id, string Question);
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC.UI.Server;
|
||||
|
||||
/// <summary>
|
||||
/// 模型窗口宿主。
|
||||
///
|
||||
/// 为什么渲染这一层留在 .NET:模型 dll 通过 <c>IModelRuntime.CreateView</c> 返回的是
|
||||
/// Avalonia <see cref="Control"/>,这是模型契约的一部分。把渲染栈换成 Flutter 等于换掉契约,
|
||||
/// 所有已发布模型都会失效。所以前后端分离的切法是:
|
||||
/// · 界面(首页 / 下载 / 设置 / 关于)→ Flutter 前端
|
||||
/// · 模型窗口(模型自带界面)→ 仍由 .NET 承载,前端只发一条「启动模型」的指令
|
||||
///
|
||||
/// 这里惰性启动一个没有主窗口的 Avalonia 桌面生命周期,之后所有模型窗口都在它的 UI 线程上创建。
|
||||
/// 无桌面会话(CI / 无头环境)时启动会失败,此时只有「启动模型」不可用,其余接口照常工作。
|
||||
/// </summary>
|
||||
public sealed class AvaloniaHost
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly TaskCompletionSource<bool> _ready =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private int _started;
|
||||
|
||||
public AvaloniaHost(AppServices services) => _services = services;
|
||||
|
||||
public bool IsAvailable { get; private set; }
|
||||
|
||||
public string? LastError { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 后端线程调用:等待「主线程已把 Avalonia 事件循环跑起来」。
|
||||
///
|
||||
/// 关键点:macOS 的 AppKit 要求 NSApplication 在**主线程**。以前这里把
|
||||
/// <c>StartWithClassicDesktopLifetime</c> 丢到一个新建的后台线程里跑,在 macOS 上
|
||||
/// 会直接崩掉整个后端进程(表现为点「启动模型」界面无反应、随后后端消失)。
|
||||
/// 现在改为由启动器在主线程调用 <see cref="RunOnCurrentThread"/>,
|
||||
/// 这里只等待就绪信号。
|
||||
/// </summary>
|
||||
public Task<bool> EnsureStartedAsync() => _ready.Task;
|
||||
|
||||
/// <summary>
|
||||
/// 必须在 UI 主线程调用。启动 Avalonia 桌面生命周期并阻塞,直到 <see cref="Shutdown"/>。
|
||||
/// 返回后(或初始化失败后)调用方负责收尾。
|
||||
/// </summary>
|
||||
public void RunOnCurrentThread()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _started, 1) == 1) return;
|
||||
|
||||
try
|
||||
{
|
||||
AppBuilder.Configure<HostApp>()
|
||||
.UsePlatformDetect()
|
||||
.AfterSetup(_ =>
|
||||
{
|
||||
IsAvailable = true;
|
||||
_ready.TrySetResult(true);
|
||||
})
|
||||
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 无桌面会话(CI / 无头环境):模型窗口不可用,但后端其余接口照常。
|
||||
LastError = ex.Message;
|
||||
_ready.TrySetResult(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从任意线程请求结束事件循环,使 <see cref="RunOnCurrentThread"/> 返回。</summary>
|
||||
public void Shutdown()
|
||||
{
|
||||
if (_started == 0) return;
|
||||
try
|
||||
{
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
desktop.Shutdown();
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 事件循环尚未建立或已退出:无需处理
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
||||
public async Task<string> LaunchAsync(ModelPackage package)
|
||||
{
|
||||
if (!await EnsureStartedAsync().ConfigureAwait(false))
|
||||
throw new InvalidOperationException(
|
||||
LastError ?? "无法初始化图形环境(当前会话没有桌面?)");
|
||||
|
||||
return await Dispatcher.UIThread.InvokeAsync<string>(async () =>
|
||||
{
|
||||
// 同一个模型已经在运行:把已有窗口提到前台,不再加载第二份实例
|
||||
// (连点「启动模型」会各占一份内存与显存,低配机器直接卡死)。
|
||||
lock (_gate)
|
||||
{
|
||||
if (_windows.TryGetValue(package.Id, out var existing))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (existing.WindowState == WindowState.Minimized)
|
||||
existing.WindowState = WindowState.Normal;
|
||||
existing.Activate();
|
||||
return $"模型 {package.Id} 已在运行";
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 窗口已失效:清掉记录,按新窗口重新打开
|
||||
_windows.Remove(package.Id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PlayerWindow? window = null;
|
||||
LoadedModel? loaded = null;
|
||||
try
|
||||
{
|
||||
Action requestClose = () => Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
try { window?.Close(); } catch { /* 已关闭 */ }
|
||||
});
|
||||
|
||||
loaded = await _services.ModelHost.LoadAsync(package, requestClose, null);
|
||||
|
||||
window = new PlayerWindow(package, loaded);
|
||||
var captured = loaded;
|
||||
var id = package.Id;
|
||||
window.Closed += (_, _) =>
|
||||
{
|
||||
try { captured.Dispose(); } catch { /* 释放失败不影响退出 */ }
|
||||
lock (_gate)
|
||||
{
|
||||
if (_windows.TryGetValue(id, out var current) && ReferenceEquals(current, window))
|
||||
_windows.Remove(id);
|
||||
}
|
||||
};
|
||||
|
||||
lock (_gate) _windows[id] = window;
|
||||
window.Show();
|
||||
return $"已启动模型 {package.Id}";
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { loaded?.Dispose(); } catch { /* 忽略 */ }
|
||||
throw;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>后端自己的 Avalonia 应用:没有主窗口,只用来承载模型窗口。</summary>
|
||||
internal sealed class HostApp : Application
|
||||
{
|
||||
public override void Initialize() { }
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
||||
desktop.MainWindow = null;
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
@@ -36,15 +36,26 @@ public static class BackendServer
|
||||
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
|
||||
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
|
||||
///
|
||||
/// 模型渲染已全部交给 Flutter,本进程只提供 HTTP API,不再有窗口宿主。
|
||||
/// 界面是 Flutter,但**模型窗口仍由 Avalonia 承载**(模型契约返回的是 Avalonia Control)。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port)
|
||||
=> Start(args, port, out _);
|
||||
|
||||
/// <summary>
|
||||
/// 构建后端,并通过 <paramref name="uiHost"/> 交出模型窗口宿主。
|
||||
///
|
||||
/// 调用方(启动器)必须在**主线程**调用 <see cref="AvaloniaHost.RunOnCurrentThread"/>:
|
||||
/// macOS 的 AppKit 要求 NSApplication 运行在主线程,否则打开模型窗口时整个进程会崩溃。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port, out AvaloniaHost uiHost)
|
||||
{
|
||||
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
|
||||
var services = AppServices.Create();
|
||||
var userService = new UserService(services.Paths.HomeRoot);
|
||||
var host = new AvaloniaHost(services);
|
||||
uiHost = host;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
||||
builder.Logging.ClearProviders();
|
||||
@@ -214,6 +225,20 @@ public static class BackendServer
|
||||
await next();
|
||||
});
|
||||
|
||||
// 人品值评语(与前端 FortuneResult.commentFor 保持一致)
|
||||
static string FortuneComment(int value)
|
||||
{
|
||||
if (value >= 96) return "欧皇附体,今天买彩票吧";
|
||||
if (value >= 90) return "运气爆棚,适合干大事";
|
||||
if (value >= 80) return "手气不错,稳";
|
||||
if (value >= 65) return "中上水平,稍微努一下";
|
||||
if (value >= 50) return "普普通通,够用";
|
||||
if (value >= 35) return "有点背,低调点";
|
||||
if (value >= 20) return "今天别赌任何东西";
|
||||
if (value >= 8) return "极差,建议躺平";
|
||||
return "非酋之王,明天再来";
|
||||
}
|
||||
|
||||
// 统一的用户响应体:前端一次拿齐签到 / 主题色需要的所有字段
|
||||
object UserPayload(UserRecord r)
|
||||
{
|
||||
@@ -310,6 +335,42 @@ public static class BackendServer
|
||||
});
|
||||
});
|
||||
|
||||
app.MapPost("/api/user/fortune", (HttpContext ctx) =>
|
||||
{
|
||||
var username = ctx.Items["user"] as string;
|
||||
if (string.IsNullOrEmpty(username))
|
||||
return Results.Json(new { error = "未登录" }, statusCode: 401);
|
||||
|
||||
var ok = userService.RollFortune(username, out var err, out var value,
|
||||
out var cost, out var rec);
|
||||
if (!ok) return Results.BadRequest(new { error = err });
|
||||
|
||||
return Results.Ok(new {
|
||||
value,
|
||||
cost,
|
||||
comment = FortuneComment(value),
|
||||
user = UserPayload(rec!)
|
||||
});
|
||||
});
|
||||
|
||||
app.MapPost("/api/user/pick", (HttpContext ctx, PickRequest? req) =>
|
||||
{
|
||||
var username = ctx.Items["user"] as string;
|
||||
if (string.IsNullOrEmpty(username))
|
||||
return Results.Json(new { error = "未登录" }, statusCode: 401);
|
||||
if (req == null) return Results.BadRequest(new { error = "请求体为空" });
|
||||
|
||||
var ok = userService.PickOne(username, req.OptionA, req.OptionB, out var err,
|
||||
out var choice, out var cost, out var rec);
|
||||
if (!ok) return Results.BadRequest(new { error = err });
|
||||
|
||||
return Results.Ok(new {
|
||||
choice,
|
||||
cost,
|
||||
user = UserPayload(rec!)
|
||||
});
|
||||
});
|
||||
|
||||
app.MapPost("/api/user/theme", (HttpContext ctx, ThemeRequest? req) =>
|
||||
{
|
||||
var username = ctx.Items["user"] as string;
|
||||
@@ -355,13 +416,23 @@ app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||||
|
||||
// 模型改为客户端内渲染(Flutter):这里只确认模型存在并把 id 交回去,
|
||||
// 不再拉起 Avalonia 窗口。保留接口是为了老客户端不至于 404。
|
||||
app.MapPost("/api/models/{id}/launch", (string id) =>
|
||||
app.MapPost("/api/models/{id}/launch", async (string id) =>
|
||||
{
|
||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
||||
var package = services.Models.Find(id);
|
||||
if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
||||
|
||||
return Results.Ok(new LaunchResultDto(true, $"在应用内打开 {package.Manifest.Name}"));
|
||||
try
|
||||
{
|
||||
services.Memory.Refresh();
|
||||
var message = await host.LaunchAsync(package);
|
||||
return Results.Ok(new LaunchResultDto(true, message));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[launch] 启动模型 {id} 失败: {ex}");
|
||||
return Results.Json(new LaunchResultDto(false, "模型启动失败,请查看后端日志"), statusCode: 503);
|
||||
}
|
||||
});
|
||||
|
||||
app.MapDelete("/api/models/{id}", (string id) =>
|
||||
|
||||
@@ -100,8 +100,9 @@ public sealed class UserService
|
||||
{
|
||||
var lines = yaml.Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||
string? username = null, pwHash = null, pwSalt = null, themeColor = null;
|
||||
int points = 0, consecutiveDays = 0, themePaid = 0;
|
||||
DateTime? lastSignIn = null, themePaidAt = null;
|
||||
decimal points = 0, themePaid = 0;
|
||||
int consecutiveDays = 0, fortuneCount = 0, pickCount = 0;
|
||||
DateTime? lastSignIn = null, themePaidAt = null, fortuneDate = null, pickDate = null;
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
@@ -114,16 +115,25 @@ public sealed class UserService
|
||||
case "username": username = val; break;
|
||||
case "pw_hash": pwHash = val; break;
|
||||
case "pw_salt": pwSalt = val; break;
|
||||
case "points": int.TryParse(val, out var p); points = p; break;
|
||||
// 旧文件里积分是整数;decimal.TryParse 兼容读取
|
||||
case "points": decimal.TryParse(val, out var p); points = p; break;
|
||||
case "last_sign_in":
|
||||
if (DateTime.TryParse(val, out var ls)) lastSignIn = ls;
|
||||
break;
|
||||
case "consecutive_days": int.TryParse(val, out var d); consecutiveDays = d; break;
|
||||
case "theme_color": themeColor = val; break;
|
||||
case "theme_paid": int.TryParse(val, out var tp); themePaid = tp; break;
|
||||
case "theme_paid": decimal.TryParse(val, out var tp); themePaid = tp; break;
|
||||
case "theme_paid_at":
|
||||
if (DateTime.TryParse(val, out var ta)) themePaidAt = ta;
|
||||
break;
|
||||
case "fortune_date":
|
||||
if (DateTime.TryParse(val, out var fd)) fortuneDate = fd;
|
||||
break;
|
||||
case "fortune_count": int.TryParse(val, out var fc); fortuneCount = fc; break;
|
||||
case "pick_date":
|
||||
if (DateTime.TryParse(val, out var pd)) pickDate = pd;
|
||||
break;
|
||||
case "pick_count": int.TryParse(val, out var pc); pickCount = pc; break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +142,13 @@ public sealed class UserService
|
||||
|
||||
return new UserRecord(username!, pwHash, pwSalt, points, lastSignIn, consecutiveDays,
|
||||
string.IsNullOrWhiteSpace(themeColor) ? DefaultThemeColor : themeColor,
|
||||
themePaid, themePaidAt);
|
||||
themePaid, themePaidAt)
|
||||
{
|
||||
FortuneDate = fortuneDate,
|
||||
FortuneCount = fortuneCount,
|
||||
PickDate = pickDate,
|
||||
PickCount = pickCount
|
||||
};
|
||||
}
|
||||
|
||||
private void SaveUser(UserRecord rec)
|
||||
@@ -146,12 +162,16 @@ public sealed class UserService
|
||||
.AppendLine($"username: {rec.Username}")
|
||||
.AppendLine($"pw_hash: {rec.PwHash}")
|
||||
.AppendLine($"pw_salt: {rec.PwSalt}")
|
||||
.AppendLine($"points: {rec.Points}")
|
||||
.AppendLine($"points: {rec.Points.ToString("0.##")}")
|
||||
.AppendLine($"last_sign_in: {rec.LastSignIn?.ToString("yyyy-MM-dd") ?? ""}")
|
||||
.AppendLine($"consecutive_days: {rec.ConsecutiveDays}")
|
||||
.AppendLine($"theme_color: {rec.ThemeColor ?? DefaultThemeColor}")
|
||||
.AppendLine($"theme_paid: {rec.ThemePaid}")
|
||||
.AppendLine($"theme_paid: {rec.ThemePaid.ToString("0.##")}")
|
||||
.AppendLine($"theme_paid_at: {rec.ThemePaidAt?.ToString("o") ?? ""}")
|
||||
.AppendLine($"fortune_date: {rec.FortuneDate?.ToString("yyyy-MM-dd") ?? ""}")
|
||||
.AppendLine($"fortune_count: {rec.FortuneCount}")
|
||||
.AppendLine($"pick_date: {rec.PickDate?.ToString("yyyy-MM-dd") ?? ""}")
|
||||
.AppendLine($"pick_count: {rec.PickCount}")
|
||||
.ToString();
|
||||
|
||||
File.WriteAllText(Path.Combine(dir, "pw.yaml"), yaml);
|
||||
@@ -322,7 +342,7 @@ public sealed class UserService
|
||||
|
||||
public UserRecord? GetFirstUser() => _users.Values.FirstOrDefault();
|
||||
|
||||
public bool UpdatePoints(string username, int deltaPoints, out string error)
|
||||
public bool UpdatePoints(string username, decimal deltaPoints, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
|
||||
@@ -426,7 +446,7 @@ public sealed class UserService
|
||||
/// 换主题色。服务端自己算价,不信客户端传的 cost。
|
||||
/// 上次购买在 1 小时内,先按 80% 退还上次花费。
|
||||
/// </summary>
|
||||
public bool ChangeThemeColor(string username, string colorHex, out string error, out int refunded)
|
||||
public bool ChangeThemeColor(string username, string colorHex, out string error, out decimal refunded)
|
||||
{
|
||||
error = "";
|
||||
refunded = 0;
|
||||
@@ -457,12 +477,12 @@ public sealed class UserService
|
||||
return false;
|
||||
}
|
||||
|
||||
// 1 小时内换色:退回上次花费的 80%
|
||||
// 1 小时内换色:退回上次花费的 80%(保留 2 位小数)
|
||||
var available = rec.Points;
|
||||
if (rec.ThemePaid > 0 && rec.ThemePaidAt.HasValue &&
|
||||
DateTime.UtcNow - rec.ThemePaidAt.Value <= RefundWindow)
|
||||
{
|
||||
refunded = (int)Math.Floor(rec.ThemePaid * RefundRate);
|
||||
refunded = Math.Floor(rec.ThemePaid * (decimal)RefundRate * 100) / 100;
|
||||
available += refunded;
|
||||
}
|
||||
|
||||
@@ -490,6 +510,119 @@ public sealed class UserService
|
||||
return left > TimeSpan.Zero ? left : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 人品值 / 二选一
|
||||
|
||||
/// <summary>
|
||||
/// 人品值当日费用。第一次免费;之后按当日已付费次数阶梯计费:
|
||||
/// 第 1–5 次 0.1 / 第 6–10 次 0.2 / 第 11–25 次 0.5 / 第 26 次起 1。
|
||||
/// </summary>
|
||||
public static decimal FortuneCost(int paidIndexToday)
|
||||
{
|
||||
if (paidIndexToday <= 0) return 0m;
|
||||
if (paidIndexToday <= 5) return 0.1m;
|
||||
if (paidIndexToday <= 10) return 0.2m;
|
||||
if (paidIndexToday <= 25) return 0.5m;
|
||||
return 1m;
|
||||
}
|
||||
|
||||
/// <summary>二选一当日费用:第一次免费,之后每次 0.5。</summary>
|
||||
public static decimal PickCost(int paidIndexToday)
|
||||
=> paidIndexToday <= 0 ? 0m : 0.5m;
|
||||
|
||||
/// <summary>算出当日费用并扣费;积分不足返回 false。成功后计数 +1。</summary>
|
||||
private bool ChargeDailyFeature(UserRecord rec, Func<int, decimal> costFn,
|
||||
DateTime? featureDate, int featureCount, out decimal cost, out string error)
|
||||
{
|
||||
error = "";
|
||||
cost = 0;
|
||||
|
||||
var today = DateTime.UtcNow.Date;
|
||||
// 跨天了先重置计数
|
||||
if (featureDate.HasValue && featureDate.Value.Date != today)
|
||||
featureCount = 0;
|
||||
|
||||
cost = costFn(featureCount);
|
||||
if (rec.Points < cost)
|
||||
{
|
||||
error = cost > 0
|
||||
? $"积分不足,本次需要 {cost.ToString("0.##")} 积分"
|
||||
: "积分不足";
|
||||
return false;
|
||||
}
|
||||
|
||||
rec.Points = Math.Round(rec.Points - cost, 2);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 摇一次人品值(服务端算随机数,客户端不信自己传的值)。
|
||||
/// 当天第一次免费,之后按阶梯扣积分。
|
||||
/// </summary>
|
||||
public bool RollFortune(string username, out string error, out int value,
|
||||
out decimal cost, out UserRecord? record)
|
||||
{
|
||||
error = "";
|
||||
value = 0;
|
||||
cost = 0;
|
||||
record = null;
|
||||
|
||||
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
|
||||
{
|
||||
error = "用户不存在";
|
||||
return false;
|
||||
}
|
||||
|
||||
var today = DateTime.UtcNow.Date;
|
||||
var count = rec.FortuneDate.HasValue && rec.FortuneDate.Value.Date == today
|
||||
? rec.FortuneCount : 0;
|
||||
|
||||
if (!ChargeDailyFeature(rec, FortuneCost, rec.FortuneDate, count, out cost, out error))
|
||||
return false;
|
||||
|
||||
rec.FortuneDate = today;
|
||||
rec.FortuneCount = count + 1;
|
||||
value = RandomNumberGenerator.GetInt32(0, 101);
|
||||
record = rec;
|
||||
SaveUser(rec);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>二选一:服务端随机挑一个。当天第一次免费,之后每次 0.5。</summary>
|
||||
public bool PickOne(string username, string optionA, string optionB, out string error,
|
||||
out string choice, out decimal cost, out UserRecord? record)
|
||||
{
|
||||
error = "";
|
||||
choice = "";
|
||||
cost = 0;
|
||||
record = null;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(optionA) || string.IsNullOrWhiteSpace(optionB))
|
||||
{
|
||||
error = "两个选项都不能为空";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
|
||||
{
|
||||
error = "用户不存在";
|
||||
return false;
|
||||
}
|
||||
|
||||
var today = DateTime.UtcNow.Date;
|
||||
var count = rec.PickDate.HasValue && rec.PickDate.Value.Date == today
|
||||
? rec.PickCount : 0;
|
||||
|
||||
if (!ChargeDailyFeature(rec, PickCost, rec.PickDate, count, out cost, out error))
|
||||
return false;
|
||||
|
||||
rec.PickDate = today;
|
||||
rec.PickCount = count + 1;
|
||||
choice = RandomNumberGenerator.GetInt32(0, 2) == 0 ? optionA : optionB;
|
||||
record = rec;
|
||||
SaveUser(rec);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 散列
|
||||
|
||||
private static string GenerateSalt()
|
||||
@@ -513,20 +646,34 @@ public class UserRecord
|
||||
public string Username { get; init; } = "";
|
||||
public string PwHash { get; init; } = "";
|
||||
public string PwSalt { get; init; } = "";
|
||||
public int Points { get; set; }
|
||||
|
||||
/// <summary>积分,精确到 0.01。</summary>
|
||||
public decimal Points { get; set; }
|
||||
public DateTime? LastSignIn { get; set; }
|
||||
public int ConsecutiveDays { get; set; }
|
||||
public string? ThemeColor { get; set; }
|
||||
|
||||
/// <summary>当前这个颜色实际花了多少分(用于 1 小时内退款)。</summary>
|
||||
public int ThemePaid { get; set; }
|
||||
public decimal ThemePaid { get; set; }
|
||||
|
||||
/// <summary>购买该颜色的时间(UTC)。</summary>
|
||||
public DateTime? ThemePaidAt { get; set; }
|
||||
|
||||
public UserRecord(string username, string pwHash, string pwSalt, int points,
|
||||
/// <summary>人品值当日最后计算日期(UTC),跨天计数清零。</summary>
|
||||
public DateTime? FortuneDate { get; set; }
|
||||
|
||||
/// <summary>人品值当日已计算次数(含免费的那次)。</summary>
|
||||
public int FortuneCount { get; set; }
|
||||
|
||||
/// <summary>二选一当日最后使用日期(UTC)。</summary>
|
||||
public DateTime? PickDate { get; set; }
|
||||
|
||||
/// <summary>二选一当日已使用次数(含免费的那次)。</summary>
|
||||
public int PickCount { get; set; }
|
||||
|
||||
public UserRecord(string username, string pwHash, string pwSalt, decimal points,
|
||||
DateTime? lastSignIn, int consecutiveDays, string? themeColor = null,
|
||||
int themePaid = 0, DateTime? themePaidAt = null)
|
||||
decimal themePaid = 0, DateTime? themePaidAt = null)
|
||||
{
|
||||
Username = username;
|
||||
PwHash = pwHash;
|
||||
|
||||
@@ -729,6 +729,19 @@ class GcApi {
|
||||
final r = await _send('POST', '/api/user/theme', body: {'color': color});
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
/// 摇人品值。价格由后端算:当天第一次免费,之后按当日次数阶梯计费。
|
||||
Future<Map<String, dynamic>> rollFortune() async {
|
||||
final r = await _send('POST', '/api/user/fortune');
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
/// 二选一。当天第一次免费,之后每次 0.5 积分。
|
||||
Future<Map<String, dynamic>> pickOne(String optionA, String optionB) async {
|
||||
final r = await _send('POST', '/api/user/pick',
|
||||
body: {'optionA': optionA, 'optionB': optionB});
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
}
|
||||
|
||||
/// 人机验证题
|
||||
|
||||
@@ -67,6 +67,8 @@ class ShellController extends ChangeNotifier {
|
||||
if (settingsResult != null) {
|
||||
settings = settingsResult;
|
||||
_applySettings(settingsResult!);
|
||||
// 主题色现在归用户账号所有(设置页不再提供),启动时按当前用户恢复
|
||||
unawaited(_applyUserTheme());
|
||||
}
|
||||
|
||||
if (firstError != null && settingsResult == null) {
|
||||
@@ -97,34 +99,31 @@ class ShellController extends ChangeNotifier {
|
||||
|
||||
void _applySettings(SettingsInfo value) {
|
||||
I18n.setLanguage(value.language);
|
||||
GcPalette.apply(value.accentColor);
|
||||
// 强调色不再来自设置:由用户账号的 theme_color 决定(见 _applyUserTheme)
|
||||
GcPalette.applyTheme(value.theme);
|
||||
}
|
||||
|
||||
/// 按当前登录用户的 theme_color 应用强调色;未登录时保持默认。
|
||||
Future<void> applyUserTheme() => _applyUserTheme();
|
||||
|
||||
Future<void> _applyUserTheme() async {
|
||||
try {
|
||||
final resp = await api.me();
|
||||
final hex = resp?['theme_color'] as String?;
|
||||
if (hex != null && hex.isNotEmpty) GcPalette.apply('#$hex');
|
||||
} catch (_) {
|
||||
// 后端没起来或未登录:保持当前颜色即可
|
||||
}
|
||||
}
|
||||
|
||||
void goTo(int value) {
|
||||
if (index == value) return;
|
||||
index = value;
|
||||
activeModelId = null; // 切页时收起模型视图
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 当前在壳内打开的模型(null 表示在看普通页面)。
|
||||
///
|
||||
/// 模型全部由 Flutter 自绘,不再由后端开 Avalonia 窗口:
|
||||
/// 点「启动模型」只是把内容区换成模型视图,标题栏与侧栏保持可用。
|
||||
String? activeModelId;
|
||||
|
||||
void openModel(String id) {
|
||||
if (activeModelId == id) return;
|
||||
activeModelId = id;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void closeModel() {
|
||||
if (activeModelId == null) return;
|
||||
activeModelId = null;
|
||||
notifyListeners();
|
||||
}
|
||||
// 模型视图已回退为后端开 Avalonia 独立窗口(见 AvaloniaHost),
|
||||
// Flutter 内嵌的 activeModelId / openModel / ModelViewPage 一套已移除。
|
||||
|
||||
/// 模型库有变化(安装 / 删除 / 下载完成):通知首页刷新。
|
||||
void modelsChanged() {
|
||||
|
||||
@@ -17,7 +17,6 @@ class I18n {
|
||||
'nav.download': '下载',
|
||||
'nav.settings': '设置',
|
||||
'nav.about': '关于',
|
||||
'nav.treasure': '百宝箱',
|
||||
'nav.user': '用户',
|
||||
'home.title': '模型库',
|
||||
'home.subtitle': '选择模型,用可交互的三维演示讲清自转、公转与四季成因。',
|
||||
@@ -76,11 +75,6 @@ class I18n {
|
||||
'set.theme.dark': '深色',
|
||||
'set.theme.light': '浅色',
|
||||
'set.theme.system': '跟随系统',
|
||||
'set.accent': '主题颜色',
|
||||
'set.accent.desc': '选择启动器的主色调,按钮、滑块与高亮会同步换色。',
|
||||
'set.accent.custom': '自定义颜色',
|
||||
'set.accent.hexHint': '格式 #RRGGBB,例如 #8FB6FF',
|
||||
'set.accent.invalid': '颜色格式无效,请使用 #RRGGBB',
|
||||
'set.language': '界面语言',
|
||||
'set.language.auto': '跟随系统',
|
||||
'set.fps': '渲染帧率',
|
||||
@@ -218,7 +212,6 @@ class I18n {
|
||||
'nav.download': 'Download',
|
||||
'nav.settings': 'Settings',
|
||||
'nav.about': 'About',
|
||||
'nav.treasure': 'Treasure',
|
||||
'nav.user': 'User',
|
||||
'home.title': 'Model library',
|
||||
'home.subtitle': 'Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.',
|
||||
@@ -277,11 +270,6 @@ class I18n {
|
||||
'set.theme.dark': 'Dark',
|
||||
'set.theme.light': 'Light',
|
||||
'set.theme.system': 'System',
|
||||
'set.accent': 'Theme color',
|
||||
'set.accent.desc': 'Pick the launcher accent color; buttons, sliders and highlights follow it.',
|
||||
'set.accent.custom': 'Custom color',
|
||||
'set.accent.hexHint': 'Format #RRGGBB, e.g. #8FB6FF',
|
||||
'set.accent.invalid': 'Invalid color, use #RRGGBB',
|
||||
'set.language': 'Language',
|
||||
'set.language.auto': 'System',
|
||||
'set.fps': 'Render frame rate',
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 模型通用接口,所有 Flutter 模型实现此接口。
|
||||
abstract class GcModel {
|
||||
String get id;
|
||||
String name();
|
||||
String description();
|
||||
Widget buildView(BuildContext context);
|
||||
}
|
||||
@@ -1,378 +0,0 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
import 'contour_model.dart';
|
||||
|
||||
/// 等高线模型 Flutter 实现
|
||||
class ContourModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'contour-map-flutter';
|
||||
|
||||
@override
|
||||
String name() => '等高线地形图 (Flutter)';
|
||||
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的等高线地形模型,支持五大地形切换';
|
||||
|
||||
@override
|
||||
Widget buildView(BuildContext context) {
|
||||
return const _ContourModelView();
|
||||
}
|
||||
}
|
||||
|
||||
class _ContourModelView extends StatefulWidget {
|
||||
const _ContourModelView();
|
||||
|
||||
@override
|
||||
State<_ContourModelView> createState() => _ContourModelViewState();
|
||||
}
|
||||
|
||||
class _ContourModelViewState extends State<_ContourModelView>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _animController;
|
||||
TerrainKind _selectedTerrain = TerrainKind.mountain;
|
||||
bool _isPlaying = false;
|
||||
bool _colored = false;
|
||||
bool _isTopView = false;
|
||||
double _progress = 0;
|
||||
|
||||
final List<TerrainKind> _terrains = [
|
||||
TerrainKind.plain,
|
||||
TerrainKind.hill,
|
||||
TerrainKind.mountain,
|
||||
TerrainKind.plateau,
|
||||
TerrainKind.basin,
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_animController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 8),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_animController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _togglePlay() {
|
||||
setState(() {
|
||||
_isPlaying = !_isPlaying;
|
||||
});
|
||||
if (_isPlaying) {
|
||||
_animController.repeat();
|
||||
} else {
|
||||
_animController.stop();
|
||||
}
|
||||
}
|
||||
|
||||
void _reset() {
|
||||
setState(() {
|
||||
_isPlaying = false;
|
||||
_progress = 0;
|
||||
_colored = false;
|
||||
_isTopView = false;
|
||||
});
|
||||
_animController.stop();
|
||||
}
|
||||
|
||||
void _selectTerrain(TerrainKind terrain) {
|
||||
setState(() {
|
||||
_selectedTerrain = terrain;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
final mutedColor = isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
// 标题栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'等高线地形 · 五大地形',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: inkColor,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
TextButton.icon(
|
||||
onPressed: _reset,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 16),
|
||||
label: const Text('重置'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 五大地形切换
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'五大地形:',
|
||||
style: TextStyle(fontSize: 12, color: mutedColor),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
..._terrains.map((t) => _terrainChip(t, _selectedTerrain == t, () => _selectTerrain(t))),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 画布区域
|
||||
Expanded(
|
||||
child: _ContourCanvas(
|
||||
terrain: _selectedTerrain,
|
||||
isPlaying: _isPlaying,
|
||||
progress: _progress,
|
||||
colored: _colored,
|
||||
isTopView: _isTopView,
|
||||
animProgress: _animController.value,
|
||||
),
|
||||
),
|
||||
// 底部控制栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
_controlBtn(
|
||||
icon: _isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
||||
label: _isPlaying ? '暂停' : '播放',
|
||||
color: const Color(0xFF4D8CFF),
|
||||
onPressed: _togglePlay,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_controlBtn(
|
||||
icon: Icons.map_rounded,
|
||||
label: _isTopView ? '立体图' : '俯视图',
|
||||
color: panelColor,
|
||||
onPressed: () => setState(() => _isTopView = !_isTopView),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_controlBtn(
|
||||
icon: Icons.palette_rounded,
|
||||
label: _colored ? '取消上色' : '上色',
|
||||
color: _colored ? const Color(0xFF4D8CFF) : panelColor,
|
||||
onPressed: () => setState(() => _colored = !_colored),
|
||||
),
|
||||
const Spacer(),
|
||||
Expanded(
|
||||
child: LinearProgressIndicator(
|
||||
value: _progress,
|
||||
minHeight: 4,
|
||||
backgroundColor: isDark ? const Color(0xFF1E3350) : const Color(0xFFE3E8F3),
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFF4D8CFF)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _terrainChip(TerrainKind terrain, bool selected, VoidCallback onTap) {
|
||||
final names = {
|
||||
TerrainKind.plain: '平原',
|
||||
TerrainKind.hill: '丘陵',
|
||||
TerrainKind.mountain: '山地',
|
||||
TerrainKind.plateau: '高原',
|
||||
TerrainKind.basin: '盆地',
|
||||
};
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 6),
|
||||
child: FilterChip(
|
||||
label: Text(names[terrain] ?? ''),
|
||||
selected: selected,
|
||||
onSelected: (_) => onTap(),
|
||||
selectedColor: const Color(0xFF4D8CFF).withOpacity(0.2),
|
||||
checkmarkColor: const Color(0xFF4D8CFF),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _controlBtn({
|
||||
required IconData icon,
|
||||
required String label,
|
||||
required Color color,
|
||||
required VoidCallback onPressed,
|
||||
}) {
|
||||
return TextButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon, size: 16, color: color),
|
||||
label: Text(label, style: TextStyle(fontSize: 12, color: color)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 等高线画布
|
||||
class _ContourCanvas extends StatelessWidget {
|
||||
final TerrainKind terrain;
|
||||
final bool isPlaying;
|
||||
final double progress;
|
||||
final bool colored;
|
||||
final bool isTopView;
|
||||
final double animProgress;
|
||||
|
||||
const _ContourCanvas({
|
||||
required this.terrain,
|
||||
required this.isPlaying,
|
||||
required this.progress,
|
||||
required this.colored,
|
||||
required this.isTopView,
|
||||
required this.animProgress,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _ContourPainter(
|
||||
terrain: terrain,
|
||||
isPlaying: isPlaying,
|
||||
progress: progress,
|
||||
colored: colored,
|
||||
isTopView: isTopView,
|
||||
animProgress: animProgress,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ContourPainter extends CustomPainter {
|
||||
final TerrainKind terrain;
|
||||
final bool isPlaying;
|
||||
final double progress;
|
||||
final bool colored;
|
||||
final bool isTopView;
|
||||
final double animProgress;
|
||||
|
||||
_ContourPainter({
|
||||
required this.terrain,
|
||||
required this.isPlaying,
|
||||
required this.progress,
|
||||
required this.colored,
|
||||
required this.isTopView,
|
||||
required this.animProgress,
|
||||
});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final bgColor = const Color(0xFF08111E);
|
||||
final lineColor = const Color(0xFF4D8CFF);
|
||||
final fillColor = const Color(0xFF1C5FA8);
|
||||
|
||||
canvas.drawColor(bgColor, BlendMode.src);
|
||||
|
||||
// 绘制等高线
|
||||
final center = Offset(size.width / 2, size.height / 2);
|
||||
final radius = math.min(size.width, size.height) * 0.35;
|
||||
|
||||
int contourCount;
|
||||
double maxHeight;
|
||||
|
||||
switch (terrain) {
|
||||
case TerrainKind.plain:
|
||||
contourCount = 3;
|
||||
maxHeight = 60;
|
||||
break;
|
||||
case TerrainKind.hill:
|
||||
contourCount = 8;
|
||||
maxHeight = 180;
|
||||
break;
|
||||
case TerrainKind.mountain:
|
||||
contourCount = 12;
|
||||
maxHeight = 1200;
|
||||
break;
|
||||
case TerrainKind.plateau:
|
||||
contourCount = 10;
|
||||
maxHeight = 1250;
|
||||
break;
|
||||
case TerrainKind.basin:
|
||||
contourCount = 10;
|
||||
maxHeight = 1060;
|
||||
break;
|
||||
}
|
||||
|
||||
final interval = maxHeight / contourCount;
|
||||
|
||||
for (int i = 0; i < contourCount; i++) {
|
||||
final ratio = (i + 1) / contourCount;
|
||||
final progressRatio = isPlaying ? animProgress : progress;
|
||||
|
||||
if (ratio > progressRatio) continue;
|
||||
|
||||
final alpha = colored ? (1 - ratio).clamp(0.2, 1.0) : 1.0;
|
||||
final paint = Paint()
|
||||
..color = colored
|
||||
? fillColor.withOpacity(alpha * 0.3)
|
||||
: lineColor.withOpacity(alpha)
|
||||
..style = colored ? PaintingStyle.fill : PaintingStyle.stroke
|
||||
..strokeWidth = 1.5;
|
||||
|
||||
Path path;
|
||||
if (terrain == TerrainKind.basin) {
|
||||
final r = radius * ratio;
|
||||
path = Path()..addOval(Rect.fromCircle(center: center, radius: r));
|
||||
} else if (terrain == TerrainKind.plateau) {
|
||||
final r = ratio < 0.5
|
||||
? radius * 0.5
|
||||
: radius * (0.5 + (ratio - 0.5) * 0.8);
|
||||
path = Path()..addOval(Rect.fromCircle(center: center, radius: r));
|
||||
} else {
|
||||
final spacing = terrain == TerrainKind.plain ? 0.15 : (terrain == TerrainKind.hill ? 0.1 : 0.08);
|
||||
final r = radius * (1 - ratio * (1 - spacing));
|
||||
path = Path()..addOval(Rect.fromCircle(center: center, radius: r));
|
||||
}
|
||||
|
||||
canvas.drawPath(path, paint);
|
||||
}
|
||||
|
||||
// 绘制山峰标记
|
||||
if (!isTopView && terrain != TerrainKind.plain) {
|
||||
final peakPaint = Paint()
|
||||
..color = const Color(0xFFFFD166)
|
||||
..style = PaintingStyle.fill;
|
||||
canvas.drawCircle(center, radius * 0.08, peakPaint);
|
||||
|
||||
final textPainter = TextPainter(
|
||||
text: TextSpan(
|
||||
text: '${maxHeight.toInt()}m',
|
||||
style: const TextStyle(fontSize: 11, color: Color(0xFFEAF2FF)),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(center.dx + 15, center.dy - 20));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _ContourPainter oldDelegate) {
|
||||
return oldDelegate.terrain != terrain ||
|
||||
oldDelegate.isPlaying != isPlaying ||
|
||||
oldDelegate.progress != progress ||
|
||||
oldDelegate.colored != colored ||
|
||||
oldDelegate.isTopView != isTopView ||
|
||||
oldDelegate.animProgress != animProgress;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/// 五大地形枚举(对应 C# TerrainKind)
|
||||
enum TerrainKind {
|
||||
plain, // 平原
|
||||
hill, // 丘陵
|
||||
mountain, // 山地
|
||||
plateau, // 高原
|
||||
basin, // 盆地
|
||||
}
|
||||
|
||||
/// 五大典型地貌部位(对应 C# LandformKind)
|
||||
enum LandformKind {
|
||||
peak, // 山峰
|
||||
ridge, // 山脊
|
||||
valley, // 山谷
|
||||
saddle, // 鞍部
|
||||
cliff, // 陡崖
|
||||
}
|
||||
|
||||
/// 等高线模型状态
|
||||
class ContourState {
|
||||
TerrainKind terrain = TerrainKind.mountain;
|
||||
LandformKind? selectedLandform;
|
||||
double progress = 0;
|
||||
bool isPlaying = false;
|
||||
bool colored = false;
|
||||
bool isTopView = false;
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
import 'geography_model.dart';
|
||||
|
||||
/// 地球地理模型 Flutter 实现
|
||||
class GeographyModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'earth-geography-flutter';
|
||||
|
||||
@override
|
||||
String name() => '地球地理 (Flutter)';
|
||||
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的地球地理模型,支持五带划分、七大洲四大洋';
|
||||
|
||||
@override
|
||||
Widget buildView(BuildContext context) {
|
||||
return const _GeographyModelView();
|
||||
}
|
||||
|
||||
/// 示例数据:五带
|
||||
List<GeoZone> get defaultZones => [
|
||||
GeoZone(
|
||||
id: 'torrid',
|
||||
nameZh: '热带',
|
||||
nameEn: 'Torrid Zone',
|
||||
latMin: -23.5,
|
||||
latMax: 23.5,
|
||||
descZh: '南北回归线之间,有太阳直射,终年高温。',
|
||||
descEn: 'Between the tropics; the Sun is overhead at some time each year.',
|
||||
),
|
||||
GeoZone(
|
||||
id: 'north-temperate',
|
||||
nameZh: '北温带',
|
||||
nameEn: 'North Temperate',
|
||||
latMin: 23.5,
|
||||
latMax: 66.5,
|
||||
descZh: '北回归线与北极圈之间,四季分明。',
|
||||
descEn: 'Between Tropic of Cancer and Arctic Circle; four distinct seasons.',
|
||||
),
|
||||
GeoZone(
|
||||
id: 'south-temperate',
|
||||
nameZh: '南温带',
|
||||
nameEn: 'South Temperate',
|
||||
latMin: -66.5,
|
||||
latMax: -23.5,
|
||||
descZh: '南回归线与南极圈之间,四季分明。',
|
||||
descEn: 'Between Tropic of Capricorn and Antarctic Circle; four seasons.',
|
||||
),
|
||||
GeoZone(
|
||||
id: 'north-frigid',
|
||||
nameZh: '北寒带',
|
||||
nameEn: 'North Frigid',
|
||||
latMin: 66.5,
|
||||
latMax: 90,
|
||||
descZh: '北极圈以北,终年寒冷,有极昼极夜。',
|
||||
descEn: 'Beyond the Arctic Circle; perpetually cold with polar day/night.',
|
||||
),
|
||||
GeoZone(
|
||||
id: 'south-frigid',
|
||||
nameZh: '南寒带',
|
||||
nameEn: 'South Frigid',
|
||||
latMin: -90,
|
||||
latMax: -66.5,
|
||||
descZh: '南极圈以南,终年寒冷,有极昼极夜。',
|
||||
descEn: 'Beyond the Antarctic Circle; perpetually cold with polar day/night.',
|
||||
),
|
||||
];
|
||||
|
||||
/// 示例数据:五大洲简化轮廓
|
||||
List<Continent> get defaultContinents => [
|
||||
Continent(
|
||||
nameZh: '亚洲',
|
||||
nameEn: 'Asia',
|
||||
points: [
|
||||
[60, 70], [100, 70], [140, 65], [180, 60],
|
||||
[180, 40], [140, 20], [120, 10], [100, 5],
|
||||
[80, 10], [60, 20], [50, 30], [40, 40],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '非洲',
|
||||
nameEn: 'Africa',
|
||||
points: [
|
||||
[35, 35], [50, 35], [50, 15], [40, 5],
|
||||
[30, -5], [20, -20], [15, -30], [20, -35],
|
||||
[30, -35], [35, -25], [40, -10], [35, 5],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '欧洲',
|
||||
nameEn: 'Europe',
|
||||
points: [
|
||||
[10, 70], [40, 70], [50, 60], [40, 50],
|
||||
[30, 45], [20, 45], [10, 50], [0, 55],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '北美洲',
|
||||
nameEn: 'North America',
|
||||
points: [
|
||||
[-170, 70], [-130, 70], [-80, 70], [-60, 50],
|
||||
[-60, 30], [-80, 20], [-100, 20], [-120, 30],
|
||||
[-160, 50], [-170, 60],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '南美洲',
|
||||
nameEn: 'South America',
|
||||
points: [
|
||||
[-80, 10], [-60, 10], [-35, -5], [-35, -20],
|
||||
[-50, -30], [-65, -50], [-75, -55], [-75, -40],
|
||||
[-70, -20], [-80, 0],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '大洋洲',
|
||||
nameEn: 'Oceania',
|
||||
points: [
|
||||
[115, -15], [150, -15], [160, -25], [150, -35],
|
||||
[130, -38], [115, -35], [113, -25],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '南极洲',
|
||||
nameEn: 'Antarctica',
|
||||
points: [
|
||||
[-180, -65], [-90, -65], [0, -65], [90, -65],
|
||||
[180, -65], [180, -90], [-180, -90],
|
||||
],
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
class _GeographyModelView extends StatefulWidget {
|
||||
const _GeographyModelView();
|
||||
|
||||
@override
|
||||
State<_GeographyModelView> createState() => _GeographyModelViewState();
|
||||
}
|
||||
|
||||
class _GeographyModelViewState extends State<_GeographyModelView> {
|
||||
String _activeView = 'zones'; // zones, coast, plates
|
||||
bool _showZones = true;
|
||||
bool _showCoast = true;
|
||||
bool _showPlates = false;
|
||||
|
||||
final GeographyModelFlutter _model = GeographyModelFlutter();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
// 标题栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'地球地理 · 五带与七大洲',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: inkColor,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
_viewButton('五带', _activeView == 'zones', () => setState(() => _activeView = 'zones')),
|
||||
_viewButton('大洲', _activeView == 'coast', () => setState(() => _activeView = 'coast')),
|
||||
TextButton.icon(
|
||||
onPressed: () => setState(() {
|
||||
_showZones = !_showZones;
|
||||
_showCoast = !_showCoast;
|
||||
}),
|
||||
icon: const Icon(Icons.tune_rounded, size: 16),
|
||||
label: const Text('图层'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 地图区域
|
||||
Expanded(
|
||||
child: _GeographyMap(
|
||||
zones: _model.defaultZones,
|
||||
continents: _model.defaultContinents,
|
||||
showZones: _showZones,
|
||||
showCoast: _showCoast,
|
||||
activeView: _activeView,
|
||||
),
|
||||
),
|
||||
// 底部说明
|
||||
if (_activeView == 'zones' && _showZones)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
color: panelColor,
|
||||
child: Text(
|
||||
'热带:南北回归线之间 | 温带:回归线与极圈之间 | 寒带:极圈以内',
|
||||
style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80)),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _viewButton(String label, bool active, VoidCallback onTap) {
|
||||
return TextButton(
|
||||
onPressed: onTap,
|
||||
style: TextButton.styleFrom(
|
||||
backgroundColor: active ? const Color(0xFF4D8CFF) : null,
|
||||
foregroundColor: active ? Colors.white : null,
|
||||
),
|
||||
child: Text(label, style: const TextStyle(fontSize: 12)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _GeographyMap extends StatelessWidget {
|
||||
final List<GeoZone> zones;
|
||||
final List<Continent> continents;
|
||||
final bool showZones;
|
||||
final bool showCoast;
|
||||
final String activeView;
|
||||
|
||||
const _GeographyMap({
|
||||
required this.zones,
|
||||
required this.continents,
|
||||
required this.showZones,
|
||||
required this.showCoast,
|
||||
required this.activeView,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _GeographyPainter(
|
||||
zones: zones,
|
||||
continents: continents,
|
||||
showZones: showZones,
|
||||
showCoast: showCoast,
|
||||
activeView: activeView,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _GeographyPainter extends CustomPainter {
|
||||
final List<GeoZone> zones;
|
||||
final List<Continent> continents;
|
||||
final bool showZones;
|
||||
final bool showCoast;
|
||||
final String activeView;
|
||||
|
||||
_GeographyPainter({
|
||||
required this.zones,
|
||||
required this.continents,
|
||||
required this.showZones,
|
||||
required this.showCoast,
|
||||
required this.activeView,
|
||||
});
|
||||
|
||||
/// 经纬度转画布坐标
|
||||
Offset _latLonToOffset(double lon, double lat, Size size) {
|
||||
final x = (lon + 180) / 360 * size.width;
|
||||
final y = (90 - lat) / 180 * size.height;
|
||||
return Offset(x, y);
|
||||
}
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final bgColor = const Color(0xFF0E2A4A);
|
||||
final oceanColor = const Color(0xFF0E2A4A);
|
||||
final zoneColors = {
|
||||
'torrid': const Color(0xFFFF6B35),
|
||||
'north-temperate': const Color(0xFFFFD93D),
|
||||
'south-temperate': const Color(0xFF6BCB77),
|
||||
'north-frigid': const Color(0xFF4D8CFF),
|
||||
'south-frigid': const Color(0xFF8B5CF6),
|
||||
};
|
||||
|
||||
// 海洋背景
|
||||
canvas.drawColor(oceanColor, BlendMode.src);
|
||||
|
||||
// 绘制五带
|
||||
if (showZones && activeView == 'zones') {
|
||||
final bandHeight = size.height / 9; // 180度纬度分9份
|
||||
final bandColors = [
|
||||
zoneColors['north-frigid']!,
|
||||
zoneColors['north-temperate']!,
|
||||
zoneColors['torrid']!,
|
||||
zoneColors['south-temperate']!,
|
||||
zoneColors['south-frigid']!,
|
||||
];
|
||||
final bandLatRanges = [
|
||||
(66.5, 90),
|
||||
(23.5, 66.5),
|
||||
(-23.5, 23.5),
|
||||
(-66.5, -23.5),
|
||||
(-90, -66.5),
|
||||
];
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
final (latMin, latMax) = bandLatRanges[i];
|
||||
final y1 = (90 - latMax) / 180 * size.height;
|
||||
final y2 = (90 - latMin) / 180 * size.height;
|
||||
canvas.drawRect(
|
||||
Rect.fromLTWH(0, y1, size.width, y2 - y1),
|
||||
Paint()..color = bandColors[i].withOpacity(0.3),
|
||||
);
|
||||
}
|
||||
|
||||
// 绘制回归线和极圈
|
||||
for (final lat in [23.5, -23.5, 66.5, -66.5]) {
|
||||
final y = (90 - lat) / 180 * size.height;
|
||||
canvas.drawLine(
|
||||
Offset(0, y),
|
||||
Offset(size.width, y),
|
||||
Paint()
|
||||
..color = Colors.white.withOpacity(0.4)
|
||||
..strokeWidth = 1
|
||||
..style = PaintingStyle.stroke
|
||||
..style = PaintingStyle.stroke,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 绘制大陆轮廓
|
||||
if (showCoast && activeView == 'coast') {
|
||||
for (final continent in continents) {
|
||||
if (continent.points.length < 2) continue;
|
||||
|
||||
final path = Path();
|
||||
final start = _latLonToOffset(continent.points[0][0], continent.points[0][1], size);
|
||||
path.moveTo(start.dx, start.dy);
|
||||
|
||||
for (int i = 1; i < continent.points.length; i++) {
|
||||
final p = _latLonToOffset(continent.points[i][0], continent.points[i][1], size);
|
||||
path.lineTo(p.dx, p.dy);
|
||||
}
|
||||
path.close();
|
||||
|
||||
canvas.drawPath(
|
||||
path,
|
||||
Paint()
|
||||
..color = const Color(0xFF4E8C4C)
|
||||
..style = PaintingStyle.fill,
|
||||
);
|
||||
canvas.drawPath(
|
||||
path,
|
||||
Paint()
|
||||
..color = Colors.white.withOpacity(0.6)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _GeographyPainter oldDelegate) {
|
||||
return oldDelegate.showZones != showZones ||
|
||||
oldDelegate.showCoast != showCoast ||
|
||||
oldDelegate.activeView != activeView;
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 地球地理模型数据
|
||||
class GeoZone {
|
||||
final String id;
|
||||
final String nameZh;
|
||||
final String nameEn;
|
||||
final double latMin;
|
||||
final double latMax;
|
||||
final String descZh;
|
||||
final String descEn;
|
||||
|
||||
GeoZone({
|
||||
required this.id,
|
||||
required this.nameZh,
|
||||
required this.nameEn,
|
||||
required this.latMin,
|
||||
required this.latMax,
|
||||
required this.descZh,
|
||||
required this.descEn,
|
||||
});
|
||||
}
|
||||
|
||||
/// 大陆板块数据
|
||||
class Continent {
|
||||
final String nameZh;
|
||||
final String nameEn;
|
||||
final List<List<double>> points; // [lon, lat]
|
||||
|
||||
Continent({
|
||||
required this.nameZh,
|
||||
required this.nameEn,
|
||||
required this.points,
|
||||
});
|
||||
}
|
||||
|
||||
/// 板块数据
|
||||
class Plate {
|
||||
final String id;
|
||||
final String nameZh;
|
||||
final String nameEn;
|
||||
final List<List<double>> points;
|
||||
|
||||
Plate({
|
||||
required this.id,
|
||||
required this.nameZh,
|
||||
required this.nameEn,
|
||||
required this.points,
|
||||
});
|
||||
}
|
||||
|
||||
/// 洲界线
|
||||
class Border {
|
||||
final String betweenZh;
|
||||
final String betweenEn;
|
||||
final String nameZh;
|
||||
final String nameEn;
|
||||
final List<List<double>> points;
|
||||
|
||||
Border({
|
||||
required this.betweenZh,
|
||||
required this.betweenEn,
|
||||
required this.nameZh,
|
||||
required this.nameEn,
|
||||
required this.points,
|
||||
});
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import 'base.dart';
|
||||
import 'contour_flutter.dart';
|
||||
import 'geography_flutter.dart';
|
||||
import 'revolution_flutter.dart';
|
||||
import 'rotation_flutter.dart';
|
||||
import 'scale_flutter.dart';
|
||||
|
||||
/// 后端模型 id → Flutter 实现。
|
||||
///
|
||||
/// 后端(`/api/models`)用的是模型包目录名(contour-map、earth-rotation…),
|
||||
/// Flutter 实现自己的 id 带 `-flutter` 后缀,这里做一次映射。
|
||||
/// Avalonia 版模型窗口已移除,所有模型统一在客户端内用 Flutter 渲染。
|
||||
final Map<String, GcModel Function()> _factories = <String, GcModel Function()>{
|
||||
'contour-map': () => ContourModelFlutter(),
|
||||
'earth-geography': () => GeographyModelFlutter(),
|
||||
'earth-rotation': () => RotationModelFlutter(),
|
||||
'earth-revolution': () => RevolutionModelFlutter(),
|
||||
'scale-calculator': () => ScaleCalculatorModelFlutter(),
|
||||
};
|
||||
|
||||
/// 按模型 id 取 Flutter 实现;没有对应实现时返回 null。
|
||||
GcModel? flutterModelFor(String id) {
|
||||
final factory = _factories[id] ?? _factories[id.replaceAll('-flutter', '')];
|
||||
return factory?.call();
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
/// 模型注册表:所有 Flutter 实现的模型都在这里注册。
|
||||
library;
|
||||
|
||||
export 'base.dart';
|
||||
export 'contour_model.dart';
|
||||
export 'contour_flutter.dart';
|
||||
export 'geography_model.dart';
|
||||
export 'geography_flutter.dart';
|
||||
export 'rotation_flutter.dart';
|
||||
export 'revolution_flutter.dart';
|
||||
export 'scale_model.dart';
|
||||
export 'scale_flutter.dart';
|
||||
|
||||
import 'base.dart';
|
||||
import 'contour_flutter.dart';
|
||||
import 'geography_flutter.dart';
|
||||
import 'rotation_flutter.dart';
|
||||
import 'revolution_flutter.dart';
|
||||
import 'scale_flutter.dart';
|
||||
|
||||
/// 所有可用的 Flutter 模型实例。
|
||||
final List<GcModel> allGcModels = [
|
||||
ContourModelFlutter(),
|
||||
GeographyModelFlutter(),
|
||||
RotationModelFlutter(),
|
||||
RevolutionModelFlutter(),
|
||||
ScaleCalculatorModelFlutter(),
|
||||
];
|
||||
|
||||
/// 根据 id 查找模型。
|
||||
GcModel? findModel(String id) {
|
||||
try {
|
||||
return allGcModels.firstWhere((m) => m.id == id);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
import 'revolution_model.dart';
|
||||
|
||||
/// 地球公转模型 Flutter 实现
|
||||
class RevolutionModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'earth-revolution-flutter';
|
||||
|
||||
@override
|
||||
String name() => '地球公转 (Flutter)';
|
||||
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的地球公转模型,观察四季成因';
|
||||
|
||||
@override
|
||||
Widget buildView(BuildContext context) {
|
||||
return const _RevolutionModelView();
|
||||
}
|
||||
|
||||
List<Season> get defaultSeasons => [
|
||||
Season(key: 'spring', date: '3/21', declinationDeg: 0, angleDeg: 0,
|
||||
teachingZh: '太阳直射赤道,全球昼夜平分。', teachingEn: 'Sun overhead at equator.'),
|
||||
Season(key: 'summer', date: '6/22', declinationDeg: 23.5, angleDeg: 90,
|
||||
teachingZh: '太阳直射北回归线,北半球昼最长。', teachingEn: 'Sun at Tropic of Cancer.'),
|
||||
Season(key: 'autumn', date: '9/23', declinationDeg: 0, angleDeg: 180,
|
||||
teachingZh: '太阳再次直射赤道,昼夜平分。', teachingEn: 'Sun back at equator.'),
|
||||
Season(key: 'winter', date: '12/22', declinationDeg: -23.5, angleDeg: 270,
|
||||
teachingZh: '太阳直射南回归线,北半球昼最短。', teachingEn: 'Sun at Tropic of Capricorn.'),
|
||||
];
|
||||
}
|
||||
|
||||
class _RevolutionModelView extends StatefulWidget {
|
||||
const _RevolutionModelView();
|
||||
|
||||
@override
|
||||
State<_RevolutionModelView> createState() => _RevolutionModelViewState();
|
||||
}
|
||||
|
||||
class _RevolutionModelViewState extends State<_RevolutionModelView>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _orbitController;
|
||||
bool _isPlaying = true;
|
||||
double _speed = 1.0;
|
||||
int _selectedSeason = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_orbitController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 12),
|
||||
)..repeat();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_orbitController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _togglePlay() {
|
||||
setState(() => _isPlaying = !_isPlaying);
|
||||
if (_isPlaying) _orbitController.repeat();
|
||||
else _orbitController.stop();
|
||||
}
|
||||
|
||||
void _reset() {
|
||||
setState(() {
|
||||
_isPlaying = true;
|
||||
_speed = 1.0;
|
||||
_selectedSeason = 0;
|
||||
});
|
||||
_orbitController.repeat();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text('地球公转 · 四季成因', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: inkColor)),
|
||||
const Spacer(),
|
||||
...['春分', '夏至', '秋分', '冬至'].asMap().entries.map((e) =>
|
||||
Padding(padding: const EdgeInsets.only(left: 6),
|
||||
child: FilterChip(
|
||||
label: Text(e.value, style: const TextStyle(fontSize: 11)),
|
||||
selected: _selectedSeason == e.key,
|
||||
onSelected: (_) => setState(() => _selectedSeason = e.key),
|
||||
selectedColor: const Color(0xFF4D8CFF).withOpacity(0.2),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _RevolutionOrbit(
|
||||
progress: _orbitController.value,
|
||||
selectedSeason: _selectedSeason,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(onPressed: _togglePlay, icon: Icon(_isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded), color: const Color(0xFF4D8CFF)),
|
||||
const SizedBox(width: 16),
|
||||
Text('速度:', style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80))),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: Slider(value: _speed, min: 0.1, max: 3.0, divisions: 29, onChanged: (v) => setState(() => _speed = v))),
|
||||
Text('${_speed.toStringAsFixed(1)}x'),
|
||||
const Spacer(),
|
||||
TextButton.icon(onPressed: _reset, icon: const Icon(Icons.refresh_rounded, size: 16), label: const Text('重置')),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RevolutionOrbit extends StatelessWidget {
|
||||
final double progress;
|
||||
final int selectedSeason;
|
||||
|
||||
const _RevolutionOrbit({required this.progress, required this.selectedSeason});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _RevolutionPainter(progress: progress, selectedSeason: selectedSeason),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RevolutionPainter extends CustomPainter {
|
||||
final double progress;
|
||||
final int selectedSeason;
|
||||
|
||||
_RevolutionPainter({required this.progress, required this.selectedSeason});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final bgColor = const Color(0xFF08111E);
|
||||
final sunColor = const Color(0xFFFFC24B);
|
||||
final orbitColor = const Color(0xFF4D8CFF);
|
||||
final earthColor = const Color(0xFF1C5FA8);
|
||||
|
||||
canvas.drawColor(bgColor, BlendMode.src);
|
||||
|
||||
final center = Offset(size.width / 2, size.height / 2);
|
||||
final orbitRadius = math.min(size.width, size.height) * 0.35;
|
||||
|
||||
// 绘制轨道
|
||||
canvas.drawCircle(center, orbitRadius, Paint()
|
||||
..color = orbitColor.withOpacity(0.3)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.5
|
||||
|
||||
..style = PaintingStyle.stroke);
|
||||
|
||||
// 绘制太阳
|
||||
canvas.drawCircle(center, 30, Paint()
|
||||
..color = sunColor
|
||||
..style = PaintingStyle.fill);
|
||||
|
||||
// 太阳发光效果
|
||||
for (int i = 4; i > 0; i--) {
|
||||
canvas.drawCircle(center, 30 + i * 12, Paint()
|
||||
..color = sunColor.withOpacity(0.1 * (5 - i))
|
||||
..style = PaintingStyle.fill);
|
||||
}
|
||||
|
||||
// 绘制地球位置(根据进度)
|
||||
final angle = progress * 2 * math.pi;
|
||||
final earthX = center.dx + math.cos(angle) * orbitRadius;
|
||||
final earthY = center.dy + math.sin(angle) * orbitRadius;
|
||||
|
||||
// 地球
|
||||
canvas.drawCircle(Offset(earthX, earthY), 15, Paint()
|
||||
..color = earthColor
|
||||
..style = PaintingStyle.fill);
|
||||
|
||||
// 地轴(倾斜23.5度)
|
||||
final tiltAngle = 23.5 * math.pi / 180;
|
||||
canvas.drawLine(
|
||||
Offset(earthX - math.sin(tiltAngle) * 25, earthY - math.cos(tiltAngle) * 25),
|
||||
Offset(earthX + math.sin(tiltAngle) * 25, earthY + math.cos(tiltAngle) * 25),
|
||||
Paint()
|
||||
..color = const Color(0xFFFF6B35)
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke);
|
||||
|
||||
// 标注四个关键位置
|
||||
final seasonLabels = ['春分', '夏至', '秋分', '冬至'];
|
||||
final seasonColors = [const Color(0xFF6BCB77), const Color(0xFFFFD93D), const Color(0xFF4D8CFF), const Color(0xFF8B5CF6)];
|
||||
|
||||
for (int i = 0; i < 4; i++) {
|
||||
final seasonAngle = i * math.pi / 2;
|
||||
final sx = center.dx + math.cos(seasonAngle) * orbitRadius;
|
||||
final sy = center.dy + math.sin(seasonAngle) * orbitRadius;
|
||||
|
||||
// 小圆点标记
|
||||
canvas.drawCircle(Offset(sx, sy), 5, Paint()
|
||||
..color = seasonColors[i]
|
||||
..style = PaintingStyle.fill);
|
||||
|
||||
// 标签
|
||||
final labelX = sx + math.cos(seasonAngle) * 25;
|
||||
final labelY = sy + math.sin(seasonAngle) * 25;
|
||||
final textPainter = TextPainter(
|
||||
text: TextSpan(text: seasonLabels[i], style: const TextStyle(fontSize: 10, color: Color(0xFFEAF2FF))),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(labelX - 15, labelY - 8));
|
||||
}
|
||||
|
||||
// 当前选中季节高亮
|
||||
if (selectedSeason >= 0 && selectedSeason < 4) {
|
||||
final selAngle = selectedSeason * math.pi / 2;
|
||||
final selX = center.dx + math.cos(selAngle) * orbitRadius;
|
||||
final selY = center.dy + math.sin(selAngle) * orbitRadius;
|
||||
|
||||
canvas.drawCircle(Offset(selX, selY), 8, Paint()
|
||||
..color = seasonColors[selectedSeason].withOpacity(0.5)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _RevolutionPainter oldDelegate) {
|
||||
return oldDelegate.progress != progress || oldDelegate.selectedSeason != selectedSeason;
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 节气数据
|
||||
class Season {
|
||||
final String key;
|
||||
final String date;
|
||||
final double declinationDeg;
|
||||
final double angleDeg;
|
||||
final String teachingZh;
|
||||
final String teachingEn;
|
||||
|
||||
Season({
|
||||
required this.key,
|
||||
required this.date,
|
||||
required this.declinationDeg,
|
||||
required this.angleDeg,
|
||||
required this.teachingZh,
|
||||
required this.teachingEn,
|
||||
});
|
||||
}
|
||||
|
||||
/// 教学要点
|
||||
class Lesson {
|
||||
final String titleZh;
|
||||
final String titleEn;
|
||||
final String bodyZh;
|
||||
final String bodyEn;
|
||||
final String view;
|
||||
final double? angleDeg;
|
||||
|
||||
Lesson({
|
||||
required this.titleZh,
|
||||
required this.titleEn,
|
||||
required this.bodyZh,
|
||||
required this.bodyEn,
|
||||
required this.view,
|
||||
this.angleDeg,
|
||||
});
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
|
||||
/// 地球自转模型 Flutter 实现
|
||||
class RotationModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'earth-rotation-flutter';
|
||||
|
||||
@override
|
||||
String name() => '地球自转 (Flutter)';
|
||||
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的地球自转模型,观察昼夜交替、晨昏线';
|
||||
|
||||
@override
|
||||
Widget buildView(BuildContext context) {
|
||||
return const _RotationModelView();
|
||||
}
|
||||
}
|
||||
|
||||
class _RotationModelView extends StatefulWidget {
|
||||
const _RotationModelView();
|
||||
|
||||
@override
|
||||
State<_RotationModelView> createState() => _RotationModelViewState();
|
||||
}
|
||||
|
||||
class _RotationModelViewState extends State<_RotationModelView>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _spinController;
|
||||
late AnimationController _tiltController;
|
||||
bool _isPlaying = true;
|
||||
double _speed = 1.0;
|
||||
bool _showLabels = true;
|
||||
bool _showTilt = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_spinController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 10),
|
||||
)..repeat();
|
||||
_tiltController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 500),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_spinController.dispose();
|
||||
_tiltController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _togglePlay() {
|
||||
setState(() {
|
||||
_isPlaying = !_isPlaying;
|
||||
});
|
||||
if (_isPlaying) {
|
||||
_spinController.repeat();
|
||||
} else {
|
||||
_spinController.stop();
|
||||
}
|
||||
}
|
||||
|
||||
void _reset() {
|
||||
setState(() {
|
||||
_isPlaying = true;
|
||||
_speed = 1.0;
|
||||
_showLabels = true;
|
||||
_showTilt = false;
|
||||
});
|
||||
_spinController.repeat();
|
||||
_tiltController.reset();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
// 标题栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'地球自转 · 昼夜交替',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: inkColor,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
_toggleButton('标注', _showLabels, () => setState(() => _showLabels = !_showLabels)),
|
||||
_toggleButton('倾角', _showTilt, () => setState(() => _showTilt = !_showTilt)),
|
||||
const SizedBox(width: 8),
|
||||
TextButton.icon(
|
||||
onPressed: _reset,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 16),
|
||||
label: const Text('重置'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 地球动画
|
||||
Expanded(
|
||||
child: _RotationEarth(
|
||||
animProgress: _spinController.value,
|
||||
showLabels: _showLabels,
|
||||
showTilt: _showTilt,
|
||||
isPlaying: _isPlaying,
|
||||
),
|
||||
),
|
||||
// 底部控制栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: _togglePlay,
|
||||
icon: Icon(_isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded),
|
||||
color: const Color(0xFF4D8CFF),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Text('速度:', style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80))),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _speed,
|
||||
min: 0.1,
|
||||
max: 3.0,
|
||||
divisions: 29,
|
||||
onChanged: (v) => setState(() => _speed = v),
|
||||
),
|
||||
),
|
||||
Text('${_speed.toStringAsFixed(1)}x', style: const TextStyle(fontSize: 12)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _toggleButton(String label, bool active, VoidCallback onTap) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 8),
|
||||
child: FilterChip(
|
||||
label: Text(label, style: const TextStyle(fontSize: 12)),
|
||||
selected: active,
|
||||
onSelected: (_) => onTap(),
|
||||
selectedColor: const Color(0xFF4D8CFF).withOpacity(0.2),
|
||||
checkmarkColor: const Color(0xFF4D8CFF),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RotationEarth extends StatelessWidget {
|
||||
final double animProgress;
|
||||
final bool showLabels;
|
||||
final bool showTilt;
|
||||
final bool isPlaying;
|
||||
|
||||
const _RotationEarth({
|
||||
required this.animProgress,
|
||||
required this.showLabels,
|
||||
required this.showTilt,
|
||||
required this.isPlaying,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _RotationPainter(
|
||||
animProgress: animProgress,
|
||||
showLabels: showLabels,
|
||||
showTilt: showTilt,
|
||||
isPlaying: isPlaying,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RotationPainter extends CustomPainter {
|
||||
final double animProgress;
|
||||
final bool showLabels;
|
||||
final bool showTilt;
|
||||
final bool isPlaying;
|
||||
|
||||
_RotationPainter({
|
||||
required this.animProgress,
|
||||
required this.showLabels,
|
||||
required this.showTilt,
|
||||
required this.isPlaying,
|
||||
});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final bgColor = const Color(0xFF08111E);
|
||||
final earthColor = const Color(0xFF1C5FA8);
|
||||
final landColor = const Color(0xFF4E8C4C);
|
||||
final iceColor = const Color(0xFFE9EFF6);
|
||||
final axisColor = const Color(0xFFFF6B35);
|
||||
final labelColor = const Color(0xFFEAF2FF);
|
||||
|
||||
canvas.drawColor(bgColor, BlendMode.src);
|
||||
|
||||
final center = Offset(size.width / 2, size.height / 2);
|
||||
final radius = math.min(size.width, size.height) * 0.3;
|
||||
|
||||
// 绘制地球球体
|
||||
final earthPaint = Paint()
|
||||
..color = earthColor
|
||||
..style = PaintingStyle.fill;
|
||||
canvas.drawCircle(center, radius, earthPaint);
|
||||
|
||||
// 绘制大陆(简化版,用椭圆模拟)
|
||||
final continents = [
|
||||
(center.dx - radius * 0.3, center.dy - radius * 0.2, radius * 0.25, radius * 0.35), // 亚洲
|
||||
(center.dx + radius * 0.2, center.dy - radius * 0.1, radius * 0.2, radius * 0.25), // 欧洲
|
||||
(center.dx - radius * 0.1, center.dy + radius * 0.2, radius * 0.15, radius * 0.3), // 非洲
|
||||
(center.dx + radius * 0.35, center.dy + radius * 0.1, radius * 0.2, radius * 0.25), // 北美
|
||||
(center.dx + radius * 0.3, center.dy + radius * 0.4, radius * 0.15, radius * 0.2), // 南美
|
||||
];
|
||||
|
||||
for (final cont in continents) {
|
||||
canvas.drawOval(
|
||||
Rect.fromLTWH(cont.$1 - cont.$3 / 2, cont.$2 - cont.$4 / 2, cont.$3, cont.$4),
|
||||
Paint()..color = landColor,
|
||||
);
|
||||
}
|
||||
|
||||
// 绘制极冰
|
||||
canvas.drawOval(
|
||||
Rect.fromLTWH(center.dx - radius * 0.15, center.dy - radius * 0.95, radius * 0.3, radius * 0.15),
|
||||
Paint()..color = iceColor,
|
||||
);
|
||||
canvas.drawOval(
|
||||
Rect.fromLTWH(center.dx - radius * 0.15, center.dy + radius * 0.8, radius * 0.3, radius * 0.15),
|
||||
Paint()..color = iceColor,
|
||||
);
|
||||
|
||||
// 绘制地轴
|
||||
if (showTilt) {
|
||||
final tiltAngle = 23.5 * math.pi / 180;
|
||||
final axisLength = radius * 1.4;
|
||||
final topY = center.dy - axisLength / 2;
|
||||
final bottomY = center.dy + axisLength / 2;
|
||||
final offsetX = math.sin(tiltAngle) * axisLength / 2;
|
||||
|
||||
canvas.drawLine(
|
||||
Offset(center.dx - offsetX, topY),
|
||||
Offset(center.dx + offsetX, bottomY),
|
||||
Paint()
|
||||
..color = axisColor
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke,
|
||||
);
|
||||
|
||||
// 北极标注
|
||||
if (showLabels) {
|
||||
final textPainter = TextPainter(
|
||||
text: const TextSpan(text: '北极', style: TextStyle(fontSize: 11, color: Color(0xFFFF6B35))),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(center.dx + offsetX + 10, topY - 5));
|
||||
}
|
||||
}
|
||||
|
||||
// 绘制晨昏线(昼夜分界)
|
||||
final sunAngle = animProgress * 2 * math.pi;
|
||||
final terminatorX = center.dx + math.cos(sunAngle) * radius * 0.3;
|
||||
|
||||
// 昼半球高光
|
||||
final dayPaint = Paint()
|
||||
..color = Colors.yellow.withOpacity(0.15)
|
||||
..style = PaintingStyle.fill;
|
||||
canvas.drawCircle(
|
||||
Offset(terminatorX + math.cos(sunAngle) * radius * 0.3, center.dy),
|
||||
radius * 0.9,
|
||||
dayPaint,
|
||||
);
|
||||
|
||||
// 标注直射点
|
||||
if (showLabels) {
|
||||
final subsolarX = center.dx + math.cos(sunAngle) * radius;
|
||||
final subsolarY = center.dy + math.sin(sunAngle * 0.3) * radius * 0.5;
|
||||
|
||||
// 太阳光线
|
||||
canvas.drawLine(
|
||||
Offset(subsolarX + math.cos(sunAngle) * 20, subsolarY + math.sin(sunAngle) * 20),
|
||||
Offset(subsolarX + math.cos(sunAngle) * 50, subsolarY + math.sin(sunAngle) * 50),
|
||||
Paint()
|
||||
..color = const Color(0xFFFFC24B)
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke,
|
||||
);
|
||||
|
||||
final textPainter = TextPainter(
|
||||
text: const TextSpan(text: '直射点', style: TextStyle(fontSize: 10, color: Color(0xFFFFC24B))),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(subsolarX + 15, subsolarY - 10));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _RotationPainter oldDelegate) {
|
||||
return oldDelegate.animProgress != animProgress ||
|
||||
oldDelegate.showLabels != showLabels ||
|
||||
oldDelegate.showTilt != showTilt;
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
import 'scale_model.dart';
|
||||
|
||||
class ScaleCalculatorModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'scale-calculator-flutter';
|
||||
@override
|
||||
String name() => '比例尺计算器 (Flutter)';
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的比例尺计算器';
|
||||
@override
|
||||
Widget buildView(BuildContext context) => const _ScaleCalculatorView();
|
||||
|
||||
List<ScalePreset> get presets => [
|
||||
ScalePreset(n: 10000, nameKey: 'preset.campus', noteKey: 'preset.campusNote'),
|
||||
ScalePreset(n: 50000, nameKey: 'preset.town', noteKey: 'preset.townNote'),
|
||||
ScalePreset(n: 250000, nameKey: 'preset.city', noteKey: 'preset.cityNote'),
|
||||
ScalePreset(n: 1000000, nameKey: 'preset.province', noteKey: 'preset.provinceNote'),
|
||||
ScalePreset(n: 10000000, nameKey: 'preset.china', noteKey: 'preset.chinaNote'),
|
||||
ScalePreset(n: 100000000, nameKey: 'preset.world', noteKey: 'preset.worldNote'),
|
||||
];
|
||||
|
||||
List<ScaleSpectrum> get spectrum => [
|
||||
ScaleSpectrum(n: 10000, labelKey: 'spec.campus', scopeKey: 'spec.campusScope'),
|
||||
ScaleSpectrum(n: 250000, labelKey: 'spec.city', scopeKey: 'spec.cityScope'),
|
||||
ScaleSpectrum(n: 10000000, labelKey: 'spec.china', scopeKey: 'spec.chinaScope'),
|
||||
ScaleSpectrum(n: 100000000, labelKey: 'spec.world', scopeKey: 'spec.worldScope'),
|
||||
];
|
||||
|
||||
List<Landmark> get landmarks => [
|
||||
Landmark(nameKey: 'lm.classroom', meters: 10),
|
||||
Landmark(nameKey: 'lm.track', meters: 400),
|
||||
Landmark(nameKey: 'lm.marathon', meters: 42195),
|
||||
Landmark(nameKey: 'lm.beijingShanghai', meters: 1080000),
|
||||
Landmark(nameKey: 'lm.equator', meters: 40000000),
|
||||
];
|
||||
}
|
||||
|
||||
class _ScaleCalculatorView extends StatefulWidget {
|
||||
const _ScaleCalculatorView();
|
||||
@override
|
||||
State<_ScaleCalculatorView> createState() => _ScaleCalculatorViewState();
|
||||
}
|
||||
|
||||
class _ScaleCalculatorViewState extends State<_ScaleCalculatorView> {
|
||||
String _mode = 'real';
|
||||
double _mapDist = 10;
|
||||
double _realDist = 100000;
|
||||
double _scaleN = 10000.0;
|
||||
String _unit = 'cm';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text('比例尺计算器', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: inkColor)),
|
||||
const Spacer(),
|
||||
_modeBtn('求实地距离', _mode == 'real'),
|
||||
_modeBtn('求图上距离', _mode == 'map'),
|
||||
_modeBtn('求比例尺', _mode == 'scale'),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _ScaleCanvas(
|
||||
mode: _mode,
|
||||
mapDist: _mapDist,
|
||||
realDist: _realDist,
|
||||
scaleN: _scaleN,
|
||||
unit: _unit,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
color: panelColor,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('已知量:', style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80))),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
decoration: const InputDecoration(labelText: '图上距离 (cm)'),
|
||||
keyboardType: TextInputType.number,
|
||||
onChanged: (v) => setState(() => _mapDist = double.tryParse(v) ?? 0),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
decoration: const InputDecoration(labelText: '比例尺 N'),
|
||||
keyboardType: TextInputType.number,
|
||||
onChanged: (v) => setState(() => _scaleN = double.tryParse(v) ?? 10000.0),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Text('结果:', style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80))),
|
||||
const SizedBox(width: 8),
|
||||
Text('实地距离 = ${(_mapDist * _scaleN / 100).toStringAsFixed(2)} m', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF4D8CFF))),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _modeBtn(String label, bool active) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 6),
|
||||
child: FilterChip(
|
||||
label: Text(label, style: const TextStyle(fontSize: 12)),
|
||||
selected: active,
|
||||
onSelected: (_) => setState(() => _mode = active ? 'real' : 'real'),
|
||||
selectedColor: const Color(0xFF4D8CFF).withOpacity(0.2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScaleCanvas extends StatelessWidget {
|
||||
final String mode;
|
||||
final double mapDist;
|
||||
final double realDist;
|
||||
final double scaleN;
|
||||
final String unit;
|
||||
|
||||
const _ScaleCanvas({required this.mode, required this.mapDist, required this.realDist, required this.scaleN, required this.unit});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _ScalePainter(mode: mode, mapDist: mapDist, realDist: realDist, scaleN: scaleN, unit: unit),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScalePainter extends CustomPainter {
|
||||
final String mode;
|
||||
final double mapDist;
|
||||
final double realDist;
|
||||
final double scaleN;
|
||||
final String unit;
|
||||
|
||||
_ScalePainter({required this.mode, required this.mapDist, required this.realDist, required this.scaleN, required this.unit});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final isDark = true;
|
||||
final bgColor = const Color(0xFF08111E);
|
||||
final barColor = const Color(0xFF4D8CFF);
|
||||
final inkColor = const Color(0xFFEAF2FF);
|
||||
|
||||
canvas.drawColor(bgColor, BlendMode.src);
|
||||
|
||||
final centerY = size.height / 2;
|
||||
final double barHeight = 40.0;
|
||||
final barY = centerY - barHeight / 2;
|
||||
final maxBarWidth = size.width * 0.8;
|
||||
final startX = (size.width - maxBarWidth) / 2;
|
||||
|
||||
// 绘制标尺
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(Rect.fromLTWH(startX, barY, maxBarWidth, barHeight), Radius.circular(4.0)),
|
||||
Paint()..color = barColor.withOpacity(0.2),
|
||||
);
|
||||
|
||||
// 刻度
|
||||
final double tickCount = 20.0;
|
||||
for (int i = 0; i <= tickCount; i++) {
|
||||
final x = startX + (maxBarWidth * i / tickCount);
|
||||
final double tickHeight = i % 5 == 0 ? 15.0 : 8.0;
|
||||
canvas.drawLine(
|
||||
Offset(x, barY + (barHeight - tickHeight) / 2),
|
||||
Offset(x, barY + (barHeight + tickHeight) / 2),
|
||||
Paint()
|
||||
..color = inkColor
|
||||
..strokeWidth = 1,
|
||||
);
|
||||
}
|
||||
|
||||
// 数值标注
|
||||
final textPainter = TextPainter(
|
||||
text: TextSpan(text: '1 : $scaleN', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF4D8CFF))),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(size.width / 2 - 40, barY + barHeight + 16));
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _ScalePainter oldDelegate) {
|
||||
return oldDelegate.mode != mode || oldDelegate.scaleN != scaleN;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 比例尺预设
|
||||
class ScalePreset {
|
||||
final int n;
|
||||
final String nameKey;
|
||||
final String noteKey;
|
||||
|
||||
ScalePreset({required this.n, required this.nameKey, required this.noteKey});
|
||||
}
|
||||
|
||||
/// 比例尺光谱
|
||||
class ScaleSpectrum {
|
||||
final int n;
|
||||
final String labelKey;
|
||||
final String scopeKey;
|
||||
|
||||
ScaleSpectrum({required this.n, required this.labelKey, required this.scopeKey});
|
||||
}
|
||||
|
||||
/// 真实地标
|
||||
class Landmark {
|
||||
final String nameKey;
|
||||
final double meters;
|
||||
|
||||
Landmark({required this.nameKey, required this.meters});
|
||||
}
|
||||
@@ -15,7 +15,9 @@ class UserRecord {
|
||||
});
|
||||
|
||||
final String username;
|
||||
final int points;
|
||||
|
||||
/// 积分,精确到 0.01
|
||||
final double points;
|
||||
|
||||
/// 连续签到天数(断签会重置)
|
||||
final int consecutiveDays;
|
||||
@@ -38,7 +40,7 @@ class UserRecord {
|
||||
final String? themeColor;
|
||||
|
||||
/// 当前这个颜色实际花了多少分
|
||||
final int themePaid;
|
||||
final double themePaid;
|
||||
|
||||
/// 退款窗口剩余秒数(0 表示没有可退的)
|
||||
final int refundSeconds;
|
||||
@@ -46,7 +48,7 @@ class UserRecord {
|
||||
factory UserRecord.fromJson(Map<String, dynamic> json) {
|
||||
return UserRecord(
|
||||
username: json['username'] as String? ?? '',
|
||||
points: (json['points'] as num?)?.toInt() ?? 0,
|
||||
points: (json['points'] as num?)?.toDouble() ?? 0,
|
||||
consecutiveDays: (json['consecutive_days'] as num?)?.toInt() ?? 0,
|
||||
cycleDay: (json['cycle_day'] as num?)?.toInt() ?? 1,
|
||||
cycleDays: (json['cycle_days'] as num?)?.toInt() ?? 30,
|
||||
@@ -54,7 +56,7 @@ class UserRecord {
|
||||
nextReward: (json['next_reward'] as num?)?.toInt() ?? 10,
|
||||
lastSignIn: json['last_sign_in'] as String?,
|
||||
themeColor: json['theme_color'] as String?,
|
||||
themePaid: (json['theme_paid'] as num?)?.toInt() ?? 0,
|
||||
themePaid: (json['theme_paid'] as num?)?.toDouble() ?? 0,
|
||||
refundSeconds: (json['refund_seconds'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
@@ -132,6 +134,14 @@ class ThemeColor {
|
||||
}
|
||||
}
|
||||
|
||||
/// 积分显示:整数不带小数位,小数保留到 0.01(去掉多余的 0)。
|
||||
String formatPoints(double v) {
|
||||
var s = v.toStringAsFixed(2);
|
||||
if (s.endsWith('.00')) return s.substring(0, s.length - 3);
|
||||
if (s.endsWith('0')) return s.substring(0, s.length - 1);
|
||||
return s;
|
||||
}
|
||||
|
||||
/// 人品值结果
|
||||
class FortuneResult {
|
||||
const FortuneResult(this.value, this.comment);
|
||||
|
||||
@@ -6,5 +6,4 @@ export 'pages/courseware.dart';
|
||||
export 'pages/download.dart';
|
||||
export 'pages/settings.dart';
|
||||
export 'pages/about.dart';
|
||||
export 'pages/treasure.dart';
|
||||
export 'pages/user_page.dart';
|
||||
@@ -89,6 +89,8 @@ class _HomePageViewState extends State<HomePageView> {
|
||||
Future<void> _launch(ModelInfo model) async {
|
||||
setState(() => _notice = null);
|
||||
try {
|
||||
// 模型窗口由后端用 Avalonia 打开(模型契约返回的是 Avalonia Control),
|
||||
// 前端只负责发这条指令并显示结果。
|
||||
final result = await widget.controller.api.launchModel(model.id);
|
||||
if (!mounted) return;
|
||||
setState(() => _notice = result.message);
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../i18n.dart';
|
||||
import '../models/base.dart';
|
||||
import '../models/lookup.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
/// 模型视图:在壳内直接渲染 Flutter 模型。
|
||||
///
|
||||
/// 以前「启动模型」是让后端另开一个 Avalonia 窗口;现在模型全部是 Flutter 实现,
|
||||
/// 直接换掉内容区即可 —— 不会多出一个窗口,也不用跨进程传状态。
|
||||
class ModelViewPage extends StatelessWidget {
|
||||
const ModelViewPage({
|
||||
super.key,
|
||||
required this.modelId,
|
||||
required this.onClose,
|
||||
});
|
||||
|
||||
final String modelId;
|
||||
final VoidCallback onClose;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final model = flutterModelFor(modelId);
|
||||
|
||||
if (model == null) {
|
||||
return Center(
|
||||
child: GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
T('model.missing'),
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
height: 1.35,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
GcHint(T('model.missingHint')),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
OutlinedButton(
|
||||
onPressed: onClose,
|
||||
child: Text(T('model.back')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
GcSpace.xxl,
|
||||
GcSpace.lg,
|
||||
GcSpace.xxl,
|
||||
GcSpace.sm,
|
||||
),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
OutlinedButton.icon(
|
||||
onPressed: onClose,
|
||||
icon: const Icon(Icons.arrow_back_rounded, size: 16),
|
||||
label: Text(T('model.back')),
|
||||
),
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
model.name(),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
model.description(),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(child: ClipRect(child: _body(model))),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(GcModel model) {
|
||||
// 模型视图自己管状态(动画、视角),换 id 时必须重建,不能复用 State
|
||||
return KeyedSubtree(
|
||||
key: ValueKey<String>(model.id),
|
||||
child: Builder(builder: (context) => model.buildView(context)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api_client.dart';
|
||||
@@ -248,8 +246,6 @@ class _SettingsPageViewState extends State<SettingsPageView> {
|
||||
}
|
||||
|
||||
Widget _appearanceCard(SettingsInfo settings) {
|
||||
final current =
|
||||
GcPalette.parseHex(settings.accentColor) ?? GcPalette.defaultAccent;
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -287,144 +283,11 @@ class _SettingsPageViewState extends State<SettingsPageView> {
|
||||
if (mounted) setState(() => _status = T('common.applied'));
|
||||
},
|
||||
),
|
||||
const SizedBox(height: GcSpace.xl),
|
||||
GcHint(T('set.accent.desc')),
|
||||
const SizedBox(height: GcSpace.md + 2),
|
||||
Wrap(
|
||||
spacing: GcSpace.sm + 2,
|
||||
runSpacing: GcSpace.sm + 2,
|
||||
children: <Widget>[
|
||||
for (final color in GcPalette.presets)
|
||||
_accentSwatch(color, current),
|
||||
_customAccentChip(),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(
|
||||
'${T('set.accent')}: ${GcPalette.toHex(current)}',
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _accentSwatch(Color color, Color current) {
|
||||
final selected = color.value == current.value;
|
||||
return Tooltip(
|
||||
message: GcPalette.toHex(color),
|
||||
child: GestureDetector(
|
||||
onTap: () => _applyAccent(GcPalette.toHex(color)),
|
||||
child: Container(
|
||||
width: 34,
|
||||
height: 34,
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(
|
||||
color: selected ? GcColors.ink : Colors.transparent,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
child: selected
|
||||
? Icon(
|
||||
Icons.check_rounded,
|
||||
size: 18,
|
||||
color: color.computeLuminance() > 0.42
|
||||
? const Color(0xFF0A1226)
|
||||
: Colors.white,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _customAccentChip() {
|
||||
return MouseRegion(
|
||||
cursor: SystemMouseCursors.click,
|
||||
child: GestureDetector(
|
||||
onTap: _pickCustomAccent,
|
||||
child: Container(
|
||||
height: 34,
|
||||
padding: const EdgeInsets.symmetric(horizontal: GcSpace.md),
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.surfaceAlt,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(color: GcColors.line),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Icon(Icons.colorize_rounded, size: 16, color: GcColors.faint),
|
||||
const SizedBox(width: GcSpace.xs + 2),
|
||||
Text(
|
||||
T('set.accent.custom'),
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.3,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickCustomAccent() async {
|
||||
final controller = TextEditingController(
|
||||
text: GcPalette.toHex(GcPalette.accent.value),
|
||||
);
|
||||
final hex = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: GcColors.surface,
|
||||
title: Text(T('set.accent.custom')),
|
||||
content: TextField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
style: Theme.of(context).textTheme.bodyLarge!.copyWith(fontSize: 13),
|
||||
decoration: InputDecoration(
|
||||
hintText: '#8FB6FF',
|
||||
helperText: T('set.accent.hexHint'),
|
||||
),
|
||||
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(T('common.cancel')),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||
child: Text(T('common.confirm')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
controller.dispose();
|
||||
if (hex != null) await _applyAccent(hex);
|
||||
}
|
||||
|
||||
Future<void> _applyAccent(String hex) async {
|
||||
final parsed = GcPalette.parseHex(hex);
|
||||
if (parsed == null) {
|
||||
if (mounted) setState(() => _status = T('set.accent.invalid'));
|
||||
return;
|
||||
}
|
||||
final normalized = GcPalette.toHex(parsed);
|
||||
GcPalette.apply(normalized); // 立即预览
|
||||
await widget.controller
|
||||
.saveSettings(SettingsPatch(accentColor: normalized));
|
||||
if (mounted) setState(() => _status = T('common.applied'));
|
||||
}
|
||||
|
||||
Widget _memoryCard(SettingsInfo settings) {
|
||||
return GcCard(
|
||||
child: Column(
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../controller.dart';
|
||||
import '../theme.dart';
|
||||
import '../i18n.dart';
|
||||
|
||||
/// 百宝箱页:今日人品、随机运势等小玩意。
|
||||
class TreasurePage extends StatefulWidget {
|
||||
const TreasurePage({super.key, required this.controller});
|
||||
|
||||
final ShellController controller;
|
||||
|
||||
@override
|
||||
State<TreasurePage> createState() => _TreasurePageState();
|
||||
}
|
||||
|
||||
class _TreasurePageState extends State<TreasurePage> {
|
||||
String _fortune = '';
|
||||
String _luckyColor = '';
|
||||
String _luckyNumber = '';
|
||||
bool _loading = false;
|
||||
final Random _rand = Random();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_refresh();
|
||||
}
|
||||
|
||||
void _refresh() {
|
||||
setState(() => _loading = true);
|
||||
// 模拟计算延迟
|
||||
Future.delayed(const Duration(milliseconds: 400), () {
|
||||
if (!mounted) return;
|
||||
final fortunes = <String>[
|
||||
'今日宜:尝试新事物,突破舒适区。',
|
||||
'运气不错,适合做重要的决定。',
|
||||
'财运旺盛,可能会有意外收获。',
|
||||
'人际和谐,适合合作与沟通。',
|
||||
'专注当下,好运自然来。',
|
||||
'保持乐观,今天会有好消息。',
|
||||
'灵感涌现,适合创作和思考。',
|
||||
'脚踏实地,一步一个脚印。',
|
||||
'贵人运旺,多与他人交流。',
|
||||
'健康第一,注意休息和锻炼。',
|
||||
];
|
||||
final colors = <String>[
|
||||
'红色', '蓝色', '绿色', '金色', '紫色', '橙色', '粉色', '青色',
|
||||
];
|
||||
setState(() {
|
||||
_fortune = fortunes[_rand.nextInt(fortunes.length)];
|
||||
_luckyColor = colors[_rand.nextInt(colors.length)];
|
||||
_luckyNumber = '${(_rand.nextInt(99)) + 1}';
|
||||
_loading = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: GcColors.appBg,
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 480),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
// 今日人品卡片
|
||||
GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Icon(
|
||||
Icons.star_rounded,
|
||||
size: 48,
|
||||
color: GcColors.accent,
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Text(
|
||||
T('treasure.fortuneTitle'),
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(
|
||||
_fortune,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
height: 1.5,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
// 幸运信息
|
||||
Wrap(
|
||||
spacing: GcSpace.md,
|
||||
runSpacing: GcSpace.md,
|
||||
children: <Widget>[
|
||||
_buildStatCard(
|
||||
icon: Icons.check_circle_outline_rounded,
|
||||
label: T('treasure.luckyColor'),
|
||||
value: _luckyColor,
|
||||
),
|
||||
_buildStatCard(
|
||||
icon: Icons.numbers_rounded,
|
||||
label: T('treasure.luckyNumber'),
|
||||
value: _luckyNumber,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.xl),
|
||||
// 刷新按钮
|
||||
FilledButton.icon(
|
||||
onPressed: _refresh,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||
label: Text(T('treasure.refresh')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatCard({
|
||||
required IconData icon,
|
||||
required String label,
|
||||
required String value,
|
||||
}) {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Icon(icon, size: 28, color: GcColors.accent),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(fontSize: 12, color: GcColors.muted),
|
||||
),
|
||||
const SizedBox(height: GcSpace.xs),
|
||||
Text(
|
||||
value,
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../controller.dart';
|
||||
@@ -41,8 +39,6 @@ class _UserPageState extends State<UserPage> {
|
||||
final _option2Ctrl = TextEditingController();
|
||||
String? _randomResult;
|
||||
|
||||
final _rand = Random();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -169,7 +165,7 @@ class _UserPageState extends State<UserPage> {
|
||||
_user = null;
|
||||
_fortune = null;
|
||||
});
|
||||
GcPalette.apply('#${ThemeColor.defaultHex}');
|
||||
GcPalette.accent.value = GcPalette.defaultAccent;
|
||||
_toast(T('user.logoutDone'));
|
||||
}
|
||||
|
||||
@@ -197,30 +193,60 @@ class _UserPageState extends State<UserPage> {
|
||||
|
||||
// ---------------------------------------------------------------- 人品值
|
||||
|
||||
void _rollFortune() {
|
||||
Future<void> _rollFortune() async {
|
||||
if (_user == null) {
|
||||
_toast(T('user.loginFirst'));
|
||||
return;
|
||||
}
|
||||
setState(() => _rolling = true);
|
||||
|
||||
// 短延时让数字有个「落定」的观感;每天不限次数
|
||||
Future<void>.delayed(const Duration(milliseconds: 260), () {
|
||||
try {
|
||||
// 服务端算随机数和价格:当天第一次免费,之后按当日次数阶梯计费
|
||||
final resp = await widget.controller.api.rollFortune();
|
||||
if (!mounted) return;
|
||||
final value = _rand.nextInt(101);
|
||||
final value = (resp['value'] as num?)?.toInt() ?? 0;
|
||||
final cost = (resp['cost'] as num?)?.toDouble() ?? 0;
|
||||
setState(() {
|
||||
_fortune = FortuneResult(value, FortuneResult.commentFor(value));
|
||||
_fortune = FortuneResult(value, resp['comment'] as String? ?? FortuneResult.commentFor(value));
|
||||
final payload = resp['user'] as Map<String, dynamic>?;
|
||||
if (payload != null) _user = UserRecord.fromJson(payload);
|
||||
_rolling = false;
|
||||
});
|
||||
});
|
||||
_toast(cost > 0 ? '本次消耗 ${formatPoints(cost)} 积分' : '今日首次免费');
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _rolling = false);
|
||||
_toast(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 二选一
|
||||
|
||||
void _pickRandom() {
|
||||
Future<void> _pickRandom() async {
|
||||
final a = _option1Ctrl.text.trim();
|
||||
final b = _option2Ctrl.text.trim();
|
||||
if (a.isEmpty || b.isEmpty) {
|
||||
_toast(T('user.fillOptions'));
|
||||
return;
|
||||
}
|
||||
setState(() => _randomResult = _rand.nextBool() ? a : b);
|
||||
if (_user == null) {
|
||||
_toast(T('user.loginFirst'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// 服务端随机 + 计费:当天第一次免费,之后每次 0.5 积分
|
||||
final resp = await widget.controller.api.pickOne(a, b);
|
||||
if (!mounted) return;
|
||||
final cost = (resp['cost'] as num?)?.toDouble() ?? 0;
|
||||
setState(() {
|
||||
_randomResult = resp['choice'] as String?;
|
||||
final payload = resp['user'] as Map<String, dynamic>?;
|
||||
if (payload != null) _user = UserRecord.fromJson(payload);
|
||||
});
|
||||
_toast(cost > 0 ? '本次消耗 ${formatPoints(cost)} 积分' : '今日首次免费');
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_toast(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 主题色
|
||||
@@ -412,7 +438,7 @@ class _UserPageState extends State<UserPage> {
|
||||
Text(
|
||||
user == null
|
||||
? T('user.loginHint')
|
||||
: '${T('user.points')} ${user.points} · '
|
||||
: '${T('user.points')} ${formatPoints(user.points)} · '
|
||||
'${T('user.days')} ${user.consecutiveDays}',
|
||||
style: TextStyle(color: GcColors.muted, fontSize: 13),
|
||||
),
|
||||
|
||||
@@ -20,7 +20,6 @@ const List<_NavItem> _navItems = <_NavItem>[
|
||||
_NavItem(Icons.download_rounded, 'nav.download'),
|
||||
_NavItem(Icons.tune_rounded, 'nav.settings'),
|
||||
_NavItem(Icons.info_outline_rounded, 'nav.about'),
|
||||
_NavItem(Icons.auto_awesome_rounded, 'nav.treasure'),
|
||||
_NavItem(Icons.person_rounded, 'nav.user'),
|
||||
];
|
||||
|
||||
@@ -148,8 +147,6 @@ class _ShellPageState extends State<ShellPage> {
|
||||
case 4:
|
||||
return AboutPageView(controller: controller);
|
||||
case 5:
|
||||
return TreasurePage(controller: controller);
|
||||
case 6:
|
||||
return UserPage(controller: controller);
|
||||
default:
|
||||
return HomePageView(controller: controller);
|
||||
|
||||
+11
-2
@@ -9,16 +9,25 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 界面与模型渲染都已迁到 Flutter,这里只剩纯服务代码:
|
||||
不再引用 Avalonia / MVVM / GC.ModelSdk -->
|
||||
<!-- 界面仍是 Flutter,但模型由 Avalonia 承载(模型契约返回 Avalonia Control),
|
||||
所以核心库需要 Avalonia + 模型 SDK,并把 GC-DRAW 的窗口一起编译进来。 -->
|
||||
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
|
||||
<Compile Remove="test\**\*.cs" />
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
<!-- 多语言表原先通过 Avalonia 的 avares:// 读取,改为嵌入资源 -->
|
||||
<EmbeddedResource Include="Assets\i18n\*.json"
|
||||
LogicalName="GC.Core.Assets.i18n.%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -13,6 +13,8 @@ public sealed class AppServices
|
||||
public IDownloadCenter Downloads { get; }
|
||||
public MemoryBudget Memory { get; }
|
||||
public IModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染(渲染在 Avalonia PlayerWindow)。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public IUpdateService Updates { get; }
|
||||
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
|
||||
@@ -32,6 +34,7 @@ public sealed class AppServices
|
||||
Sources = DownloadModule.Sources;
|
||||
Downloads = DownloadModule.Downloads;
|
||||
Memory = new MemoryBudget();
|
||||
ModelHost = new ModelHost(paths, Settings, Memory);
|
||||
Selector = DownloadModule.Selector;
|
||||
Updates = DownloadModule.Updates;
|
||||
LauncherUpdates = DownloadModule.LauncherUpdates;
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using GC.Models;
|
||||
using GC.ModelSdk;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
|
||||
/// 启动器对“场景 / 行星 / 节气”一无所知,只认契约。
|
||||
/// </summary>
|
||||
public sealed class ModelHost
|
||||
{
|
||||
public const int SupportedApiVersion = 1;
|
||||
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private readonly MemoryBudget _memory;
|
||||
|
||||
public ModelHost(AppPaths paths, SettingsService settings, MemoryBudget memory)
|
||||
{
|
||||
_paths = paths;
|
||||
_settings = settings;
|
||||
_memory = memory;
|
||||
}
|
||||
|
||||
/// <summary>同步加载(全部在 UI 线程,用于自检 / 命令行)。</summary>
|
||||
public LoadedModel Load(ModelPackage package, Action requestClose, Action<double, string?>? progress = null)
|
||||
{
|
||||
var session = CreateSession(package, requestClose, progress);
|
||||
try
|
||||
{
|
||||
session.Runtime.Prepare(session.Context);
|
||||
var view = session.Runtime.CreateView(session.Context)
|
||||
?? throw new InvalidOperationException("模型没有返回界面");
|
||||
return session.Complete(view);
|
||||
}
|
||||
catch
|
||||
{
|
||||
session.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步加载:数据准备放在后台线程(<see cref="IModelRuntime.Prepare"/>),
|
||||
/// 界面构建回到 UI 线程,进度通过 <paramref name="progress"/> 实时汇报。
|
||||
/// </summary>
|
||||
public async Task<LoadedModel> LoadAsync(ModelPackage package, Action requestClose,
|
||||
Action<double, string?>? progress = null)
|
||||
{
|
||||
var session = CreateSession(package, requestClose, progress);
|
||||
try
|
||||
{
|
||||
await Task.Run(() => session.Runtime.Prepare(session.Context)).ConfigureAwait(true);
|
||||
var view = session.Runtime.CreateView(session.Context)
|
||||
?? throw new InvalidOperationException("模型没有返回界面");
|
||||
return session.Complete(view);
|
||||
}
|
||||
catch
|
||||
{
|
||||
session.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? progress)
|
||||
{
|
||||
// ---- 契约协商 -------------------------------------------------------
|
||||
// 先做廉价检查:不满足就直接拒绝,避免加载了才发现不兼容。
|
||||
var declaredApi = package.Manifest.ApiVersion;
|
||||
if (declaredApi < 1)
|
||||
throw new InvalidOperationException($"模型清单的 apiVersion 非法: {declaredApi}");
|
||||
|
||||
if (declaredApi > SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"该模型需要更新的启动器(模型契约 v{declaredApi},当前支持 v{SupportedApiVersion})。" +
|
||||
"请先更新启动器,或让模型作者发布兼容版本。");
|
||||
|
||||
var minApp = package.Manifest.MinAppVersion;
|
||||
if (!string.IsNullOrWhiteSpace(minApp) &&
|
||||
CompareVersions(LauncherRuntimeInfo.CurrentLauncherVersion, minApp!) < 0)
|
||||
throw new InvalidOperationException(
|
||||
$"该模型要求启动器 ≥ v{minApp},当前为 v{LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||
|
||||
// ---- 完整性:dll 会被直接执行,加载前必须确认它没被改过 ----------------
|
||||
var integrity = ModelIntegrity.VerifyForLoad(package.Directory, package.Id);
|
||||
if (!integrity.Ok)
|
||||
{
|
||||
var message = $"模型完整性校验失败({package.Id}):{integrity.Message}。" +
|
||||
"请删除该模型目录让启动器重新下载。";
|
||||
if (Environment.GetEnvironmentVariable("GC_ALLOW_TAMPERED_MODELS") == "1")
|
||||
Console.Error.WriteLine("[warn] " + message + "(已按 GC_ALLOW_TAMPERED_MODELS 放行)");
|
||||
else
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
else if (!integrity.Present && Environment.GetEnvironmentVariable("GC_STRICT_MODELS") == "1")
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"模型缺少完整性记录({package.Id}),严格模式下拒绝加载");
|
||||
}
|
||||
|
||||
var assemblyPath = package.AssemblyPath;
|
||||
if (!File.Exists(assemblyPath))
|
||||
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
|
||||
|
||||
var directory = Path.GetDirectoryName(assemblyPath)!;
|
||||
var context = new ModelLoadContext(directory);
|
||||
try
|
||||
{
|
||||
var assembly = context.LoadFromAssemblyPath(assemblyPath);
|
||||
var type = ResolveFactoryType(assembly, package.Manifest.Type);
|
||||
if (type == null)
|
||||
throw new InvalidOperationException("模型程序集里没有找到 IModelFactory 实现");
|
||||
|
||||
if (Activator.CreateInstance(type) is not IModelFactory factory)
|
||||
throw new InvalidOperationException($"无法创建模型入口:{type.FullName}");
|
||||
|
||||
if (factory.ApiVersion != SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" +
|
||||
"请更新到匹配的版本");
|
||||
|
||||
var runtime = factory.Create();
|
||||
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
|
||||
return new Session(context, runtime, modelContext);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.Unload();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static Type? ResolveFactoryType(Assembly assembly, string? typeName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(typeName))
|
||||
{
|
||||
var exact = assembly.GetType(typeName!, throwOnError: false);
|
||||
if (exact != null) return exact;
|
||||
}
|
||||
|
||||
foreach (var type in assembly.GetTypes())
|
||||
{
|
||||
if (type.IsAbstract || type.IsInterface) continue;
|
||||
if (typeof(IModelFactory).IsAssignableFrom(type)) return type;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>比较 1.0.10 与 1.0.9 这类版本号(按数字段比较,不按字符串)。</summary>
|
||||
private static int CompareVersions(string left, string right)
|
||||
{
|
||||
static int[] Parts(string value)
|
||||
{
|
||||
var text = value.Trim().TrimStart('v', 'V');
|
||||
var pieces = text.Split('.');
|
||||
var numbers = new int[Math.Max(4, pieces.Length)];
|
||||
for (var i = 0; i < pieces.Length; i++)
|
||||
{
|
||||
var digits = new string(Array.FindAll(pieces[i].ToCharArray(), char.IsDigit));
|
||||
if (digits.Length > 6) digits = digits[..6];
|
||||
numbers[i] = int.TryParse(digits, out var n) ? n : 0;
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
|
||||
var a = Parts(left);
|
||||
var b = Parts(right);
|
||||
for (var i = 0; i < Math.Max(a.Length, b.Length); i++)
|
||||
{
|
||||
var x = i < a.Length ? a[i] : 0;
|
||||
var y = i < b.Length ? b[i] : 0;
|
||||
if (x != y) return x < y ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private sealed class Session : IDisposable
|
||||
{
|
||||
private readonly ModelLoadContext _context;
|
||||
|
||||
public Session(ModelLoadContext context, IModelRuntime runtime, ModelContext modelContext)
|
||||
{
|
||||
_context = context;
|
||||
Runtime = runtime;
|
||||
Context = modelContext;
|
||||
}
|
||||
|
||||
public IModelRuntime Runtime { get; }
|
||||
public ModelContext Context { get; }
|
||||
|
||||
public LoadedModel Complete(Control view) => new(_context, Runtime, view);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
|
||||
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>一次性模型实例:窗口关闭后释放视图、卸载程序集。</summary>
|
||||
public sealed class LoadedModel : IDisposable
|
||||
{
|
||||
private readonly ModelLoadContext _context;
|
||||
private readonly IModelRuntime _runtime;
|
||||
private bool _disposed;
|
||||
|
||||
public LoadedModel(ModelLoadContext context, IModelRuntime runtime, Control view)
|
||||
{
|
||||
_context = context;
|
||||
_runtime = runtime;
|
||||
View = view;
|
||||
}
|
||||
|
||||
public Control View { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
// 顺序:先释放视图(停计时器/Dispose 位图),再释放运行时,最后卸载程序集。
|
||||
// 否则视图里的事件订阅会继续持有 ALC 内的类型,collectible 上下文无法回收。
|
||||
try { (View as IDisposable)?.Dispose(); }
|
||||
catch (Exception ex) { Console.Error.WriteLine($"释放模型视图失败: {ex.Message}"); }
|
||||
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
|
||||
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型程序集加载上下文:契约与 Avalonia 一律回到默认上下文,保证类型一致。</summary>
|
||||
public sealed class ModelLoadContext : AssemblyLoadContext
|
||||
{
|
||||
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"GC.ModelSdk",
|
||||
"Avalonia",
|
||||
"Avalonia.Base",
|
||||
"Avalonia.Controls",
|
||||
"Avalonia.Desktop",
|
||||
"Avalonia.Skia",
|
||||
"Avalonia.Themes.Fluent",
|
||||
"SkiaSharp",
|
||||
"HarfBuzzSharp"
|
||||
};
|
||||
|
||||
private readonly string _directory;
|
||||
|
||||
public ModelLoadContext(string directory) : base("model:" + Path.GetFileName(directory), isCollectible: true)
|
||||
=> _directory = directory;
|
||||
|
||||
protected override Assembly? Load(AssemblyName assemblyName)
|
||||
{
|
||||
var name = assemblyName.Name;
|
||||
if (string.IsNullOrEmpty(name)) return null;
|
||||
if (Shared.Contains(name)) return null; // 用启动器已加载的那份
|
||||
if (name.StartsWith("System.", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
if (name is "System" or "netstandard" or "mscorlib") return null;
|
||||
|
||||
var candidate = Path.Combine(_directory, name + ".dll");
|
||||
return File.Exists(candidate) ? LoadFromAssemblyPath(candidate) : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>启动器提供给模型的环境。</summary>
|
||||
public sealed class ModelContext : IModelContext
|
||||
{
|
||||
private readonly Action _requestClose;
|
||||
private readonly Action<double, string?>? _progress;
|
||||
|
||||
public ModelContext(ModelPackage package, string language, int memoryMb, Action requestClose,
|
||||
Action<double, string?>? progress)
|
||||
{
|
||||
_progress = progress;
|
||||
ModelId = package.Id;
|
||||
ModelDirectory = package.Directory;
|
||||
DataDirectory = package.DataDirectory;
|
||||
Language = language;
|
||||
MemoryBudgetMb = memoryMb;
|
||||
_requestClose = requestClose;
|
||||
}
|
||||
|
||||
public string ModelId { get; }
|
||||
public string ModelDirectory { get; }
|
||||
public string DataDirectory { get; }
|
||||
public string Language { get; }
|
||||
public int MemoryBudgetMb { get; }
|
||||
|
||||
public void RequestClose() => _requestClose();
|
||||
|
||||
public void ReportProgress(double value, string? message = null) => _progress?.Invoke(value, message);
|
||||
|
||||
public void Log(string message) => Console.WriteLine(message);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
# GC 1.1.2 更新日志
|
||||
|
||||
**版本范围**:1.1.1 → 1.1.2
|
||||
**发布日期**:2026-11-21
|
||||
**规模**:18 个功能提交(含合并共 28 个),184 个文件,+15,556 / −15,135
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
这一版的核心是**把界面从 Avalonia 整体迁到 Flutter**,同时补上了账号体系与自动化发布链路。
|
||||
|
||||
- 全平台界面重写为 Flutter,模型不再另开窗口,直接在应用内渲染
|
||||
- 新增本地用户系统:注册登录(带人机验证)、每日签到、积分、主题色购买
|
||||
- 等高线课件以 WebView 形式完整离线内置
|
||||
- 新增 GitHub 镜像下载源,与 Xhmcl 并发测速自动择优
|
||||
- 新增 GitHub Actions:夜间构建、评论触发编译、PR 自动审查
|
||||
|
||||
---
|
||||
|
||||
## 新增功能
|
||||
|
||||
### 用户系统
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| 注册 / 登录 | 用户名唯一(1–20 字符、不含空格);密码只存 `sha512(密码 + 随机盐)`,不存明文 |
|
||||
| 人机验证 | 注册需回答算术题,5 分钟有效、一次性、答错作废 |
|
||||
| 每日签到 | 30 天一循环,断签重置连续天数 |
|
||||
| 积分 | 只能通过签到获得,**不提供任何充值渠道** |
|
||||
| 主题色 | 默认蓝免费,预置色 50 积分,自定义色 150 积分;购买后 1 小时内换色退 80% |
|
||||
| 人品值 | 0–100 随机 + 分档评语,每天不限次数,纯娱乐不影响积分 |
|
||||
| 二选一 | 填两个选项,随机帮你选一个 |
|
||||
|
||||
签到积分表:
|
||||
|
||||
| 连续天数 | 1–6 | 7 | 8–13 | 14 | 15–20 | 21 | 22–27 | 28 | 29 | 30 |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| 积分 | 10 | 30 | 15 | 40 | 20 | 50 | 25 | 60 | 40 | 100 |
|
||||
|
||||
数据落盘在 `.GC/user/`:
|
||||
|
||||
```
|
||||
.GC/user/user.yaml 当前登录(用户名 + 会话令牌),启动自动登录
|
||||
.GC/user/<用户名>/pw.yaml 用户名、积分、签到、主题色
|
||||
```
|
||||
|
||||
### 等高线课件
|
||||
|
||||
- 原课件的 HTML / JS / CSS / 图片 / 视频完整搬入 Flutter assets,**完全离线可用**
|
||||
- 用本地 HttpServer(支持 Range)承载,绕开 `file://` 与 CSP 限制
|
||||
- 侧栏新增「等高线课件」入口,后端未就绪也能打开
|
||||
|
||||
### 模型全面 Flutter 化
|
||||
|
||||
- **等高线地形图**:五大地貌(平原 / 丘陵 / 山地 / 高原 / 盆地),拖动旋转、滚轮缩放、法线光照、四周裙边侧壁
|
||||
- **四步实验动画**:等高切割 → 形成交线 → 垂直投影 → 疏密判坡,俯视 / 立体一键切换
|
||||
- **地球地理**:五带划分、七大洲轮廓、图层开关、回归线与极圈标注
|
||||
- **地球公转 / 自转**、**比例尺计算器**同步重写
|
||||
- 模型在内容区内嵌渲染,侧栏与标题栏保持可用,不再弹独立窗口
|
||||
|
||||
### 下载源
|
||||
|
||||
- 新增 GitHub 镜像源(`Morris-morris-cloud/GC`),与 Xhmcl 并发测速
|
||||
- 单源探测超时 **2 秒**,取最快且可用的源,结果缓存 3 分钟
|
||||
- 一个源不可用时自动切到另一个
|
||||
|
||||
### 自动化
|
||||
|
||||
| 工作流 | 触发 | 产出 |
|
||||
| --- | --- | --- |
|
||||
| `nightly-prerelease` | 每天 21:00(Asia/Shanghai) | 三平台编译,发布 `nightly` 预发布 |
|
||||
| `build-bot` | Issue/PR 评论 `@build-bot build <mac\|win-amd\|win-arm\|all>` | 发布 `ip-prerelease` 预发布 |
|
||||
| `build-release` | Issue/PR 评论 `@build-release-bot build <版本号>` | 发布正式 Release(带 `SHA256SUMS.txt`) |
|
||||
| `pr-review` | PR 新建 / 推送 | 检查能否编译、静态分析、合并冲突、是否落后 main |
|
||||
|
||||
---
|
||||
|
||||
## 改进
|
||||
|
||||
- **下载页**显示模型下载进度条,下载源读取速度明显提升
|
||||
- **关于页**新增「重新下载启动器」,下载后做 sha256 完整性校验
|
||||
- 标题栏支持最小化 / 最大化 / 关闭,颜色跟随主题
|
||||
- 修复浅色主题下标题栏不跟随主题色的问题
|
||||
- 主题色统一由账号决定,设置页不再单独设置颜色
|
||||
- 模型清单加载改为「内置默认 + i18n 文件覆盖」,此前完全忽略语言包
|
||||
- `GcLog` 日志保留天数 14 → 7 天
|
||||
- 后端端口扫描范围 10 → 30,端口被占用时更容易找到可用端口
|
||||
|
||||
---
|
||||
|
||||
## 修复
|
||||
|
||||
| 问题 | 原因 |
|
||||
| --- | --- |
|
||||
| macOS Release 版启动后「无法连接后端」 | `Release.entitlements` 缺 `network.client / network.server`,App Sandbox 拦掉了发往 127.0.0.1 的请求 |
|
||||
| macOS 点「启动模型」进程崩溃 | AppKit 要求 `NSApplication` 在主线程运行,此前在后建线程跑事件循环 |
|
||||
| 等高线渲染三处缺陷 | 等高线被切成虚线(`Chain()` 只向尾部延伸)、判坡整片红(坡度归一化写死)、切割只叠半透明板(山尖仍在) |
|
||||
| 模型安装可写到模型库外 | 模型 Id 未限制路径分隔符 / 绝对路径 / 符号链接 |
|
||||
| 本地目录源可被同机伪造后端利用 | 健康检查改为一次性会话令牌双向校验;包 URL 只允许 http(s) 公网地址,拦截 `file:` / 私有 IP / 环回 / 元数据地址 |
|
||||
| 多个源全部失败时报「已是最新」 | 改为明确输出错误,不再把失败当成功 |
|
||||
| macOS 部署目标过低 | 10.14 → 12.0,兼容新版 Xcode |
|
||||
| 仓库误提交构建产物与临时脚本 | 清理并补充 `.gitignore`(含 79MB 课件产物) |
|
||||
|
||||
---
|
||||
|
||||
## 移除 / 不兼容
|
||||
|
||||
- **Avalonia 整套界面与窗口宿主已移除**,模型只通过 Flutter 渲染
|
||||
- **百宝箱页面已删除**(今日人品等能力并入用户页)
|
||||
- **设置页的主题色选择已删除**,改用账号主题色
|
||||
- `.GC/user/<用户名>.yaml` 旧布局会在启动时**自动迁移**到 `<用户名>/pw.yaml`
|
||||
|
||||
---
|
||||
|
||||
## 升级说明
|
||||
|
||||
- **Windows**:`GCL-1.1.2-win-amd64.zip` / `GCL-1.1.2-win-arm64.zip`
|
||||
- **macOS**:`GCL-1.1.2-mac-arm64.zip`
|
||||
- macOS 包为 **ad-hoc 签名**(无开发者证书),首次打开需右键 →「打开」,或在「系统设置 → 隐私与安全性」里放行
|
||||
- 从 1.1.1 覆盖安装即可,`.GC/` 下的账号、模型、设置都会保留
|
||||
- 升级后每个包都会校验 sha256(来自已签名清单),不一致会拒绝安装
|
||||
|
||||
---
|
||||
|
||||
## 已知问题
|
||||
|
||||
- 主题色退款可被反复利用:买 A(−50)→ 退 40 → 净支出 10 分即可换一次色,1 小时内可连续操作。当前按「1 小时内退 80%」的规则实现,属预期行为
|
||||
- `nightly` / `ip-prerelease` 两个预发布的 tag 不是版本号,客户端升级逻辑会跳过它们,不会被误推给用户
|
||||
- CI 里**不会**重新生成 `version.json`(需要 SAVEDOG 签名私钥),发布清单仍需本地 `./build.sh stamp`
|
||||
|
||||
---
|
||||
|
||||
<details>
|
||||
<summary>提交清单(18 个)</summary>
|
||||
|
||||
```
|
||||
38781c9 refactor(ui): 删除百宝箱页;设置页去掉主题色
|
||||
ecb71ad feat(user): 用户系统重做——人机验证、30 天签到、主题色购买与退款、人品值
|
||||
e7c1429 feat(ci): 新增 @build-release-bot build <版本号>
|
||||
5b82a88 fix(build-bot): report job 加 GH_REPO;已合并 PR 改为编默认分支
|
||||
936ef83 fix: macOS 构建去掉 --no-codesign;build-bot 失败也回帖结果
|
||||
ab0cee8 ci: build-bot 增加「开始编译」回执;macOS runner 改用 macos-latest
|
||||
f64f270 ci: 修 pr-review 日志路径不一致导致「(无日志)」
|
||||
0d383f9 ci: 修正 pr-review 的冲突判断与静态分析阈值
|
||||
ea1fa6b feat: 全面迁移到 Flutter + 新增 GitHub 源与 CI 流水线
|
||||
b9cb56c fix: 清理误提交的构建产物和临时脚本,补充 .gitignore
|
||||
2640de0 build: macOS 发布包编译完成
|
||||
4872505 feat: rewrite all models in Flutter
|
||||
9cd4fa6 fix: 修复 15 项优化与 bug
|
||||
46ed844 fix(security): 加固模型安装与本地目录源,防止同机后端伪装
|
||||
355ca89 feat(courseware): Flutter WebView 还原等高线课件并去除授权验证
|
||||
5b62897 feat(contour-map): 重写为可交互 3D 等高线模型,新增五大地貌专题
|
||||
ead63e8 fix(macos): 模型窗口改由主线程承载,修复启动模型失败与后端崩溃
|
||||
3efdf74 fix(macos): Release 版补 network 权限,修复启动后无法连接后端
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -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/<id></c>。</summary>
|
||||
string ModelDirectory { get; }
|
||||
|
||||
/// <summary>模型数据目录:<c>model/<id>/<id>.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);
|
||||
}
|
||||
@@ -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/<lang>.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;
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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"
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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,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>
|
||||
@@ -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,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,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,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 }
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user