Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4043ed5e72 | ||
|
|
46ed84475d | ||
|
|
1dd3b40cb6 | ||
|
|
355ca89a68 | ||
|
|
4ef291568a | ||
|
|
5b628971a9 | ||
|
|
faaee9abe2 | ||
|
|
ead63e8ffe | ||
|
|
01c2d017c6 | ||
|
|
3efdf74258 |
No files matched your search
@@ -38,10 +38,20 @@ internal static class FlutterShell
|
|||||||
var uiPath = FindUi(dir);
|
var uiPath = FindUi(dir);
|
||||||
if (uiPath == null) return false;
|
if (uiPath == null) return false;
|
||||||
|
|
||||||
var port = Port;
|
// 本次会话的一次性令牌:进程内后端与 Flutter 前端都从这里拿到同一个值。
|
||||||
|
// 只有我们拉起的后端才持有它,同机其他进程伪造的健康响应过不了 IsHealthy 的身份校验。
|
||||||
|
// 允许外部预设(自动化测试 / 高级部署固定令牌),未预设才现场生成随机值。
|
||||||
|
var token = Environment.GetEnvironmentVariable(Services.GcUiContract.TokenEnvVar);
|
||||||
|
if (string.IsNullOrEmpty(token)) token = Services.GcUiContract.NewSessionToken();
|
||||||
|
Environment.SetEnvironmentVariable(Services.GcUiContract.TokenEnvVar, token);
|
||||||
|
|
||||||
// 用户可能重复启动:已有后端在跑就直接复用,退出时也不要关掉别人的进程。
|
var port = Port;
|
||||||
if (!IsHealthy(port))
|
AvaloniaHost? uiHost = null;
|
||||||
|
|
||||||
|
// 用户可能重复启动:只有当端口上已有一个「持有同一令牌」的后端时才复用。
|
||||||
|
// 同机其他程序即便占端口并返回 200,也没有令牌,会被 IsHealthy 拒绝,
|
||||||
|
// 于是我们改到下一个端口起自己的后端,绝不把前端交给伪装服务。
|
||||||
|
if (!IsHealthy(port, token))
|
||||||
{
|
{
|
||||||
// 端口可能被别的程序占用:17890 起向后试几个,选第一个能起来且健康的。
|
// 端口可能被别的程序占用:17890 起向后试几个,选第一个能起来且健康的。
|
||||||
var start = Environment.GetEnvironmentVariable(Services.GcUiContract.PortEnvVar) is { Length: > 0 }
|
var start = Environment.GetEnvironmentVariable(Services.GcUiContract.PortEnvVar) is { Length: > 0 }
|
||||||
@@ -50,13 +60,14 @@ internal static class FlutterShell
|
|||||||
|
|
||||||
for (var candidate = start; candidate < start + Services.GcUiContract.PortScanRange; candidate++)
|
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 (app == null) continue;
|
||||||
|
|
||||||
if (WaitHealthy(candidate, TimeSpan.FromSeconds(25)))
|
if (WaitHealthy(candidate, token, TimeSpan.FromSeconds(25)))
|
||||||
{
|
{
|
||||||
port = candidate;
|
port = candidate;
|
||||||
_backend = app;
|
_backend = app;
|
||||||
|
uiHost = host;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +79,7 @@ internal static class FlutterShell
|
|||||||
|
|
||||||
AppDomain.CurrentDomain.ProcessExit += (_, _) => StopBackend(_backend);
|
AppDomain.CurrentDomain.ProcessExit += (_, _) => StopBackend(_backend);
|
||||||
|
|
||||||
var ui = Start(uiPath, dir, port);
|
var ui = Start(uiPath, dir, port, token);
|
||||||
if (ui == null)
|
if (ui == null)
|
||||||
{
|
{
|
||||||
StopBackend(_backend);
|
StopBackend(_backend);
|
||||||
@@ -76,7 +87,29 @@ internal static class FlutterShell
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
ui.WaitForExit();
|
// 前端窗口已拉起。模型窗口由 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);
|
StopBackend(_backend);
|
||||||
_backend = null;
|
_backend = null;
|
||||||
return true;
|
return true;
|
||||||
@@ -108,11 +141,14 @@ internal static class FlutterShell
|
|||||||
// ---------------------------------------------------------------- 进程管理
|
// ---------------------------------------------------------------- 进程管理
|
||||||
|
|
||||||
/// <summary>在本进程内启动后端;端口被占用等失败情况返回 null。</summary>
|
/// <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
|
try
|
||||||
{
|
{
|
||||||
var app = BackendServer.Start(args, port);
|
var app = BackendServer.Start(args, port, out var host);
|
||||||
|
uiHost = host;
|
||||||
app.StartAsync().GetAwaiter().GetResult();
|
app.StartAsync().GetAwaiter().GetResult();
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
@@ -137,7 +173,7 @@ internal static class FlutterShell
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Process Start(string fileName, string workingDirectory, int port)
|
private static Process Start(string fileName, string workingDirectory, int port, string token)
|
||||||
{
|
{
|
||||||
var info = new ProcessStartInfo(fileName)
|
var info = new ProcessStartInfo(fileName)
|
||||||
{
|
{
|
||||||
@@ -147,6 +183,8 @@ internal static class FlutterShell
|
|||||||
|
|
||||||
// 把实际端口传给前端:它读这个环境变量拼 baseUrl,换端口不需要重新编译界面。
|
// 把实际端口传给前端:它读这个环境变量拼 baseUrl,换端口不需要重新编译界面。
|
||||||
info.Environment[Services.GcUiContract.PortEnvVar] = port.ToString();
|
info.Environment[Services.GcUiContract.PortEnvVar] = port.ToString();
|
||||||
|
// 同一个会话令牌也交给前端,作为每个 /api 请求的身份凭证。
|
||||||
|
info.Environment[Services.GcUiContract.TokenEnvVar] = token;
|
||||||
|
|
||||||
// macOS .app 内的二进制也需要可执行位;发布包由 zip 解开时可能丢失。
|
// macOS .app 内的二进制也需要可执行位;发布包由 zip 解开时可能丢失。
|
||||||
if (!OperatingSystem.IsWindows())
|
if (!OperatingSystem.IsWindows())
|
||||||
@@ -160,13 +198,27 @@ internal static class FlutterShell
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- 健康检查
|
// ---------------------------------------------------------------- 健康检查
|
||||||
|
|
||||||
private static bool IsHealthy(int port)
|
/// <summary>
|
||||||
|
/// 健康探测必须带本次会话令牌:后端校验通过才说明这是「我们拉起的那个后端」。
|
||||||
|
/// 同机伪装进程即使返回 HTTP 200,也因为没有令牌而拿不到 200(后端会 401),
|
||||||
|
/// 但这里额外再比对响应体里的密钥指纹,双保险——即便对方原样回一个 200 也骗不过。
|
||||||
|
/// </summary>
|
||||||
|
private static bool IsHealthy(int port, string token)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var response = Http.GetAsync($"http://127.0.0.1:{port}/api/health")
|
using var request = new HttpRequestMessage(HttpMethod.Get, $"http://127.0.0.1:{port}/api/health");
|
||||||
.GetAwaiter().GetResult();
|
request.Headers.TryAddWithoutValidation(Services.GcUiContract.TokenHeader, token);
|
||||||
return response.IsSuccessStatusCode;
|
using var response = Http.Send(request);
|
||||||
|
if (!response.IsSuccessStatusCode) return false;
|
||||||
|
|
||||||
|
// 状态码 200 还不够:伪装进程可能盲回一个 200。真正的后端会用会话令牌
|
||||||
|
// 派生指纹填进 health 响应,这里比对指纹确认对方确实持有同一个令牌。
|
||||||
|
var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||||
|
using var json = System.Text.Json.JsonDocument.Parse(body);
|
||||||
|
var proof = json.RootElement.TryGetProperty("sessionProof", out var p) ? p.GetString() : null;
|
||||||
|
var expected = Services.GcUiContract.DeriveSessionProof(token);
|
||||||
|
return string.Equals(proof, expected, StringComparison.OrdinalIgnoreCase);
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -174,12 +226,12 @@ internal static class FlutterShell
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool WaitHealthy(int port, TimeSpan timeout)
|
private static bool WaitHealthy(int port, string token, TimeSpan timeout)
|
||||||
{
|
{
|
||||||
var deadline = DateTime.UtcNow + timeout;
|
var deadline = DateTime.UtcNow + timeout;
|
||||||
while (DateTime.UtcNow < deadline)
|
while (DateTime.UtcNow < deadline)
|
||||||
{
|
{
|
||||||
if (IsHealthy(port)) return true;
|
if (IsHealthy(port, token)) return true;
|
||||||
Thread.Sleep(250);
|
Thread.Sleep(250);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
using System.Net.Sockets;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
@@ -29,10 +32,14 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
var file = File.Exists(primary) ? primary : fallback;
|
var file = File.Exists(primary) ? primary : fallback;
|
||||||
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
||||||
|
|
||||||
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的
|
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的。
|
||||||
|
// 验签结论随 version.SignatureTrust 一起上送,由 UpdateService 按策略裁决;
|
||||||
|
// 这里至少要把失败如实记下来,不能静默丢弃(与其他远程源行为一致)。
|
||||||
var text = File.ReadAllText(file);
|
var text = File.ReadAllText(file);
|
||||||
_rawManifest = text;
|
_rawManifest = text;
|
||||||
var version = ManifestLoader.Parse(text, out _);
|
var version = ManifestLoader.Parse(text, out var verification);
|
||||||
|
if (verification.Trust is ManifestTrust.Invalid or ManifestTrust.Unsigned)
|
||||||
|
Console.Error.WriteLine($"[directory] 清单验签失败({verification.Trust}): {verification.Error}");
|
||||||
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||||
_launcherVersion = version.Launcher.Version.Trim();
|
_launcherVersion = version.Launcher.Version.Trim();
|
||||||
return Task.FromResult(version);
|
return Task.FromResult(version);
|
||||||
@@ -57,6 +64,8 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
if (depth > 8) return;
|
if (depth > 8) return;
|
||||||
foreach (var sub in Directory.GetDirectories(dir))
|
foreach (var sub in Directory.GetDirectories(dir))
|
||||||
{
|
{
|
||||||
|
// 符号链接目录可能指向根目录之外:既不递归进去,也不作为条目暴露。
|
||||||
|
if (IsReparsePoint(sub)) continue;
|
||||||
var name = Path.GetFileName(sub);
|
var name = Path.GetFileName(sub);
|
||||||
if (name.StartsWith('.')) continue;
|
if (name.StartsWith('.')) continue;
|
||||||
var rel = Relative(baseDir, sub);
|
var rel = Relative(baseDir, sub);
|
||||||
@@ -71,6 +80,7 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
}
|
}
|
||||||
foreach (var file in Directory.GetFiles(dir))
|
foreach (var file in Directory.GetFiles(dir))
|
||||||
{
|
{
|
||||||
|
if (IsReparsePoint(file)) continue;
|
||||||
var name = Path.GetFileName(file);
|
var name = Path.GetFileName(file);
|
||||||
if (name.StartsWith('.')) continue;
|
if (name.StartsWith('.')) continue;
|
||||||
result.Add(new RepoEntry
|
result.Add(new RepoEntry
|
||||||
@@ -106,16 +116,81 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
|
|
||||||
var url = package.Url;
|
var url = package.Url;
|
||||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
|
||||||
|
// 清单里的 URL 属于外部输入,必须约束来源:
|
||||||
|
// · file:// 和绝对路径只允许读 _root 之内,杜绝任意本地文件读取;
|
||||||
|
// · 网络 URL 仅允许 http(s),且目标不能是环回/私有/链路本地/元数据地址,防 SSRF。
|
||||||
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
|
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
|
||||||
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
|
{
|
||||||
if (Path.IsPathRooted(url) && File.Exists(url))
|
var local = new Uri(url).LocalPath;
|
||||||
return await File.ReadAllBytesAsync(url, ct);
|
return await File.ReadAllBytesAsync(SafePath(Path.GetRelativePath(_root, local)), ct);
|
||||||
if (Uri.TryCreate(url, UriKind.Absolute, out _))
|
}
|
||||||
|
if (Path.IsPathRooted(url))
|
||||||
|
{
|
||||||
|
if (File.Exists(url)) return await File.ReadAllBytesAsync(SafePath(Path.GetRelativePath(_root, url)), ct);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (IsAllowedHttpUrl(url))
|
||||||
return await Http.GetByteArrayAsync(url, ct);
|
return await Http.GetByteArrayAsync(url, ct);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 仅允许 http/https:挡住 file: 导致的任意本地文件读取和 gopher: 之类的协议滥用。
|
||||||
|
/// IP 字面量直接判公网;主机名(清单里的正常发布 URL)允许,但拒绝 localhost 与
|
||||||
|
/// 常见本地后缀,避免指向本机。域名解析到内网的情况由 HttpClient 侧的实际连接地址
|
||||||
|
/// 兜底——本地目录源的主路径本就是本地文件,网络只是兜底。
|
||||||
|
/// </summary>
|
||||||
|
private static bool IsAllowedHttpUrl(string url)
|
||||||
|
{
|
||||||
|
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) return false;
|
||||||
|
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||||
|
|
||||||
|
if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6)
|
||||||
|
return IsPublicAddress(uri.Host);
|
||||||
|
|
||||||
|
var host = uri.Host;
|
||||||
|
if (string.IsNullOrEmpty(host)) return false;
|
||||||
|
if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
|
// 仅允许含点、且各段是字母数字/连字符的常规域名;拒绝 .local/.internal 等本地域。
|
||||||
|
if (host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
host.EndsWith(".internal", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return false;
|
||||||
|
foreach (var label in host.Split('.'))
|
||||||
|
if (label.Length == 0 || label[0] == '-' || label[^1] == '-' ||
|
||||||
|
!label.All(c => char.IsAsciiLetterOrDigit(c) || c == '-'))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsPublicAddress(string host)
|
||||||
|
{
|
||||||
|
if (!IPAddress.TryParse(host, out var ip)) return false;
|
||||||
|
if (IPAddress.IsLoopback(ip) || IPAddress.Any.Equals(ip) || IPAddress.IPv6Any.Equals(ip)) return false;
|
||||||
|
|
||||||
|
if (ip.AddressFamily == AddressFamily.InterNetwork)
|
||||||
|
{
|
||||||
|
var b = ip.GetAddressBytes();
|
||||||
|
if (b[0] == 10 || b[0] == 127 || b[0] == 0) return false; // 私有 / 环回 / 本网
|
||||||
|
if (b[0] == 169 && b[1] == 254) return false; // 链路本地 / 云元数据
|
||||||
|
if (b[0] == 172 && b[1] >= 16 && b[1] <= 31) return false; // 私有
|
||||||
|
if (b[0] == 192 && b[1] == 168) return false; // 私有
|
||||||
|
if (b[0] == 100 && b[1] >= 64 && b[1] <= 127) return false; // CGNAT (IPv4 共享地址)
|
||||||
|
if (b[0] == 192 && b[1] == 0) return false; // IETF 协议分配
|
||||||
|
if (b[0] == 198 && (b[1] == 18 || b[1] == 19)) return false; // 基准测试
|
||||||
|
if (b[0] >= 224) return false; // 组播 / 保留
|
||||||
|
}
|
||||||
|
else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
|
||||||
|
{
|
||||||
|
if (ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6Multicast) return false;
|
||||||
|
var b = ip.GetAddressBytes();
|
||||||
|
if (b[0] == 0xfd || b[0] == 0xfc) return false; // 唯一本地地址
|
||||||
|
if (ip.IsIPv4MappedToIPv6) return IsPublicAddress(ip.MapToIPv4().ToString());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>在 dist/<系统>-<架构>/ 里找这个平台的启动器包;找不到返回 null。</summary>
|
/// <summary>在 dist/<系统>-<架构>/ 里找这个平台的启动器包;找不到返回 null。</summary>
|
||||||
private string? FindInDist(RepoPackage package)
|
private string? FindInDist(RepoPackage package)
|
||||||
{
|
{
|
||||||
@@ -137,6 +212,7 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>把相对路径解析成 _root 内的真实路径:拒绝越界,且逐级拒绝符号链接。</summary>
|
||||||
private string SafePath(string relative)
|
private string SafePath(string relative)
|
||||||
{
|
{
|
||||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||||
@@ -144,9 +220,38 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
|
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
|
||||||
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||||
throw new InvalidOperationException($"路径越界: {relative}");
|
throw new InvalidOperationException($"路径越界: {relative}");
|
||||||
|
|
||||||
|
// 词法校验之后还要解析符号链接:root 内的链接可能指向根目录之外。
|
||||||
|
// 逐级检查 _root 到 full 的每一段,任何重解析点都直接拒绝。
|
||||||
|
var rel = Path.GetRelativePath(_root, full);
|
||||||
|
if (rel != "." && rel != "")
|
||||||
|
{
|
||||||
|
var cursor = _root;
|
||||||
|
foreach (var segment in rel.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries))
|
||||||
|
{
|
||||||
|
if (segment == "..") throw new InvalidOperationException($"路径越界: {relative}");
|
||||||
|
cursor = Path.Combine(cursor, segment);
|
||||||
|
if (IsReparsePoint(cursor))
|
||||||
|
throw new InvalidOperationException($"路径含符号链接,已拒绝: {relative}");
|
||||||
|
}
|
||||||
|
}
|
||||||
return full;
|
return full;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool IsReparsePoint(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!File.Exists(path) && !Directory.Exists(path)) return false;
|
||||||
|
return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 取不到属性时按不可信处理,避免绕过符号链接检查。
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static string Relative(string baseDir, string file) =>
|
private static string Relative(string baseDir, string file) =>
|
||||||
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
|
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using GC.Models;
|
using GC.Models;
|
||||||
@@ -8,17 +9,43 @@ namespace GC.Services;
|
|||||||
|
|
||||||
public static class ModelInstaller
|
public static class ModelInstaller
|
||||||
{
|
{
|
||||||
|
// 与后端 /api/models/{id} 的白名单保持一致:单段名称,首字符必须字母或数字。
|
||||||
|
// 拒绝 . / .. / 路径分隔符 / 盘符 / 绝对路径,杜绝把 model.Id 当成路径来用。
|
||||||
|
private static readonly Regex SafeId = new(
|
||||||
|
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.Compiled);
|
||||||
|
|
||||||
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
|
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
|
||||||
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
|
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
|
||||||
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
|
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var target = Path.Combine(modelRoot, model.Id);
|
ArgumentNullException.ThrowIfNull(model);
|
||||||
var staging = target + ".installing";
|
if (string.IsNullOrWhiteSpace(modelRoot))
|
||||||
|
throw new InvalidOperationException("模型根目录未配置");
|
||||||
|
|
||||||
|
// ---- 1. 模型标识必须是单段安全名称,且解析后仍在模型根目录内 ----
|
||||||
|
var target = SafeChildPath(modelRoot, model.Id);
|
||||||
|
var rootFull = Path.GetFullPath(modelRoot);
|
||||||
|
var staging = VerifyUnderRoot(target + ".installing", rootFull);
|
||||||
|
var backup = VerifyUnderRoot(target + ".old", rootFull);
|
||||||
|
|
||||||
|
// ---- 2. 源目录与三个目标路径都不能是符号链接/重解析点 ----
|
||||||
|
EnsureNoLink(model.Directory);
|
||||||
|
foreach (var p in new[] { target, staging, backup }) EnsureNoLink(p);
|
||||||
|
|
||||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||||
Directory.CreateDirectory(staging);
|
Directory.CreateDirectory(staging);
|
||||||
|
|
||||||
|
// 枚举时跳过符号链接/重解析点:源目录里若有人放了指向外部的链接,
|
||||||
|
// 绝不能顺着它把模型库外的文件读进来。
|
||||||
|
var enumeration = new EnumerationOptions
|
||||||
|
{
|
||||||
|
RecurseSubdirectories = true,
|
||||||
|
AttributesToSkip = FileAttributes.ReparsePoint,
|
||||||
|
IgnoreInaccessible = false
|
||||||
|
};
|
||||||
|
var files = Directory.GetFiles(model.Directory, "*", enumeration);
|
||||||
|
|
||||||
long total = 0;
|
long total = 0;
|
||||||
var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories);
|
|
||||||
foreach (var file in files)
|
foreach (var file in files)
|
||||||
{
|
{
|
||||||
try { total += new FileInfo(file).Length; } catch { }
|
try { total += new FileInfo(file).Length; } catch { }
|
||||||
@@ -32,11 +59,7 @@ public static class ModelInstaller
|
|||||||
ct.ThrowIfCancellationRequested();
|
ct.ThrowIfCancellationRequested();
|
||||||
var relative = Path.GetRelativePath(model.Directory, file);
|
var relative = Path.GetRelativePath(model.Directory, file);
|
||||||
// 路径穿越防护:相对路径必须完整落在 staging 目录内
|
// 路径穿越防护:相对路径必须完整落在 staging 目录内
|
||||||
var dest = Path.GetFullPath(Path.Combine(staging, relative));
|
var dest = VerifyUnderRoot(Path.Combine(staging, relative), Path.GetFullPath(staging));
|
||||||
var stagingFull = Path.GetFullPath(staging)
|
|
||||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
|
||||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
|
||||||
throw new InvalidOperationException($"非法的模型文件路径: {relative}");
|
|
||||||
var destDir = Path.GetDirectoryName(dest);
|
var destDir = Path.GetDirectoryName(dest);
|
||||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||||
|
|
||||||
@@ -52,7 +75,6 @@ public static class ModelInstaller
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
|
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
|
||||||
var backup = target + ".old";
|
|
||||||
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
||||||
var hasBackup = false;
|
var hasBackup = false;
|
||||||
try
|
try
|
||||||
@@ -85,4 +107,36 @@ public static class ModelInstaller
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>把 id 限定为单段安全名称,并确认拼出来的路径仍在 root 内。</summary>
|
||||||
|
private static string SafeChildPath(string root, string? id)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(id) ||
|
||||||
|
id == "." || id == ".." ||
|
||||||
|
id.IndexOfAny(new[] { '/', '\\', ':' }) >= 0 ||
|
||||||
|
Path.IsPathRooted(id) ||
|
||||||
|
!SafeId.IsMatch(id))
|
||||||
|
throw new InvalidOperationException($"非法的模型标识: {id}");
|
||||||
|
|
||||||
|
var rootFull = Path.GetFullPath(root);
|
||||||
|
return VerifyUnderRoot(Path.Combine(rootFull, id), rootFull);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>解析绝对路径并确认 candidate 位于 root 之内。</summary>
|
||||||
|
private static string VerifyUnderRoot(string candidate, string rootFull)
|
||||||
|
{
|
||||||
|
var full = Path.GetFullPath(candidate);
|
||||||
|
var prefix = rootFull.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||||
|
if (!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||||
|
throw new InvalidOperationException($"路径越界: {candidate}");
|
||||||
|
return full;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>拒绝符号链接 / junction / 重解析点,避免顺着链接写到模型库外。</summary>
|
||||||
|
private static void EnsureNoLink(string path)
|
||||||
|
{
|
||||||
|
if (!File.Exists(path) && !Directory.Exists(path)) return;
|
||||||
|
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
|
||||||
|
throw new InvalidOperationException($"拒绝符号链接路径: {path}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,8 @@ public sealed record HealthDto(
|
|||||||
string Version,
|
string Version,
|
||||||
string Platform,
|
string Platform,
|
||||||
bool UiAvailable,
|
bool UiAvailable,
|
||||||
string? UiError);
|
string? UiError,
|
||||||
|
string? SessionProof = null);
|
||||||
|
|
||||||
public sealed record ModelDto(
|
public sealed record ModelDto(
|
||||||
string Id,
|
string Id,
|
||||||
|
|||||||
@@ -29,7 +29,9 @@ public sealed class AvaloniaHost
|
|||||||
private readonly AppServices _services;
|
private readonly AppServices _services;
|
||||||
private readonly object _gate = new();
|
private readonly object _gate = new();
|
||||||
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
|
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private Task<bool>? _startTask;
|
private readonly TaskCompletionSource<bool> _ready =
|
||||||
|
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
private int _started;
|
||||||
|
|
||||||
public AvaloniaHost(AppServices services) => _services = services;
|
public AvaloniaHost(AppServices services) => _services = services;
|
||||||
|
|
||||||
@@ -37,56 +39,60 @@ public sealed class AvaloniaHost
|
|||||||
|
|
||||||
public string? LastError { get; private set; }
|
public string? LastError { get; private set; }
|
||||||
|
|
||||||
public Task<bool> EnsureStartedAsync()
|
/// <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()
|
||||||
{
|
{
|
||||||
lock (_gate)
|
if (Interlocked.Exchange(ref _started, 1) == 1) return;
|
||||||
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
_startTask ??= Task.Run(StartCore);
|
AppBuilder.Configure<HostApp>()
|
||||||
return _startTask;
|
.UsePlatformDetect()
|
||||||
|
.AfterSetup(_ =>
|
||||||
|
{
|
||||||
|
IsAvailable = true;
|
||||||
|
_ready.TrySetResult(true);
|
||||||
|
})
|
||||||
|
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 无桌面会话(CI / 无头环境):模型窗口不可用,但后端其余接口照常。
|
||||||
|
LastError = ex.Message;
|
||||||
|
_ready.TrySetResult(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool StartCore()
|
/// <summary>从任意线程请求结束事件循环,使 <see cref="RunOnCurrentThread"/> 返回。</summary>
|
||||||
|
public void Shutdown()
|
||||||
{
|
{
|
||||||
var ready = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
if (_started == 0) return;
|
||||||
|
try
|
||||||
var thread = new Thread(() =>
|
|
||||||
{
|
{
|
||||||
try
|
Dispatcher.UIThread.Post(() =>
|
||||||
{
|
{
|
||||||
AppBuilder.Configure<HostApp>()
|
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||||
.UsePlatformDetect()
|
desktop.Shutdown();
|
||||||
.AfterSetup(_ => ready.TrySetResult(true))
|
});
|
||||||
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
LastError = ex.Message;
|
|
||||||
ready.TrySetResult(false);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
{
|
|
||||||
IsBackground = true,
|
|
||||||
Name = "gc-ui-avalonia"
|
|
||||||
};
|
|
||||||
|
|
||||||
// Windows 上 Avalonia 需要 STA 线程;macOS / Linux 不支持也不必要。
|
|
||||||
if (OperatingSystem.IsWindows())
|
|
||||||
{
|
|
||||||
try { thread.SetApartmentState(ApartmentState.STA); }
|
|
||||||
catch { /* 忽略:部分运行时不允许设置 */ }
|
|
||||||
}
|
}
|
||||||
|
catch
|
||||||
thread.Start();
|
|
||||||
|
|
||||||
if (!ready.Task.Wait(TimeSpan.FromSeconds(30)))
|
|
||||||
{
|
{
|
||||||
LastError = "图形环境初始化超时";
|
// 事件循环尚未建立或已退出:无需处理
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
IsAvailable = ready.Task.Result;
|
|
||||||
return IsAvailable;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
||||||
|
|||||||
@@ -30,19 +30,33 @@ public static class BackendServer
|
|||||||
{
|
{
|
||||||
/// <summary>按命令行 / GC_UI_PORT 解析端口并构建(未启动)的后端。</summary>
|
/// <summary>按命令行 / GC_UI_PORT 解析端口并构建(未启动)的后端。</summary>
|
||||||
public static WebApplication StartFromCommandLine(string[] args)
|
public static WebApplication StartFromCommandLine(string[] args)
|
||||||
=> Start(args, ResolvePort(args));
|
=> Start(args, ResolvePort(args), out _);
|
||||||
|
|
||||||
|
/// <summary>同上,并交出模型窗口宿主(独立进程入口用:主线程留给 Avalonia)。</summary>
|
||||||
|
public static WebApplication StartFromCommandLine(string[] args, out AvaloniaHost uiHost)
|
||||||
|
=> Start(args, ResolvePort(args), out uiHost);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
|
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
|
||||||
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
|
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static WebApplication Start(string[] args, int port)
|
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 的做法一致。
|
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
||||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||||
|
|
||||||
var services = AppServices.Create();
|
var services = AppServices.Create();
|
||||||
var uiHost = new AvaloniaHost(services);
|
var host = new AvaloniaHost(services);
|
||||||
|
uiHost = host;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
||||||
builder.Logging.ClearProviders();
|
builder.Logging.ClearProviders();
|
||||||
@@ -155,14 +169,44 @@ public static class BackendServer
|
|||||||
await next();
|
await next();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 会话令牌校验:启动器拉起时经 GC_UI_TOKEN 注入一次性令牌,前端每个 /api 请求
|
||||||
|
// 都必须带回。这样同机其他进程即使占了端口、伪造 /api/health 返回 200,也过不了
|
||||||
|
// 这一关——它拿不到令牌。独立进程 / 调试模式未设置令牌时放行,保持兼容。
|
||||||
|
var sessionToken = Environment.GetEnvironmentVariable(GcUiContract.TokenEnvVar);
|
||||||
|
if (!string.IsNullOrEmpty(sessionToken))
|
||||||
|
{
|
||||||
|
var expected = System.Text.Encoding.UTF8.GetBytes(sessionToken);
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
if (context.Request.Path.StartsWithSegments("/api"))
|
||||||
|
{
|
||||||
|
// 正常请求从请求头取;封面图由 Image.network 发起、无法加自定义头,
|
||||||
|
// 用同名 query 参数携带(GET 只读资源,参数不会落到日志正文)。
|
||||||
|
var supplied = context.Request.Headers[GcUiContract.TokenHeader].ToString();
|
||||||
|
if (string.IsNullOrEmpty(supplied))
|
||||||
|
supplied = context.Request.Query[GcUiContract.TokenHeader].ToString();
|
||||||
|
var actual = System.Text.Encoding.UTF8.GetBytes(supplied);
|
||||||
|
// 长度不等时 CryptographicOperations 仍安全比较,但先比对长度省一次分支泄漏。
|
||||||
|
if (actual.Length != expected.Length ||
|
||||||
|
!System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(actual, expected))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// ---- 健康检查 -------------------------------------------------------------
|
// ---- 健康检查 -------------------------------------------------------------
|
||||||
|
|
||||||
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||||||
true,
|
true,
|
||||||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
LauncherRuntimeInfo.CurrentRid,
|
LauncherRuntimeInfo.CurrentRid,
|
||||||
uiHost.IsAvailable,
|
host.IsAvailable,
|
||||||
uiHost.LastError)));
|
host.LastError,
|
||||||
|
GcUiContract.DeriveSessionProof(sessionToken))));
|
||||||
|
|
||||||
// ---- 已安装模型 -----------------------------------------------------------
|
// ---- 已安装模型 -----------------------------------------------------------
|
||||||
|
|
||||||
@@ -190,7 +234,7 @@ public static class BackendServer
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
services.Memory.Refresh();
|
services.Memory.Refresh();
|
||||||
var message = await uiHost.LaunchAsync(package);
|
var message = await host.LaunchAsync(package);
|
||||||
return Results.Ok(new LaunchResultDto(true, message));
|
return Results.Ok(new LaunchResultDto(true, message));
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
|||||||
@@ -1,6 +1,22 @@
|
|||||||
using GC.UI.Server;
|
using GC.UI.Server;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
// 独立进程入口:`GC.UI.Server --port 17890`
|
// 独立进程入口:`GC.UI.Server --port 17890`
|
||||||
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
|
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
|
||||||
var app = BackendServer.StartFromCommandLine(args);
|
var app = BackendServer.StartFromCommandLine(args, out var host);
|
||||||
app.Run();
|
|
||||||
|
// 模型窗口由 Avalonia 承载,macOS 的 AppKit 要求 NSApplication 在主线程。
|
||||||
|
// 所以后端交给 Kestrel 自己的线程池在后台跑,主线程留给 Avalonia 事件循环。
|
||||||
|
app.StartAsync().GetAwaiter().GetResult();
|
||||||
|
host.RunOnCurrentThread();
|
||||||
|
|
||||||
|
if (host.IsAvailable)
|
||||||
|
{
|
||||||
|
// 事件循环结束 → 收尾后端
|
||||||
|
app.StopAsync().GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 无图形环境(无头调试):退化为纯后端常驻
|
||||||
|
app.WaitForShutdown();
|
||||||
|
}
|
||||||
@@ -0,0 +1,663 @@
|
|||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const STEP_COPY = [
|
||||||
|
{ title: "等高切割", description: "观察水平面与山体在同一海拔相交,形成连续闭合线。" },
|
||||||
|
{ title: "形成交线", description: "每个水平切面都会留下同高交线,多层交线共同描述山体起伏。" },
|
||||||
|
{ title: "投影成图", description: "把各高度交线垂直投影到同一平面,得到完整等高线地形图。" },
|
||||||
|
{ title: "疏密判坡", description: "等高线越密,坡度越陡;等高线越疏,坡度越缓。" }
|
||||||
|
];
|
||||||
|
|
||||||
|
const DEFAULT_VIEW = {
|
||||||
|
title: "实验流程",
|
||||||
|
summary: "点击开始实验,在当前背景中观察等高切割与交线形成,再通过右侧图解理解垂直投影和疏密判坡。",
|
||||||
|
features: ["同一条等高线上海拔相等", "相邻等高线高差保持一致"],
|
||||||
|
hint: "点击“开始实验”,直接在当前画面播放形成交线视频"
|
||||||
|
};
|
||||||
|
|
||||||
|
const LANDFORMS = {
|
||||||
|
peak: {
|
||||||
|
name: "山峰",
|
||||||
|
subtitle: "闭合等高线",
|
||||||
|
image: "assets/peak-3d.jpg",
|
||||||
|
topImage: "assets/peak-top.jpg",
|
||||||
|
alt: "山峰立体示意图,蓝色等高线围绕山体逐级闭合",
|
||||||
|
topAlt: "山峰真实俯视图,多层近同心闭合等高线向中心收缩",
|
||||||
|
summary: "山峰四周较低、中心突起;等高线闭合成环,海拔数值由外向内逐渐升高。",
|
||||||
|
features: ["中心海拔高、四周海拔低", "闭合线越向内,数值越大", "若数值向内降低,则应判为洼地"],
|
||||||
|
hint: "山峰:闭合曲线,数值向中心升高"
|
||||||
|
},
|
||||||
|
ridge: {
|
||||||
|
name: "山脊",
|
||||||
|
subtitle: "凸低为脊",
|
||||||
|
image: "assets/ridge-3d.jpg",
|
||||||
|
topImage: "assets/ridge-top.jpg",
|
||||||
|
alt: "山脊立体示意图,蓝色等高线沿凸出的脊线向低处弯曲",
|
||||||
|
topAlt: "山脊真实俯视图,等高线沿狭长高地呈舌状延伸",
|
||||||
|
summary: "等高线弯曲部分向海拔低处凸出,脊线常成为两侧水系的分水岭。",
|
||||||
|
features: ["等高线凸向低值方向", "脊线由高处向低处延伸", "雨水沿脊线两侧分流"],
|
||||||
|
hint: "山脊:等高线向低处凸出,凸低为脊"
|
||||||
|
},
|
||||||
|
valley: {
|
||||||
|
name: "山谷",
|
||||||
|
subtitle: "凸高为谷",
|
||||||
|
image: "assets/valley-3d.jpg",
|
||||||
|
topImage: "assets/valley-top.jpg",
|
||||||
|
alt: "山谷立体示意图,两座山体之间的谷地有河流穿过",
|
||||||
|
topAlt: "山谷真实俯视图,两侧坡面夹持低槽,等高线形成 V 形凹入",
|
||||||
|
summary: "等高线弯曲部分向海拔高处凸出,谷底低洼并容易汇水形成河流。",
|
||||||
|
features: ["等高线凸向高值方向", "V 形尖端指向上游高处", "谷底常发育河流"],
|
||||||
|
hint: "山谷:等高线向高处凸出,凸高为谷"
|
||||||
|
},
|
||||||
|
saddle: {
|
||||||
|
name: "鞍部",
|
||||||
|
subtitle: "两峰之间",
|
||||||
|
image: "assets/saddle-3d.jpg",
|
||||||
|
topImage: "assets/saddle-top.jpg",
|
||||||
|
alt: "鞍部立体示意图,两座山峰之间形成马鞍状低地",
|
||||||
|
topAlt: "鞍部真实俯视图,两组峰顶闭合圈之间的等高线明显收腰",
|
||||||
|
summary: "鞍部位于相邻两座山峰之间,是沿山脊方向相对低洼的过渡地带。",
|
||||||
|
features: ["两组闭合等高线相邻", "中部线条收窄,形似马鞍", "常是翻越山岭的低垭口"],
|
||||||
|
hint: "鞍部:两峰之间相对低洼,俯视轮廓呈收腰形"
|
||||||
|
},
|
||||||
|
cliff: {
|
||||||
|
name: "陡崖",
|
||||||
|
subtitle: "密集或重合",
|
||||||
|
image: "assets/cliff-3d.jpg",
|
||||||
|
topImage: "assets/cliff-top.jpg",
|
||||||
|
alt: "陡崖立体示意图,崖壁处蓝色等高线高度密集",
|
||||||
|
topAlt: "陡崖真实俯视图,崖壁处大量等高线极密集并近似重合",
|
||||||
|
summary: "陡崖坡面近直立,不同高程的等高线会高度密集,局部可投影到同一位置而重合。",
|
||||||
|
features: ["密集表示陡坡,重合才是陡崖特征", "单位水平距离内高差很大", "n 条线重合时:(n−1)d ≤ ΔH < (n+1)d"],
|
||||||
|
hint: "陡崖:等高线密集或重合,坡度极陡"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const dom = {
|
||||||
|
app: document.getElementById("app-shell"),
|
||||||
|
experimentVideo: document.getElementById("experiment-video"),
|
||||||
|
densityBackground: document.getElementById("density-background"),
|
||||||
|
landformImage: document.getElementById("landform-image"),
|
||||||
|
landformTopImage: document.getElementById("landform-top-image"),
|
||||||
|
projectionDiagram: document.getElementById("projection-diagram"),
|
||||||
|
densityDiagram: document.getElementById("density-diagram"),
|
||||||
|
mediaLoading: document.getElementById("media-loading"),
|
||||||
|
mediaLabelKicker: document.getElementById("media-label-kicker"),
|
||||||
|
mediaLabelTitle: document.getElementById("media-label-title"),
|
||||||
|
mediaLabelCopy: document.getElementById("media-label-copy"),
|
||||||
|
progress: document.getElementById("video-progress-fill"),
|
||||||
|
playButton: document.getElementById("play-button"),
|
||||||
|
playIcon: document.getElementById("play-icon"),
|
||||||
|
playLabel: document.getElementById("play-label"),
|
||||||
|
resetButton: document.getElementById("reset-button"),
|
||||||
|
fullscreenButton: document.getElementById("fullscreen-button"),
|
||||||
|
fullscreenLabel: document.getElementById("fullscreen-label"),
|
||||||
|
workflowOpen: document.getElementById("workflow-open"),
|
||||||
|
flowSteps: Array.from(document.querySelectorAll(".flow-step[data-step]")),
|
||||||
|
flowCount: document.getElementById("flow-count"),
|
||||||
|
flowLineFill: document.getElementById("flow-line-fill"),
|
||||||
|
taskTitle: document.getElementById("task-title"),
|
||||||
|
taskDescription: document.getElementById("task-description"),
|
||||||
|
terrainTabs: Array.from(document.querySelectorAll(".terrain-tab[data-landform]")),
|
||||||
|
returnExperiment: document.getElementById("return-experiment"),
|
||||||
|
observationHeading: document.getElementById("observation-heading"),
|
||||||
|
observationSummary: document.getElementById("observation-summary"),
|
||||||
|
featureList: document.getElementById("feature-list"),
|
||||||
|
topViewToggle: document.getElementById("top-view-toggle"),
|
||||||
|
topViewToggleLabel: document.getElementById("top-view-toggle-label"),
|
||||||
|
topViewToggleHint: document.getElementById("top-view-toggle-hint"),
|
||||||
|
topViewThumbnail: document.getElementById("top-view-thumbnail"),
|
||||||
|
hintText: document.getElementById("hint-text"),
|
||||||
|
controlPanel: document.querySelector(".control-panel"),
|
||||||
|
panelClose: document.getElementById("panel-close"),
|
||||||
|
panelOpen: document.getElementById("panel-open"),
|
||||||
|
toast: document.getElementById("toast")
|
||||||
|
};
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
selectedLandform: null,
|
||||||
|
pendingLandform: null,
|
||||||
|
viewMode: "perspective",
|
||||||
|
step: 0,
|
||||||
|
imageToken: 0,
|
||||||
|
scanTimer: 0,
|
||||||
|
annotationTimer: 0,
|
||||||
|
toastTimer: 0,
|
||||||
|
pendingStep: null,
|
||||||
|
workflowTimer: 0,
|
||||||
|
workflowRunToken: 0,
|
||||||
|
workflowAutoPlaying: false
|
||||||
|
};
|
||||||
|
|
||||||
|
const ICONS = {
|
||||||
|
play: '<svg viewBox="0 0 24 24"><path d="m9 6 9 6-9 6V6Z"/></svg>',
|
||||||
|
pause: '<svg viewBox="0 0 24 24"><path d="M7 6h4v12H7V6Zm6 0h4v12h-4V6Z"/></svg>'
|
||||||
|
};
|
||||||
|
|
||||||
|
function showToast(message) {
|
||||||
|
window.clearTimeout(state.toastTimer);
|
||||||
|
dom.toast.textContent = message;
|
||||||
|
dom.toast.classList.add("is-visible");
|
||||||
|
state.toastTimer = window.setTimeout(function () {
|
||||||
|
dom.toast.classList.remove("is-visible");
|
||||||
|
}, 2600);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideLoading() {
|
||||||
|
dom.mediaLoading.classList.add("is-hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelWorkflowSequence() {
|
||||||
|
window.clearTimeout(state.workflowTimer);
|
||||||
|
state.workflowTimer = 0;
|
||||||
|
state.workflowRunToken += 1;
|
||||||
|
state.workflowAutoPlaying = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setWorkflowDiagram(element, active) {
|
||||||
|
element.toggleAttribute("hidden", !active);
|
||||||
|
element.classList.toggle("is-active", active);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideWorkflowVisuals() {
|
||||||
|
setWorkflowDiagram(dom.projectionDiagram, false);
|
||||||
|
setWorkflowDiagram(dom.densityDiagram, false);
|
||||||
|
dom.densityBackground.classList.remove("is-visible");
|
||||||
|
dom.app.classList.remove("has-workflow-visual");
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncWorkflowPresentation(index) {
|
||||||
|
const safeIndex = Math.max(0, Math.min(3, Number(index) || 0));
|
||||||
|
const isExperiment = !state.selectedLandform;
|
||||||
|
const showProjection = isExperiment && safeIndex === 2;
|
||||||
|
const showDensity = isExperiment && safeIndex === 3;
|
||||||
|
const densityWasVisible = dom.densityBackground.classList.contains("is-visible");
|
||||||
|
setWorkflowDiagram(dom.projectionDiagram, showProjection);
|
||||||
|
setWorkflowDiagram(dom.densityDiagram, showDensity);
|
||||||
|
dom.densityBackground.classList.toggle("is-visible", showDensity);
|
||||||
|
dom.app.classList.toggle("has-workflow-visual", showProjection || showDensity);
|
||||||
|
if (isExperiment) dom.experimentVideo.classList.toggle("is-visible", !showDensity);
|
||||||
|
if (showDensity && !densityWasVisible) triggerScan(dom.densityBackground);
|
||||||
|
}
|
||||||
|
|
||||||
|
function beginStaticWorkflowSequence() {
|
||||||
|
cancelWorkflowSequence();
|
||||||
|
const token = state.workflowRunToken;
|
||||||
|
state.workflowAutoPlaying = true;
|
||||||
|
renderStep(2);
|
||||||
|
setPlayButton();
|
||||||
|
dom.hintText.textContent = "自动演示:" + STEP_COPY[2].description;
|
||||||
|
state.workflowTimer = window.setTimeout(function () {
|
||||||
|
if (token !== state.workflowRunToken) return;
|
||||||
|
renderStep(3);
|
||||||
|
dom.hintText.textContent = "自动演示:" + STEP_COPY[3].description;
|
||||||
|
state.workflowTimer = window.setTimeout(function () {
|
||||||
|
if (token !== state.workflowRunToken) return;
|
||||||
|
state.workflowTimer = 0;
|
||||||
|
state.workflowAutoPlaying = false;
|
||||||
|
setPlayButton();
|
||||||
|
dom.hintText.textContent = "实验流程播放完成 · 可重新实验或选择典型地貌观察";
|
||||||
|
}, 3600);
|
||||||
|
}, 3200);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderStep(index) {
|
||||||
|
const safeIndex = Math.max(0, Math.min(3, Number(index) || 0));
|
||||||
|
state.step = safeIndex;
|
||||||
|
const copy = STEP_COPY[safeIndex];
|
||||||
|
dom.flowCount.textContent = (safeIndex + 1) + "/4";
|
||||||
|
dom.flowLineFill.style.width = (safeIndex / 3) * 100 + "%";
|
||||||
|
dom.taskTitle.textContent = copy.title;
|
||||||
|
dom.taskDescription.textContent = copy.description;
|
||||||
|
dom.flowSteps.forEach(function (button, buttonIndex) {
|
||||||
|
button.classList.toggle("is-active", buttonIndex === safeIndex);
|
||||||
|
button.classList.toggle("is-complete", buttonIndex < safeIndex);
|
||||||
|
button.setAttribute("aria-current", buttonIndex === safeIndex ? "step" : "false");
|
||||||
|
});
|
||||||
|
syncWorkflowPresentation(safeIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderObservation(view) {
|
||||||
|
dom.observationHeading.textContent = view.name || view.title;
|
||||||
|
dom.observationSummary.textContent = view.summary;
|
||||||
|
dom.featureList.replaceChildren();
|
||||||
|
view.features.forEach(function (feature) {
|
||||||
|
const item = document.createElement("li");
|
||||||
|
item.textContent = feature;
|
||||||
|
dom.featureList.appendChild(item);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPlayButton() {
|
||||||
|
const duration = dom.experimentVideo.duration;
|
||||||
|
const finished = dom.experimentVideo.ended || (Number.isFinite(duration) && duration > 0 && dom.experimentVideo.currentTime >= duration - 0.08);
|
||||||
|
if (!dom.experimentVideo.paused) {
|
||||||
|
dom.playLabel.textContent = "暂停实验";
|
||||||
|
dom.playIcon.innerHTML = ICONS.pause;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dom.playIcon.innerHTML = ICONS.play;
|
||||||
|
if (!state.selectedLandform && state.step >= 2) {
|
||||||
|
dom.playLabel.textContent = "重新实验";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (finished) dom.playLabel.textContent = "重新实验";
|
||||||
|
else if (dom.experimentVideo.currentTime > 0.12) dom.playLabel.textContent = "继续实验";
|
||||||
|
else dom.playLabel.textContent = "开始实验";
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateMediaLabel(view) {
|
||||||
|
if (view) {
|
||||||
|
dom.mediaLabelKicker.textContent = state.viewMode === "top" ? "典型地貌 · 真实俯视图" : "典型地貌 · 立体示意";
|
||||||
|
dom.mediaLabelTitle.textContent = view.name;
|
||||||
|
dom.mediaLabelCopy.textContent = state.viewMode === "top" ? view.subtitle + "|" + view.summary : view.summary;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dom.mediaLabelKicker.textContent = "实验流程";
|
||||||
|
dom.mediaLabelTitle.textContent = "形成交线与垂直投影";
|
||||||
|
dom.mediaLabelCopy.textContent = dom.experimentVideo.paused
|
||||||
|
? "点击“开始实验”,直接在当前画面播放形成交线视频"
|
||||||
|
: STEP_COPY[state.step].description;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateViewToggle() {
|
||||||
|
const view = LANDFORMS[state.selectedLandform];
|
||||||
|
const hasLandform = Boolean(view);
|
||||||
|
const isTopView = hasLandform && state.viewMode === "top";
|
||||||
|
dom.topViewToggle.disabled = !hasLandform;
|
||||||
|
dom.topViewToggle.classList.toggle("is-active", isTopView);
|
||||||
|
dom.topViewToggle.setAttribute("aria-pressed", String(isTopView));
|
||||||
|
dom.topViewToggleLabel.textContent = isTopView ? "立体图" : "俯视图";
|
||||||
|
dom.topViewToggleHint.textContent = hasLandform ? "点击切换" : "选择地貌后切换";
|
||||||
|
dom.topViewToggle.setAttribute(
|
||||||
|
"aria-label",
|
||||||
|
hasLandform ? "切换为" + (isTopView ? "立体图" : "俯视图") : "请先选择一种典型地貌"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!view) {
|
||||||
|
dom.topViewThumbnail.hidden = true;
|
||||||
|
dom.topViewThumbnail.removeAttribute("src");
|
||||||
|
dom.topViewThumbnail.alt = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dom.topViewThumbnail.src = isTopView ? view.image : view.topImage;
|
||||||
|
dom.topViewThumbnail.alt = isTopView ? view.name + "立体图预览" : view.name + "真实俯视图预览";
|
||||||
|
dom.topViewThumbnail.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function triggerScan(targetImage) {
|
||||||
|
window.clearTimeout(state.scanTimer);
|
||||||
|
dom.app.classList.remove("is-scanning");
|
||||||
|
dom.densityBackground.classList.remove("is-revealing");
|
||||||
|
dom.landformImage.classList.remove("is-revealing");
|
||||||
|
dom.landformTopImage.classList.remove("is-revealing");
|
||||||
|
void dom.app.offsetWidth;
|
||||||
|
dom.app.classList.add("is-scanning");
|
||||||
|
(targetImage || (state.viewMode === "top" ? dom.landformTopImage : dom.landformImage)).classList.add("is-revealing");
|
||||||
|
state.scanTimer = window.setTimeout(function () {
|
||||||
|
dom.app.classList.remove("is-scanning");
|
||||||
|
dom.densityBackground.classList.remove("is-revealing");
|
||||||
|
dom.landformImage.classList.remove("is-revealing");
|
||||||
|
dom.landformTopImage.classList.remove("is-revealing");
|
||||||
|
}, 1220);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function decodeImage(image) {
|
||||||
|
if (typeof image.decode === "function") {
|
||||||
|
await image.decode();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!image.complete) {
|
||||||
|
await new Promise(function (resolve, reject) {
|
||||||
|
image.addEventListener("load", resolve, { once: true });
|
||||||
|
image.addEventListener("error", reject, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideTerrainAnnotation() {
|
||||||
|
window.clearTimeout(state.annotationTimer);
|
||||||
|
dom.app.classList.remove("is-landform");
|
||||||
|
if (window.TerrainAnnotation) window.TerrainAnnotation.hide();
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearTerrainAnnotationNow() {
|
||||||
|
window.clearTimeout(state.annotationTimer);
|
||||||
|
state.annotationTimer = 0;
|
||||||
|
if (window.TerrainAnnotation) window.TerrainAnnotation.hide(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleTerrainAnnotation(withScan) {
|
||||||
|
window.clearTimeout(state.annotationTimer);
|
||||||
|
dom.app.classList.add("is-landform");
|
||||||
|
state.annotationTimer = window.setTimeout(function () {
|
||||||
|
if (!state.selectedLandform || !window.TerrainAnnotation) return;
|
||||||
|
window.TerrainAnnotation.show(state.selectedLandform, state.viewMode);
|
||||||
|
}, withScan ? 420 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyLandformView(view, withScan) {
|
||||||
|
const isTopView = state.viewMode === "top";
|
||||||
|
hideWorkflowVisuals();
|
||||||
|
dom.experimentVideo.classList.remove("is-visible");
|
||||||
|
dom.landformImage.classList.toggle("is-visible", !isTopView);
|
||||||
|
dom.landformTopImage.classList.toggle("is-visible", isTopView);
|
||||||
|
updateMediaLabel(view);
|
||||||
|
updateViewToggle();
|
||||||
|
dom.hintText.textContent = isTopView
|
||||||
|
? view.name + "俯视图:" + view.hint.replace(view.name + ":", "")
|
||||||
|
: view.hint;
|
||||||
|
if (withScan) triggerScan();
|
||||||
|
scheduleTerrainAnnotation(withScan);
|
||||||
|
}
|
||||||
|
|
||||||
|
function collapsePanelForCompactView() {
|
||||||
|
if (!window.matchMedia("(max-width: 680px)").matches) return;
|
||||||
|
dom.controlPanel.classList.add("is-collapsed");
|
||||||
|
dom.panelOpen.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function selectLandform(key) {
|
||||||
|
const view = LANDFORMS[key];
|
||||||
|
if (!view) return;
|
||||||
|
const token = ++state.imageToken;
|
||||||
|
cancelWorkflowSequence();
|
||||||
|
state.pendingLandform = key;
|
||||||
|
clearTerrainAnnotationNow();
|
||||||
|
hideWorkflowVisuals();
|
||||||
|
const nextMode = state.selectedLandform ? state.viewMode : "perspective";
|
||||||
|
dom.experimentVideo.pause();
|
||||||
|
const perspectiveProbe = new Image();
|
||||||
|
const topProbe = new Image();
|
||||||
|
perspectiveProbe.src = view.image;
|
||||||
|
topProbe.src = view.topImage;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.all([decodeImage(perspectiveProbe), decodeImage(topProbe)]);
|
||||||
|
} catch (error) {
|
||||||
|
if (token === state.imageToken) {
|
||||||
|
state.pendingLandform = null;
|
||||||
|
syncWorkflowPresentation(state.step);
|
||||||
|
showToast("地貌图片加载失败,请检查对应资源文件");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (token !== state.imageToken) return;
|
||||||
|
|
||||||
|
state.pendingLandform = null;
|
||||||
|
state.selectedLandform = key;
|
||||||
|
state.viewMode = nextMode;
|
||||||
|
dom.landformImage.src = view.image;
|
||||||
|
dom.landformImage.alt = view.alt;
|
||||||
|
dom.landformTopImage.src = view.topImage;
|
||||||
|
dom.landformTopImage.alt = view.topAlt;
|
||||||
|
|
||||||
|
dom.terrainTabs.forEach(function (button) {
|
||||||
|
const active = button.dataset.landform === key;
|
||||||
|
button.classList.toggle("is-active", active);
|
||||||
|
button.setAttribute("aria-pressed", String(active));
|
||||||
|
});
|
||||||
|
dom.returnExperiment.hidden = false;
|
||||||
|
renderObservation(view);
|
||||||
|
applyLandformView(view, true);
|
||||||
|
collapsePanelForCompactView();
|
||||||
|
setPlayButton();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleTopView() {
|
||||||
|
const view = LANDFORMS[state.selectedLandform];
|
||||||
|
if (!view) return;
|
||||||
|
const previousMode = state.viewMode;
|
||||||
|
const token = ++state.imageToken;
|
||||||
|
state.pendingLandform = null;
|
||||||
|
clearTerrainAnnotationNow();
|
||||||
|
state.viewMode = previousMode === "top" ? "perspective" : "top";
|
||||||
|
try {
|
||||||
|
await decodeImage(state.viewMode === "top" ? dom.landformTopImage : dom.landformImage);
|
||||||
|
} catch (error) {
|
||||||
|
state.viewMode = previousMode;
|
||||||
|
showToast("对应视图加载失败,请检查图片资源");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (token !== state.imageToken) return;
|
||||||
|
applyLandformView(view, true);
|
||||||
|
collapsePanelForCompactView();
|
||||||
|
}
|
||||||
|
|
||||||
|
function showExperiment() {
|
||||||
|
cancelWorkflowSequence();
|
||||||
|
state.imageToken += 1;
|
||||||
|
state.pendingLandform = null;
|
||||||
|
state.selectedLandform = null;
|
||||||
|
state.viewMode = "perspective";
|
||||||
|
dom.app.classList.remove("is-scanning");
|
||||||
|
hideWorkflowVisuals();
|
||||||
|
hideTerrainAnnotation();
|
||||||
|
dom.landformImage.classList.remove("is-visible", "is-revealing");
|
||||||
|
dom.landformTopImage.classList.remove("is-visible", "is-revealing");
|
||||||
|
dom.experimentVideo.classList.add("is-visible");
|
||||||
|
dom.terrainTabs.forEach(function (button) {
|
||||||
|
button.classList.remove("is-active");
|
||||||
|
button.setAttribute("aria-pressed", "false");
|
||||||
|
});
|
||||||
|
dom.returnExperiment.hidden = true;
|
||||||
|
renderObservation(DEFAULT_VIEW);
|
||||||
|
updateViewToggle();
|
||||||
|
updateMediaLabel(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function playVideo() {
|
||||||
|
dom.experimentVideo.play().then(function () {
|
||||||
|
setPlayButton();
|
||||||
|
updateMediaLabel(null);
|
||||||
|
dom.hintText.textContent = "实验播放中:" + STEP_COPY[state.step].description;
|
||||||
|
}).catch(function (error) {
|
||||||
|
if (error && error.name === "AbortError") return;
|
||||||
|
showToast("视频暂时无法播放,请检查浏览器媒体权限");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleExperimentPlayback() {
|
||||||
|
if (state.selectedLandform || state.pendingLandform || state.step >= 2) {
|
||||||
|
showExperiment();
|
||||||
|
if (Number.isFinite(dom.experimentVideo.duration) && dom.experimentVideo.duration > 0) {
|
||||||
|
dom.experimentVideo.currentTime = 0;
|
||||||
|
} else {
|
||||||
|
state.pendingStep = 0;
|
||||||
|
}
|
||||||
|
renderStep(0);
|
||||||
|
playVideo();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!dom.experimentVideo.paused) {
|
||||||
|
dom.experimentVideo.pause();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const duration = dom.experimentVideo.duration;
|
||||||
|
if (dom.experimentVideo.ended || (Number.isFinite(duration) && dom.experimentVideo.currentTime >= duration - 0.08)) {
|
||||||
|
dom.experimentVideo.currentTime = 0;
|
||||||
|
renderStep(0);
|
||||||
|
}
|
||||||
|
playVideo();
|
||||||
|
}
|
||||||
|
|
||||||
|
function playFromBeginning() {
|
||||||
|
showExperiment();
|
||||||
|
renderStep(0);
|
||||||
|
if (Number.isFinite(dom.experimentVideo.duration) && dom.experimentVideo.duration > 0) {
|
||||||
|
dom.experimentVideo.currentTime = 0;
|
||||||
|
} else {
|
||||||
|
state.pendingStep = 0;
|
||||||
|
}
|
||||||
|
playVideo();
|
||||||
|
}
|
||||||
|
|
||||||
|
function playStep(index) {
|
||||||
|
const safeIndex = Math.max(0, Math.min(3, Number(index) || 0));
|
||||||
|
showExperiment();
|
||||||
|
renderStep(safeIndex);
|
||||||
|
if (safeIndex <= 1) {
|
||||||
|
if (Number.isFinite(dom.experimentVideo.duration) && dom.experimentVideo.duration > 0) {
|
||||||
|
dom.experimentVideo.currentTime = safeIndex === 0 ? 0 : dom.experimentVideo.duration / 2;
|
||||||
|
} else {
|
||||||
|
state.pendingStep = safeIndex;
|
||||||
|
}
|
||||||
|
playVideo();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.pendingStep = null;
|
||||||
|
dom.experimentVideo.pause();
|
||||||
|
setPlayButton();
|
||||||
|
updateMediaLabel(null);
|
||||||
|
dom.hintText.textContent = STEP_COPY[safeIndex].title + ":" + STEP_COPY[safeIndex].description;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetExperience() {
|
||||||
|
state.pendingStep = null;
|
||||||
|
dom.experimentVideo.pause();
|
||||||
|
showExperiment();
|
||||||
|
renderStep(0);
|
||||||
|
if (Number.isFinite(dom.experimentVideo.duration) && dom.experimentVideo.duration > 0) {
|
||||||
|
dom.experimentVideo.currentTime = 0;
|
||||||
|
} else {
|
||||||
|
state.pendingStep = 0;
|
||||||
|
}
|
||||||
|
dom.progress.style.width = "0%";
|
||||||
|
dom.hintText.textContent = DEFAULT_VIEW.hint;
|
||||||
|
setPlayButton();
|
||||||
|
showToast("已重置到视频首帧");
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleFullscreen() {
|
||||||
|
if (!document.fullscreenElement) {
|
||||||
|
if (!dom.app.requestFullscreen) {
|
||||||
|
showToast("当前浏览器不支持全屏");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dom.app.requestFullscreen().catch(function () { showToast("当前浏览器未允许进入全屏"); });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (document.exitFullscreen) document.exitFullscreen().catch(function () {});
|
||||||
|
}
|
||||||
|
|
||||||
|
dom.experimentVideo.addEventListener("loadeddata", hideLoading, { once: true });
|
||||||
|
dom.experimentVideo.addEventListener("canplay", hideLoading, { once: true });
|
||||||
|
dom.experimentVideo.addEventListener("loadedmetadata", function () {
|
||||||
|
if (state.pendingStep === null) return;
|
||||||
|
const pending = state.pendingStep;
|
||||||
|
state.pendingStep = null;
|
||||||
|
const duration = dom.experimentVideo.duration;
|
||||||
|
if (Number.isFinite(duration) && duration > 0) {
|
||||||
|
dom.experimentVideo.currentTime = pending === 0 ? 0 : duration / 2;
|
||||||
|
renderStep(pending);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
dom.experimentVideo.addEventListener("error", function () {
|
||||||
|
hideLoading();
|
||||||
|
showToast("形成交线视频加载失败,请确认“contour-formation.mp4”在当前目录");
|
||||||
|
});
|
||||||
|
dom.experimentVideo.addEventListener("play", function () {
|
||||||
|
setPlayButton();
|
||||||
|
updateMediaLabel(null);
|
||||||
|
dom.hintText.textContent = "实验播放中:" + STEP_COPY[state.step].description;
|
||||||
|
});
|
||||||
|
dom.experimentVideo.addEventListener("pause", function () {
|
||||||
|
setPlayButton();
|
||||||
|
updateMediaLabel(null);
|
||||||
|
if (!state.selectedLandform && state.step >= 2) {
|
||||||
|
dom.hintText.textContent = STEP_COPY[state.step].title + ":" + STEP_COPY[state.step].description;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!dom.experimentVideo.ended && dom.experimentVideo.currentTime > 0.12 && !state.selectedLandform) {
|
||||||
|
dom.hintText.textContent = "实验已暂停 · 点击“继续实验”恢复播放";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
dom.experimentVideo.addEventListener("ended", function () {
|
||||||
|
if (
|
||||||
|
state.selectedLandform ||
|
||||||
|
state.pendingLandform ||
|
||||||
|
state.step > 1 ||
|
||||||
|
!dom.experimentVideo.ended
|
||||||
|
) return;
|
||||||
|
dom.progress.style.width = "100%";
|
||||||
|
beginStaticWorkflowSequence();
|
||||||
|
});
|
||||||
|
dom.experimentVideo.addEventListener("timeupdate", function () {
|
||||||
|
const duration = dom.experimentVideo.duration;
|
||||||
|
const ratio = Number.isFinite(duration) && duration > 0 ? dom.experimentVideo.currentTime / duration : 0;
|
||||||
|
dom.progress.style.width = Math.max(0, Math.min(100, ratio * 100)) + "%";
|
||||||
|
if (!state.selectedLandform && state.step === 0 && ratio >= 0.5) {
|
||||||
|
renderStep(1);
|
||||||
|
dom.hintText.textContent = "实验播放中:" + STEP_COPY[1].description;
|
||||||
|
}
|
||||||
|
if (!dom.experimentVideo.paused) updateMediaLabel(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
dom.playButton.addEventListener("click", toggleExperimentPlayback);
|
||||||
|
dom.workflowOpen.addEventListener("click", playFromBeginning);
|
||||||
|
dom.resetButton.addEventListener("click", resetExperience);
|
||||||
|
dom.returnExperiment.addEventListener("click", resetExperience);
|
||||||
|
dom.topViewToggle.addEventListener("click", toggleTopView);
|
||||||
|
dom.terrainTabs.forEach(function (button) {
|
||||||
|
button.addEventListener("click", function () { selectLandform(button.dataset.landform); });
|
||||||
|
});
|
||||||
|
dom.flowSteps.forEach(function (button) {
|
||||||
|
button.addEventListener("click", function () { playStep(Number(button.dataset.step)); });
|
||||||
|
});
|
||||||
|
|
||||||
|
dom.fullscreenButton.addEventListener("click", toggleFullscreen);
|
||||||
|
document.addEventListener("fullscreenchange", function () {
|
||||||
|
dom.fullscreenLabel.textContent = document.fullscreenElement ? "退出全屏" : "全屏";
|
||||||
|
});
|
||||||
|
dom.panelClose.addEventListener("click", function () {
|
||||||
|
dom.controlPanel.classList.add("is-collapsed");
|
||||||
|
dom.panelOpen.hidden = false;
|
||||||
|
});
|
||||||
|
dom.panelOpen.addEventListener("click", function () {
|
||||||
|
dom.controlPanel.classList.remove("is-collapsed");
|
||||||
|
dom.panelOpen.hidden = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener("keydown", function (event) {
|
||||||
|
if (event.code === "Space" && !/BUTTON|INPUT|VIDEO/.test(document.activeElement.tagName)) {
|
||||||
|
event.preventDefault();
|
||||||
|
toggleExperimentPlayback();
|
||||||
|
}
|
||||||
|
if (/^[1-5]$/.test(event.key) && !event.metaKey && !event.ctrlKey && !event.altKey) {
|
||||||
|
const keys = ["peak", "ridge", "valley", "saddle", "cliff"];
|
||||||
|
selectLandform(keys[Number(event.key) - 1]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.setTimeout(hideLoading, 7000);
|
||||||
|
renderStep(0);
|
||||||
|
renderObservation(DEFAULT_VIEW);
|
||||||
|
updateViewToggle();
|
||||||
|
updateMediaLabel(null);
|
||||||
|
setPlayButton();
|
||||||
|
|
||||||
|
window.__GEO_LAB_TEST__ = {
|
||||||
|
getState: function () {
|
||||||
|
return {
|
||||||
|
selectedLandform: state.selectedLandform,
|
||||||
|
pendingLandform: state.pendingLandform,
|
||||||
|
viewMode: state.viewMode,
|
||||||
|
step: state.step,
|
||||||
|
videoPlaying: !dom.experimentVideo.paused,
|
||||||
|
videoTime: dom.experimentVideo.currentTime,
|
||||||
|
videoSource: dom.experimentVideo.currentSrc || dom.experimentVideo.src,
|
||||||
|
workflowDiagram: !dom.projectionDiagram.hasAttribute("hidden") ? "projection" : !dom.densityDiagram.hasAttribute("hidden") ? "density" : null,
|
||||||
|
workflowAutoPlaying: state.workflowAutoPlaying,
|
||||||
|
densityBackground: dom.densityBackground.classList.contains("is-visible"),
|
||||||
|
scanning: dom.app.classList.contains("is-scanning"),
|
||||||
|
terrainAnnotation: window.TerrainAnnotation ? window.TerrainAnnotation.getState() : null,
|
||||||
|
fullscreen: Boolean(document.fullscreenElement)
|
||||||
|
};
|
||||||
|
},
|
||||||
|
selectLandform: selectLandform,
|
||||||
|
toggleTopView: toggleTopView,
|
||||||
|
showExperiment: showExperiment,
|
||||||
|
playStep: playStep,
|
||||||
|
reset: resetExperience
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
After Width: | Height: | Size: 698 KiB |
|
After Width: | Height: | Size: 961 KiB |
|
After Width: | Height: | Size: 593 KiB |
|
After Width: | Height: | Size: 621 KiB |
|
After Width: | Height: | Size: 947 KiB |
|
After Width: | Height: | Size: 675 KiB |
|
After Width: | Height: | Size: 945 KiB |
|
After Width: | Height: | Size: 622 KiB |
|
After Width: | Height: | Size: 963 KiB |
@@ -0,0 +1,671 @@
|
|||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const THREE = window.THREE;
|
||||||
|
const root = document.getElementById("terrain-annotation");
|
||||||
|
const canvas = document.getElementById("terrain-annotation-canvas");
|
||||||
|
const callout = document.getElementById("terrain-callout");
|
||||||
|
const calloutTitle = document.getElementById("terrain-callout-title");
|
||||||
|
const calloutCopy = document.getElementById("terrain-callout-copy");
|
||||||
|
const calloutConnector = document.getElementById("terrain-callout-connector");
|
||||||
|
const calloutConnectorShape = document.getElementById("terrain-callout-connector-shape");
|
||||||
|
const stage = document.querySelector(".media-stage");
|
||||||
|
|
||||||
|
if (!THREE || !root || !canvas || !callout || !calloutTitle || !calloutCopy || !calloutConnector || !calloutConnectorShape || !stage) return;
|
||||||
|
|
||||||
|
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||||
|
const compactLayout = window.matchMedia("(max-width: 680px)");
|
||||||
|
const SOURCE_ASPECT = 1586 / 992;
|
||||||
|
const GUIDE_COLOR = "#f6b21a";
|
||||||
|
const OUTLINE_COLOR = 0x082742;
|
||||||
|
const TARGET_OUTER_RADIUS = 20;
|
||||||
|
const ROLE_STYLES = {
|
||||||
|
main: { width: 8, outline: 14, opacity: 1, dashed: 0, dashCount: 1, dashRatio: 1, dashSpeed: 0 },
|
||||||
|
branch: { width: 6.5, outline: 11.5, opacity: 1, dashed: 1, dashCount: 4, dashRatio: 0.62, dashSpeed: 0 },
|
||||||
|
ring: { width: 6, outline: 10.5, opacity: 1, dashed: 0, dashCount: 1, dashRatio: 1, dashSpeed: 0 },
|
||||||
|
contour: { width: 4.5, outline: 8.5, opacity: 1, dashed: 0, dashCount: 1, dashRatio: 1, dashSpeed: 0 },
|
||||||
|
bracket: { width: 5.5, outline: 10, opacity: 1, dashed: 1, dashCount: 4, dashRatio: 0.62, dashSpeed: 0 }
|
||||||
|
};
|
||||||
|
|
||||||
|
const ANNOTATIONS = {
|
||||||
|
peak: {
|
||||||
|
title: "山峰 · 最高中心",
|
||||||
|
copy: "闭合等高线由外向内数值升高,中心位置为山峰。",
|
||||||
|
color: GUIDE_COLOR,
|
||||||
|
perspective: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", arrow: true, points: [[0.628, 0.575], [0.650, 0.455], [0.670, 0.280], [0.709, 0.143]] }
|
||||||
|
],
|
||||||
|
target: [0.709, 0.143],
|
||||||
|
placement: { side: "right", dx: 34, dy: 24 }
|
||||||
|
},
|
||||||
|
top: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", arrow: true, points: [[0.575, 0.645], [0.610, 0.555], [0.645, 0.485], [0.668, 0.449]] }
|
||||||
|
],
|
||||||
|
target: [0.668, 0.449],
|
||||||
|
placement: { side: "right", dx: 34, dy: -10 }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ridge: {
|
||||||
|
title: "山脊 · 分水脊线",
|
||||||
|
copy: "等高线向低处凸出,脊线两侧水流向外分开。",
|
||||||
|
color: GUIDE_COLOR,
|
||||||
|
perspective: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", arrow: true, points: [[0.765, 0.245], [0.720, 0.365], [0.675, 0.500], [0.625, 0.645]] },
|
||||||
|
{ role: "branch", arrow: true, points: [[0.675, 0.500], [0.635, 0.535], [0.595, 0.565]] },
|
||||||
|
{ role: "branch", arrow: true, points: [[0.675, 0.500], [0.715, 0.535], [0.755, 0.570]] }
|
||||||
|
],
|
||||||
|
target: [0.675, 0.500],
|
||||||
|
placement: { side: "left", dx: -34, dy: -85 }
|
||||||
|
},
|
||||||
|
top: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", arrow: true, points: [[0.690, 0.270], [0.655, 0.395], [0.620, 0.520], [0.590, 0.650]] },
|
||||||
|
{ role: "branch", arrow: true, points: [[0.620, 0.520], [0.582, 0.545], [0.548, 0.575]] },
|
||||||
|
{ role: "branch", arrow: true, points: [[0.620, 0.520], [0.658, 0.548], [0.695, 0.580]] }
|
||||||
|
],
|
||||||
|
target: [0.620, 0.520],
|
||||||
|
placement: { side: "left", dx: -34, dy: -85 }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
valley: {
|
||||||
|
title: "山谷 · 汇水谷线",
|
||||||
|
copy: "V形尖端指向上游,水流沿谷底向下游汇集。",
|
||||||
|
color: GUIDE_COLOR,
|
||||||
|
perspective: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", arrow: true, points: [[0.690, 0.410], [0.678, 0.520], [0.676, 0.550], [0.660, 0.650], [0.640, 0.790]] },
|
||||||
|
{ role: "branch", arrow: true, points: [[0.590, 0.560], [0.630, 0.560], [0.676, 0.550]] },
|
||||||
|
{ role: "branch", arrow: true, points: [[0.750, 0.560], [0.710, 0.560], [0.676, 0.550]] }
|
||||||
|
],
|
||||||
|
target: [0.676, 0.550],
|
||||||
|
placement: { side: "right", dx: 34, dy: -80 }
|
||||||
|
},
|
||||||
|
top: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", arrow: true, points: [[0.600, 0.355], [0.565, 0.470], [0.525, 0.585], [0.470, 0.690]] },
|
||||||
|
{ role: "branch", arrow: true, points: [[0.455, 0.520], [0.490, 0.555], [0.525, 0.585]] },
|
||||||
|
{ role: "branch", arrow: true, points: [[0.600, 0.510], [0.565, 0.550], [0.525, 0.585]] }
|
||||||
|
],
|
||||||
|
target: [0.525, 0.585],
|
||||||
|
placement: { side: "right", dx: 34, dy: 70 }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
saddle: {
|
||||||
|
title: "鞍部 · 两峰低口",
|
||||||
|
copy: "两组闭合等高线之间的低口,就是鞍部。",
|
||||||
|
color: GUIDE_COLOR,
|
||||||
|
perspective: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", points: [[0.625, 0.425], [0.675, 0.465], [0.725, 0.420]] }
|
||||||
|
],
|
||||||
|
target: [0.675, 0.465],
|
||||||
|
placement: { side: "below", dx: 0, dy: 38 }
|
||||||
|
},
|
||||||
|
top: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", points: [[0.515, 0.475], [0.560, 0.505], [0.610, 0.475]] }
|
||||||
|
],
|
||||||
|
target: [0.560, 0.505],
|
||||||
|
placement: { side: "below", dx: 0, dy: 38 }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
cliff: {
|
||||||
|
title: "陡崖 · 密集重合带",
|
||||||
|
copy: "等高线极密集或重合,表示此处坡度陡峭。",
|
||||||
|
color: GUIDE_COLOR,
|
||||||
|
perspective: {
|
||||||
|
traces: [
|
||||||
|
{ role: "contour", points: [[0.535, 0.345], [0.565, 0.352], [0.590, 0.360]] },
|
||||||
|
{ role: "contour", points: [[0.532, 0.390], [0.562, 0.398], [0.590, 0.405]] },
|
||||||
|
{ role: "contour", points: [[0.530, 0.435], [0.560, 0.443], [0.590, 0.452]] },
|
||||||
|
{ role: "main", arrow: true, points: [[0.595, 0.305], [0.590, 0.405], [0.598, 0.510]] }
|
||||||
|
],
|
||||||
|
target: [0.590, 0.405],
|
||||||
|
placement: { side: "right", dx: 34, dy: 0 }
|
||||||
|
},
|
||||||
|
top: {
|
||||||
|
traces: [
|
||||||
|
{ role: "main", arrow: true, points: [[0.535, 0.560], [0.585, 0.520], [0.635, 0.480]] },
|
||||||
|
{ role: "contour", points: [[0.555, 0.455], [0.575, 0.515], [0.595, 0.575]] },
|
||||||
|
{ role: "contour", points: [[0.590, 0.435], [0.610, 0.495], [0.630, 0.555]] }
|
||||||
|
],
|
||||||
|
target: [0.585, 0.520],
|
||||||
|
placement: { side: "below", dx: 0, dy: 70 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let renderer;
|
||||||
|
let scene;
|
||||||
|
let camera;
|
||||||
|
let annotationGroup;
|
||||||
|
let aspect = 1;
|
||||||
|
let stageHeight = 1;
|
||||||
|
let animationFrame = 0;
|
||||||
|
let revealStart = 0;
|
||||||
|
let calloutTimer = 0;
|
||||||
|
let hideTimer = 0;
|
||||||
|
let currentKey = null;
|
||||||
|
let currentMode = "perspective";
|
||||||
|
let buildToken = 0;
|
||||||
|
let animatedMaterials = [];
|
||||||
|
let revealGeometries = [];
|
||||||
|
let pulseMeshes = [];
|
||||||
|
let delayedMarkers = [];
|
||||||
|
let runnerDots = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
renderer = new THREE.WebGLRenderer({ canvas: canvas, alpha: true, antialias: true, powerPreference: "high-performance" });
|
||||||
|
renderer.setClearColor(0x000000, 0);
|
||||||
|
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.75));
|
||||||
|
scene = new THREE.Scene();
|
||||||
|
camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
|
||||||
|
camera.position.z = 4;
|
||||||
|
} catch (error) {
|
||||||
|
root.dataset.renderer = "unavailable";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sourceToScreen(point) {
|
||||||
|
let renderedWidth = 1;
|
||||||
|
let renderedHeight = 1;
|
||||||
|
let offsetX = 0;
|
||||||
|
let offsetY = 0;
|
||||||
|
if (compactLayout.matches) {
|
||||||
|
if (aspect >= SOURCE_ASPECT) {
|
||||||
|
renderedWidth = SOURCE_ASPECT / aspect;
|
||||||
|
offsetX = (1 - renderedWidth) / 2;
|
||||||
|
} else {
|
||||||
|
renderedHeight = aspect / SOURCE_ASPECT;
|
||||||
|
offsetY = (1 - renderedHeight) / 2;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (aspect >= SOURCE_ASPECT) {
|
||||||
|
renderedHeight = aspect / SOURCE_ASPECT;
|
||||||
|
offsetY = (1 - renderedHeight) / 2;
|
||||||
|
} else {
|
||||||
|
renderedWidth = SOURCE_ASPECT / aspect;
|
||||||
|
offsetX = (1 - renderedWidth) / 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [offsetX + point[0] * renderedWidth, offsetY + point[1] * renderedHeight];
|
||||||
|
}
|
||||||
|
|
||||||
|
function toWorld(point) {
|
||||||
|
const screenPoint = sourceToScreen(point);
|
||||||
|
return new THREE.Vector3((screenPoint[0] - 0.5) * 2 * aspect, (0.5 - screenPoint[1]) * 2, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getVisualScale() {
|
||||||
|
return Math.max(0.72, Math.min(1, stage.clientWidth / 1200));
|
||||||
|
}
|
||||||
|
|
||||||
|
function disposeMaterial(material) {
|
||||||
|
if (Array.isArray(material)) material.forEach(disposeMaterial);
|
||||||
|
else if (material && typeof material.dispose === "function") material.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearAnnotation() {
|
||||||
|
if (!annotationGroup) return;
|
||||||
|
annotationGroup.traverse(function (object) {
|
||||||
|
if (object.geometry) object.geometry.dispose();
|
||||||
|
if (object.material) disposeMaterial(object.material);
|
||||||
|
});
|
||||||
|
scene.remove(annotationGroup);
|
||||||
|
annotationGroup = null;
|
||||||
|
animatedMaterials = [];
|
||||||
|
revealGeometries = [];
|
||||||
|
pulseMeshes = [];
|
||||||
|
delayedMarkers = [];
|
||||||
|
runnerDots = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function createRibbonGeometry(samples, widthInPixels) {
|
||||||
|
const positions = [];
|
||||||
|
const uvs = [];
|
||||||
|
const indices = [];
|
||||||
|
const halfWidth = widthInPixels / Math.max(1, stageHeight);
|
||||||
|
samples.forEach(function (point, index) {
|
||||||
|
const previous = samples[Math.max(0, index - 1)];
|
||||||
|
const next = samples[Math.min(samples.length - 1, index + 1)];
|
||||||
|
const tangentX = next.x - previous.x;
|
||||||
|
const tangentY = next.y - previous.y;
|
||||||
|
const length = Math.hypot(tangentX, tangentY) || 1;
|
||||||
|
const normalX = -tangentY / length;
|
||||||
|
const normalY = tangentX / length;
|
||||||
|
const progress = index / Math.max(1, samples.length - 1);
|
||||||
|
positions.push(point.x + normalX * halfWidth, point.y + normalY * halfWidth, point.z);
|
||||||
|
positions.push(point.x - normalX * halfWidth, point.y - normalY * halfWidth, point.z);
|
||||||
|
uvs.push(progress, 0, progress, 1);
|
||||||
|
if (index < samples.length - 1) {
|
||||||
|
const base = index * 2;
|
||||||
|
indices.push(base, base + 1, base + 2, base + 1, base + 3, base + 2);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const geometry = new THREE.BufferGeometry();
|
||||||
|
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
|
||||||
|
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
|
||||||
|
geometry.setIndex(indices);
|
||||||
|
geometry.computeBoundingSphere();
|
||||||
|
return geometry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeLineMaterial(color, style) {
|
||||||
|
return new THREE.ShaderMaterial({
|
||||||
|
uniforms: {
|
||||||
|
uTime: { value: 0 },
|
||||||
|
uColor: { value: new THREE.Color(color) },
|
||||||
|
uOpacity: { value: style.opacity },
|
||||||
|
uMotion: { value: reducedMotion.matches ? 0 : 1 },
|
||||||
|
uDashed: { value: style.dashed },
|
||||||
|
uDashCount: { value: style.dashCount },
|
||||||
|
uDashRatio: { value: style.dashRatio },
|
||||||
|
uDashSpeed: { value: style.dashSpeed }
|
||||||
|
},
|
||||||
|
vertexShader: [
|
||||||
|
"varying vec2 vUv;",
|
||||||
|
"void main() {",
|
||||||
|
" vUv = uv;",
|
||||||
|
" gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);",
|
||||||
|
"}"
|
||||||
|
].join("\n"),
|
||||||
|
fragmentShader: [
|
||||||
|
"uniform float uTime;",
|
||||||
|
"uniform vec3 uColor;",
|
||||||
|
"uniform float uOpacity;",
|
||||||
|
"uniform float uMotion;",
|
||||||
|
"uniform float uDashed;",
|
||||||
|
"uniform float uDashCount;",
|
||||||
|
"uniform float uDashRatio;",
|
||||||
|
"uniform float uDashSpeed;",
|
||||||
|
"varying vec2 vUv;",
|
||||||
|
"void main() {",
|
||||||
|
" float edge = 1.0 - smoothstep(0.43, 0.50, abs(vUv.y - 0.5));",
|
||||||
|
" float dashPhase = fract(vUv.x * uDashCount - uTime * uDashSpeed * uMotion);",
|
||||||
|
" float dash = 1.0 - smoothstep(uDashRatio - 0.04, uDashRatio + 0.04, dashPhase);",
|
||||||
|
" float pattern = mix(1.0, dash, uDashed);",
|
||||||
|
" float alpha = uOpacity * edge * pattern;",
|
||||||
|
" gl_FragColor = vec4(uColor, alpha);",
|
||||||
|
"}"
|
||||||
|
].join("\n"),
|
||||||
|
transparent: true,
|
||||||
|
depthTest: false,
|
||||||
|
depthWrite: false,
|
||||||
|
blending: THREE.NormalBlending
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createArrow(points, color, sizeInPixels, delay, stopBeforePixels) {
|
||||||
|
const end = toWorld(points[points.length - 1]);
|
||||||
|
const before = toWorld(points[points.length - 2]);
|
||||||
|
const direction = end.clone().sub(before).normalize();
|
||||||
|
const angle = Math.atan2(direction.y, direction.x);
|
||||||
|
const unit = 2 / Math.max(1, stageHeight);
|
||||||
|
const visualScale = getVisualScale();
|
||||||
|
const scaledSize = sizeInPixels * visualScale;
|
||||||
|
const arrowPosition = end.clone().addScaledVector(direction, -(stopBeforePixels || 0) * visualScale * unit);
|
||||||
|
function createArrowGeometry(pixelSize) {
|
||||||
|
const size = pixelSize * unit;
|
||||||
|
const geometry = new THREE.BufferGeometry();
|
||||||
|
geometry.setAttribute("position", new THREE.Float32BufferAttribute([
|
||||||
|
0, 0, 0,
|
||||||
|
-size * 1.90, size * 0.88, 0,
|
||||||
|
-size * 1.90, -size * 0.88, 0
|
||||||
|
], 3));
|
||||||
|
return geometry;
|
||||||
|
}
|
||||||
|
const outlineMaterial = new THREE.MeshBasicMaterial({ color: OUTLINE_COLOR, transparent: true, opacity: 1, depthTest: false, depthWrite: false });
|
||||||
|
const material = new THREE.MeshBasicMaterial({ color: color, transparent: true, opacity: 1, depthTest: false, depthWrite: false });
|
||||||
|
const outline = new THREE.Mesh(createArrowGeometry(scaledSize + 2.5 * visualScale), outlineMaterial);
|
||||||
|
const arrow = new THREE.Mesh(createArrowGeometry(scaledSize), material);
|
||||||
|
outline.position.copy(arrowPosition).addScaledVector(direction, 1.25 * visualScale * unit);
|
||||||
|
arrow.position.copy(arrowPosition);
|
||||||
|
outline.rotation.z = angle;
|
||||||
|
arrow.rotation.z = angle;
|
||||||
|
outline.renderOrder = 40;
|
||||||
|
arrow.renderOrder = 41;
|
||||||
|
annotationGroup.add(outline, arrow);
|
||||||
|
delayedMarkers.push({ mesh: outline, delay: delay + 0.46 });
|
||||||
|
delayedMarkers.push({ mesh: arrow, delay: delay + 0.46 });
|
||||||
|
}
|
||||||
|
|
||||||
|
function createRunnerDots(curve, delay, count) {
|
||||||
|
const pixelUnit = 2 / Math.max(1, stageHeight);
|
||||||
|
const visualScale = getVisualScale();
|
||||||
|
const phases = count === 1 ? [0.18] : count === 2 ? [0.18, 0.70] : [0.12, 0.45, 0.78];
|
||||||
|
phases.forEach(function (phase, index) {
|
||||||
|
const glowMaterial = new THREE.MeshBasicMaterial({
|
||||||
|
color: 0xffffff,
|
||||||
|
transparent: true,
|
||||||
|
opacity: 0.28,
|
||||||
|
depthTest: false,
|
||||||
|
depthWrite: false,
|
||||||
|
blending: THREE.AdditiveBlending
|
||||||
|
});
|
||||||
|
const dotMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 1, depthTest: false, depthWrite: false });
|
||||||
|
const glow = new THREE.Mesh(new THREE.CircleGeometry(11 * visualScale * pixelUnit, 40), glowMaterial);
|
||||||
|
const dot = new THREE.Mesh(new THREE.CircleGeometry(7.5 * visualScale * pixelUnit, 40), dotMaterial);
|
||||||
|
const position = curve.getPointAt(phase);
|
||||||
|
glow.position.copy(position);
|
||||||
|
dot.position.copy(position);
|
||||||
|
glow.renderOrder = 44;
|
||||||
|
dot.renderOrder = 45;
|
||||||
|
glow.visible = false;
|
||||||
|
dot.visible = false;
|
||||||
|
annotationGroup.add(glow, dot);
|
||||||
|
runnerDots.push({ glow: glow, dot: dot, curve: curve, phase: phase, delay: delay + 0.18, pulseOffset: index * 1.8 });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTrace(trace, color, index, target) {
|
||||||
|
const style = ROLE_STYLES[trace.role] || ROLE_STYLES.main;
|
||||||
|
const worldPoints = trace.points.map(toWorld);
|
||||||
|
const curve = new THREE.CatmullRomCurve3(worldPoints, Boolean(trace.closed), "centripetal", 0.5);
|
||||||
|
const pathLengthPixels = curve.getLength() * stageHeight / 2;
|
||||||
|
const samples = curve.getSpacedPoints(Math.max(36, trace.points.length * 12));
|
||||||
|
const visualScale = getVisualScale();
|
||||||
|
const outlineGeometry = createRibbonGeometry(samples, style.outline * visualScale);
|
||||||
|
const lineGeometry = createRibbonGeometry(samples, style.width * visualScale);
|
||||||
|
const outlineMaterial = makeLineMaterial(OUTLINE_COLOR, style);
|
||||||
|
const lineMaterial = makeLineMaterial(color, style);
|
||||||
|
const outline = new THREE.Mesh(outlineGeometry, outlineMaterial);
|
||||||
|
const line = new THREE.Mesh(lineGeometry, lineMaterial);
|
||||||
|
const isMain = trace.role === "main";
|
||||||
|
outline.renderOrder = isMain ? 30 : 20;
|
||||||
|
line.renderOrder = isMain ? 31 : 21;
|
||||||
|
annotationGroup.add(outline, line);
|
||||||
|
animatedMaterials.push(outlineMaterial, lineMaterial);
|
||||||
|
const delay = index * 0.075;
|
||||||
|
if (trace.role === "main") createRunnerDots(curve, delay, pathLengthPixels < 180 ? 1 : pathLengthPixels < 320 ? 2 : 3);
|
||||||
|
revealGeometries.push({ geometry: outlineGeometry, count: outlineGeometry.index.count, delay: delay });
|
||||||
|
revealGeometries.push({ geometry: lineGeometry, count: lineGeometry.index.count, delay: delay });
|
||||||
|
if (trace.arrow && !trace.closed) {
|
||||||
|
const endPoint = trace.points[trace.points.length - 1];
|
||||||
|
const endsAtTarget = target && Math.hypot(endPoint[0] - target[0], endPoint[1] - target[1]) < 0.002;
|
||||||
|
const arrowScale = Math.max(0.82, Math.min(1, pathLengthPixels / 240));
|
||||||
|
createArrow(trace.points, color, (trace.role === "branch" ? 14 : 15) * arrowScale, delay, endsAtTarget ? TARGET_OUTER_RADIUS + 4 : 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTarget(point, color) {
|
||||||
|
const position = toWorld(point);
|
||||||
|
const pixelUnit = 2 / Math.max(1, stageHeight);
|
||||||
|
const visualScale = getVisualScale();
|
||||||
|
const halo = new THREE.Mesh(
|
||||||
|
new THREE.CircleGeometry(25 * visualScale * pixelUnit, 64),
|
||||||
|
new THREE.MeshBasicMaterial({ color: color, transparent: true, opacity: 0.20, depthTest: false, depthWrite: false, blending: THREE.AdditiveBlending })
|
||||||
|
);
|
||||||
|
const outer = new THREE.Mesh(
|
||||||
|
new THREE.CircleGeometry(TARGET_OUTER_RADIUS * visualScale * pixelUnit, 64),
|
||||||
|
new THREE.MeshBasicMaterial({ color: OUTLINE_COLOR, transparent: true, opacity: 1, depthTest: false, depthWrite: false })
|
||||||
|
);
|
||||||
|
const gold = new THREE.Mesh(
|
||||||
|
new THREE.CircleGeometry(17.5 * visualScale * pixelUnit, 64),
|
||||||
|
new THREE.MeshBasicMaterial({ color: color, transparent: true, opacity: 1, depthTest: false, depthWrite: false })
|
||||||
|
);
|
||||||
|
const white = new THREE.Mesh(
|
||||||
|
new THREE.CircleGeometry(13.5 * visualScale * pixelUnit, 64),
|
||||||
|
new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 1, depthTest: false, depthWrite: false })
|
||||||
|
);
|
||||||
|
const inner = new THREE.Mesh(
|
||||||
|
new THREE.CircleGeometry(10 * visualScale * pixelUnit, 56),
|
||||||
|
new THREE.MeshBasicMaterial({ color: OUTLINE_COLOR, transparent: true, opacity: 1, depthTest: false, depthWrite: false })
|
||||||
|
);
|
||||||
|
const core = new THREE.Mesh(
|
||||||
|
new THREE.CircleGeometry(7.5 * visualScale * pixelUnit, 56),
|
||||||
|
new THREE.MeshBasicMaterial({ color: color, transparent: true, opacity: 1, depthTest: false, depthWrite: false })
|
||||||
|
);
|
||||||
|
[halo, outer, gold, white, inner, core].forEach(function (mesh, index) {
|
||||||
|
mesh.position.copy(position);
|
||||||
|
mesh.renderOrder = 49 + index;
|
||||||
|
annotationGroup.add(mesh);
|
||||||
|
});
|
||||||
|
pulseMeshes.push(halo);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCallout(definition, view) {
|
||||||
|
const targetScreen = sourceToScreen(view.target);
|
||||||
|
const placement = view.placement;
|
||||||
|
calloutTitle.textContent = definition.title + (currentMode === "top" ? " · 俯视判读" : "");
|
||||||
|
calloutCopy.textContent = definition.copy;
|
||||||
|
const width = stage.clientWidth;
|
||||||
|
const height = stage.clientHeight;
|
||||||
|
const targetX = targetScreen[0] * width;
|
||||||
|
const targetY = targetScreen[1] * height;
|
||||||
|
const cardWidth = callout.offsetWidth || Math.min(width <= 680 ? 210 : width <= 920 ? 250 : 280, width - 28);
|
||||||
|
const cardHeight = callout.offsetHeight || 88;
|
||||||
|
let side = placement.side;
|
||||||
|
let x = targetX + placement.dx;
|
||||||
|
let y = targetY + placement.dy;
|
||||||
|
const targetGap = TARGET_OUTER_RADIUS * getVisualScale() + 18;
|
||||||
|
const horizontalGap = Math.max(Math.abs(placement.dx), targetGap);
|
||||||
|
const verticalGap = Math.max(Math.abs(placement.dy), targetGap);
|
||||||
|
|
||||||
|
if (side === "right") x = targetX + horizontalGap;
|
||||||
|
else if (side === "left") x = targetX - horizontalGap;
|
||||||
|
else if (side === "below") y = targetY + verticalGap;
|
||||||
|
else if (side === "above") y = targetY - verticalGap;
|
||||||
|
|
||||||
|
if (side === "right" && x + cardWidth > width - 14) {
|
||||||
|
side = "left";
|
||||||
|
x = targetX - horizontalGap;
|
||||||
|
} else if (side === "left" && x - cardWidth < 14) {
|
||||||
|
side = "right";
|
||||||
|
x = targetX + horizontalGap;
|
||||||
|
} else if (side === "below" && y + cardHeight > height - 14) {
|
||||||
|
side = "above";
|
||||||
|
y = targetY - verticalGap;
|
||||||
|
} else if (side === "above" && y - cardHeight < 14) {
|
||||||
|
side = "below";
|
||||||
|
y = targetY + verticalGap;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (side === "right" || side === "left") {
|
||||||
|
const horizontalMargin = compactLayout.matches ? 0 : 14;
|
||||||
|
if (side === "right") x = Math.max(horizontalMargin, Math.min(width - cardWidth - horizontalMargin, x));
|
||||||
|
else x = Math.max(cardWidth + horizontalMargin, Math.min(width - horizontalMargin, x));
|
||||||
|
y = Math.max(cardHeight / 2 + 14, Math.min(height - cardHeight / 2 - 14, y));
|
||||||
|
} else {
|
||||||
|
x = Math.max(cardWidth / 2 + 14, Math.min(width - cardWidth / 2 - 14, x));
|
||||||
|
}
|
||||||
|
|
||||||
|
const connectorBaseHalf = 28 * getVisualScale();
|
||||||
|
let anchorX = x;
|
||||||
|
let anchorY = y;
|
||||||
|
let baseOne;
|
||||||
|
let baseTwo;
|
||||||
|
if (side === "right" || side === "left") {
|
||||||
|
const verticalLimit = Math.max(0, cardHeight / 2 - connectorBaseHalf - 4);
|
||||||
|
anchorY = y + Math.max(-verticalLimit, Math.min(verticalLimit, targetY - y));
|
||||||
|
baseOne = [anchorX, anchorY - connectorBaseHalf];
|
||||||
|
baseTwo = [anchorX, anchorY + connectorBaseHalf];
|
||||||
|
} else {
|
||||||
|
const horizontalLimit = Math.max(0, cardWidth / 2 - connectorBaseHalf - 4);
|
||||||
|
anchorX = x + Math.max(-horizontalLimit, Math.min(horizontalLimit, targetX - x));
|
||||||
|
baseOne = [anchorX - connectorBaseHalf, anchorY];
|
||||||
|
baseTwo = [anchorX + connectorBaseHalf, anchorY];
|
||||||
|
}
|
||||||
|
const connectorX = anchorX - targetX;
|
||||||
|
const connectorY = anchorY - targetY;
|
||||||
|
const connectorLength = Math.hypot(connectorX, connectorY) || 1;
|
||||||
|
const tipRadius = TARGET_OUTER_RADIUS * getVisualScale() * 0.72;
|
||||||
|
const tipX = targetX + connectorX / connectorLength * tipRadius;
|
||||||
|
const tipY = targetY + connectorY / connectorLength * tipRadius;
|
||||||
|
calloutConnector.setAttribute("viewBox", "0 0 " + width + " " + height);
|
||||||
|
calloutConnectorShape.setAttribute(
|
||||||
|
"points",
|
||||||
|
tipX.toFixed(1) + "," + tipY.toFixed(1) + " " +
|
||||||
|
baseOne[0].toFixed(1) + "," + baseOne[1].toFixed(1) + " " +
|
||||||
|
baseTwo[0].toFixed(1) + "," + baseTwo[1].toFixed(1)
|
||||||
|
);
|
||||||
|
|
||||||
|
const pointerInset = 32;
|
||||||
|
const pointerOffsetX = Math.max(-cardWidth / 2 + pointerInset, Math.min(cardWidth / 2 - pointerInset, targetX - x));
|
||||||
|
const pointerOffsetY = Math.max(-cardHeight / 2 + pointerInset, Math.min(cardHeight / 2 - pointerInset, targetY - y));
|
||||||
|
root.style.setProperty("--callout-x", x + "px");
|
||||||
|
root.style.setProperty("--callout-y", y + "px");
|
||||||
|
root.style.setProperty("--pointer-offset-x", pointerOffsetX + "px");
|
||||||
|
root.style.setProperty("--pointer-offset-y", pointerOffsetY + "px");
|
||||||
|
root.dataset.side = side;
|
||||||
|
root.dataset.tone = currentKey === "cliff" ? "warning" : "default";
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildAnnotation(key, mode, animate) {
|
||||||
|
const definition = ANNOTATIONS[key];
|
||||||
|
if (!definition) return;
|
||||||
|
const view = definition[mode === "top" ? "top" : "perspective"];
|
||||||
|
clearAnnotation();
|
||||||
|
annotationGroup = new THREE.Group();
|
||||||
|
scene.add(annotationGroup);
|
||||||
|
view.traces.forEach(function (trace, index) { createTrace(trace, definition.color, index, view.target); });
|
||||||
|
createTarget(view.target, definition.color);
|
||||||
|
updateCallout(definition, view);
|
||||||
|
revealGeometries.forEach(function (item) {
|
||||||
|
item.geometry.setDrawRange(0, animate && !reducedMotion.matches ? 0 : item.count);
|
||||||
|
});
|
||||||
|
delayedMarkers.forEach(function (item) { item.mesh.visible = !animate || reducedMotion.matches; });
|
||||||
|
runnerDots.forEach(function (item) {
|
||||||
|
const position = item.curve.getPointAt(item.phase);
|
||||||
|
item.glow.position.copy(position);
|
||||||
|
item.dot.position.copy(position);
|
||||||
|
item.glow.visible = !animate || reducedMotion.matches;
|
||||||
|
item.dot.visible = !animate || reducedMotion.matches;
|
||||||
|
});
|
||||||
|
revealStart = performance.now() - (animate && !reducedMotion.matches ? 0 : 760);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resize() {
|
||||||
|
const width = Math.max(1, stage.clientWidth);
|
||||||
|
const height = Math.max(1, stage.clientHeight);
|
||||||
|
const nextAspect = width / height;
|
||||||
|
const sizeChanged = Math.abs(nextAspect - aspect) > 0.001 || Math.abs(height - stageHeight) > 1;
|
||||||
|
aspect = nextAspect;
|
||||||
|
stageHeight = height;
|
||||||
|
renderer.setSize(width, height, false);
|
||||||
|
camera.left = -nextAspect;
|
||||||
|
camera.right = nextAspect;
|
||||||
|
camera.top = 1;
|
||||||
|
camera.bottom = -1;
|
||||||
|
camera.updateProjectionMatrix();
|
||||||
|
if (sizeChanged && currentKey && !root.hidden) buildAnnotation(currentKey, currentMode, false);
|
||||||
|
renderer.render(scene, camera);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderFrame(now) {
|
||||||
|
if (!currentKey || root.hidden || document.hidden) {
|
||||||
|
animationFrame = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const seconds = now * 0.001;
|
||||||
|
const elapsed = (now - revealStart) / 760;
|
||||||
|
animatedMaterials.forEach(function (material) {
|
||||||
|
material.uniforms.uTime.value = seconds;
|
||||||
|
material.uniforms.uMotion.value = reducedMotion.matches ? 0 : 1;
|
||||||
|
});
|
||||||
|
if (!reducedMotion.matches) {
|
||||||
|
revealGeometries.forEach(function (item) {
|
||||||
|
const progress = Math.max(0, Math.min(1, (elapsed - item.delay) / 0.62));
|
||||||
|
const eased = 1 - Math.pow(1 - progress, 3);
|
||||||
|
const count = Math.floor(item.count * eased / 6) * 6;
|
||||||
|
item.geometry.setDrawRange(0, Math.max(0, count));
|
||||||
|
});
|
||||||
|
delayedMarkers.forEach(function (item) { item.mesh.visible = elapsed >= item.delay; });
|
||||||
|
const motionSeconds = Math.max(0, (now - revealStart) * 0.001);
|
||||||
|
runnerDots.forEach(function (item) {
|
||||||
|
const visible = elapsed >= item.delay;
|
||||||
|
item.glow.visible = visible;
|
||||||
|
item.dot.visible = visible;
|
||||||
|
if (!visible) return;
|
||||||
|
const position = item.curve.getPointAt((item.phase + motionSeconds * 0.065) % 1);
|
||||||
|
item.glow.position.copy(position);
|
||||||
|
item.dot.position.copy(position);
|
||||||
|
item.glow.scale.setScalar(1 + Math.sin(seconds * 3.6 + item.pulseOffset) * 0.14);
|
||||||
|
});
|
||||||
|
const pulse = 1 + Math.sin(seconds * 3.2) * 0.10;
|
||||||
|
pulseMeshes.forEach(function (mesh) { mesh.scale.setScalar(pulse); });
|
||||||
|
}
|
||||||
|
renderer.render(scene, camera);
|
||||||
|
if (reducedMotion.matches) {
|
||||||
|
animationFrame = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
animationFrame = window.requestAnimationFrame(renderFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
function startRendering() {
|
||||||
|
if (!animationFrame) animationFrame = window.requestAnimationFrame(renderFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
function show(key, mode) {
|
||||||
|
if (!ANNOTATIONS[key]) return;
|
||||||
|
window.clearTimeout(calloutTimer);
|
||||||
|
window.clearTimeout(hideTimer);
|
||||||
|
buildToken += 1;
|
||||||
|
currentKey = key;
|
||||||
|
currentMode = mode === "top" ? "top" : "perspective";
|
||||||
|
root.hidden = false;
|
||||||
|
root.classList.remove("is-visible", "is-callout-visible");
|
||||||
|
resize();
|
||||||
|
buildAnnotation(currentKey, currentMode, true);
|
||||||
|
const token = buildToken;
|
||||||
|
window.requestAnimationFrame(function () {
|
||||||
|
if (token === buildToken) root.classList.add("is-visible");
|
||||||
|
});
|
||||||
|
calloutTimer = window.setTimeout(function () {
|
||||||
|
if (token === buildToken) root.classList.add("is-callout-visible");
|
||||||
|
}, reducedMotion.matches ? 0 : 430);
|
||||||
|
startRendering();
|
||||||
|
}
|
||||||
|
|
||||||
|
function hide(immediate) {
|
||||||
|
buildToken += 1;
|
||||||
|
currentKey = null;
|
||||||
|
window.clearTimeout(calloutTimer);
|
||||||
|
window.clearTimeout(hideTimer);
|
||||||
|
root.classList.remove("is-visible", "is-callout-visible");
|
||||||
|
if (immediate) {
|
||||||
|
root.hidden = true;
|
||||||
|
clearAnnotation();
|
||||||
|
if (animationFrame) {
|
||||||
|
window.cancelAnimationFrame(animationFrame);
|
||||||
|
animationFrame = 0;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hideTimer = window.setTimeout(function () {
|
||||||
|
if (!currentKey) {
|
||||||
|
root.hidden = true;
|
||||||
|
clearAnnotation();
|
||||||
|
}
|
||||||
|
}, 220);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof ResizeObserver === "function") {
|
||||||
|
const observer = new ResizeObserver(resize);
|
||||||
|
observer.observe(stage);
|
||||||
|
} else {
|
||||||
|
window.addEventListener("resize", resize, { passive: true });
|
||||||
|
}
|
||||||
|
const handleMotionPreference = function () {
|
||||||
|
if (currentKey) {
|
||||||
|
buildAnnotation(currentKey, currentMode, false);
|
||||||
|
startRendering();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (typeof reducedMotion.addEventListener === "function") reducedMotion.addEventListener("change", handleMotionPreference);
|
||||||
|
else if (typeof reducedMotion.addListener === "function") reducedMotion.addListener(handleMotionPreference);
|
||||||
|
document.addEventListener("visibilitychange", function () {
|
||||||
|
if (!document.hidden && currentKey) startRendering();
|
||||||
|
});
|
||||||
|
|
||||||
|
window.TerrainAnnotation = {
|
||||||
|
show: show,
|
||||||
|
hide: hide,
|
||||||
|
getState: function () {
|
||||||
|
return { key: currentKey, mode: currentMode, renderer: "three-r" + THREE.REVISION, side: root.dataset.side || null };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
After Width: | Height: | Size: 701 KiB |
|
After Width: | Height: | Size: 1.0 MiB |
@@ -0,0 +1,333 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head><meta http-equiv="Content-Security-Policy" content="default-src 'self' file: data: blob:; connect-src 'self' file: data: blob:; img-src 'self' file: data: blob:; media-src 'self' file: data: blob:; font-src 'self' data:; style-src 'unsafe-inline' 'self' file: data:; script-src 'unsafe-inline' 'self' file: data: blob:; base-uri 'none'; form-action 'none'; frame-src 'none'; object-src 'none'; worker-src 'none'">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||||
|
<meta name="theme-color" content="#d7ecff">
|
||||||
|
<title>等高线地形——五大典型地貌判读</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="app-shell" id="app-shell">
|
||||||
|
<section class="media-stage" aria-label="等高线实验观察区">
|
||||||
|
<video
|
||||||
|
class="stage-media stage-video is-visible"
|
||||||
|
id="experiment-video"
|
||||||
|
src="assets/contour-formation.mp4"
|
||||||
|
preload="auto"
|
||||||
|
playsinline
|
||||||
|
aria-label="等高线形成交线实验视频"
|
||||||
|
></video>
|
||||||
|
<img
|
||||||
|
class="stage-media stage-image workflow-step-background"
|
||||||
|
id="density-background"
|
||||||
|
src="assets/density-background.jpg"
|
||||||
|
alt="山体两侧以疏密不同的等高线对比坡度"
|
||||||
|
decoding="async"
|
||||||
|
>
|
||||||
|
<img class="stage-media stage-image" id="landform-image" alt="" decoding="async">
|
||||||
|
<img class="stage-media stage-image stage-top-image" id="landform-top-image" alt="" decoding="async">
|
||||||
|
<div class="media-shade" aria-hidden="true"></div>
|
||||||
|
<div class="scan-effect" id="scan-effect" aria-hidden="true">
|
||||||
|
<span class="scan-grid"></span>
|
||||||
|
<span class="scan-beam"></span>
|
||||||
|
</div>
|
||||||
|
<svg
|
||||||
|
class="workflow-diagram workflow-diagram--projection"
|
||||||
|
id="projection-diagram"
|
||||||
|
viewBox="0 0 300 455"
|
||||||
|
role="img"
|
||||||
|
aria-labelledby="projection-diagram-title projection-diagram-description"
|
||||||
|
hidden
|
||||||
|
>
|
||||||
|
<title id="projection-diagram-title">垂直投影</title>
|
||||||
|
<desc id="projection-diagram-description">立体山体上的多层等高交线沿垂线投影到同一平面,形成平面等高线。</desc>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="projection-card-fill" x1="0" y1="0" x2="1" y2="1">
|
||||||
|
<stop offset="0" stop-color="#ffffff" stop-opacity=".94"/>
|
||||||
|
<stop offset="1" stop-color="#edf7ff" stop-opacity=".88"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="projection-beam" gradientUnits="userSpaceOnUse" x1="0" y1="60" x2="0" y2="340">
|
||||||
|
<stop offset="0" stop-color="#26c7ff" stop-opacity=".18"/>
|
||||||
|
<stop offset=".42" stop-color="#1089ff" stop-opacity=".72"/>
|
||||||
|
<stop offset="1" stop-color="#126fff" stop-opacity=".96"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="projection-layer-stroke" x1="0" y1="0" x2="1" y2="0">
|
||||||
|
<stop offset="0" stop-color="#3a7fff"/>
|
||||||
|
<stop offset=".5" stop-color="#31d8ff"/>
|
||||||
|
<stop offset="1" stop-color="#3a7fff"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="projection-plane-fill" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="0" stop-color="#eaf7ff" stop-opacity=".64"/>
|
||||||
|
<stop offset="1" stop-color="#b9ddff" stop-opacity=".20"/>
|
||||||
|
</linearGradient>
|
||||||
|
<filter id="projection-card-shadow" x="-30%" y="-20%" width="160%" height="160%">
|
||||||
|
<feDropShadow dx="0" dy="14" stdDeviation="14" flood-color="#052b50" flood-opacity=".20"/>
|
||||||
|
</filter>
|
||||||
|
<filter id="projection-glow" x="-80%" y="-80%" width="260%" height="260%">
|
||||||
|
<feGaussianBlur stdDeviation="2.6" result="blur"/>
|
||||||
|
<feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
|
||||||
|
</filter>
|
||||||
|
<marker id="projection-arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="6" markerHeight="6" orient="auto">
|
||||||
|
<path d="M1 1 7 4 1 7" fill="none" stroke="#147dff" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</marker>
|
||||||
|
</defs>
|
||||||
|
<rect class="diagram-card" x="3" y="3" width="294" height="449" rx="17" fill="url(#projection-card-fill)" filter="url(#projection-card-shadow)"/>
|
||||||
|
<text class="diagram-heading" x="20" y="38">垂直投影</text>
|
||||||
|
<g class="projection-stack" filter="url(#projection-glow)">
|
||||||
|
<ellipse class="projection-layer" style="--i:0" cx="150" cy="64" rx="43" ry="10"/>
|
||||||
|
<ellipse class="projection-layer" style="--i:1" cx="150" cy="84" rx="58" ry="12"/>
|
||||||
|
<ellipse class="projection-layer" style="--i:2" cx="150" cy="105" rx="75" ry="13"/>
|
||||||
|
<ellipse class="projection-layer" style="--i:3" cx="150" cy="126" rx="94" ry="15"/>
|
||||||
|
<ellipse class="projection-layer" style="--i:4" cx="150" cy="148" rx="111" ry="16"/>
|
||||||
|
<ellipse class="projection-layer" style="--i:5" cx="150" cy="170" rx="126" ry="18"/>
|
||||||
|
</g>
|
||||||
|
<g class="projection-columns">
|
||||||
|
<line class="projection-column" x1="49" y1="166" x2="49" y2="347" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="65" y1="154" x2="65" y2="331" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="83" y1="139" x2="83" y2="323" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="103" y1="121" x2="103" y2="331" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="125" y1="101" x2="125" y2="338" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="150" y1="73" x2="150" y2="347" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="175" y1="101" x2="175" y2="338" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="197" y1="121" x2="197" y2="331" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="217" y1="139" x2="217" y2="323" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="235" y1="154" x2="235" y2="331" marker-end="url(#projection-arrow)"/>
|
||||||
|
<line class="projection-column" x1="251" y1="166" x2="251" y2="347" marker-end="url(#projection-arrow)"/>
|
||||||
|
<g class="projection-crossings" filter="url(#projection-glow)">
|
||||||
|
<circle cx="65" cy="154" r="2.4"/><circle cx="83" cy="139" r="2.4"/><circle cx="103" cy="121" r="2.4"/>
|
||||||
|
<circle cx="125" cy="101" r="2.4"/><circle cx="150" cy="73" r="2.4"/><circle cx="175" cy="101" r="2.4"/>
|
||||||
|
<circle cx="197" cy="121" r="2.4"/><circle cx="217" cy="139" r="2.4"/><circle cx="235" cy="154" r="2.4"/>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
<g class="projection-plane">
|
||||||
|
<polygon points="34,300 266,300 285,395 15,395" fill="url(#projection-plane-fill)" stroke="#7fa6d4" stroke-width="1.1"/>
|
||||||
|
<path class="projection-grid" d="M30 318h240M26 340h248M22 365h256M19 383h262M63 300 48 395M91 300l-8 95M121 300l-3 95M150 300v95M179 300l3 95M209 300l8 95M237 300l15 95"/>
|
||||||
|
<ellipse class="projection-contour" style="--i:0" cx="150" cy="347" rx="101" ry="43"/>
|
||||||
|
<ellipse class="projection-contour" style="--i:1" cx="150" cy="347" rx="79" ry="34"/>
|
||||||
|
<ellipse class="projection-contour" style="--i:2" cx="150" cy="347" rx="59" ry="27"/>
|
||||||
|
<ellipse class="projection-contour" style="--i:3" cx="150" cy="347" rx="42" ry="20"/>
|
||||||
|
<ellipse class="projection-contour" style="--i:4" cx="150" cy="347" rx="24" ry="12"/>
|
||||||
|
<ellipse class="projection-contour" style="--i:5" cx="150" cy="347" rx="11" ry="6"/>
|
||||||
|
<g class="projection-landings" filter="url(#projection-glow)">
|
||||||
|
<circle cx="49" cy="347" r="2.8"/><circle cx="65" cy="331" r="2.8"/><circle cx="83" cy="323" r="2.8"/>
|
||||||
|
<circle cx="103" cy="331" r="2.8"/><circle cx="125" cy="338" r="2.8"/><circle cx="150" cy="347" r="2.8"/>
|
||||||
|
<circle cx="175" cy="338" r="2.8"/><circle cx="197" cy="331" r="2.8"/><circle cx="217" cy="323" r="2.8"/>
|
||||||
|
<circle cx="235" cy="331" r="2.8"/><circle cx="251" cy="347" r="2.8"/>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
<text class="diagram-footer" x="150" y="431" text-anchor="middle">立体交线 → 平面等高线</text>
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
<svg
|
||||||
|
class="workflow-diagram workflow-diagram--density"
|
||||||
|
id="density-diagram"
|
||||||
|
viewBox="0 0 368 283"
|
||||||
|
role="img"
|
||||||
|
aria-labelledby="density-diagram-title density-diagram-description"
|
||||||
|
hidden
|
||||||
|
>
|
||||||
|
<title id="density-diagram-title">疏密判坡</title>
|
||||||
|
<desc id="density-diagram-description">等高线稀疏的一侧坡缓,等高线密集的一侧坡陡。</desc>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="density-card-fill" x1="0" y1="0" x2="1" y2="1">
|
||||||
|
<stop offset="0" stop-color="#ffffff" stop-opacity=".94"/>
|
||||||
|
<stop offset="1" stop-color="#edf7ff" stop-opacity=".88"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="density-contour-stroke" gradientUnits="userSpaceOnUse" x1="95" y1="0" x2="320" y2="0">
|
||||||
|
<stop offset="0" stop-color="#1587ff"/>
|
||||||
|
<stop offset=".50" stop-color="#3e95ff"/>
|
||||||
|
<stop offset=".64" stop-color="#f0a43d"/>
|
||||||
|
<stop offset="1" stop-color="#ff8517"/>
|
||||||
|
</linearGradient>
|
||||||
|
<filter id="density-card-shadow" x="-30%" y="-35%" width="160%" height="180%">
|
||||||
|
<feDropShadow dx="0" dy="14" stdDeviation="14" flood-color="#052b50" flood-opacity=".20"/>
|
||||||
|
</filter>
|
||||||
|
<filter id="density-dot-glow" x="-120%" y="-120%" width="340%" height="340%">
|
||||||
|
<feGaussianBlur stdDeviation="3" result="blur"/>
|
||||||
|
<feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
|
||||||
|
</filter>
|
||||||
|
<path id="density-contour-shape" d="M342 164C342 111 309 75 258 65c-32-6-49-3-80-12-27-7-45 8-67 13-27 6-47 4-64 18-21 17-29 41-24 67 5 23 25 33 53 33 29 1 42 24 67 42 25 19 59 29 107 27 55-2 90-35 92-89Z"/>
|
||||||
|
</defs>
|
||||||
|
<rect class="diagram-card" x="3" y="3" width="362" height="277" rx="17" fill="url(#density-card-fill)" filter="url(#density-card-shadow)"/>
|
||||||
|
<text class="diagram-heading" x="20" y="38">疏密判坡</text>
|
||||||
|
<g class="density-contours">
|
||||||
|
<use class="density-contour" style="--i:0" href="#density-contour-shape"/>
|
||||||
|
<use class="density-contour" style="--i:1" href="#density-contour-shape" transform="translate(273 164) scale(.84) translate(-273 -164)"/>
|
||||||
|
<use class="density-contour" style="--i:2" href="#density-contour-shape" transform="translate(273 164) scale(.70) translate(-273 -164)"/>
|
||||||
|
<use class="density-contour" style="--i:3" href="#density-contour-shape" transform="translate(273 164) scale(.58) translate(-273 -164)"/>
|
||||||
|
<use class="density-contour" style="--i:4" href="#density-contour-shape" transform="translate(273 164) scale(.47) translate(-273 -164)"/>
|
||||||
|
<use class="density-contour" style="--i:5" href="#density-contour-shape" transform="translate(273 164) scale(.37) translate(-273 -164)"/>
|
||||||
|
<use class="density-contour" style="--i:6" href="#density-contour-shape" transform="translate(273 164) scale(.29) translate(-273 -164)"/>
|
||||||
|
<use class="density-contour" style="--i:7" href="#density-contour-shape" transform="translate(273 164) scale(.22) translate(-273 -164)"/>
|
||||||
|
<use class="density-contour" style="--i:8" href="#density-contour-shape" transform="translate(273 164) scale(.15) translate(-273 -164)"/>
|
||||||
|
</g>
|
||||||
|
<g class="density-callout density-callout--gentle">
|
||||||
|
<rect x="14" y="211" width="116" height="37" rx="8"/>
|
||||||
|
<path d="M60 190 52 207"/>
|
||||||
|
<circle cx="60" cy="190" r="7"/>
|
||||||
|
<text x="22" y="236">线疏 · 坡缓</text>
|
||||||
|
</g>
|
||||||
|
<g class="density-callout density-callout--steep">
|
||||||
|
<rect x="257" y="50" width="100" height="37" rx="8"/>
|
||||||
|
<path d="M293 125 307 88"/>
|
||||||
|
<circle cx="293" cy="125" r="7"/>
|
||||||
|
<text x="266" y="75">线密 · 坡陡</text>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
<div class="terrain-annotation" id="terrain-annotation" hidden>
|
||||||
|
<canvas id="terrain-annotation-canvas" aria-hidden="true"></canvas>
|
||||||
|
<svg class="terrain-callout-connector" id="terrain-callout-connector" aria-hidden="true" preserveAspectRatio="none">
|
||||||
|
<polygon id="terrain-callout-connector-shape"></polygon>
|
||||||
|
</svg>
|
||||||
|
<div class="terrain-callout" id="terrain-callout" role="status" aria-live="polite">
|
||||||
|
<span class="terrain-callout-kicker">动态判读</span>
|
||||||
|
<strong id="terrain-callout-title"></strong>
|
||||||
|
<p id="terrain-callout-copy"></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="media-loading" id="media-loading" role="status">
|
||||||
|
<span class="loading-ring"></span>
|
||||||
|
<span>实验影像加载中</span>
|
||||||
|
</div>
|
||||||
|
<div class="media-label" id="media-label" aria-live="polite">
|
||||||
|
<span class="media-label-kicker" id="media-label-kicker">实验流程</span>
|
||||||
|
<strong id="media-label-title">形成交线与垂直投影</strong>
|
||||||
|
<small id="media-label-copy">点击“开始实验”,直接在当前画面播放形成交线视频</small>
|
||||||
|
</div>
|
||||||
|
<div class="video-progress" aria-hidden="true"><span id="video-progress-fill"></span></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="heading-group">
|
||||||
|
<span class="subject-chip">高中地理</span>
|
||||||
|
<div class="heading-copy">
|
||||||
|
<h1>等高线地形——五大典型地貌判读</h1>
|
||||||
|
<p>观察水平切割、垂直投影与等高线地貌特征</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="top-actions">
|
||||||
|
<button class="glass-button" id="workflow-open" type="button">
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5.5A3.5 3.5 0 0 1 7.5 2H11v17H7.5A3.5 3.5 0 0 0 4 22V5.5Zm16 0A3.5 3.5 0 0 0 16.5 2H13v17h3.5a3.5 3.5 0 0 1 3.5 3V5.5Z"/></svg>
|
||||||
|
<span>实验流程</span>
|
||||||
|
</button>
|
||||||
|
<button class="glass-button" id="fullscreen-button" type="button">
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5"/></svg>
|
||||||
|
<span id="fullscreen-label">全屏</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<aside class="control-panel" aria-labelledby="panel-title">
|
||||||
|
<div class="panel-scroll">
|
||||||
|
<section class="flow-section">
|
||||||
|
<div class="section-heading">
|
||||||
|
<h2 id="panel-title">实验流程 · <span id="flow-count">1/4</span></h2>
|
||||||
|
<button class="panel-close" id="panel-close" type="button" aria-label="收起观察面板">×</button>
|
||||||
|
</div>
|
||||||
|
<div class="flow-track" id="flow-track">
|
||||||
|
<span class="flow-line" aria-hidden="true"><i id="flow-line-fill"></i></span>
|
||||||
|
<button class="flow-step is-active" type="button" data-step="0" aria-label="查看步骤一:等高切割">
|
||||||
|
<span class="step-dot">1</span><span class="step-name">等高切割</span>
|
||||||
|
</button>
|
||||||
|
<button class="flow-step" type="button" data-step="1" aria-label="查看步骤二:形成交线">
|
||||||
|
<span class="step-dot">2</span><span class="step-name">形成交线</span>
|
||||||
|
</button>
|
||||||
|
<button class="flow-step" type="button" data-step="2" aria-label="查看步骤三:投影成图">
|
||||||
|
<span class="step-dot">3</span><span class="step-name">投影成图</span>
|
||||||
|
</button>
|
||||||
|
<button class="flow-step" type="button" data-step="3" aria-label="查看步骤四:疏密判坡">
|
||||||
|
<span class="step-dot">4</span><span class="step-name">疏密判坡</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="glass-card task-card" aria-labelledby="task-title">
|
||||||
|
<span class="card-eyebrow">当前步骤</span>
|
||||||
|
<h3 id="task-title">等高切割</h3>
|
||||||
|
<p id="task-description">观察水平面与山体在同一海拔相交,形成连续闭合线。</p>
|
||||||
|
<div class="fixed-condition" aria-label="实验固定条件">
|
||||||
|
<span><i></i>水平切面</span>
|
||||||
|
<strong>等高距 d = 10 m</strong>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="glass-card terrain-card" aria-labelledby="terrain-title">
|
||||||
|
<div class="card-title-row">
|
||||||
|
<span class="card-eyebrow" id="terrain-title">典型地貌</span>
|
||||||
|
<button class="text-action" id="return-experiment" type="button" hidden>返回实验</button>
|
||||||
|
</div>
|
||||||
|
<div class="terrain-tabs" id="terrain-tabs" role="list" aria-label="五大典型地貌">
|
||||||
|
<button class="terrain-tab" type="button" data-landform="peak" aria-pressed="false">
|
||||||
|
<svg viewBox="0 0 42 34" aria-hidden="true"><path d="M4 29 16 9l5 8 5-12 12 24H4Z"/><path d="m20 19 4 6h-8l4-6Z" class="solid"/></svg>
|
||||||
|
<span>山峰</span>
|
||||||
|
</button>
|
||||||
|
<button class="terrain-tab" type="button" data-landform="ridge" aria-pressed="false">
|
||||||
|
<svg viewBox="0 0 42 34" aria-hidden="true"><path d="M3 29 12 9l7 5 7-10 13 25"/><path d="M10 28c5-7 9-10 14-11"/></svg>
|
||||||
|
<span>山脊</span>
|
||||||
|
</button>
|
||||||
|
<button class="terrain-tab" type="button" data-landform="valley" aria-pressed="false">
|
||||||
|
<svg viewBox="0 0 42 34" aria-hidden="true"><path d="M4 6c8 4 12 12 17 24C26 18 30 10 38 6"/><path d="M21 11v19" class="accent"/></svg>
|
||||||
|
<span>山谷</span>
|
||||||
|
</button>
|
||||||
|
<button class="terrain-tab" type="button" data-landform="saddle" aria-pressed="false">
|
||||||
|
<svg viewBox="0 0 42 34" aria-hidden="true"><path d="M4 25V8h10l7 8 7-8h10v17"/><path d="M14 9c0 6 2 9 7 9s7-3 7-9"/></svg>
|
||||||
|
<span>鞍部</span>
|
||||||
|
</button>
|
||||||
|
<button class="terrain-tab" type="button" data-landform="cliff" aria-pressed="false">
|
||||||
|
<svg viewBox="0 0 42 34" aria-hidden="true"><path d="M7 29V5h17l10 8v16"/><path d="M11 11h18M11 16h21M11 21h22"/></svg>
|
||||||
|
<span>陡崖</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="glass-card observation-card" aria-labelledby="observation-heading">
|
||||||
|
<div class="observation-copy">
|
||||||
|
<span class="card-eyebrow">当前观察</span>
|
||||||
|
<h3 id="observation-heading">实验演示</h3>
|
||||||
|
<p id="observation-summary">点击开始实验,在当前背景中观察等高切割、交线形成与垂直投影。</p>
|
||||||
|
<ul class="feature-list" id="feature-list">
|
||||||
|
<li>同一条等高线上海拔相等</li>
|
||||||
|
<li>相邻等高线高差保持一致</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<button class="top-view-card" id="top-view-toggle" type="button" disabled aria-pressed="false">
|
||||||
|
<span id="top-view-toggle-label">俯视图</span>
|
||||||
|
<small id="top-view-toggle-hint">选择地貌后切换</small>
|
||||||
|
<img id="top-view-thumbnail" alt="" decoding="async" hidden>
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<button class="panel-open" id="panel-open" type="button" aria-label="展开观察面板" hidden>
|
||||||
|
<span></span><span></span><span></span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div class="experiment-actions">
|
||||||
|
<button class="primary-button" id="play-button" type="button">
|
||||||
|
<span class="round-icon" id="play-icon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 24 24"><path d="m9 6 9 6-9 6V6Z"/></svg>
|
||||||
|
</span>
|
||||||
|
<span id="play-label">开始实验</span>
|
||||||
|
</button>
|
||||||
|
<button class="glass-button reset-button" id="reset-button" type="button">
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4v6h6M5.4 15.5A8 8 0 1 0 6 7"/></svg>
|
||||||
|
<span>重置</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="hint-bar" id="hint-bar">
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 10v6M12 7h.01"/></svg>
|
||||||
|
<span id="hint-text">点击“开始实验”,观看形成交线视频</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toast" id="toast" role="status" aria-live="polite"></div>
|
||||||
|
</main>
|
||||||
|
<script src="assets/three.min.js"></script>
|
||||||
|
<script src="assets/terrain-annotation.js"></script>
|
||||||
|
<script src="assets/app.js"></script>
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -397,27 +397,45 @@ class GcApi {
|
|||||||
|
|
||||||
final String baseUrl;
|
final String baseUrl;
|
||||||
|
|
||||||
|
/// 启动器注入的一次性会话令牌。后端在发布包模式下会校验它,
|
||||||
|
/// 防止前端误连到同机其他进程伪造的「后端」。
|
||||||
|
static final String? _sessionToken = _readSessionToken();
|
||||||
|
|
||||||
|
static String? _readSessionToken() {
|
||||||
|
const fromDefine = String.fromEnvironment('GC_UI_TOKEN');
|
||||||
|
if (fromDefine.isNotEmpty) return fromDefine;
|
||||||
|
final fromEnv = Platform.environment['GC_UI_TOKEN'];
|
||||||
|
return (fromEnv != null && fromEnv.isNotEmpty) ? fromEnv : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 带会话令牌的请求头;没有令牌时返回 const 空 map(调试/独立后端模式)。
|
||||||
|
Map<String, String> get _authHeaders =>
|
||||||
|
_sessionToken == null ? const {} : {'X-GC-UI-Token': _sessionToken!};
|
||||||
|
|
||||||
Uri _uri(String path, [Map<String, String>? query]) =>
|
Uri _uri(String path, [Map<String, String>? query]) =>
|
||||||
Uri.parse('$baseUrl$path').replace(queryParameters: query);
|
Uri.parse('$baseUrl$path').replace(queryParameters: query);
|
||||||
|
|
||||||
Future<dynamic> _send(String method, String path,
|
Future<dynamic> _send(String method, String path,
|
||||||
{Map<String, String>? query, Object? body}) async {
|
{Map<String, String>? query, Object? body}) async {
|
||||||
final uri = _uri(path, query);
|
final uri = _uri(path, query);
|
||||||
|
final auth = _authHeaders;
|
||||||
late http.Response response;
|
late http.Response response;
|
||||||
try {
|
try {
|
||||||
switch (method) {
|
switch (method) {
|
||||||
case 'GET':
|
case 'GET':
|
||||||
response = await _client.get(uri).timeout(const Duration(seconds: 30));
|
response = await _client.get(uri, headers: auth)
|
||||||
|
.timeout(const Duration(seconds: 30));
|
||||||
break;
|
break;
|
||||||
case 'POST':
|
case 'POST':
|
||||||
response = await _client
|
response = await _client
|
||||||
.post(uri,
|
.post(uri,
|
||||||
headers: const {'Content-Type': 'application/json'},
|
headers: <String, String>{...auth, 'Content-Type': 'application/json'},
|
||||||
body: body == null ? null : jsonEncode(body))
|
body: body == null ? null : jsonEncode(body))
|
||||||
.timeout(const Duration(seconds: 120));
|
.timeout(const Duration(seconds: 120));
|
||||||
break;
|
break;
|
||||||
case 'DELETE':
|
case 'DELETE':
|
||||||
response = await _client.delete(uri).timeout(const Duration(seconds: 30));
|
response = await _client.delete(uri, headers: auth)
|
||||||
|
.timeout(const Duration(seconds: 30));
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw ApiException('不支持的方法 $method');
|
throw ApiException('不支持的方法 $method');
|
||||||
@@ -516,6 +534,13 @@ class GcApi {
|
|||||||
await _send('POST', '/api/shell/open-url', body: {'url': url})
|
await _send('POST', '/api/shell/open-url', body: {'url': url})
|
||||||
as Map<String, dynamic>);
|
as Map<String, dynamic>);
|
||||||
|
|
||||||
/// 模型封面图地址(直接给 Image.network 用)。
|
/// 模型封面图地址(直接给 Image.network 用,带不上自定义头,令牌走 query 参数)。
|
||||||
String previewUrl(ModelInfo model) => '$baseUrl${model.previewUrl}';
|
String previewUrl(ModelInfo model) {
|
||||||
|
if (_sessionToken == null) return '$baseUrl${model.previewUrl}';
|
||||||
|
final uri = Uri.parse('$baseUrl${model.previewUrl}');
|
||||||
|
return uri.replace(queryParameters: {
|
||||||
|
...uri.queryParameters,
|
||||||
|
'X-GC-UI-Token': _sessionToken!,
|
||||||
|
}).toString();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,7 @@ class I18n {
|
|||||||
'app.name': 'Morris GC',
|
'app.name': 'Morris GC',
|
||||||
'app.tagline': '天文教学模型 · 可视化启动器',
|
'app.tagline': '天文教学模型 · 可视化启动器',
|
||||||
'nav.home': '主页',
|
'nav.home': '主页',
|
||||||
|
'nav.courseware': '等高线课件',
|
||||||
'nav.download': '下载',
|
'nav.download': '下载',
|
||||||
'nav.settings': '设置',
|
'nav.settings': '设置',
|
||||||
'nav.about': '关于',
|
'nav.about': '关于',
|
||||||
@@ -148,6 +149,7 @@ class I18n {
|
|||||||
'app.name': 'Morris GC',
|
'app.name': 'Morris GC',
|
||||||
'app.tagline': 'Astronomy teaching models · visual launcher',
|
'app.tagline': 'Astronomy teaching models · visual launcher',
|
||||||
'nav.home': 'Home',
|
'nav.home': 'Home',
|
||||||
|
'nav.courseware': 'Contour Course',
|
||||||
'nav.download': 'Download',
|
'nav.download': 'Download',
|
||||||
'nav.settings': 'Settings',
|
'nav.settings': 'Settings',
|
||||||
'nav.about': 'About',
|
'nav.about': 'About',
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
// 保留这个文件是为了让 shell.dart 等调用方的 import 路径不变。
|
// 保留这个文件是为了让 shell.dart 等调用方的 import 路径不变。
|
||||||
|
|
||||||
export 'pages/home.dart';
|
export 'pages/home.dart';
|
||||||
|
export 'pages/courseware.dart';
|
||||||
export 'pages/download.dart';
|
export 'pages/download.dart';
|
||||||
export 'pages/settings.dart';
|
export 'pages/settings.dart';
|
||||||
export 'pages/about.dart';
|
export 'pages/about.dart';
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||||
|
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
/// 等高线课件页:用 WebView 承载去除授权验证后的离线 HTML 课件。
|
||||||
|
///
|
||||||
|
/// 资源(index.html + assets/)作为 Flutter assets 打包。桌面 WebView 不能直接
|
||||||
|
/// 读 flutter assets,因此用一个仅监听 127.0.0.1 的静态服务器(端口 0 自动分配,
|
||||||
|
/// 不与后端/其他进程冲突)把 assets 暴露成 http://127.0.0.1:<port>/ 再交给
|
||||||
|
/// WebView 加载。图片、视频、Three.js 与全部交互都保持原课件原样。
|
||||||
|
class CoursewarePage extends StatefulWidget {
|
||||||
|
const CoursewarePage({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<CoursewarePage> createState() => _CoursewarePageState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _CoursewarePageState extends State<CoursewarePage>
|
||||||
|
with AutomaticKeepAliveClientMixin {
|
||||||
|
@override
|
||||||
|
bool get wantKeepAlive => true;
|
||||||
|
|
||||||
|
HttpServer? _server;
|
||||||
|
int? _port;
|
||||||
|
InAppWebViewController? _controller;
|
||||||
|
double _progress = 0;
|
||||||
|
String? _error;
|
||||||
|
Directory? _extractDir;
|
||||||
|
|
||||||
|
/// 打包后的 app 工作目录不固定,不能直接用相对路径读 flutter assets。
|
||||||
|
/// 首次进入时把课件资源解压到临时目录,服务器再从这里提供文件。
|
||||||
|
Future<Directory> _extractAssets() async {
|
||||||
|
final dir = await Directory.systemTemp.createTemp('gc-courseware-');
|
||||||
|
final manifest = await AssetManifest.loadFromAssetBundle(rootBundle);
|
||||||
|
const prefix = 'courseware/';
|
||||||
|
for (final key in manifest.listAssets()) {
|
||||||
|
if (!key.startsWith(prefix)) continue;
|
||||||
|
final rel = key.substring(prefix.length);
|
||||||
|
if (rel.isEmpty) continue;
|
||||||
|
final data = await rootBundle.load(key);
|
||||||
|
final out = File('${dir.path}/$rel');
|
||||||
|
await out.parent.create(recursive: true);
|
||||||
|
await out.writeAsBytes(data.buffer.asUint8List(
|
||||||
|
data.offsetInBytes, data.lengthInBytes));
|
||||||
|
}
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_start();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _start() async {
|
||||||
|
try {
|
||||||
|
_extractDir = await _extractAssets();
|
||||||
|
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
_server = server;
|
||||||
|
_port = server.port;
|
||||||
|
server.listen(_handleRequest);
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
} catch (e) {
|
||||||
|
if (mounted) setState(() => _error = e.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只服务课件目录内的文件,路径做规范化防止越界。
|
||||||
|
Future<void> _handleRequest(HttpRequest req) async {
|
||||||
|
var path = Uri.decodeFull(req.uri.path);
|
||||||
|
if (path == '/' || path.isEmpty) path = '/index.html';
|
||||||
|
// 去掉开头斜杠,拼到资源根目录
|
||||||
|
final rel = path.replaceFirst(RegExp(r'^/+'), '');
|
||||||
|
final normalized = _normalize(rel);
|
||||||
|
final file = File('${_extractDir?.path ?? "."}/$normalized');
|
||||||
|
try {
|
||||||
|
if (!await file.exists()) {
|
||||||
|
req.response.statusCode = HttpStatus.notFound;
|
||||||
|
req.response.write('404 $rel');
|
||||||
|
await req.response.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final length = await file.length();
|
||||||
|
// _mimeOf 返回完整 MIME(含主/子类型);charset 由 HTML 的 meta 声明。
|
||||||
|
req.response.headers.contentType = ContentType.parse(_mimeOf(rel));
|
||||||
|
req.response.headers.set('Accept-Ranges', 'bytes');
|
||||||
|
|
||||||
|
// 视频拖动依赖 HTTP Range;解析 "bytes=start-end" 返回 206。
|
||||||
|
final range = req.headers.value('range');
|
||||||
|
if (range != null && range.startsWith('bytes=')) {
|
||||||
|
final span = range.substring(6).split('-');
|
||||||
|
var start = int.tryParse(span.first) ?? 0;
|
||||||
|
var end = span.length > 1 ? int.tryParse(span.last) : null;
|
||||||
|
if (start < 0) start = 0;
|
||||||
|
if (start >= length) {
|
||||||
|
req.response.statusCode = HttpStatus.requestedRangeNotSatisfiable;
|
||||||
|
req.response.headers.set('Content-Range', 'bytes */$length');
|
||||||
|
await req.response.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
end ??= length - 1;
|
||||||
|
if (end >= length) end = length - 1;
|
||||||
|
if (end < start) end = start;
|
||||||
|
req.response.statusCode = HttpStatus.partialContent;
|
||||||
|
req.response.headers.set('Content-Range', 'bytes $start-$end/$length');
|
||||||
|
req.response.headers.set('Content-Length', '${end - start + 1}');
|
||||||
|
await req.response.addStream(
|
||||||
|
file.openRead(start, end + 1).cast<List<int>>());
|
||||||
|
await req.response.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
req.response.headers.set('Content-Length', '$length');
|
||||||
|
await req.response.addStream(file.openRead().cast<List<int>>());
|
||||||
|
await req.response.close();
|
||||||
|
} catch (e) {
|
||||||
|
req.response.statusCode = HttpStatus.internalServerError;
|
||||||
|
await req.response.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 折叠 .. 与 .,防止 ../ 越界读取其他文件。
|
||||||
|
static String _normalize(String path) {
|
||||||
|
final parts = <String>[];
|
||||||
|
for (final seg in path.split('/')) {
|
||||||
|
if (seg.isEmpty || seg == '.') continue;
|
||||||
|
if (seg == '..') {
|
||||||
|
if (parts.isNotEmpty) parts.removeLast();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
parts.add(seg);
|
||||||
|
}
|
||||||
|
return parts.join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _mimeOf(String path) {
|
||||||
|
final ext = path.split('.').last.toLowerCase();
|
||||||
|
switch (ext) {
|
||||||
|
case 'html':
|
||||||
|
case 'htm':
|
||||||
|
return 'text/html';
|
||||||
|
case 'css':
|
||||||
|
return 'text/css';
|
||||||
|
case 'js':
|
||||||
|
return 'text/javascript';
|
||||||
|
case 'json':
|
||||||
|
return 'application/json';
|
||||||
|
case 'png':
|
||||||
|
return 'image/png';
|
||||||
|
case 'jpg':
|
||||||
|
case 'jpeg':
|
||||||
|
return 'image/jpeg';
|
||||||
|
case 'gif':
|
||||||
|
return 'image/gif';
|
||||||
|
case 'svg':
|
||||||
|
return 'image/svg+xml';
|
||||||
|
case 'mp4':
|
||||||
|
return 'video/mp4';
|
||||||
|
case 'webm':
|
||||||
|
return 'video/webm';
|
||||||
|
case 'ico':
|
||||||
|
return 'image/x-icon';
|
||||||
|
default:
|
||||||
|
return 'application/octet-stream';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _reload() async {
|
||||||
|
if (_port == null) return;
|
||||||
|
await _controller?.loadUrl(
|
||||||
|
urlRequest: URLRequest(
|
||||||
|
url: WebUri('http://127.0.0.1:$_port/index.html'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
unawaited(() async {
|
||||||
|
await _server?.close();
|
||||||
|
try {
|
||||||
|
await _extractDir?.delete(recursive: true);
|
||||||
|
} catch (_) {
|
||||||
|
// 临时目录清理失败无需影响页面销毁。
|
||||||
|
}
|
||||||
|
}());
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
super.build(context);
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: <Widget>[
|
||||||
|
_toolbar(),
|
||||||
|
Expanded(child: _body()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _toolbar() {
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.surface,
|
||||||
|
border: Border(bottom: BorderSide(color: GcColors.line)),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
const Icon(Icons.terrain_rounded, size: 20),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
const Text(
|
||||||
|
'等高线地形 · 五大典型地貌判读',
|
||||||
|
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
IconButton(
|
||||||
|
tooltip: '刷新',
|
||||||
|
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||||
|
onPressed: _reload,
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: '全屏',
|
||||||
|
icon: const Icon(Icons.fullscreen_rounded, size: 18),
|
||||||
|
onPressed: () => _controller?.evaluateJavascript(
|
||||||
|
source: 'document.documentElement.requestFullscreen?.();',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _body() {
|
||||||
|
if (_error != null) {
|
||||||
|
return Center(child: Text('课件加载失败:$_error'));
|
||||||
|
}
|
||||||
|
if (_port == null) {
|
||||||
|
return const Center(child: CircularProgressIndicator(strokeWidth: 2));
|
||||||
|
}
|
||||||
|
return _webview();
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _webview() {
|
||||||
|
return Stack(
|
||||||
|
children: <Widget>[
|
||||||
|
InAppWebView(
|
||||||
|
initialUrlRequest: URLRequest(
|
||||||
|
url: WebUri('http://127.0.0.1:$_port/index.html'),
|
||||||
|
),
|
||||||
|
initialSettings: InAppWebViewSettings(
|
||||||
|
javaScriptEnabled: true,
|
||||||
|
mediaPlaybackRequiresUserGesture: false,
|
||||||
|
allowsInlineMediaPlayback: true,
|
||||||
|
supportZoom: false,
|
||||||
|
clearCache: false,
|
||||||
|
// 本地可信内容,允许混合加载。
|
||||||
|
mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
|
||||||
|
),
|
||||||
|
onWebViewCreated: (controller) => _controller = controller,
|
||||||
|
onProgressChanged: (_, progress) {
|
||||||
|
if (mounted && progress < 100) {
|
||||||
|
setState(() => _progress = progress / 100);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onLoadStop: (_, __) {
|
||||||
|
if (mounted) setState(() => _progress = 1);
|
||||||
|
},
|
||||||
|
onReceivedError: (_, request, error) {
|
||||||
|
if (mounted) {
|
||||||
|
setState(() => _error = '${error.type} ${error.description}');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
if (_progress < 1)
|
||||||
|
Positioned(
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
child: SizedBox(
|
||||||
|
height: 2,
|
||||||
|
child: LinearProgressIndicator(value: _progress),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -276,12 +276,12 @@ class _HomePageViewState extends State<HomePageView> {
|
|||||||
),
|
),
|
||||||
const SizedBox(width: GcSpace.md),
|
const SizedBox(width: GcSpace.md),
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onPressed: () => widget.controller.goTo(1),
|
onPressed: () => widget.controller.goTo(2),
|
||||||
child: Text(T('home.download')),
|
child: Text(T('home.download')),
|
||||||
),
|
),
|
||||||
const SizedBox(width: GcSpace.xs),
|
const SizedBox(width: GcSpace.xs),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => widget.controller.goTo(2),
|
onPressed: () => widget.controller.goTo(3),
|
||||||
child: Text(T('home.settings')),
|
child: Text(T('home.settings')),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -414,7 +414,7 @@ class _HomePageViewState extends State<HomePageView> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: GcSpace.xl),
|
const SizedBox(height: GcSpace.xl),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
onPressed: () => widget.controller.goTo(1),
|
onPressed: () => widget.controller.goTo(2),
|
||||||
child: Text(T('home.emptyAction')),
|
child: Text(T('home.emptyAction')),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ class _NavItem {
|
|||||||
|
|
||||||
const List<_NavItem> _navItems = <_NavItem>[
|
const List<_NavItem> _navItems = <_NavItem>[
|
||||||
_NavItem(Icons.dashboard_rounded, 'nav.home'),
|
_NavItem(Icons.dashboard_rounded, 'nav.home'),
|
||||||
|
_NavItem(Icons.terrain_rounded, 'nav.courseware'),
|
||||||
_NavItem(Icons.download_rounded, 'nav.download'),
|
_NavItem(Icons.download_rounded, 'nav.download'),
|
||||||
_NavItem(Icons.tune_rounded, 'nav.settings'),
|
_NavItem(Icons.tune_rounded, 'nav.settings'),
|
||||||
_NavItem(Icons.info_outline_rounded, 'nav.about'),
|
_NavItem(Icons.info_outline_rounded, 'nav.about'),
|
||||||
@@ -89,7 +90,10 @@ class _ShellPageState extends State<ShellPage> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _content(ShellController controller) {
|
Widget _content(ShellController controller) {
|
||||||
if (!controller.backendReady) {
|
// 课件页是纯前端资源,不依赖后端:即使后端未就绪也可打开。
|
||||||
|
// 注意 _buildPage 内部对 index 1 返回课件页,这里单独放行它。
|
||||||
|
final courseware = controller.index == 1;
|
||||||
|
if (!courseware && !controller.backendReady) {
|
||||||
if (controller.loadError != null) {
|
if (controller.loadError != null) {
|
||||||
return _BackendDown(controller: controller);
|
return _BackendDown(controller: controller);
|
||||||
}
|
}
|
||||||
@@ -124,10 +128,13 @@ class _ShellPageState extends State<ShellPage> {
|
|||||||
Widget _buildPage(ShellController controller, int index) {
|
Widget _buildPage(ShellController controller, int index) {
|
||||||
switch (index) {
|
switch (index) {
|
||||||
case 1:
|
case 1:
|
||||||
return DownloadPageView(controller: controller);
|
// 课件页自持有 WebView 状态,不需要 controller。
|
||||||
|
return const CoursewarePage();
|
||||||
case 2:
|
case 2:
|
||||||
return SettingsPageView(controller: controller);
|
return DownloadPageView(controller: controller);
|
||||||
case 3:
|
case 3:
|
||||||
|
return SettingsPageView(controller: controller);
|
||||||
|
case 4:
|
||||||
return AboutPageView(controller: controller);
|
return AboutPageView(controller: controller);
|
||||||
default:
|
default:
|
||||||
return HomePageView(controller: controller);
|
return HomePageView(controller: controller);
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
|
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
|
||||||
#include "ephemeral/Flutter-Generated.xcconfig"
|
#include "ephemeral/Flutter-Generated.xcconfig"
|
||||||
@@ -1 +1,2 @@
|
|||||||
|
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
|
||||||
#include "ephemeral/Flutter-Generated.xcconfig"
|
#include "ephemeral/Flutter-Generated.xcconfig"
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
platform :osx, '12.0'
|
||||||
|
|
||||||
|
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
|
||||||
|
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
|
||||||
|
|
||||||
|
project 'Runner', {
|
||||||
|
'Debug' => :debug,
|
||||||
|
'Profile' => :release,
|
||||||
|
'Release' => :release,
|
||||||
|
}
|
||||||
|
|
||||||
|
def flutter_root
|
||||||
|
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__)
|
||||||
|
unless File.exist?(generated_xcode_build_settings_path)
|
||||||
|
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first"
|
||||||
|
end
|
||||||
|
|
||||||
|
File.foreach(generated_xcode_build_settings_path) do |line|
|
||||||
|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
|
||||||
|
return matches[1].strip if matches
|
||||||
|
end
|
||||||
|
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\""
|
||||||
|
end
|
||||||
|
|
||||||
|
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
|
||||||
|
|
||||||
|
flutter_macos_podfile_setup
|
||||||
|
|
||||||
|
target 'Runner' do
|
||||||
|
use_frameworks!
|
||||||
|
use_modular_headers!
|
||||||
|
|
||||||
|
flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__))
|
||||||
|
target 'RunnerTests' do
|
||||||
|
inherit! :search_paths
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
post_install do |installer|
|
||||||
|
installer.pods_project.targets.each do |target|
|
||||||
|
flutter_additional_macos_build_settings(target)
|
||||||
|
# Xcode 27 起最低部署目标为 12.0;逐个 pod 提升,避免旧 pod 的 10.13/10.14 报错。
|
||||||
|
target.build_configurations.each do |config|
|
||||||
|
config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '12.0'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -27,6 +27,8 @@
|
|||||||
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
|
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
|
||||||
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };
|
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };
|
||||||
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };
|
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };
|
||||||
|
6115A3AA09C0554E004627A7 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8206FEA4073335056184BFE7 /* Pods_RunnerTests.framework */; };
|
||||||
|
D97968A61668AD5CB0F4AD81 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A3E308B8A5C9BFB85DE87E1A /* Pods_Runner.framework */; };
|
||||||
/* End PBXBuildFile section */
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
/* Begin PBXContainerItemProxy section */
|
/* Begin PBXContainerItemProxy section */
|
||||||
@@ -60,11 +62,13 @@
|
|||||||
/* End PBXCopyFilesBuildPhase section */
|
/* End PBXCopyFilesBuildPhase section */
|
||||||
|
|
||||||
/* Begin PBXFileReference section */
|
/* Begin PBXFileReference section */
|
||||||
|
182DFB26FB114E38C6E212AD /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = "<group>"; };
|
||||||
|
280B76C220FC1F5F9A19A983 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
|
||||||
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
|
331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
|
||||||
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
|
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
|
||||||
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
|
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
|
||||||
33CC10ED2044A3C60003C045 /* gc_ui.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "gc_ui.app"; sourceTree = BUILT_PRODUCTS_DIR; };
|
33CC10ED2044A3C60003C045 /* gc_ui.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = gc_ui.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||||
33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };
|
33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };
|
||||||
33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
|
33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
|
||||||
@@ -76,8 +80,14 @@
|
|||||||
33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };
|
33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };
|
||||||
33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
|
33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
|
||||||
33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
|
33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
|
||||||
|
41137AAB2DF4C73772AD6680 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
|
||||||
|
75F404C3BC9A85A0940A1E7A /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = "<group>"; };
|
||||||
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
|
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
|
||||||
|
8206FEA4073335056184BFE7 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
|
8892D008E4FA6821A291BE17 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = "<group>"; };
|
||||||
|
8EFF00FDE3D0667C00609F10 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
|
||||||
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
|
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
|
||||||
|
A3E308B8A5C9BFB85DE87E1A /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
/* End PBXFileReference section */
|
/* End PBXFileReference section */
|
||||||
|
|
||||||
/* Begin PBXFrameworksBuildPhase section */
|
/* Begin PBXFrameworksBuildPhase section */
|
||||||
@@ -85,6 +95,7 @@
|
|||||||
isa = PBXFrameworksBuildPhase;
|
isa = PBXFrameworksBuildPhase;
|
||||||
buildActionMask = 2147483647;
|
buildActionMask = 2147483647;
|
||||||
files = (
|
files = (
|
||||||
|
6115A3AA09C0554E004627A7 /* Pods_RunnerTests.framework in Frameworks */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
};
|
};
|
||||||
@@ -92,6 +103,7 @@
|
|||||||
isa = PBXFrameworksBuildPhase;
|
isa = PBXFrameworksBuildPhase;
|
||||||
buildActionMask = 2147483647;
|
buildActionMask = 2147483647;
|
||||||
files = (
|
files = (
|
||||||
|
D97968A61668AD5CB0F4AD81 /* Pods_Runner.framework in Frameworks */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
};
|
};
|
||||||
@@ -125,6 +137,7 @@
|
|||||||
331C80D6294CF71000263BE5 /* RunnerTests */,
|
331C80D6294CF71000263BE5 /* RunnerTests */,
|
||||||
33CC10EE2044A3C60003C045 /* Products */,
|
33CC10EE2044A3C60003C045 /* Products */,
|
||||||
D73912EC22F37F3D000D13A0 /* Frameworks */,
|
D73912EC22F37F3D000D13A0 /* Frameworks */,
|
||||||
|
A82E8A367D68D5C69E25C9BA /* Pods */,
|
||||||
);
|
);
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
};
|
};
|
||||||
@@ -172,9 +185,25 @@
|
|||||||
path = Runner;
|
path = Runner;
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
};
|
};
|
||||||
|
A82E8A367D68D5C69E25C9BA /* Pods */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
280B76C220FC1F5F9A19A983 /* Pods-Runner.debug.xcconfig */,
|
||||||
|
8EFF00FDE3D0667C00609F10 /* Pods-Runner.release.xcconfig */,
|
||||||
|
41137AAB2DF4C73772AD6680 /* Pods-Runner.profile.xcconfig */,
|
||||||
|
75F404C3BC9A85A0940A1E7A /* Pods-RunnerTests.debug.xcconfig */,
|
||||||
|
8892D008E4FA6821A291BE17 /* Pods-RunnerTests.release.xcconfig */,
|
||||||
|
182DFB26FB114E38C6E212AD /* Pods-RunnerTests.profile.xcconfig */,
|
||||||
|
);
|
||||||
|
name = Pods;
|
||||||
|
path = Pods;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
D73912EC22F37F3D000D13A0 /* Frameworks */ = {
|
D73912EC22F37F3D000D13A0 /* Frameworks */ = {
|
||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
|
A3E308B8A5C9BFB85DE87E1A /* Pods_Runner.framework */,
|
||||||
|
8206FEA4073335056184BFE7 /* Pods_RunnerTests.framework */,
|
||||||
);
|
);
|
||||||
name = Frameworks;
|
name = Frameworks;
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
@@ -186,6 +215,7 @@
|
|||||||
isa = PBXNativeTarget;
|
isa = PBXNativeTarget;
|
||||||
buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
|
buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
|
||||||
buildPhases = (
|
buildPhases = (
|
||||||
|
EBEBA5BB2F5B8B60B8CBB8D2 /* [CP] Check Pods Manifest.lock */,
|
||||||
331C80D1294CF70F00263BE5 /* Sources */,
|
331C80D1294CF70F00263BE5 /* Sources */,
|
||||||
331C80D2294CF70F00263BE5 /* Frameworks */,
|
331C80D2294CF70F00263BE5 /* Frameworks */,
|
||||||
331C80D3294CF70F00263BE5 /* Resources */,
|
331C80D3294CF70F00263BE5 /* Resources */,
|
||||||
@@ -204,11 +234,13 @@
|
|||||||
isa = PBXNativeTarget;
|
isa = PBXNativeTarget;
|
||||||
buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
|
buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
|
||||||
buildPhases = (
|
buildPhases = (
|
||||||
|
6098269FDFAA15D26448E434 /* [CP] Check Pods Manifest.lock */,
|
||||||
33CC10E92044A3C60003C045 /* Sources */,
|
33CC10E92044A3C60003C045 /* Sources */,
|
||||||
33CC10EA2044A3C60003C045 /* Frameworks */,
|
33CC10EA2044A3C60003C045 /* Frameworks */,
|
||||||
33CC10EB2044A3C60003C045 /* Resources */,
|
33CC10EB2044A3C60003C045 /* Resources */,
|
||||||
33CC110E2044A8840003C045 /* Bundle Framework */,
|
33CC110E2044A8840003C045 /* Bundle Framework */,
|
||||||
3399D490228B24CF009A79C7 /* ShellScript */,
|
3399D490228B24CF009A79C7 /* ShellScript */,
|
||||||
|
A1BACCAA4E3E0600DECC8167 /* [CP] Embed Pods Frameworks */,
|
||||||
);
|
);
|
||||||
buildRules = (
|
buildRules = (
|
||||||
);
|
);
|
||||||
@@ -329,6 +361,67 @@
|
|||||||
shellPath = /bin/sh;
|
shellPath = /bin/sh;
|
||||||
shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire";
|
shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire";
|
||||||
};
|
};
|
||||||
|
6098269FDFAA15D26448E434 /* [CP] Check Pods Manifest.lock */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputFileListPaths = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
|
||||||
|
"${PODS_ROOT}/Manifest.lock",
|
||||||
|
);
|
||||||
|
name = "[CP] Check Pods Manifest.lock";
|
||||||
|
outputFileListPaths = (
|
||||||
|
);
|
||||||
|
outputPaths = (
|
||||||
|
"$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
|
||||||
|
showEnvVarsInLog = 0;
|
||||||
|
};
|
||||||
|
A1BACCAA4E3E0600DECC8167 /* [CP] Embed Pods Frameworks */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputFileListPaths = (
|
||||||
|
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
|
||||||
|
);
|
||||||
|
name = "[CP] Embed Pods Frameworks";
|
||||||
|
outputFileListPaths = (
|
||||||
|
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
|
||||||
|
showEnvVarsInLog = 0;
|
||||||
|
};
|
||||||
|
EBEBA5BB2F5B8B60B8CBB8D2 /* [CP] Check Pods Manifest.lock */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputFileListPaths = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
|
||||||
|
"${PODS_ROOT}/Manifest.lock",
|
||||||
|
);
|
||||||
|
name = "[CP] Check Pods Manifest.lock";
|
||||||
|
outputFileListPaths = (
|
||||||
|
);
|
||||||
|
outputPaths = (
|
||||||
|
"$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt",
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
|
||||||
|
showEnvVarsInLog = 0;
|
||||||
|
};
|
||||||
/* End PBXShellScriptBuildPhase section */
|
/* End PBXShellScriptBuildPhase section */
|
||||||
|
|
||||||
/* Begin PBXSourcesBuildPhase section */
|
/* Begin PBXSourcesBuildPhase section */
|
||||||
@@ -380,6 +473,7 @@
|
|||||||
/* Begin XCBuildConfiguration section */
|
/* Begin XCBuildConfiguration section */
|
||||||
331C80DB294CF71000263BE5 /* Debug */ = {
|
331C80DB294CF71000263BE5 /* Debug */ = {
|
||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 75F404C3BC9A85A0940A1E7A /* Pods-RunnerTests.debug.xcconfig */;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
@@ -394,6 +488,7 @@
|
|||||||
};
|
};
|
||||||
331C80DC294CF71000263BE5 /* Release */ = {
|
331C80DC294CF71000263BE5 /* Release */ = {
|
||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 8892D008E4FA6821A291BE17 /* Pods-RunnerTests.release.xcconfig */;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
@@ -408,6 +503,7 @@
|
|||||||
};
|
};
|
||||||
331C80DD294CF71000263BE5 /* Profile */ = {
|
331C80DD294CF71000263BE5 /* Profile */ = {
|
||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 182DFB26FB114E38C6E212AD /* Pods-RunnerTests.profile.xcconfig */;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
@@ -461,7 +557,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
@@ -543,7 +639,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = YES;
|
MTL_ENABLE_DEBUG_INFO = YES;
|
||||||
ONLY_ACTIVE_ARCH = YES;
|
ONLY_ACTIVE_ARCH = YES;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
@@ -593,7 +689,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
|
|||||||
@@ -4,4 +4,7 @@
|
|||||||
<FileRef
|
<FileRef
|
||||||
location = "group:Runner.xcodeproj">
|
location = "group:Runner.xcodeproj">
|
||||||
</FileRef>
|
</FileRef>
|
||||||
|
<FileRef
|
||||||
|
location = "group:Pods/Pods.xcodeproj">
|
||||||
|
</FileRef>
|
||||||
</Workspace>
|
</Workspace>
|
||||||
@@ -6,6 +6,8 @@
|
|||||||
<true/>
|
<true/>
|
||||||
<key>com.apple.security.cs.allow-jit</key>
|
<key>com.apple.security.cs.allow-jit</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<key>com.apple.security.network.client</key>
|
||||||
|
<true/>
|
||||||
<key>com.apple.security.network.server</key>
|
<key>com.apple.security.network.server</key>
|
||||||
<true/>
|
<true/>
|
||||||
</dict>
|
</dict>
|
||||||
|
|||||||
@@ -4,5 +4,9 @@
|
|||||||
<dict>
|
<dict>
|
||||||
<key>com.apple.security.app-sandbox</key>
|
<key>com.apple.security.app-sandbox</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<key>com.apple.security.network.client</key>
|
||||||
|
<true/>
|
||||||
|
<key>com.apple.security.network.server</key>
|
||||||
|
<true/>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
@@ -62,6 +62,70 @@ packages:
|
|||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
flutter_inappwebview:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: flutter_inappwebview
|
||||||
|
sha256: "80092d13d3e29b6227e25b67973c67c7210bd5e35c4b747ca908e31eb71a46d5"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.1.5"
|
||||||
|
flutter_inappwebview_android:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_inappwebview_android
|
||||||
|
sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.3"
|
||||||
|
flutter_inappwebview_internal_annotations:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_inappwebview_internal_annotations
|
||||||
|
sha256: "787171d43f8af67864740b6f04166c13190aa74a1468a1f1f1e9ee5b90c359cd"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.2.0"
|
||||||
|
flutter_inappwebview_ios:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_inappwebview_ios
|
||||||
|
sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.2"
|
||||||
|
flutter_inappwebview_macos:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_inappwebview_macos
|
||||||
|
sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.2"
|
||||||
|
flutter_inappwebview_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_inappwebview_platform_interface
|
||||||
|
sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.3.0+1"
|
||||||
|
flutter_inappwebview_web:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_inappwebview_web
|
||||||
|
sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.2"
|
||||||
|
flutter_inappwebview_windows:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_inappwebview_windows
|
||||||
|
sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.6.0"
|
||||||
flutter_lints:
|
flutter_lints:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description:
|
description:
|
||||||
@@ -75,6 +139,11 @@ packages:
|
|||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
flutter_web_plugins:
|
||||||
|
dependency: transitive
|
||||||
|
description: flutter
|
||||||
|
source: sdk
|
||||||
|
version: "0.0.0"
|
||||||
http:
|
http:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -155,6 +224,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.9.0"
|
version: "1.9.0"
|
||||||
|
plugin_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: plugin_platform_interface
|
||||||
|
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.8"
|
||||||
sky_engine:
|
sky_engine:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description: flutter
|
description: flutter
|
||||||
@@ -242,4 +319,4 @@ packages:
|
|||||||
version: "1.1.1"
|
version: "1.1.1"
|
||||||
sdks:
|
sdks:
|
||||||
dart: ">=3.5.4 <4.0.0"
|
dart: ">=3.5.4 <4.0.0"
|
||||||
flutter: ">=3.18.0-18.0.pre.54"
|
flutter: ">=3.24.0"
|
||||||
@@ -34,6 +34,9 @@ dependencies:
|
|||||||
# 与 GC-UI 后端(本地 HTTP 服务)通信
|
# 与 GC-UI 后端(本地 HTTP 服务)通信
|
||||||
http: ^1.2.2
|
http: ^1.2.2
|
||||||
|
|
||||||
|
# 桌面 WebView:承载离线等高线课件(Win/macOS/Linux)
|
||||||
|
flutter_inappwebview: 6.1.5
|
||||||
|
|
||||||
# The following adds the Cupertino Icons font to your application.
|
# The following adds the Cupertino Icons font to your application.
|
||||||
# Use with the CupertinoIcons class for iOS style icons.
|
# Use with the CupertinoIcons class for iOS style icons.
|
||||||
cupertino_icons: ^1.0.8
|
cupertino_icons: ^1.0.8
|
||||||
@@ -60,10 +63,10 @@ flutter:
|
|||||||
# the material Icons class.
|
# the material Icons class.
|
||||||
uses-material-design: true
|
uses-material-design: true
|
||||||
|
|
||||||
# To add assets to your application, add an assets section, like this:
|
assets:
|
||||||
# assets:
|
# 离线等高线课件(去除授权验证后的纯净版),整体作为目录打包。
|
||||||
# - images/a_dot_burr.jpeg
|
- courseware/
|
||||||
# - images/a_dot_ham.jpeg
|
- courseware/assets/
|
||||||
|
|
||||||
# An image asset can refer to one or more resolution-specific "variants", see
|
# An image asset can refer to one or more resolution-specific "variants", see
|
||||||
# https://flutter.dev/to/resolution-aware-images
|
# https://flutter.dev/to/resolution-aware-images
|
||||||
|
|||||||
@@ -172,6 +172,16 @@ public static class GcUiContract
|
|||||||
/// <summary>传给后端与前端的环境变量名。</summary>
|
/// <summary>传给后端与前端的环境变量名。</summary>
|
||||||
public const string PortEnvVar = "GC_UI_PORT";
|
public const string PortEnvVar = "GC_UI_PORT";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 启动器为本次会话生成的一次性令牌,经环境变量同时传给进程内后端与 Flutter 前端。
|
||||||
|
/// 前端每个请求都要带该令牌,后端据此确认对方是自己拉起的那个前端;
|
||||||
|
/// 同机伪装进程即便占了端口,也没有令牌,无法被前端当成后端复用。
|
||||||
|
/// </summary>
|
||||||
|
public const string TokenEnvVar = "GC_UI_TOKEN";
|
||||||
|
|
||||||
|
/// <summary>前端携带一次性令牌的请求头。</summary>
|
||||||
|
public const string TokenHeader = "X-GC-UI-Token";
|
||||||
|
|
||||||
/// <summary>读取环境变量里指定的端口;非法或未设置时返回 <see cref="DefaultPort"/>。</summary>
|
/// <summary>读取环境变量里指定的端口;非法或未设置时返回 <see cref="DefaultPort"/>。</summary>
|
||||||
public static int PortFromEnvironment()
|
public static int PortFromEnvironment()
|
||||||
{
|
{
|
||||||
@@ -180,4 +190,25 @@ public static class GcUiContract
|
|||||||
? port
|
? port
|
||||||
: DefaultPort;
|
: DefaultPort;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>生成 256 位会话令牌(hex);cryptographically random,无法预测。</summary>
|
||||||
|
public static string NewSessionToken()
|
||||||
|
{
|
||||||
|
var bytes = new byte[32];
|
||||||
|
System.Security.Cryptography.RandomNumberGenerator.Fill(bytes);
|
||||||
|
return Convert.ToHexString(bytes).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 由令牌派生一段短指纹,后端在 /api/health 里回给启动器用于身份确认。
|
||||||
|
/// 回指纹而非令牌本身,避免会话令牌出现在明文 HTTP 响应体里;启动器用同一函数
|
||||||
|
/// 算期望值比对,不匹配的「健康」响应一律视为伪装服务。
|
||||||
|
/// </summary>
|
||||||
|
public static string DeriveSessionProof(string? token)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(token)) return "";
|
||||||
|
var bytes = System.Text.Encoding.UTF8.GetBytes("gc-health-proof:" + token);
|
||||||
|
var hash = System.Security.Cryptography.SHA256.HashData(bytes);
|
||||||
|
return Convert.ToHexString(hash.AsSpan(0, 16)).ToLowerInvariant();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -5,8 +5,8 @@
|
|||||||
"en": "Contour Map"
|
"en": "Contour Map"
|
||||||
},
|
},
|
||||||
"descriptionI18n": {
|
"descriptionI18n": {
|
||||||
"zh-CN": "立体地形与平面等高线联动,判读山峰、山脊、山谷、鞍部、陡崖五种部位。",
|
"zh-CN": "可旋转 3D 地形 + 等高切割/交线/投影/判坡四步动画,判读山峰、山脊、山谷、鞍部、陡崖五大典型地貌。",
|
||||||
"en": "Link 3D relief with contour lines; identify peaks, ridges, valleys, saddles and cliffs."
|
"en": "Rotatable 3D terrain with a four-step animation of contour cutting, lines, projection and slope; identify five classic landforms."
|
||||||
},
|
},
|
||||||
"author": "Morris GC",
|
"author": "Morris GC",
|
||||||
"tags": [
|
"tags": [
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
],
|
],
|
||||||
"assembly": "ContourMapModel.dll",
|
"assembly": "ContourMapModel.dll",
|
||||||
"type": "GC.ContourMap.ContourMapFactory",
|
"type": "GC.ContourMap.ContourMapFactory",
|
||||||
"version": "1.1",
|
"version": "1.2",
|
||||||
"chrome": {
|
"chrome": {
|
||||||
"titleBar": "#0C1828",
|
"titleBar": "#0C1828",
|
||||||
"titleBorder": "#1B2740",
|
"titleBorder": "#1B2740",
|
||||||
|
|||||||
@@ -1,130 +1,116 @@
|
|||||||
{
|
{
|
||||||
"zh-CN": {
|
"zh-CN": {
|
||||||
"title": "如何使用 · 等高线地形图",
|
"title": "如何使用 · 等高线地形与五大典型地貌",
|
||||||
"sections": [
|
"sections": [
|
||||||
{
|
{
|
||||||
"h": "开始使用(跟着做)",
|
"h": "开始使用(跟着做)",
|
||||||
"lines": [
|
"lines": [
|
||||||
"第 1 步:顶部选一种地形(山地 / 盆地 / 丘陵 / 高原 / 平原),画面会换成对应的等高线图。",
|
"第 1 步:点右下角「开始实验」,在立体地形里观察水平切面下降、交线形成、垂直投影与疏密判坡四步动画。",
|
||||||
"第 2 步:把鼠标移到图上任意位置,底部会显示该点的海拔、相对高度和地形部位。",
|
"第 2 步:在立体地形上按住鼠标拖动可旋转视角,滚轮缩放;这是可交互的 3D 地形。",
|
||||||
"第 3 步:观察左边的立体地形与右边的等高线图,找出同一个山峰,看它在两张图上分别长什么样。",
|
"第 3 步:点画布上方「五大典型地貌」标签(山峰/山脊/山谷/鞍部/陡崖),画面换成对应的专门地形并叠加完整等高线,观察各自的等高线特征。",
|
||||||
"第 4 步:点右下角「取消上色」,只留等高线;再点一次恢复分层设色,对比哪种更便于判读。",
|
"第 4 步:点底部「俯视图 / 立体图」在等高线地图与 3D 地形间切换;鼠标悬停任意位置,底部显示该点海拔与地形部位。",
|
||||||
"第 5 步:对着右侧的判读要点,依次在图上找出一个山峰、一条山脊、一条山谷、一处鞍部和一处陡崖。"
|
"第 5 步:点「上色 / 取消上色」对比分层设色与纯等高线;点「全屏」进入全屏演示。"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "等高线是什么",
|
"h": "键盘快捷键",
|
||||||
"lines": [
|
"lines": [
|
||||||
"在地图上,把海拔相同的点用线连起来,这条线就叫等高线。",
|
"空格:播放 / 暂停实验。",
|
||||||
"相邻两条等高线之间的高差叫等高距:本图山地、高原、盆地用 100 米,丘陵用 10 米,平原用 5 米。",
|
"数字 1 – 5:依次切换到山峰、山脊、山谷、鞍部、陡崖。"
|
||||||
"等高线的闭合圈,数值由中心向四周递减的是山峰;四周高中间低的是盆地。",
|
|
||||||
"等高线向海拔低处凸出的是山脊(分水线);向海拔高处凸出的是山谷(集水线)。",
|
|
||||||
"两个山峰之间低下去的地方叫鞍部;等高线重叠或挤成一团的地方是陡崖。",
|
|
||||||
"等高线越密,坡度越陡;越疏,坡度越缓。",
|
|
||||||
"每 5 条等高线加粗一条叫计曲线,上面标着海拔,方便读数。"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "海拔与相对高度",
|
"h": "四步实验流程",
|
||||||
"lines": [
|
"lines": [
|
||||||
"海拔:地面某一点高出海平面的垂直距离。",
|
"等高切割:一个水平面从山顶向下移动,与山体在同一海拔相交。",
|
||||||
"相对高度:两个地点海拔的差值,也就是图上两点的落差。",
|
"形成交线:每个水平切面留下一条闭合交线,多层交线共同描述山体起伏。",
|
||||||
"底部读数里的「相对高度」是本图最低点到该点的高差。"
|
"投影成图:各高度的交线沿垂线投影到同一平面,累积成完整等高线图。",
|
||||||
|
"疏密判坡:坡度着色叠加等高线,陡处线密、缓处线疏。"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "五种地体的等高线特征",
|
"h": "五大典型地貌的判读",
|
||||||
"lines": [
|
"lines": [
|
||||||
"山地:海拔高、起伏大,等高线密集且数值跨度大。",
|
"山峰:等高线闭合,数值由中心向四周递减(若向内降低则为洼地)。",
|
||||||
"盆地:四周高、中间低,等高线由外向内数值递减,常有河流发育。",
|
"山脊:等高线向海拔低处凸出(凸低为脊),脊线是分水线。",
|
||||||
"丘陵:海拔不高、坡度和缓,等高线稀疏弯曲。",
|
"山谷:等高线向海拔高处凸出(凸高为谷),谷线是集水线,常发育河流。",
|
||||||
"高原:海拔高而顶面平坦,等高线中部稀疏、边缘密集。",
|
"鞍部:两座山峰之间相对低洼,俯视轮廓呈马鞍状收腰。",
|
||||||
"平原:海拔低、地面平坦,等高线很少甚至没有。"
|
"陡崖:等高线密集甚至重合,近乎垂直;n 条线重合时 (n−1)d ≤ ΔH < (n+1)d。"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "地图上的教科书符号",
|
"h": "等高线基础",
|
||||||
"lines": [
|
"lines": [
|
||||||
"分层设色:按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白),同一档内颜色完全相同。",
|
"同一条等高线上各点海拔相等;相邻等高线之间的高差叫等高距(本图 100 米)。",
|
||||||
"山峰用 ▲ 加高程数字标注。",
|
"等高线越密坡越陡,越疏坡越缓。",
|
||||||
"河流用蓝色线表示,沿谷底(等高线凸向高处的一侧)流。",
|
"每 5 条加粗一条叫计曲线,标注海拔便于读数。",
|
||||||
"陡崖用红色锯齿线表示。",
|
"海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。"
|
||||||
"指北针在图幅右上角,比例尺在左下角,分层设色图例在右下角。",
|
|
||||||
"地形剖面图在图幅底部:沿南北中线剖开地面,标出各点海拔,看清起伏。"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "容易出错的地方",
|
"h": "地图符号",
|
||||||
"lines": [
|
"lines": [
|
||||||
"把「等高线密集 = 陡」记反:密集是陡,稀疏是缓。",
|
"分层设色按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白)。",
|
||||||
"把山脊和山谷看反:看凸出的方向 —— 凸向低处是山脊,凸向高处是山谷。",
|
"山峰用 ▲ 加高程数字标注;河流用蓝色线沿谷底绘制;陡崖用红色锯齿线表示。",
|
||||||
"忽视等高距:等高距变了,同样的等高线密度代表的坡度就不同。",
|
"指北针在图幅右上,比例尺在左下,分层设色图例在右下,地形剖面图在底部。"
|
||||||
"把计曲线当成普通等高线:计曲线加粗并标了数值,读高程要看它。"
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"en": {
|
"en": {
|
||||||
"title": "How to use · Contour Map",
|
"title": "How to use · Contour Lines & Five Landforms",
|
||||||
"sections": [
|
"sections": [
|
||||||
{
|
{
|
||||||
"h": "Getting started (follow along)",
|
"h": "Getting started (follow along)",
|
||||||
"lines": [
|
"lines": [
|
||||||
"Step 1: pick a terrain type at the top (mountains / basin / hills / plateau / plain) — the map switches to its contour map.",
|
"Step 1: press Start to watch the four-step animation — contour cutting, line formation, vertical projection and slope reading.",
|
||||||
"Step 2: move the pointer anywhere on the map; the footer shows elevation, relative height and the terrain feature.",
|
"Step 2: drag with the mouse to rotate the 3D terrain, scroll to zoom; it is fully interactive.",
|
||||||
"Step 3: compare the 3D block on the left with the contour map on the right — find the same peak in both.",
|
"Step 3: click a landform tab above the canvas (peak / ridge / valley / saddle / cliff) to load its dedicated terrain with its full contour pattern.",
|
||||||
"Step 4: click “No colour” at the bottom right to keep only the contour lines; click again to restore the colour fill.",
|
"Step 4: toggle Top view / 3D view at the bottom; hover anywhere to read elevation and terrain feature.",
|
||||||
"Step 5: using the panel on the right, find one peak, one ridge, one valley, one saddle and one cliff."
|
"Step 5: use Colour / No colour to compare hypsometric tint with pure contour lines; use Fullscreen for presentation."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "What contour lines are",
|
"h": "Keyboard shortcuts",
|
||||||
"lines": [
|
"lines": [
|
||||||
"Connect points of equal elevation on a map and you get a contour line.",
|
"Space: play / pause the experiment.",
|
||||||
"The height gap between neighbouring contours is the contour interval: 100 m for mountains, plateau and basin; 10 m for hills; 5 m for plain.",
|
"Numbers 1 – 5: switch to peak, ridge, valley, saddle, cliff."
|
||||||
"A closed loop whose values decrease outward is a peak; high ground around a low centre is a basin.",
|
|
||||||
"Contours bulging toward lower ground form a ridge (watershed); bulging toward higher ground form a valley (drainage).",
|
|
||||||
"The low ground between two peaks is a saddle; overlapping or tightly crowded contours mark a cliff.",
|
|
||||||
"The closer the contours, the steeper the slope; the wider apart, the gentler.",
|
|
||||||
"Every 5th contour is bolded as an index contour and labelled with its elevation."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "Elevation and relative height",
|
"h": "The four experiment steps",
|
||||||
"lines": [
|
"lines": [
|
||||||
"Elevation is the vertical height of a point above sea level.",
|
"Contour cutting: a horizontal plane descends from the summit and intersects the mountain at one elevation.",
|
||||||
"Relative height is the difference between two elevations — the drop between two points on the map.",
|
"Forming lines: each slice leaves a closed intersection line; stacked lines describe the relief.",
|
||||||
"The relative height in the footer is measured from the lowest point of this map."
|
"Projection: intersection lines are projected vertically onto one plane, building the contour map.",
|
||||||
|
"Slope density: slope shading over contours — dense lines mean steep, sparse lines mean gentle."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "Contour patterns of the five terrains",
|
"h": "Reading the five landforms",
|
||||||
"lines": [
|
"lines": [
|
||||||
"Mountains: high elevation, large relief, dense contours over a wide value range.",
|
"Peak: closed contours, values decrease outward (if they decrease inward it is a depression).",
|
||||||
"Basin: high rim, low centre; values decrease inward, often with a river.",
|
"Ridge: contours bulge toward lower ground; a watershed line.",
|
||||||
"Hills: low elevation, gentle slopes, sparse winding contours.",
|
"Valley: contours bulge toward higher ground; a drainage line, often a stream.",
|
||||||
"Plateau: high but flat on top — contours sparse in the middle and crowded at the edges.",
|
"Saddle: low ground between two peaks, pinched like a saddle in plan view.",
|
||||||
"Plain: low and flat — few or no contour lines at all."
|
"Cliff: contours crowd or overlap, nearly vertical; n overlapping lines: (n−1)d ≤ ΔH < (n+1)d."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "Textbook map symbols",
|
"h": "Contour basics",
|
||||||
"lines": [
|
"lines": [
|
||||||
"Hypsometric tint: fixed colour bands by elevation (dark green → light green → green → pale yellow → yellow → light brown → brown → white); each band is a flat colour.",
|
"All points on one contour share the same elevation; the gap between neighbours is the contour interval (100 m here).",
|
||||||
"Peaks are marked with a ▲ and their elevation.",
|
"Closer contours mean steeper slopes; wider spacing means gentler slopes.",
|
||||||
"Rivers are drawn in blue along the valley floor (where contours bulge uphill).",
|
"Every 5th contour is bolded as an index contour and labelled with elevation.",
|
||||||
"Cliffs are marked with a red saw-tooth line.",
|
"Elevation is height above sea level; relative height is the difference between two elevations."
|
||||||
"A north arrow sits top-right, a scale bar bottom-left, and the tint legend bottom-right.",
|
|
||||||
"The terrain profile along the bottom cuts the ground open and labels elevations, showing the relief at a glance."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"h": "Common mistakes",
|
"h": "Map symbols",
|
||||||
"lines": [
|
"lines": [
|
||||||
"Reversing dense and sparse: dense means steep, sparse means gentle.",
|
"Hypsometric tint uses fixed colour bands (dark green → light green → green → pale yellow → yellow → light brown → brown → white).",
|
||||||
"Mixing up ridge and valley — look which way the bulge points: toward lower ground is a ridge, toward higher ground is a valley.",
|
"Peaks are marked with ▲ plus elevation; rivers are blue lines along valleys; cliffs use a red saw-tooth line.",
|
||||||
"Ignoring the contour interval: change it and the same spacing means a different slope.",
|
"North arrow top-right, scale bar bottom-left, tint legend bottom-right, terrain profile along the bottom."
|
||||||
"Treating index contours as ordinary ones — they are bold and labelled, so read elevations off them."
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
{
|
{
|
||||||
"app.title": "Contour Map",
|
"app.title": "Contour Lines · Five Classic Landforms",
|
||||||
"app.subtitle": "Grade 7 · Reading terrain maps: from 3D relief to contour lines"
|
"app.subtitle": "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs"
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
{
|
{
|
||||||
"app.title": "等高线地形图",
|
"app.title": "等高线地形 · 五大典型地貌判读",
|
||||||
"app.subtitle": "七年级上册 · 地形图的判读:从立体地形到平面等高线"
|
"app.subtitle": "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖"
|
||||||
}
|
}
|
||||||
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 65 KiB |
@@ -24,6 +24,7 @@ public sealed class ContourMapRuntime : IModelRuntime
|
|||||||
{
|
{
|
||||||
private TerrainField? _field;
|
private TerrainField? _field;
|
||||||
private Dictionary<string, string>? _texts;
|
private Dictionary<string, string>? _texts;
|
||||||
|
private ContourPage? _page;
|
||||||
|
|
||||||
public void Prepare(IModelContext context)
|
public void Prepare(IModelContext context)
|
||||||
{
|
{
|
||||||
@@ -41,22 +42,55 @@ public sealed class ContourMapRuntime : IModelRuntime
|
|||||||
public Control CreateView(IModelContext context)
|
public Control CreateView(IModelContext context)
|
||||||
{
|
{
|
||||||
_texts ??= LoadTexts(context.DataDirectory, context.Language);
|
_texts ??= LoadTexts(context.DataDirectory, context.Language);
|
||||||
// 五种地体都在界面里现场生成(切换很快,不必预先生成全部)
|
// 实验地形 + 五大地貌都在界面里现场生成(切换很快,不必预先生成全部)
|
||||||
return new ContourPage(_texts).Build();
|
_page = new ContourPage(_texts);
|
||||||
|
return _page.Build();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
|
_page?.Dispose();
|
||||||
|
_page = null;
|
||||||
_field = null;
|
_field = null;
|
||||||
_texts = null;
|
_texts = null;
|
||||||
System.GC.SuppressFinalize(this);
|
System.GC.SuppressFinalize(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 文案 = 内置默认(保证任何语言都有词)+ dataDir/i18n/<lang>.json 覆盖。
|
||||||
|
/// 语言包缺失或某条没翻译时自动退回内置默认,不会露出裸 key。
|
||||||
|
/// </summary>
|
||||||
private static Dictionary<string, string> LoadTexts(string dataDir, string language)
|
private static Dictionary<string, string> LoadTexts(string dataDir, string language)
|
||||||
{
|
{
|
||||||
var map = new Dictionary<string, string>(DefaultTexts.Zh);
|
|
||||||
var isEn = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
|
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;
|
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;
|
return map;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,16 +2,22 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Input;
|
||||||
using Avalonia.Layout;
|
using Avalonia.Layout;
|
||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
|
|
||||||
namespace GC.ContourMap;
|
namespace GC.ContourMap;
|
||||||
|
|
||||||
/// <summary>等高线模型的界面:顶部标题、中间双图联动、右侧判读要点、底部实时读数。</summary>
|
/// <summary>
|
||||||
|
/// 等高线模型界面(完整复刻 HTML 课件功能):
|
||||||
|
/// 顶部标题 + 全屏;左侧可交互 3D 画布;右侧实验流程/五大地貌/判读要点观察面板;
|
||||||
|
/// 底部播放控制、俯视切换、上色开关、实时读数;支持键盘 1-5 / 空格快捷键。
|
||||||
|
/// </summary>
|
||||||
public sealed class ContourPage
|
public sealed class ContourPage
|
||||||
{
|
{
|
||||||
private static readonly Color CAppBg = Color.Parse("#0B1524");
|
private static readonly Color CAppBg = Color.Parse("#0B1524");
|
||||||
private static readonly Color CPanel = Color.Parse("#101E31");
|
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 CLine = Color.Parse("#1E3350");
|
||||||
private static readonly Color CInk = Color.Parse("#EAF2FF");
|
private static readonly Color CInk = Color.Parse("#EAF2FF");
|
||||||
private static readonly Color CInkDim = Color.Parse("#93A8C6");
|
private static readonly Color CInkDim = Color.Parse("#93A8C6");
|
||||||
@@ -20,37 +26,61 @@ public sealed class ContourPage
|
|||||||
private static readonly Color CWarn = Color.Parse("#FFB454");
|
private static readonly Color CWarn = Color.Parse("#FFB454");
|
||||||
private static readonly Color CGood = Color.Parse("#5FD69B");
|
private static readonly Color CGood = Color.Parse("#5FD69B");
|
||||||
|
|
||||||
private TerrainField _field;
|
|
||||||
private readonly Dictionary<string, string> _texts;
|
private readonly Dictionary<string, string> _texts;
|
||||||
private readonly Dictionary<TerrainKind, TerrainField> _cache = new();
|
private readonly Dictionary<LandformKind, TerrainField> _landformCache = new();
|
||||||
private Border? _colorBtn;
|
private TerrainField _experimentField;
|
||||||
private TextBlock? _colorBtnText;
|
|
||||||
private TerrainKind _kind = TerrainKind.Mountain;
|
|
||||||
private ContourView? _view;
|
private ContourView? _view;
|
||||||
private TextBlock? _readout;
|
private TextBlock? _readout;
|
||||||
private TextBlock? _featureText;
|
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)
|
public ContourPage(Dictionary<string, string> texts)
|
||||||
{
|
{
|
||||||
_texts = texts;
|
_texts = texts;
|
||||||
_field = GetField(TerrainKind.Mountain);
|
_experimentField = new TerrainField(TerrainKind.Mountain, 192);
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>取(并缓存)某类地体的高度场,切换时不重复计算。</summary>
|
|
||||||
private TerrainField GetField(TerrainKind kind)
|
|
||||||
{
|
|
||||||
if (!_cache.TryGetValue(kind, out var f))
|
|
||||||
{
|
|
||||||
f = new TerrainField(kind, 192);
|
|
||||||
_cache[kind] = f;
|
|
||||||
}
|
|
||||||
return f;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private string T(string key) => _texts.TryGetValue(key, out var v) ? v : key;
|
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 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()
|
public Control Build()
|
||||||
{
|
{
|
||||||
var root = new Grid { Background = B(CAppBg) };
|
var root = new Grid { Background = B(CAppBg) };
|
||||||
@@ -60,12 +90,18 @@ public sealed class ContourPage
|
|||||||
|
|
||||||
root.Children.Add(BuildHeader());
|
root.Children.Add(BuildHeader());
|
||||||
|
|
||||||
var body = new Grid { Margin = new Thickness(14, 8, 14, 6) };
|
var body = new Grid { Margin = new Thickness(12, 8, 12, 6) };
|
||||||
body.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
|
body.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
|
||||||
body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(288)));
|
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(_field, T);
|
_view = new ContourView(_experimentField, T);
|
||||||
_view.HoverChanged += OnHover;
|
_view.HoverChanged += OnHover;
|
||||||
|
_view.StepChanged += OnStepChanged;
|
||||||
|
_view.ProgressChanged += OnProgressChanged;
|
||||||
|
_view.PlaybackFinished += OnPlaybackFinished;
|
||||||
|
|
||||||
var canvasHolder = new Border
|
var canvasHolder = new Border
|
||||||
{
|
{
|
||||||
Background = B(Color.Parse("#08111E")),
|
Background = B(Color.Parse("#08111E")),
|
||||||
@@ -75,66 +111,103 @@ public sealed class ContourPage
|
|||||||
ClipToBounds = true,
|
ClipToBounds = true,
|
||||||
Child = _view
|
Child = _view
|
||||||
};
|
};
|
||||||
Grid.SetColumn(canvasHolder, 0);
|
Grid.SetRow(canvasHolder, 1);
|
||||||
body.Children.Add(canvasHolder);
|
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();
|
var side = BuildSidePanel();
|
||||||
Grid.SetColumn(side, 1);
|
Grid.SetColumn(side, 1);
|
||||||
|
Grid.SetRow(side, 0);
|
||||||
|
Grid.SetRowSpan(side, 2);
|
||||||
body.Children.Add(side);
|
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);
|
Grid.SetRow(body, 1);
|
||||||
root.Children.Add(body);
|
root.Children.Add(body);
|
||||||
|
|
||||||
root.Children.Add(BuildFooter());
|
var footer = BuildFooter();
|
||||||
Grid.SetRow(root.Children[^1], 2);
|
Grid.SetRow(footer, 2);
|
||||||
|
root.Children.Add(footer);
|
||||||
|
|
||||||
|
root.AttachedToVisualTree += (_, _) =>
|
||||||
|
{
|
||||||
|
_topLevel = TopLevel.GetTopLevel(root);
|
||||||
|
};
|
||||||
|
root.KeyDown += OnKeyDown;
|
||||||
|
root.Focusable = true;
|
||||||
|
|
||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>窗口关闭时释放视图计时器,避免持有控件。</summary>
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_disposed) return;
|
||||||
|
_disposed = true;
|
||||||
|
_view?.DisposeView();
|
||||||
|
}
|
||||||
|
|
||||||
private Control BuildHeader()
|
private Control BuildHeader()
|
||||||
{
|
{
|
||||||
var title = new TextBlock
|
var title = new TextBlock
|
||||||
{
|
{
|
||||||
Text = T("app.title"),
|
Text = T("app.title"),
|
||||||
Foreground = B(CInk),
|
Foreground = B(CInk),
|
||||||
FontSize = 16,
|
FontSize = 18,
|
||||||
FontWeight = FontWeight.SemiBold
|
FontWeight = FontWeight.SemiBold
|
||||||
};
|
};
|
||||||
var sub = new TextBlock
|
var sub = new TextBlock
|
||||||
{
|
{
|
||||||
Text = T("app.subtitle"),
|
Text = T("app.subtitle"),
|
||||||
Foreground = B(CInkFaint),
|
Foreground = B(CInkDim),
|
||||||
FontSize = 10.5
|
FontSize = 11.5
|
||||||
};
|
};
|
||||||
var stack = new StackPanel { Spacing = 2 };
|
var stack = new StackPanel { Spacing = 2 };
|
||||||
stack.Children.Add(title);
|
stack.Children.Add(title);
|
||||||
stack.Children.Add(sub);
|
stack.Children.Add(sub);
|
||||||
|
|
||||||
// 地体类型选择:教科书里的五种基本地形
|
var fsLabel = new TextBlock { Text = T("btn.fullscreen"), Foreground = B(CInk), FontSize = 11.5 };
|
||||||
var kinds = new (TerrainKind Kind, string Key)[]
|
var fsBtn = new Border
|
||||||
{
|
{
|
||||||
(TerrainKind.Mountain, "kind.mountain"),
|
Background = B(CPanel2),
|
||||||
(TerrainKind.Basin, "kind.basin"),
|
BorderBrush = B(CLine),
|
||||||
(TerrainKind.Hill, "kind.hill"),
|
BorderThickness = new Thickness(1),
|
||||||
(TerrainKind.Plateau, "kind.plateau"),
|
CornerRadius = new CornerRadius(8),
|
||||||
(TerrainKind.Plain, "kind.plain"),
|
Padding = new Thickness(12, 6),
|
||||||
|
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||||
|
Child = fsLabel
|
||||||
};
|
};
|
||||||
|
fsBtn.PointerPressed += (_, _) => ToggleFullscreen(fsLabel);
|
||||||
|
|
||||||
var tabs = new StackPanel
|
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||||
{
|
grid.Children.Add(stack);
|
||||||
Orientation = Orientation.Horizontal,
|
Grid.SetColumn(fsBtn, 1);
|
||||||
Spacing = 6,
|
grid.Children.Add(fsBtn);
|
||||||
Margin = new Thickness(0, 9, 0, 0)
|
|
||||||
};
|
|
||||||
foreach (var (kind, key) in kinds)
|
|
||||||
{
|
|
||||||
var btn = MakeKindTab(kind, T(key));
|
|
||||||
tabs.Children.Add(btn);
|
|
||||||
}
|
|
||||||
|
|
||||||
var header = new StackPanel();
|
|
||||||
header.Children.Add(stack);
|
|
||||||
header.Children.Add(tabs);
|
|
||||||
|
|
||||||
return new Border
|
return new Border
|
||||||
{
|
{
|
||||||
@@ -142,70 +215,49 @@ public sealed class ContourPage
|
|||||||
BorderBrush = B(CLine),
|
BorderBrush = B(CLine),
|
||||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||||
Padding = new Thickness(18, 11, 18, 12),
|
Padding = new Thickness(18, 11, 18, 12),
|
||||||
Child = header
|
Child = grid
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>地体类型按钮:选中高亮。</summary>
|
|
||||||
private Button MakeKindTab(TerrainKind kind, string label)
|
|
||||||
{
|
|
||||||
var b = new Button
|
|
||||||
{
|
|
||||||
Content = label,
|
|
||||||
FontSize = 11.5,
|
|
||||||
Padding = new Thickness(13, 5),
|
|
||||||
CornerRadius = new CornerRadius(8),
|
|
||||||
BorderThickness = new Thickness(1),
|
|
||||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
|
||||||
Tag = kind
|
|
||||||
};
|
|
||||||
|
|
||||||
void Style()
|
|
||||||
{
|
|
||||||
var on = _kind == kind;
|
|
||||||
b.Background = B(on ? CAccent : Color.Parse("#16263C"));
|
|
||||||
b.BorderBrush = B(on ? CAccent : Color.Parse("#263A56"));
|
|
||||||
b.Foreground = B(on ? Colors.White : CInkDim);
|
|
||||||
}
|
|
||||||
Style();
|
|
||||||
|
|
||||||
b.Click += (_, _) =>
|
|
||||||
{
|
|
||||||
_kind = kind;
|
|
||||||
_field = GetField(kind);
|
|
||||||
_view?.SetField(_field);
|
|
||||||
// 重新刷新所有 tab 的选中态
|
|
||||||
if (b.Parent is StackPanel sp)
|
|
||||||
foreach (var c in sp.Children)
|
|
||||||
if (c is Button sib && sib.Tag is TerrainKind)
|
|
||||||
{
|
|
||||||
var on = (TerrainKind)sib.Tag == _kind;
|
|
||||||
sib.Background = B(on ? CAccent : Color.Parse("#16263C"));
|
|
||||||
sib.BorderBrush = B(on ? CAccent : Color.Parse("#263A56"));
|
|
||||||
sib.Foreground = B(on ? Colors.White : CInkDim);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return b;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Control BuildSidePanel()
|
private Control BuildSidePanel()
|
||||||
{
|
{
|
||||||
var panel = new StackPanel { Spacing = 10, Margin = new Thickness(12, 0, 0, 0) };
|
var panel = new StackPanel { Spacing = 8, Margin = new Thickness(12, 0, 0, 0) };
|
||||||
|
|
||||||
panel.Children.Add(Section(T("side.features")));
|
// ── 实验流程四步 ──
|
||||||
|
panel.Children.Add(Section(T("flow.title")));
|
||||||
foreach (var (titleKey, descKey) in new[]
|
for (var i = 0; i < 4; i++)
|
||||||
{
|
|
||||||
("feature.peak", "feature.peakDesc"),
|
|
||||||
("feature.ridge", "feature.ridgeDesc"),
|
|
||||||
("feature.valley", "feature.valleyDesc"),
|
|
||||||
("feature.saddle", "feature.saddleDesc"),
|
|
||||||
("feature.cliff", "feature.cliffDesc")
|
|
||||||
})
|
|
||||||
{
|
{
|
||||||
panel.Children.Add(FeatureRow(T(titleKey), T(descKey)));
|
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(Section(T("side.rules")));
|
||||||
panel.Children.Add(Bullet(T("rule.interval")));
|
panel.Children.Add(Bullet(T("rule.interval")));
|
||||||
panel.Children.Add(Bullet(T("rule.dense")));
|
panel.Children.Add(Bullet(T("rule.dense")));
|
||||||
@@ -228,55 +280,221 @@ public sealed class ContourPage
|
|||||||
return scroll;
|
return scroll;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Control Section(string text) => new TextBlock
|
private Border MakeFlowButton(int index)
|
||||||
{
|
{
|
||||||
Text = text,
|
var name = new TextBlock
|
||||||
Foreground = B(CInkDim),
|
|
||||||
FontSize = 11.5,
|
|
||||||
FontWeight = FontWeight.SemiBold,
|
|
||||||
Margin = new Thickness(0, 4, 0, 0)
|
|
||||||
};
|
|
||||||
|
|
||||||
private Control Bullet(string text) => new TextBlock
|
|
||||||
{
|
|
||||||
Text = "• " + text,
|
|
||||||
Foreground = B(CInkDim),
|
|
||||||
FontSize = 11,
|
|
||||||
TextWrapping = TextWrapping.Wrap,
|
|
||||||
LineHeight = 17
|
|
||||||
};
|
|
||||||
|
|
||||||
private Control FeatureRow(string name, string desc)
|
|
||||||
{
|
|
||||||
var title = new TextBlock
|
|
||||||
{
|
{
|
||||||
Text = name,
|
Text = $"{index + 1}. {T("flow.step." + index)}",
|
||||||
Foreground = B(CWarn),
|
Foreground = B(CInk),
|
||||||
FontSize = 12,
|
FontSize = 12.5,
|
||||||
FontWeight = FontWeight.SemiBold
|
FontWeight = FontWeight.SemiBold
|
||||||
};
|
};
|
||||||
var d = new TextBlock
|
var desc = new TextBlock
|
||||||
{
|
{
|
||||||
Text = desc,
|
Text = T("flow.desc." + index),
|
||||||
Foreground = B(CInkFaint),
|
Foreground = B(CInkFaint),
|
||||||
FontSize = 10.5,
|
FontSize = 11,
|
||||||
TextWrapping = TextWrapping.Wrap,
|
TextWrapping = TextWrapping.Wrap,
|
||||||
LineHeight = 16
|
LineHeight = 15
|
||||||
};
|
};
|
||||||
var stack = new StackPanel { Spacing = 1 };
|
var stack = new StackPanel { Spacing = 1 };
|
||||||
stack.Children.Add(title);
|
stack.Children.Add(name);
|
||||||
stack.Children.Add(d);
|
stack.Children.Add(desc);
|
||||||
return stack;
|
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()
|
private Control BuildFooter()
|
||||||
{
|
{
|
||||||
_readout = new TextBlock
|
// 播放 / 重置
|
||||||
|
_playLabel = new TextBlock { Text = T("btn.play"), Foreground = B(Colors.White), FontSize = 11.5, FontWeight = FontWeight.SemiBold };
|
||||||
|
_playBtn = new Border
|
||||||
{
|
{
|
||||||
Text = T("footer.hint"),
|
Background = B(CAccent),
|
||||||
Foreground = B(CInkDim),
|
CornerRadius = new CornerRadius(8),
|
||||||
FontSize = 11.5
|
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
|
_featureText = new TextBlock
|
||||||
{
|
{
|
||||||
Text = "",
|
Text = "",
|
||||||
@@ -286,64 +504,115 @@ public sealed class ContourPage
|
|||||||
HorizontalAlignment = HorizontalAlignment.Right
|
HorizontalAlignment = HorizontalAlignment.Right
|
||||||
};
|
};
|
||||||
|
|
||||||
// 右下角「上色」开关:点击一次去掉分层设色,只显示线稿,再点恢复
|
var info = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||||
_colorBtnText = new TextBlock
|
info.Children.Add(_readout);
|
||||||
{
|
Grid.SetColumn(_featureText, 1);
|
||||||
Text = T("btn.color"),
|
info.Children.Add(_featureText);
|
||||||
FontSize = 11.5,
|
|
||||||
Foreground = B(Colors.White)
|
|
||||||
};
|
|
||||||
_colorBtn = new Border
|
|
||||||
{
|
|
||||||
Background = B(CAccent),
|
|
||||||
CornerRadius = new CornerRadius(8),
|
|
||||||
Padding = new Thickness(13, 6),
|
|
||||||
Margin = new Thickness(0, 0, 12, 0),
|
|
||||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
|
||||||
Child = _colorBtnText
|
|
||||||
};
|
|
||||||
_colorBtn.PointerPressed += (_, _) => ToggleColor();
|
|
||||||
|
|
||||||
var left = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
var leftStack = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center };
|
||||||
left.Children.Add(_readout);
|
leftStack.Children.Add(_hintText);
|
||||||
Grid.SetColumn(_colorBtn, 1);
|
leftStack.Children.Add(info);
|
||||||
left.Children.Add(_colorBtn);
|
|
||||||
|
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") };
|
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||||
row.Children.Add(left);
|
row.Children.Add(progStack);
|
||||||
Grid.SetColumn(_featureText, 1);
|
Grid.SetColumn(controls, 1);
|
||||||
row.Children.Add(_featureText);
|
row.Children.Add(controls);
|
||||||
|
|
||||||
return new Border
|
return new Border
|
||||||
{
|
{
|
||||||
Background = B(CPanel),
|
Background = B(CPanel),
|
||||||
BorderBrush = B(CLine),
|
BorderBrush = B(CLine),
|
||||||
BorderThickness = new Thickness(0, 1, 0, 0),
|
BorderThickness = new Thickness(0, 1, 0, 0),
|
||||||
Padding = new Thickness(18, 9),
|
Padding = new Thickness(16, 9),
|
||||||
Child = row
|
Child = row
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>切换分层设色。</summary>
|
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()
|
private void ToggleColor()
|
||||||
{
|
{
|
||||||
if (_view == null) return;
|
if (_view == null) return;
|
||||||
_view.Colored = !_view.Colored;
|
_view.Colored = !_view.Colored;
|
||||||
if (_colorBtn != null)
|
if (_colorBtn != null) _colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55"));
|
||||||
_colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55"));
|
if (_colorBtnText != null) _colorBtnText.Text = _view.Colored ? T("btn.colorOn") : T("btn.color");
|
||||||
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)
|
private void OnHover(double u, double v, float height, TerrainFeature feature)
|
||||||
{
|
{
|
||||||
if (_readout == null || _featureText == null) return;
|
if (_readout == null || _featureText == null) return;
|
||||||
|
var field = _view?.Field ?? _experimentField;
|
||||||
var relative = height - _field.MinHeight;
|
var relative = height - field.MinHeight;
|
||||||
_readout.Text = string.Format(
|
_readout.Text = T("footer.readout", (int)height, (int)relative);
|
||||||
System.Globalization.CultureInfo.InvariantCulture,
|
|
||||||
T("footer.readout"), (int)height, (int)relative);
|
|
||||||
|
|
||||||
_featureText.Text = FeatureName(feature);
|
_featureText.Text = FeatureName(feature);
|
||||||
_featureText.Foreground = B(feature switch
|
_featureText.Foreground = B(feature switch
|
||||||
{
|
{
|
||||||
@@ -366,4 +635,87 @@ public sealed class ContourPage
|
|||||||
TerrainFeature.Slope => T("feature.slope"),
|
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);
|
||||||
}
|
}
|
||||||
@@ -2,24 +2,88 @@ using System.Collections.Generic;
|
|||||||
|
|
||||||
namespace GC.ContourMap;
|
namespace GC.ContourMap;
|
||||||
|
|
||||||
/// <summary>内置全量文案兜底:没有语言包也能完整显示。</summary>
|
/// <summary>内置全量文案兜底:没有语言包也能完整显示(复刻 HTML 课件全部文案)。</summary>
|
||||||
internal static class DefaultTexts
|
internal static class DefaultTexts
|
||||||
{
|
{
|
||||||
public static readonly Dictionary<string, string> Zh = new()
|
public static readonly Dictionary<string, string> Zh = new()
|
||||||
{
|
{
|
||||||
["app.title"] = "等高线地形图",
|
// 标题
|
||||||
["app.subtitle"] = "七年级上册 · 地形图的判读:从立体地形到平面等高线",
|
["app.title"] = "等高线地形 · 五大典型地貌判读",
|
||||||
|
["app.subtitle"] = "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖",
|
||||||
|
|
||||||
["kind.mountain"] = "山地",
|
// 实验流程四步
|
||||||
["kind.basin"] = "盆地",
|
["flow.title"] = "实验流程",
|
||||||
["kind.hill"] = "丘陵",
|
["flow.step.0"] = "等高切割",
|
||||||
["kind.plateau"] = "高原",
|
["flow.step.1"] = "形成交线",
|
||||||
["kind.plain"] = "平原",
|
["flow.step.2"] = "投影成图",
|
||||||
["legend.title"] = "分层设色",
|
["flow.step.3"] = "疏密判坡",
|
||||||
["profile.title"] = "地形剖面图",
|
["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.color"] = "上色",
|
||||||
["btn.colorOn"] = "取消上色",
|
["btn.colorOn"] = "取消上色",
|
||||||
|
["btn.fullscreen"] = "全屏",
|
||||||
|
["btn.exitFullscreen"] = "退出全屏",
|
||||||
|
["btn.backExperiment"] = "返回实验",
|
||||||
|
|
||||||
|
// 侧栏判读要点(通用地形)
|
||||||
["side.features"] = "五种地形部位",
|
["side.features"] = "五种地形部位",
|
||||||
["feature.peak"] = "山峰",
|
["feature.peak"] = "山峰",
|
||||||
["feature.peakDesc"] = "等高线闭合,数值由中心向四周递减。",
|
["feature.peakDesc"] = "等高线闭合,数值由中心向四周递减。",
|
||||||
@@ -33,30 +97,99 @@ internal static class DefaultTexts
|
|||||||
["feature.cliffDesc"] = "等高线重叠或非常密集,近乎垂直。",
|
["feature.cliffDesc"] = "等高线重叠或非常密集,近乎垂直。",
|
||||||
["feature.slope"] = "坡面",
|
["feature.slope"] = "坡面",
|
||||||
|
|
||||||
|
// 判读规则
|
||||||
["side.rules"] = "判读要点",
|
["side.rules"] = "判读要点",
|
||||||
["rule.interval"] = "等高距:相邻两条等高线的高度差,本图 100 米。",
|
["rule.interval"] = "等高距:相邻两条等高线的高度差,本图 100 米。",
|
||||||
["rule.dense"] = "等高线越密坡越陡,越疏坡越缓。",
|
["rule.dense"] = "等高线越密坡越陡,越疏坡越缓。",
|
||||||
["rule.index"] = "每 5 条加粗一条计曲线,标注海拔便于读数。",
|
["rule.index"] = "每 5 条加粗一条计曲线,标注海拔便于读数。",
|
||||||
["rule.height"] = "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。",
|
["rule.height"] = "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。",
|
||||||
|
|
||||||
["footer.hint"] = "把鼠标移到任意一侧,可查看该点的海拔与地形部位",
|
// 底部读数 / 图例
|
||||||
["footer.readout"] = "海拔 {0} m 相对高度 {1} m"
|
["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()
|
public static readonly Dictionary<string, string> En = new()
|
||||||
{
|
{
|
||||||
["app.title"] = "Contour Map",
|
["app.title"] = "Contour Lines · Five Classic Landforms",
|
||||||
["app.subtitle"] = "Grade 7 · Reading terrain maps: from 3D relief to contour lines",
|
["app.subtitle"] = "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs",
|
||||||
|
|
||||||
["kind.mountain"] = "Mountains",
|
["flow.title"] = "Experiment flow",
|
||||||
["kind.basin"] = "Basin",
|
["flow.step.0"] = "Contour cutting",
|
||||||
["kind.hill"] = "Hills",
|
["flow.step.1"] = "Forming lines",
|
||||||
["kind.plateau"] = "Plateau",
|
["flow.step.2"] = "Projection",
|
||||||
["kind.plain"] = "Plain",
|
["flow.step.3"] = "Slope density",
|
||||||
["legend.title"] = "Hypsometric tint",
|
["flow.desc.0"] = "Watch a horizontal plane intersect the mountain at one elevation, forming closed lines.",
|
||||||
["profile.title"] = "Terrain profile",
|
["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.color"] = "Colour",
|
||||||
["btn.colorOn"] = "No colour",
|
["btn.colorOn"] = "No colour",
|
||||||
|
["btn.fullscreen"] = "Fullscreen",
|
||||||
|
["btn.exitFullscreen"] = "Exit fullscreen",
|
||||||
|
["btn.backExperiment"] = "Back to experiment",
|
||||||
|
|
||||||
["side.features"] = "Five terrain features",
|
["side.features"] = "Five terrain features",
|
||||||
["feature.peak"] = "Peak",
|
["feature.peak"] = "Peak",
|
||||||
@@ -77,7 +210,16 @@ internal static class DefaultTexts
|
|||||||
["rule.index"] = "Every 5th contour is bolded and labelled as an index contour.",
|
["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.",
|
["rule.height"] = "Elevation above sea level; relative height is the difference of two elevations.",
|
||||||
|
|
||||||
["footer.hint"] = "Move the pointer over either side to read elevation and terrain feature",
|
["footer.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"
|
["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"
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -123,8 +123,6 @@ public static class TerrainAnalyzer
|
|||||||
public static (byte R, byte G, byte B) ColorForHeight(float h, float min, float max)
|
public static (byte R, byte G, byte B) ColorForHeight(float h, float min, float max)
|
||||||
{
|
{
|
||||||
// 按绝对高程分档(教科书就是这么画的:看的是海拔,不是相对高度)
|
// 按绝对高程分档(教科书就是这么画的:看的是海拔,不是相对高度)
|
||||||
const float band = 200f; // 每 200 米一档
|
|
||||||
|
|
||||||
if (h < 200) return (0x1E, 0x6B, 0x3A); // 深绿:< 200 m
|
if (h < 200) return (0x1E, 0x6B, 0x3A); // 深绿:< 200 m
|
||||||
if (h < 400) return (0x4E, 0x9E, 0x4E); // 浅绿:200–400
|
if (h < 400) return (0x4E, 0x9E, 0x4E); // 浅绿:200–400
|
||||||
if (h < 600) return (0xA8, 0xC6, 0x66); // 绿:400–600
|
if (h < 600) return (0xA8, 0xC6, 0x66); // 绿:400–600
|
||||||
@@ -136,6 +134,31 @@ public static class TerrainAnalyzer
|
|||||||
return (0xF5, 0xF5, 0xF0); // 白:> 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>
|
/// <summary>该颜色属于哪一档(用于图例)。</summary>
|
||||||
public static string BandName(float h) => h switch
|
public static string BandName(float h) => h switch
|
||||||
{
|
{
|
||||||
@@ -152,4 +175,20 @@ public static class TerrainAnalyzer
|
|||||||
|
|
||||||
private static byte Lerp(byte a, byte b, double k)
|
private static byte Lerp(byte a, byte b, double k)
|
||||||
=> (byte)Math.Clamp(a + (b - a) * k, 0, 255);
|
=> (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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,16 @@ public enum TerrainKind
|
|||||||
Plain // 平原:海拔低、地面平坦
|
Plain // 平原:海拔低、地面平坦
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>五大典型地貌部位(等高线判读的核心对象)。</summary>
|
||||||
|
public enum LandformKind
|
||||||
|
{
|
||||||
|
Peak, // 山峰:闭合等高线,数值向内升高
|
||||||
|
Ridge, // 山脊:等高线凸向低处,凸低为脊
|
||||||
|
Valley, // 山谷:等高线凸向高处,凸高为谷
|
||||||
|
Saddle, // 鞍部:两峰之间相对低洼,俯视收腰
|
||||||
|
Cliff // 陡崖:等高线密集甚至重合
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 地形高度场(等高线模型的数据核心)。
|
/// 地形高度场(等高线模型的数据核心)。
|
||||||
///
|
///
|
||||||
@@ -42,6 +52,9 @@ public sealed class TerrainField
|
|||||||
/// <summary>这块地形属于哪种类型(决定界面标题与说明)。</summary>
|
/// <summary>这块地形属于哪种类型(决定界面标题与说明)。</summary>
|
||||||
public TerrainKind Kind { get; }
|
public TerrainKind Kind { get; }
|
||||||
|
|
||||||
|
/// <summary>若这块地形是某个典型地貌部位,则记录其种类;否则为 null。</summary>
|
||||||
|
public LandformKind? Landform { get; }
|
||||||
|
|
||||||
public TerrainField(TerrainKind kind = TerrainKind.Mountain, int size = 192)
|
public TerrainField(TerrainKind kind = TerrainKind.Mountain, int size = 192)
|
||||||
{
|
{
|
||||||
Size = size;
|
Size = size;
|
||||||
@@ -50,6 +63,16 @@ public sealed class TerrainField
|
|||||||
Build(kind);
|
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>
|
/// <summary>该类型对应的等高距:平原/丘陵用 20m,山地/高原/盆地用 100m。</summary>
|
||||||
public float EffectiveInterval => Kind switch
|
public float EffectiveInterval => Kind switch
|
||||||
{
|
{
|
||||||
@@ -266,6 +289,157 @@ public sealed class TerrainField
|
|||||||
MinHeight = min; MaxHeight = max;
|
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)
|
private static double SmoothStep(double a, double b, double x)
|
||||||
{
|
{
|
||||||
var t = Math.Clamp((x - a) / (b - a), 0, 1);
|
var t = Math.Clamp((x - a) / (b - a), 0, 1);
|
||||||
@@ -452,46 +626,77 @@ public sealed class TerrainField
|
|||||||
private static double Lerp(double a, double b, double t)
|
private static double Lerp(double a, double b, double t)
|
||||||
=> a + (b - a) * Math.Clamp(double.IsNaN(t) ? 0.5 : t, 0, 1);
|
=> a + (b - a) * Math.Clamp(double.IsNaN(t) ? 0.5 : t, 0, 1);
|
||||||
|
|
||||||
/// <summary>把零散线段按端点邻近关系串成折线。</summary>
|
/// <summary>
|
||||||
|
/// 把零散线段按端点串成完整折线。
|
||||||
|
/// 关键点:必须**两端都延伸**。只往尾部延伸时,起点落在曲线中段就会把一条等高线
|
||||||
|
/// 切成许多短链,渲染出来是断续的虚线(学生看到的就是“虚线等高线”)。
|
||||||
|
/// </summary>
|
||||||
private static List<List<(double U, double V)>> Chain(
|
private static List<List<(double U, double V)>> Chain(
|
||||||
List<(double U1, double V1, double U2, double V2)> segments)
|
List<(double U1, double V1, double U2, double V2)> segments)
|
||||||
{
|
{
|
||||||
const double Eps = 0.004;
|
// 量化到 1e-4 的网格做端点索引:共享边上的交点由同一次插值算出,
|
||||||
var result = new List<List<(double, double)>>();
|
// 端点值完全一致;网格远小于采样间距(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 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++)
|
for (var i = 0; i < segments.Count; i++)
|
||||||
{
|
{
|
||||||
if (used[i]) continue;
|
if (used[i]) continue;
|
||||||
used[i] = true;
|
used[i] = true;
|
||||||
var line = new List<(double, double)>
|
var line = new List<(double U, double V)>
|
||||||
{
|
{
|
||||||
(segments[i].U1, segments[i].V1),
|
(segments[i].U1, segments[i].V1),
|
||||||
(segments[i].U2, segments[i].V2)
|
(segments[i].U2, segments[i].V2)
|
||||||
};
|
};
|
||||||
|
|
||||||
// 向两端延伸
|
// 向尾部延伸
|
||||||
var grown = true;
|
while (true)
|
||||||
while (grown)
|
|
||||||
{
|
{
|
||||||
grown = false;
|
var (tu, tv) = line[^1];
|
||||||
var (tailU, tailV) = line[^1];
|
var j = NextAt(tu, tv);
|
||||||
for (var j = 0; j < segments.Count; j++)
|
if (j < 0) break;
|
||||||
{
|
used[j] = true;
|
||||||
if (used[j]) continue;
|
var s = segments[j];
|
||||||
var s = segments[j];
|
line.Add(Key(s.U1, s.V1) == Key(tu, tv) ? (s.U2, s.V2) : (s.U1, s.V1));
|
||||||
if (Near(tailU, tailV, s.U1, s.V1, Eps))
|
|
||||||
{
|
|
||||||
line.Add((s.U2, s.V2)); used[j] = true; grown = true; break;
|
|
||||||
}
|
|
||||||
if (Near(tailU, tailV, s.U2, s.V2, Eps))
|
|
||||||
{
|
|
||||||
line.Add((s.U1, s.V1)); used[j] = true; grown = true; break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (line.Count >= 4) result.Add(line);
|
// 向头部延伸
|
||||||
|
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;
|
return result;
|
||||||
|
|||||||