refactor: 全窗口统一 Avalonia,移除 Flutter/Dart,新增 Java 实现
- 恢复同代 GC Avalonia 主界面(主页/下载/设置/关于)替换 Flutter - 模型窗口统一 Avalonia;HTML 课件用 WebView.Avalonia 内嵌渲染 - 新增 CoursewareServer(回环 HTTP + Range)与 CoursewareWindow - 彻底移除 Flutter/Dart 前端及构建脚本相关逻辑 - 新增 ./build.sh run 开发运行命令 - 项目源码整理到 C#/ 子目录,新增 Java/ 实现 - 工作日志随项目迁移
This commit is contained in:
1 parent
3f1f48f54c
commit
cf05e886ac
405 files changed
+18226
-19263
No files matched your search
@@ -0,0 +1,9 @@
|
||||
.gradle/
|
||||
.gradle-home/
|
||||
build/
|
||||
.GC/
|
||||
*.class
|
||||
*.log
|
||||
.DS_Store
|
||||
.idea/
|
||||
*.iml
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Morris GC
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
# GC Java · 天文教学模型启动器(HMCL 风格)
|
||||
|
||||
把原来的 **GC(C# / .NET 8 / Avalonia + Flutter 前后端)** 完整重写为 **单进程 Java / Swing** 桌面应用。
|
||||
启动器界面参考 **HMCL** 的左侧导航 + 首页 Hero + 模型卡片布局;五个教学模型的算法、数据、界面与交互全部在 Java 中重新实现,不依赖任何 .NET 运行时。
|
||||
|
||||

|
||||
|
||||
## 快速开始
|
||||
|
||||
要求:**JDK 17+**(已在 JDK 26 上验证)。项目自带 Gradle Wrapper,首次运行会从**腾讯云镜像**下载 Gradle。
|
||||
|
||||
```bash
|
||||
cd Java
|
||||
|
||||
./gradlew run # 启动 HMCL 风格 GUI
|
||||
./gradlew selftest # 35 项核心 / 模型 / 账户断言
|
||||
./gradlew gui-selftest # 无头渲染 5 个模型 + 5 个页面截图到 build/screenshots
|
||||
./gradlew installDist # 生成可分发的 build/install/gc-java/
|
||||
```
|
||||
|
||||
或使用脚本:
|
||||
|
||||
```bash
|
||||
./run.sh # GUI(优先使用已构建发行目录)
|
||||
./gcctl selftest # CLI 自检
|
||||
./build.sh # 编译 + 自检 + UI 冒烟 + 组装 build/gc-dist
|
||||
```
|
||||
|
||||
Windows:`.\build.ps1`(参数与 `build.sh` 相同,产物在 `build\gc-dist\`)。
|
||||
|
||||
Gradle Wrapper 固定为 **Gradle 9.9.2**,`gradle/wrapper/gradle-wrapper.properties`:
|
||||
|
||||
```properties
|
||||
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-9.9.2-bin.zip
|
||||
```
|
||||
|
||||
若网络无法访问腾讯云,可把该地址换成官方 `https://services.gradle.org/distributions/gradle-9.9.2-bin.zip`。
|
||||
|
||||
## 界面
|
||||
|
||||
| 页面 | 说明 |
|
||||
| --- | --- |
|
||||
| 首页 | HMCL 风格 Hero、模型选择器、启动按钮、统计卡、已安装模型网格、公告 |
|
||||
| 模型库 | 模型封面、版本、体积、作者;启动 / 打开目录 / 删除 |
|
||||
| 下载 | 更新源、离线模型源、检查更新、进度、远端模型列表、导入本地模型 |
|
||||
| 设置 | 语言、深浅主题、渲染帧率、内存预算、自动更新、签名策略、存储目录 |
|
||||
| 账户 | HMCL 侧边栏本地账户:登录/注册、人机验证、30 天签到、积分、每日人品值、二选一、主题色购买与 1 小时退款 |
|
||||
| 关于 | 版本、平台、源码语言 Java、构建工具 Gradle 9.9.2、内置模型、许可 |
|
||||
|
||||
| 首页 | 模型库 | 下载 |
|
||||
| --- | --- | --- |
|
||||
|  |  |  |
|
||||
|
||||
| 设置 | 关于 |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
|
||||
## 本地账户与积分
|
||||
|
||||
侧边栏底部账号卡打开本地账户窗口(对应原 `GC.UI.Server.UserService`):
|
||||
|
||||
- 注册 / 登录;密码只存 `SHA-512(salt + ":" + password)`,数据在 `.GC/user/`
|
||||
- 30 天签到周期,连续签到递增积分
|
||||
- 每日人品值、每日二选一(积分增减)
|
||||
- 预置主题色 50 积分、自定义主题色 150 积分;1 小时内换色退 80%
|
||||
- 购买后立即写入设置并应用到 HMCL 风格强调色
|
||||
|
||||
## 五个教学模型
|
||||
|
||||
打开模型后是独立窗口,画布铺满,所有计算与 GUI 共用 `src/main/java/com/gc/model` 下同一套算法。
|
||||
|
||||
| 模型 | Java 实现 | 功能 |
|
||||
| --- | --- | --- |
|
||||
| 比例尺计算器 | `model/scale/ScaleMath` + `ui/ScalePanel` | 求实地/图上/比例尺三种模式、图上/实地双标尺、线段式自动换挡、比例尺光谱、三种写法、大小判读、解题步骤、真实地标、练习闯关 |
|
||||
| 等高线地形图 | `model/contour/TerrainField` / `TerrainAnalyzer` + `ui/ContourPanel` | 5 种基本地形 + 5 种典型地貌、分层设色、Marching Squares 等高线、河流/山峰/陡崖标注、悬停判读、3D 轴测拖动旋转、等高线演示动画 |
|
||||
| 地球自转 | `model/earth/EarthMath` + `ui/EarthPanel` | 地球球体、大陆轮廓、经纬网、昼夜/晨昏线、太阳直射点、地轴倾角、播放/暂停/速度/拖动/缩放、迷你轨道、教学要点 |
|
||||
| 地球公转 | 同上 | 公转轨道、四季与二分二至、地轴指向不变、直射纬度与日期、节气定位、教学要点、地球特写 |
|
||||
| 地球地理 | `EarthMath` + `ui/GeographyPanel` | 五带划分、七大洲四大洋、海陆轮廓、洲界、六大板块、悬停经纬度与温度带判读 |
|
||||
|
||||
| 比例尺 | 等高线 |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
|
||||
| 自转 | 公转 | 地理 |
|
||||
| --- | --- | --- |
|
||||
|  |  |  |
|
||||
|
||||
## CLI
|
||||
|
||||
无参数启动 GUI;带参数运行 CLI,GUI 与 CLI 共用算法。
|
||||
|
||||
```text
|
||||
gcctl 启动 HMCL 风格 GUI
|
||||
gcctl selftest 全部内置断言
|
||||
gcctl gui-selftest 无头 UI 冒烟 + 截图
|
||||
gcctl hash-file <path> SHA-256
|
||||
gcctl hash-dir <path> 目录指纹
|
||||
gcctl canonical <file|-> 规范化 JSON
|
||||
gcctl version-normalize <tag> 版本规整
|
||||
gcctl version-compare <a> <b> 版本比较(-1/0/1)
|
||||
gcctl paths [root] .GC 目录布局
|
||||
gcctl settings-default 默认设置
|
||||
gcctl model-scan [root] 扫描模型库
|
||||
gcctl safezip-name <name> zip 路径安全判定
|
||||
gcctl human-size <bytes> 人类可读体积
|
||||
gcctl update-check 检查模型 / 启动器更新
|
||||
gcctl savedog verify <manifest> 清单验签
|
||||
gcctl savedog apply 应用 .GC/update/apply-request.json
|
||||
gcctl savedog status 更新状态
|
||||
gcctl savedog keygen [dir] [id] 生成 ECDSA P-256 密钥
|
||||
gcctl savedog sign <file> <pem> <id> 签名清单
|
||||
```
|
||||
|
||||
模型算法命令:
|
||||
|
||||
```text
|
||||
gcctl model scale solve <real|map|scale> <mapCm> <realCm> <N>
|
||||
gcctl model scale human <cm> | segment <N> <pxPerCm> <targetPx>
|
||||
gcctl model scale grade <N> | spectrum <N> | quiz <seed> | check <answer> <expect>
|
||||
gcctl model contour build <kind|landform> [size]
|
||||
gcctl model contour sample <kind> <u> <v> | levels <kind> | extract <kind> <level>
|
||||
gcctl model contour classify <kind> <u> <v> | color <height> | slope <kind> <u> <v>
|
||||
gcctl model rotation subsolar <orbitDeg> <tiltDeg> | date <orbitDeg> | angle <spinDeg> <orbitDeg>
|
||||
gcctl model revolution subsolar <orbitDeg> | season <orbitDeg> | step <spinDeg> <orbitDeg> <dt> <speed>
|
||||
gcctl model geo zones | declination <lat> | latlon <lat> <lon>
|
||||
```
|
||||
|
||||
## 运行目录
|
||||
|
||||
与原版一致,所有用户数据放在程序旁的 `.GC`:
|
||||
|
||||
```text
|
||||
<安装目录>/
|
||||
bin/gc-java 启动脚本(Gradle installDist)
|
||||
lib/gc-java-2.0.0.jar 应用
|
||||
model/ 随包内置的 5 个模型(首次启动复制到 .GC/model)
|
||||
.GC/
|
||||
bin/ 非本体文件
|
||||
config/settings.json 设置
|
||||
model/ 模型库(首次启动从 model/ 种子化)
|
||||
cache/ 下载暂存
|
||||
update/ 待应用的启动器更新
|
||||
safedog/ 更新守护运行目录
|
||||
logs/gc-YYYYMMDD.log 中文日志
|
||||
logs/gc-YYYYMMDD.en.log 英文日志
|
||||
```
|
||||
|
||||
开发态(仓库内运行)直接使用 `Java/model` 并同步到 `Java/.GC/model`。
|
||||
`EMS_HOME`、`EMS_DATA`、`EMS_MODELS` 可覆盖路径。
|
||||
|
||||
## 从 C# 到 Java 的对应关系
|
||||
|
||||
| 原 C# 模块 | Java 位置 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `GC/src/Services/*` | `core/AppPaths` `Settings` `Log` `Http` `VersionUtil` `I18n` | 路径、设置、日志、HTTP、版本、语言 |
|
||||
| `GC/src/Security/*` | `core/Security` `Hash` `Json` | ECDSA 验签、SHA-256、规范化 JSON、安全 zip、完整性、健康标记 |
|
||||
| `GC/src/Models/*` | `core/ModelManifest` | 模型清单与扫描 |
|
||||
| `GC-DOWNLOAD/*` | `core/UpdateService` `GiteaRemote` `LocalRemote` `Remote` | 更新清单、Gitea/GitHub/本地源、模型安装 |
|
||||
| `GC-SAVEDOG/*` | `core/Updater` | verify / apply / status / keygen / sign |
|
||||
| `GC-UI/backend/.../UserService.cs` | `core/UserService` + `ui/AccountDialog` | 本地注册/登录/签到/积分/主题色 |
|
||||
| `GC-DRAW/PlayerWindow.cs` | `ui/ModelWindow` | 模型窗口宿主 |
|
||||
| `GC-UI/frontend/*` | `ui/MainWindow` + `HomePage` / `ModelsPage` / `DownloadPage` / `SettingsPage` / `AboutPage` / `AccountDialog` | HMCL 风格前端 + 本地账户 |
|
||||
| `model/scale-calculator` | `model/scale` + `ui/ScalePanel` | 比例尺 |
|
||||
| `model/contour-map` | `model/contour` + `ui/ContourPanel` | 等高线 |
|
||||
| `model/earth-rotation` / `earth-revolution` | `model/earth` + `ui/EarthPanel` | 地球自转/公转 |
|
||||
| `model/earth-geography` | `model/earth` + `ui/GeographyPanel` | 地理 |
|
||||
|
||||
模型清单、`scene.json`、`land.json`、`i18n/`、`help.json`、`scales.json`、`coastline.json`、`plates.json` 等数据原样保留在 `Java/model/`,Java 渲染器直接读取。
|
||||
|
||||
### 为什么不是“加载原 DLL”?
|
||||
|
||||
原模型的界面契约返回的是 Avalonia `Control`,程序集是 **.NET IL**,JVM 无法加载,也不存在 Avalonia 运行时。
|
||||
因此 Java 版把五个官方模型**逐项重写**为 Swing 渲染器,并直接复用原模型的算法公式与数据文件;
|
||||
模型窗口、交互、教学文案、直射纬度/日期/坡度/等高线等计算结果与 C# 源码一致。
|
||||
第三方 C# DLL 模型不会被 JVM 执行;如需扩展,按 `BuiltinModels` 注册新的 Java 渲染器即可。
|
||||
|
||||
## 安全与更新
|
||||
|
||||
- 版本清单验签:**ECDSA P-256 / SHA-256(IEEE P1363 签名格式)**,内置 `gc-2026-12` 公钥,可用 `GC_TRUSTED_KEYS=id:base64` 注入。
|
||||
- 规范化 JSON:递归键排序、无空白、保留数字原文、非 ASCII 不转义、签名时移除根级 `signature`——与 C# 端字节级一致;已用原仓库签名 `C#/version.json` 验证通过。
|
||||
- 模型安装:只接受 `<id>.json` 与 `<id>.model/`,先写 cache/staging,复算 `manifestSha256` 与 `filesSha256`,通过后原子替换;远端版本低于本地时**绝不降级**。
|
||||
- zip 加固:拒绝绝对路径、`../`、盘符、UNC;限制条目数 20000、解压 2 GiB、压缩比异常。
|
||||
- 启动器更新:下载到 `.GC/update/`,`savedog apply` 进行安全解压、备份替换、失败回滚,并写 `health.json` / `state.json` / `last-good.json`。
|
||||
- 断网、清单缺失、签名不符:保留本地模型,界面状态栏提示,不会清空模型库。
|
||||
|
||||
## 自检
|
||||
|
||||
```text
|
||||
$ ./gradlew selftest
|
||||
...
|
||||
PASS model-scan = 5
|
||||
PASS safezip-abs = REJECT
|
||||
PASS safezip-drive = REJECT
|
||||
|
||||
SELFTEST PASS 35 passed, 0 failed
|
||||
```
|
||||
|
||||
`./gradlew gui-selftest` 在无显示环境构造 5 个模型面板与 5 个页面,离屏渲染 PNG;`docs/screenshots/` 即由该命令生成。
|
||||
|
||||
## 已知边界
|
||||
|
||||
- 加载 **任意第三方 C# DLL 模型** 不在 Java 版能力范围内(JVM 无法执行 .NET IL);五个官方模型全部可用。
|
||||
- 原版 Flutter 前端与 .NET 本地 HTTP 后端合并为**单进程 Swing**,符合“禁止前后端分离”的重写规范。
|
||||
- 更新源默认仍是原仓库的 `version.json`;若远端清单版本高于本地,会按签名与哈希校验后安装模型数据。C# 模型包中的 DLL 会被一起下载但 JVM 不加载,渲染使用 Java 内置实现。
|
||||
- 主题色自定义、深浅主题、帧率/内存设置已持久化;渲染帧率作为模型动画的参考值(Swing 定时器 16 ms ≈ 60 FPS)。
|
||||
|
||||
## 许可
|
||||
|
||||
MIT。原项目版权归 Morris GC;Java 重写版保留原模型数据与教学文案。
|
||||
@@ -0,0 +1,113 @@
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
group = "com.gc"
|
||||
version = "2.0.0"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://mirrors.cloud.tencent.com/nexus/repository/maven-public/") }
|
||||
}
|
||||
|
||||
// 宿主平台的原生库:JOGL(OpenGL)与 JavaFX WebView(原始 HTML 课件)。
|
||||
val hostOs = System.getProperty("os.name").lowercase()
|
||||
val hostArch = System.getProperty("os.arch").lowercase()
|
||||
val isMac = hostOs.contains("mac")
|
||||
val isWin = hostOs.contains("win")
|
||||
val isArm = hostArch.contains("aarch64") || hostArch.contains("arm64")
|
||||
val javafxClassifier = when {
|
||||
isMac -> if (isArm) "mac-aarch64" else "mac"
|
||||
isWin -> "win"
|
||||
else -> if (isArm) "linux-aarch64" else "linux"
|
||||
}
|
||||
val jogampNatives = when {
|
||||
isMac -> "natives-macosx-universal"
|
||||
isWin -> "natives-windows-amd64"
|
||||
else -> if (isArm) "natives-linux-aarch64" else "natives-linux-amd64"
|
||||
}
|
||||
val javafxVersion = "21.0.7"
|
||||
|
||||
dependencies {
|
||||
// OpenGL:JOGL 2.6(GLJPanel 嵌入 Swing,原生库随后打包进发行目录)
|
||||
implementation("org.jogamp.jogl:jogl-all:2.6.0")
|
||||
implementation("org.jogamp.gluegen:gluegen-rt:2.6.0")
|
||||
runtimeOnly("org.jogamp.jogl:jogl-all:2.6.0:$jogampNatives")
|
||||
runtimeOnly("org.jogamp.gluegen:gluegen-rt:2.6.0:$jogampNatives")
|
||||
|
||||
// JavaFX WebView:承载原始离线 HTML 课件(视频 / Three.js / 交互)
|
||||
for (artifact in listOf("base", "graphics", "controls", "media", "web", "swing")) {
|
||||
implementation("org.openjfx:javafx-$artifact:$javafxVersion:$javafxClassifier")
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.encoding = "UTF-8"
|
||||
options.release.set(17)
|
||||
}
|
||||
|
||||
application {
|
||||
mainClass.set("com.gc.Main")
|
||||
applicationDefaultJvmArgs = listOf(
|
||||
"-Dfile.encoding=UTF-8",
|
||||
"-Dsun.java2d.uiScale.enabled=true",
|
||||
"-Dprism.lcdtext=false",
|
||||
"-Djavafx.animation.fullspeed=true"
|
||||
)
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
manifest {
|
||||
attributes["Main-Class"] = "com.gc.Main"
|
||||
}
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
}
|
||||
|
||||
tasks.register<JavaExec>("selftest") {
|
||||
group = "verification"
|
||||
description = "运行全部内置断言(核心 + 5 个模型)"
|
||||
dependsOn("classes")
|
||||
classpath = sourceSets.main.get().runtimeClasspath
|
||||
mainClass.set("com.gc.Main")
|
||||
args("selftest")
|
||||
workingDir = projectDir
|
||||
}
|
||||
|
||||
tasks.register<JavaExec>("gui-selftest") {
|
||||
group = "verification"
|
||||
description = "无头构造 5 个模型面板与 5 个页面并离屏渲染截图"
|
||||
dependsOn("classes")
|
||||
classpath = sourceSets.main.get().runtimeClasspath
|
||||
mainClass.set("com.gc.Main")
|
||||
args("gui-selftest")
|
||||
workingDir = projectDir
|
||||
jvmArgs("-Djava.awt.headless=true")
|
||||
}
|
||||
|
||||
tasks.named<JavaExec>("run") {
|
||||
workingDir = projectDir
|
||||
standardInput = System.`in`
|
||||
}
|
||||
|
||||
distributions {
|
||||
main {
|
||||
contents {
|
||||
from("model") { into("model") }
|
||||
from("courseware") { into("courseware") }
|
||||
from("run.sh", "run.bat", "gcctl")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("printRuntimeClasspath") {
|
||||
doLast { println(sourceSets.main.get().runtimeClasspath.asPath) }
|
||||
}
|
||||
|
||||
tasks.named("build") {
|
||||
dependsOn("selftest")
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
# Windows 一键构建:编译 + 自检 + 离屏 UI 冒烟 + 发行目录
|
||||
$ErrorActionPreference = "Stop"
|
||||
Set-Location $PSScriptRoot
|
||||
if (-not $env:JAVA_HOME) {
|
||||
Write-Host "请先设置 JAVA_HOME 指向 JDK 17+" -ForegroundColor Yellow
|
||||
}
|
||||
.\gradlew.bat clean selftest gui-selftest installDist --console=plain
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
if (Test-Path build\gc-dist) { Remove-Item -Recurse -Force build\gc-dist }
|
||||
New-Item -ItemType Directory -Path build\gc-dist | Out-Null
|
||||
Copy-Item -Recurse build\install\gc-java\* build\gc-dist\
|
||||
Copy-Item run.bat,run.sh,gcctl build\gc-dist\
|
||||
Copy-Item -Recurse model build\gc-dist\model
|
||||
Write-Host ""
|
||||
Write-Host "构建完成:build\gc-dist\" -ForegroundColor Green
|
||||
Write-Host " build\gc-dist\bin\gc-java.bat GUI"
|
||||
Write-Host " build\gc-dist\bin\gc-java.bat selftest CLI 自检"
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
# 一键构建:编译 + 自检 + 离屏 UI 冒烟 + 组装发行目录 build/gc-dist
|
||||
set -e
|
||||
DIR=$(cd "$(dirname "$0")" && pwd)
|
||||
cd "$DIR"
|
||||
JAVA_HOME=${JAVA_HOME:-$(/usr/libexec/java_home 2>/dev/null || true)}
|
||||
./gradlew clean classes selftest gui-selftest installDist --console=plain
|
||||
rm -rf build/gc-dist
|
||||
mkdir -p build/gc-dist
|
||||
cp -R build/install/gc-java/. build/gc-dist/
|
||||
cp run.sh run.bat gcctl build/gc-dist/ 2>/dev/null || true
|
||||
cp -R model build/gc-dist/model
|
||||
chmod +x build/gc-dist/bin/gc-java build/gc-dist/run.sh 2>/dev/null || true
|
||||
echo ""
|
||||
echo "构建完成:build/gc-dist/"
|
||||
echo " ./build/gc-dist/bin/gc-java # GUI"
|
||||
echo " ./build/gc-dist/bin/gc-java selftest # CLI 自检"
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
# gcctl 兼容入口:./gcctl -> HMCL 风格 GUI
|
||||
# ./gcctl selftest -> CLI 自检
|
||||
# ./gcctl model ... -> 模型算法命令
|
||||
DIR=$(cd "$(dirname "$0")" && pwd)
|
||||
exec "$DIR/run.sh" "$@"
|
||||
@@ -0,0 +1,4 @@
|
||||
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
|
||||
org.gradle.parallel=true
|
||||
org.gradle.caching=true
|
||||
kotlin.daemon.jvmargs=-Xmx1g
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-9.9.2-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# gradlew start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh gradlew
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+112
@@ -0,0 +1,112 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem gradlew startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables, and ensure extensions are enabled
|
||||
setlocal EnableExtensions
|
||||
|
||||
@rem Catch executions from older scripts and ensure they exit cleanly.
|
||||
@rem This can be removed once we can be reasonably confident that few people
|
||||
@rem will be migrating directly to this new wrapper.
|
||||
goto afterSafetyNet
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
goto exitWithErrorLevel
|
||||
:afterSafetyNet
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
1>&2 echo.
|
||||
1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
1>&2 echo.
|
||||
1>&2 echo Please set the JAVA_HOME variable in your environment to match the
|
||||
1>&2 echo location of your Java installation.
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
goto exitWithErrorLevel
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
1>&2 echo.
|
||||
1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
1>&2 echo.
|
||||
1>&2 echo Please set the JAVA_HOME variable in your environment to match the
|
||||
1>&2 echo location of your Java installation.
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
goto exitWithErrorLevel
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute gradlew
|
||||
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
|
||||
@rem which allows us to clear the local environment before executing the java command
|
||||
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
|
||||
|
||||
@rem This label must not be changed. We rely on old scripts being able to jump to this point.
|
||||
:exitWithErrorLevel
|
||||
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
|
||||
"%COMSPEC%" /c exit %ERRORLEVEL%
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"id": "contour-map",
|
||||
"nameI18n": {
|
||||
"zh-CN": "等高线地形图",
|
||||
"en": "Contour Map"
|
||||
},
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "可旋转 3D 地形 + 等高切割/交线/投影/判坡四步动画,判读山峰、山脊、山谷、鞍部、陡崖五大典型地貌。",
|
||||
"en": "Rotatable 3D terrain with a four-step animation of contour cutting, lines, projection and slope; identify five classic landforms."
|
||||
},
|
||||
"author": "Morris GC",
|
||||
"tags": [
|
||||
"geography",
|
||||
"map",
|
||||
"contour",
|
||||
"terrain"
|
||||
],
|
||||
"assembly": "ContourMapModel.dll",
|
||||
"type": "GC.ContourMap.ContourMapFactory",
|
||||
"version": "1.2",
|
||||
"chrome": {
|
||||
"titleBar": "#0C1828",
|
||||
"titleBorder": "#1B2740",
|
||||
"titleText": "#EAF2FF",
|
||||
"button": "#9FB4D4",
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "d18eb85c8d",
|
||||
"updatedAt": "2026-11-21T10:55:36Z"
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
{
|
||||
"zh-CN": {
|
||||
"title": "如何使用 · 等高线地形与五大典型地貌",
|
||||
"sections": [
|
||||
{
|
||||
"h": "开始使用(跟着做)",
|
||||
"lines": [
|
||||
"第 1 步:点右下角「开始实验」,在立体地形里观察水平切面下降、交线形成、垂直投影与疏密判坡四步动画。",
|
||||
"第 2 步:在立体地形上按住鼠标拖动可旋转视角,滚轮缩放;这是可交互的 3D 地形。",
|
||||
"第 3 步:点画布上方「五大典型地貌」标签(山峰/山脊/山谷/鞍部/陡崖),画面换成对应的专门地形并叠加完整等高线,观察各自的等高线特征。",
|
||||
"第 4 步:点底部「俯视图 / 立体图」在等高线地图与 3D 地形间切换;鼠标悬停任意位置,底部显示该点海拔与地形部位。",
|
||||
"第 5 步:点「上色 / 取消上色」对比分层设色与纯等高线;点「全屏」进入全屏演示。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "键盘快捷键",
|
||||
"lines": [
|
||||
"空格:播放 / 暂停实验。",
|
||||
"数字 1 – 5:依次切换到山峰、山脊、山谷、鞍部、陡崖。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "四步实验流程",
|
||||
"lines": [
|
||||
"等高切割:一个水平面从山顶向下移动,与山体在同一海拔相交。",
|
||||
"形成交线:每个水平切面留下一条闭合交线,多层交线共同描述山体起伏。",
|
||||
"投影成图:各高度的交线沿垂线投影到同一平面,累积成完整等高线图。",
|
||||
"疏密判坡:坡度着色叠加等高线,陡处线密、缓处线疏。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "五大典型地貌的判读",
|
||||
"lines": [
|
||||
"山峰:等高线闭合,数值由中心向四周递减(若向内降低则为洼地)。",
|
||||
"山脊:等高线向海拔低处凸出(凸低为脊),脊线是分水线。",
|
||||
"山谷:等高线向海拔高处凸出(凸高为谷),谷线是集水线,常发育河流。",
|
||||
"鞍部:两座山峰之间相对低洼,俯视轮廓呈马鞍状收腰。",
|
||||
"陡崖:等高线密集甚至重合,近乎垂直;n 条线重合时 (n−1)d ≤ ΔH < (n+1)d。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "等高线基础",
|
||||
"lines": [
|
||||
"同一条等高线上各点海拔相等;相邻等高线之间的高差叫等高距(本图 100 米)。",
|
||||
"等高线越密坡越陡,越疏坡越缓。",
|
||||
"每 5 条加粗一条叫计曲线,标注海拔便于读数。",
|
||||
"海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "地图符号",
|
||||
"lines": [
|
||||
"分层设色按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白)。",
|
||||
"山峰用 ▲ 加高程数字标注;河流用蓝色线沿谷底绘制;陡崖用红色锯齿线表示。",
|
||||
"指北针在图幅右上,比例尺在左下,分层设色图例在右下,地形剖面图在底部。"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"en": {
|
||||
"title": "How to use · Contour Lines & Five Landforms",
|
||||
"sections": [
|
||||
{
|
||||
"h": "Getting started (follow along)",
|
||||
"lines": [
|
||||
"Step 1: press Start to watch the four-step animation — contour cutting, line formation, vertical projection and slope reading.",
|
||||
"Step 2: drag with the mouse to rotate the 3D terrain, scroll to zoom; it is fully interactive.",
|
||||
"Step 3: click a landform tab above the canvas (peak / ridge / valley / saddle / cliff) to load its dedicated terrain with its full contour pattern.",
|
||||
"Step 4: toggle Top view / 3D view at the bottom; hover anywhere to read elevation and terrain feature.",
|
||||
"Step 5: use Colour / No colour to compare hypsometric tint with pure contour lines; use Fullscreen for presentation."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "Keyboard shortcuts",
|
||||
"lines": [
|
||||
"Space: play / pause the experiment.",
|
||||
"Numbers 1 – 5: switch to peak, ridge, valley, saddle, cliff."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "The four experiment steps",
|
||||
"lines": [
|
||||
"Contour cutting: a horizontal plane descends from the summit and intersects the mountain at one elevation.",
|
||||
"Forming lines: each slice leaves a closed intersection line; stacked lines describe the relief.",
|
||||
"Projection: intersection lines are projected vertically onto one plane, building the contour map.",
|
||||
"Slope density: slope shading over contours — dense lines mean steep, sparse lines mean gentle."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "Reading the five landforms",
|
||||
"lines": [
|
||||
"Peak: closed contours, values decrease outward (if they decrease inward it is a depression).",
|
||||
"Ridge: contours bulge toward lower ground; a watershed line.",
|
||||
"Valley: contours bulge toward higher ground; a drainage line, often a stream.",
|
||||
"Saddle: low ground between two peaks, pinched like a saddle in plan view.",
|
||||
"Cliff: contours crowd or overlap, nearly vertical; n overlapping lines: (n−1)d ≤ ΔH < (n+1)d."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "Contour basics",
|
||||
"lines": [
|
||||
"All points on one contour share the same elevation; the gap between neighbours is the contour interval (100 m here).",
|
||||
"Closer contours mean steeper slopes; wider spacing means gentler slopes.",
|
||||
"Every 5th contour is bolded as an index contour and labelled with elevation.",
|
||||
"Elevation is height above sea level; relative height is the difference between two elevations."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "Map symbols",
|
||||
"lines": [
|
||||
"Hypsometric tint uses fixed colour bands (dark green → light green → green → pale yellow → yellow → light brown → brown → white).",
|
||||
"Peaks are marked with ▲ plus elevation; rivers are blue lines along valleys; cliffs use a red saw-tooth line.",
|
||||
"North arrow top-right, scale bar bottom-left, tint legend bottom-right, terrain profile along the bottom."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"app.title": "Contour Lines · Five Classic Landforms",
|
||||
"app.subtitle": "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"app.title": "等高线地形 · 五大典型地貌判读",
|
||||
"app.subtitle": "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖"
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"id": "earth-geography",
|
||||
"nameI18n": {
|
||||
"zh-CN": "地球地理",
|
||||
"en": "Earth Geography"
|
||||
},
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "五带划分、七大洲四大洋轮廓、六大板块与洲界,纯线稿教学图。",
|
||||
"en": "Climate zones, continent/ocean outlines, plates and borders — clean line art."
|
||||
},
|
||||
"assembly": "EarthGeographyModel.dll",
|
||||
"type": "GC.EarthModels.GeographyModelFactory",
|
||||
"author": "Morris GC",
|
||||
"tags": [
|
||||
"geography",
|
||||
"earth",
|
||||
"atlas"
|
||||
],
|
||||
"dataDir": "earth-geography.model",
|
||||
"version": "1.9",
|
||||
"chrome": {
|
||||
"titleBar": "#0C1828",
|
||||
"titleBorder": "#1B2740",
|
||||
"titleText": "#EAF2FF",
|
||||
"button": "#9FB4D4",
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "cc68b8863b",
|
||||
"updatedAt": "2026-11-21T10:55:36Z"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"borders":[{"between":"亚洲-非洲","name":"苏伊士运河","lines":[[[32.6,31.3],[32.4,30.5],[32.3,29.9]]]},{"between":"亚洲-欧洲","name":"亚欧分界(乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡)","segments":[{"name":"乌拉尔山","nameI18n":{"zh-CN":"乌拉尔山","en":"Ural Mts."},"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0]]]},{"name":"乌拉尔河","nameI18n":{"zh-CN":"乌拉尔河","en":"Ural River"},"lines":[[[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5]]]},{"name":"里海","nameI18n":{"zh-CN":"里海","en":"Caspian Sea"},"lines":[[[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5]]]},{"name":"大高加索山","nameI18n":{"zh-CN":"大高加索山","en":"Greater Caucasus"},"lines":[[[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2]]]},{"name":"黑海","nameI18n":{"zh-CN":"黑海","en":"Black Sea"},"lines":[[[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5]]]},{"name":"土耳其海峡","nameI18n":{"zh-CN":"土耳其海峡","en":"Turkish Straits"},"lines":[[[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]}],"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0],[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5],[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5],[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2],[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5],[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]},{"between":"欧洲-非洲","name":"直布罗陀海峡","lines":[[[-5.6,36.0],[-4.0,36.2],[0.0,36.5]]]},{"between":"北美-南美","name":"巴拿马运河","lines":[[[-79.6,9.1],[-78.5,8.9],[-77.5,8.6]]]},{"between":"南美-南极","name":"德雷克海峡","nameI18n":{"zh-CN":"德雷克海峡","en":"Drake Passage"},"lines":[[[-68.0,-56.0],[-66.5,-57.5],[-65.0,-59.0],[-63.5,-60.5],[-62.0,-62.0]]]},{"between":"亚洲-北美","name":"白令海峡","lines":[[[-169.0,65.5],[-170.5,65.8],[-172.0,66.0]]]},{"between":"亚洲-大洋洲","name":"印尼群岛","lines":[[[120.0,-1.0],[125.0,-2.0],[130.0,-3.0]]]},{"between":"南极洲","name":"南极圈","lines":[[[-180.0,-66.5],[-170.0,-66.5],[-160.0,-66.5],[-150.0,-66.5],[-140.0,-66.5],[-130.0,-66.5],[-120.0,-66.5],[-110.0,-66.5],[-100.0,-66.5],[-90.0,-66.5],[-80.0,-66.5],[-70.0,-66.5],[-60.0,-66.5],[-50.0,-66.5],[-40.0,-66.5],[-30.0,-66.5],[-20.0,-66.5],[-10.0,-66.5],[0.0,-66.5],[10.0,-66.5],[20.0,-66.5],[30.0,-66.5],[40.0,-66.5],[50.0,-66.5],[60.0,-66.5],[70.0,-66.5],[80.0,-66.5],[90.0,-66.5],[100.0,-66.5],[110.0,-66.5],[120.0,-66.5],[130.0,-66.5],[140.0,-66.5],[150.0,-66.5],[160.0,-66.5],[170.0,-66.5],[180.0,-66.5]]]}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"lines":[[[180.0,-16.17],[179.56,-16.64],[179.93,-16.52],[179.93,-16.74],[179.2,-16.71],[178.71,-16.98],[178.5,-16.79],[178.58,-16.62],[180.0,-16.17]],[[143.18,-11.95],[143.11,-12.3],[143.4,-12.64],[143.76,-14.35],[143.96,-14.46],[144.47,-14.23],[145.29,-14.94],[145.43,-16.41],[145.91,-16.91],[146.13,-17.64],[146.03,-18.27],[146.33,-18.55],[146.38,-18.98],[147.42,-19.38],[147.74,-19.77],[148.76,-20.29],[148.88,-20.48],[148.68,-20.58],[149.45,-21.58],[149.7,-22.44],[149.97,-22.55],[150.02,-22.17],[150.54,-22.56],[150.62,-22.37],[150.84,-23.46],[151.83,-24.12],[153.16,-25.96],[153.12,-27.19],[153.62,-28.67],[153.03,-30.56],[152.94,-31.43],[152.47,-32.44],[151.81,-32.9],[151.29,-33.58],[150.81,-35.01],[150.19,-35.83],[149.93,-37.53],[149.48,-37.77],[147.88,-37.93],[146.86,-38.66],[146.22,-38.73],[146.47,-38.84],[146.4,-39.15],[145.4,-38.53],[145.48,-38.24],[144.96,-38.5],[144.72,-38.34],[145.12,-38.09],[144.89,-37.9],[144.4,-38.14],[144.66,-38.21],[143.54,-38.82],[142.46,-38.39],[141.42,-38.36],[140.39,-37.9],[139.78,-37.25],[139.73,-36.37],[138.97,-35.58],[139.29,-35.61],[139.28,-35.38],[138.18,-35.61],[138.51,-35.02],[138.09,-34.17],[137.69,-35.14],[136.88,-35.24],[137.01,-34.92],[137.39,-34.91],[137.49,-34.16],[137.93,-33.58],[137.85,-33.2],[137.99,-33.09],[137.78,-32.58],[137.79,-32.82],[137.24,-33.63],[136.43,-34.03],[135.89,-34.66],[135.97,-34.98],[135.65,-34.94],[135.12,-34.59],[135.45,-34.58],[135.22,-33.96],[134.72,-33.26],[134.3,-33.16],[134.1,-32.75],[134.23,-32.55],[133.66,-32.21],[132.76,-31.96],[132.22,-32.01],[131.14,-31.5],[128.95,-31.7],[127.32,-32.26],[125.92,-32.3],[124.24,-33.02],[123.51,-33.92],[122.15,-33.99],[121.41,-33.83],[119.85,-33.98],[119.45,-34.37],[117.86,-35.05],[116.52,-34.99],[115.01,-34.26],[114.99,-33.52],[115.36,-33.64],[115.68,-33.19],[115.7,-31.7],[115.08,-30.56],[114.86,-29.14],[114.17,-28.08],[114.03,-27.35],[113.19,-26.18],[113.32,-26.24],[113.36,-26.08],[113.58,-26.56],[113.84,-26.5],[113.45,-25.6],[113.71,-25.83],[113.72,-26.13],[113.85,-26.01],[113.99,-26.32],[114.22,-26.29],[114.21,-25.85],[113.42,-24.44],[113.76,-23.42],[113.68,-22.64],[114.02,-21.88],[114.14,-22.48],[114.71,-21.82],[116.71,-20.65],[117.41,-20.72],[119.1,-20.0],[119.59,-20.04],[121.0,-19.6],[121.83,-18.48],[122.34,-18.11],[122.15,-17.55],[122.26,-17.14],[122.97,-16.44],[123.56,-17.52],[123.59,-17.03],[123.83,-17.12],[123.87,-16.92],[123.49,-16.49],[123.61,-16.22],[124.77,-16.4],[124.41,-16.3],[124.65,-15.87],[124.5,-15.97],[124.38,-15.76],[124.44,-15.49],[124.69,-15.27],[125.06,-15.44],[124.84,-15.16],[125.04,-15.0],[125.36,-15.12],[125.18,-14.71],[125.58,-14.48],[125.63,-14.26],[125.66,-14.53],[126.02,-14.49],[126.05,-13.98],[126.57,-14.16],[126.9,-13.74],[127.46,-14.03],[128.2,-14.75],[128.07,-15.33],[128.58,-14.78],[129.06,-14.88],[129.22,-15.16],[129.27,-14.87],[129.63,-15.14],[129.64,-14.85],[129.85,-14.83],[129.38,-14.39],[129.84,-13.57],[130.26,-13.3],[130.17,-12.96],[130.62,-12.65],[130.62,-12.43],[130.87,-12.56],[131.29,-12.07],[131.44,-12.28],[132.41,-12.29],[132.71,-12.12],[132.67,-11.65],[131.82,-11.3],[131.96,-11.18],[135.03,-12.19],[135.92,-11.83],[135.7,-12.21],[136.01,-12.19],[136.08,-12.42],[136.26,-12.43],[136.27,-12.13],[136.54,-11.96],[136.95,-12.35],[136.54,-12.78],[136.46,-13.22],[135.93,-13.3],[135.95,-13.94],[135.45,-14.92],[138.25,-16.72],[139.01,-16.9],[139.25,-17.33],[140.04,-17.7],[140.51,-17.62],[140.83,-17.41],[141.41,-16.07],[141.62,-15.06],[141.47,-13.8],[141.61,-12.94],[141.93,-12.74],[141.69,-12.35],[141.96,-12.05],[142.17,-10.95],[142.6,-10.75],[142.87,-11.82],[143.18,-11.95]],[[178.28,-17.37],[178.59,-17.65],[178.67,-18.08],[177.96,-18.26],[177.32,-18.08],[177.26,-17.86],[177.5,-17.54],[178.28,-17.37]],[[164.2,-20.25],[165.19,-20.77],[166.94,-22.09],[166.97,-22.32],[166.47,-22.26],[164.93,-21.29],[164.38,-20.74],[164.04,-20.17],[164.2,-20.25]],[[127.73,0.85],[127.88,0.83],[128.22,1.4],[128.69,1.57],[128.7,1.11],[128.26,0.73],[128.9,0.22],[127.98,0.47],[127.89,0.3],[127.98,-0.25],[128.43,-0.89],[127.69,-0.24],[127.61,0.85],[127.43,1.14],[127.63,1.84],[128.04,2.2],[127.89,1.83],[128.01,1.33],[127.65,1.01],[127.73,0.85]],[[69.19,-49.11],[69.59,-48.97],[69.64,-49.12],[69.41,-49.18],[69.54,-49.26],[70.32,-49.06],[70.56,-49.2],[70.39,-49.43],[69.76,-49.43],[70.31,-49.58],[70.12,-49.7],[69.15,-49.53],[68.81,-49.7],[68.77,-49.07],[69.0,-48.66],[69.19,-49.11]],[[63.37,80.7],[62.52,80.82],[64.1,81.0],[64.31,81.17],[65.17,81.14],[65.44,80.93],[63.37,80.7]],[[-25.43,70.92],[-25.4,70.65],[-26.22,70.45],[-28.04,70.49],[-27.62,70.91],[-25.82,71.04],[-25.43,70.92]],[[117.31,8.44],[117.35,8.71],[119.22,10.48],[119.55,11.31],[119.69,10.5],[118.78,9.92],[118.44,9.26],[117.31,8.44]],[[122.5,11.62],[122.89,11.44],[123.16,11.54],[123.12,11.29],[122.77,10.82],[121.95,10.44],[122.1,11.64],[121.92,11.85],[122.5,11.62]],[[123.13,9.06],[122.4,9.82],[122.86,10.09],[122.98,10.89],[123.26,10.99],[123.57,10.78],[123.16,9.86],[123.32,9.27],[123.13,9.06]],[[124.58,11.34],[124.93,11.37],[125.0Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"continents":[{"id":"eurasia","nameI18n":{"zh-CN":"亚欧大陆","en":"Eurasia"},"label":[85,52],"lines":[[[127.7,0.8],[127.9,0.8],[128.2,1.4],[128.7,1.6],[128.7,1.1],[128.3,0.9],[128.3,0.7],[128.9,0.2],[128.0,0.5],[127.9,0.3]],[[127.7,0.3],[127.4,1.1],[127.6,1.8],[128.0,2.2],[128.0,1.3],[127.7,0.8]],[[63.4,80.7],[62.5,80.8],[63.1,81.0],[64.1,81.0],[64.3,81.2],[65.4,81.1],[65.4,80.9],[63.4,80.7]],[[117.3,8.4],[117.3,8.7],[119.2,10.5],[119.3,11.0],[119.6,11.3],[119.5,11.0],[119.7,10.5],[118.8,9.9],[118.4,9.3],[117.3,8.4]],[[122.5,11.6],[122.8,11.6],[122.9,11.4],[123.2,11.5],[122.8,10.8],[122.0,10.4],[122.1,11.6],[121.9,11.9],[122.5,11.6]],[[123.1,9.1],[122.4,9.8],[122.5,10.0],[122.9,10.1],[122.8,10.5],[123.0,10.9],[123.3,11.0],[123.6,10.8],[123.2,9.9],[123.3,9.3],[123.1,9.1]],[[124.6,11.3],[124.9,11.4],[125.3,10.3],[125.1,10.2],[125.0,10.4],[125.0,10.0],[124.8,10.2],[124.7,11.0],[124.4,10.9],[124.3,11.5],[124.6,11.3]],[[125.2,12.5],[125.5,12.2],[125.7,11.1],[125.2,11.1],[124.9,11.6],[125.0,11.8],[124.4,12.2],[124.3,12.6],[125.2,12.5]],[[120.7,13.5],[121.2,13.4],[121.5,13.1],[121.5,12.6],[121.2,12.2],[120.5,13.4],[120.3,13.4],[120.7,13.5]],[[22.6,58.6],[23.3,58.5],[22.0,57.9],[22.2,58.2],[21.9,58.3],[21.9,58.5],[22.6,58.6]],[[21.6,78.6],[22.0,78.6],[22.3,78.2],[23.0,78.3],[23.5,78.1],[23.1,78.0],[24.9,77.8],[22.8,77.3],[22.4,77.3],[22.7,77.6],[21.1,77.4],[20.9,77.6],[21.7,77.9],[20.2,78.5],[21.6,78.6]],[[47.4,80.9],[48.4,80.8],[48.7,80.6],[47.7,80.8],[46.1,80.4],[46.0,80.6],[44.9,80.6],[47.4,80.9]],[[50.3,80.9],[51.7,80.7],[51.0,80.5],[48.8,80.4],[48.7,80.3],[49.0,80.2],[48.4,80.1],[46.6,80.3],[49.1,80.5],[49.2,80.8],[50.3,80.9]],[[50.3,69.2],[50.2,69.0],[48.9,68.7],[48.4,68.8],[48.3,69.0],[48.4,69.3],[49.0,69.5],[50.3,69.2]],[[23.9,35.5],[24.2,35.6],[24.1,35.5],[24.4,35.4],[25.7,35.3],[25.8,35.1],[26.3,35.3],[26.2,35.0]],[[23.9,35.5],[24.2,35.6],[24.1,35.5],[24.4,35.4],[25.7,35.3],[25.8,35.1],[26.3,35.3],[26.2,35.0],[24.8,34.9],[24.5,35.2],[23.6,35.3],[23.7,35.7],[23.9,35.5]],[[23.4,39.0],[23.5,38.8],[24.1,38.6],[24.6,38.0],[22.9,38.9],[23.4,39.0]],[[34.5,35.6],[33.9,35.3],[34.0,35.0],[33.0,34.6],[32.4,34.7],[32.3,35.1],[32.9,35.2],[32.9,35.4],[34.5,35.6]],[[19.1,57.8],[18.8,57.7],[18.9,57.4],[18.1,56.9],[18.3,57.1],[18.1,57.6],[18.9,57.9],[19.1,57.8]],[[12.6,55.8],[12.2,55.5],[12.4,55.3],[12.1,55.2],[12.1,54.8],[11.9,54.8],[11.7,55.2],[11.3,55.2],[11.0,55.7],[11.6,56.0],[11.8,55.7],[11.9,56.0],[12.2,56.1],[12.6,56.1],[12.6,55.8]],[[96.5,81.1],[97.9,80.7],[97.1,80.6],[97.0,80.5],[97.4,80.3],[97.2,80.2],[93.9,80.0],[91.5,80.4],[92.8,80.6],[93.3,80.8],[92.6,80.8],[93.4,81.0],[95.8,81.3],[96.5,81.1]],[[97.7,80.2],[98.0,80.0],[97.6,79.8],[98.4,79.9],[98.6,80.1],[100.1,79.8],[99.7,79.3],[99.0,79.3],[99.9,79.0],[99.4,78.8],[94.8,79.1],[94.2,79.4],[93.1,79.5],[95.0,80.1],[97.7,80.2]],[[102.9,79.3],[102.4,78.8],[103.0,79.1],[103.8,79.1],[105.1,78.8],[105.3,78.5],[104.7,78.3],[99.3,78.0],[100.0,78.3],[100.4,78.8],[101.0,78.8],[100.9,78.9],[101.5,79.3],[102.9,79.3]],[[140.0,75.8],[140.8,75.6],[141.0,76.0],[141.5,76.1],[143.7,75.9],[145.4,75.5],[144.7,75.4],[144.9,75.3],[144.0,75.0],[142.8,75.3],[142.7,75.5],[143.0,75.6],[142.9,75.7],[142.1,75.7],[142.6,75.1],[143.1,75.0],[142.5,74.8],[142.0,75.0],[140.3,74.8],[139.7,75.0],[139.1,74.7],[138.1,74.8],[136.9,75.3],[137.3,75.3],[137.2,75.6],[137.7,75.8],[137.5,75.9],[137.6,76.0],[138.2,76.1],[138.9,76.2],[140.0,75.8]],[[142.2,73.9],[143.5,73.5],[143.5,73.2],[140.7,73.5],[139.7,73.4],[140.4,73.5],[141.1,73.9],[142.2,73.9]],[[146.8,75.4],[150.8,75.2],[150.6,74.9],[148.1,74.8],[146.1,75.2],[146.4,75.6],[146.8,75.4]],[[126.0,9.3],[126.2,9.3],[126.3,9.0],[126.1,8.6],[126.4,8.5],[126.6,7.2],[126.2,6.9],[126.2,6.3],[125.7,7.3],[125.4,6.7],[125.7,6.0],[125.3,5.6],[125.2,6.1],[124.9,5.9],[124.2,6.2],[124.0,7.0],[124.2,7.4],[124.0,7.7],[123.5,7.8],[123.4,7.4],[123.1,7.7],[122.8,7.5],[122.6,7.8],[122.0,7.0],[121.9,7.2],[122.2,7.9],[122.9,8.2],[123.4,8.7],[123.7,8.6],[123.8,8.0],[124.2,8.2],[124.4,8.6],[124.7,8.6],[124.9,9.0],[125.5,9.0],[125.5,9.8],[126.0,9.3]],[[121.1,18.6],[121.8,18.3],[122.3,18.5],[122.2,17.7],[122.5,17.1],[122.1,16.2],[121.6,15.9],[121.4,15.3],[121.7,14.8],[121.6,14.6],[121.9,14.0],[122.2,13.9],[122.2,14.1],[122.6,14.3],[122.9,14.2],[123.1,13.8],[123.3,13.8],[123.3,14.1],[123.8,13.8],[123.5,13.6],[123.8,13.1],[124.1,13.0],[124.1,12.6],[123.9,12.9],[123.3,13.0],[123.2,13.4],[122.6,13.9],[122.6,13.2],[121.8,13.9],[121.3,13.6],[120.8,13.9],[120.6,13.8],[120.6,14.2],[120.9,14.6],[120.6,14.9],[120.6,14.5],[120.4,14.5],[120.1,14.9],[119.8,16.3],[120.2,16.0],[120.4,16.1],[120.3,16.6],[120.6,18.5],[121.1,18.6]],[[124.9,1.0],[124.4,0.5],[123.8,0.3],[123.3,0.3],[123.0,0.5],[120.6,0.5],[120.2,0.3]],[[119.9,0.0],[119.8,0.2],[120.3,1.0],[120.4,0.8],[120.9,1.3],[122.8,0.8],[123.9,0.8],[125.1,1.7],[125.2,1.5],[124.9,1.0]],[[96.5,5.2],[97.5,5.2],[98.3,4.1],[99.7,3.2],[100.5,2.2],[100.9,1.9],[100.8,2.2],[101.0,2.3],[102.4,0.8],[103.0,0.6],[103.0,0.4],[102.5,0.2],[103.3,0.5],[10Line truncated
|
||||
@@ -0,0 +1,124 @@
|
||||
{
|
||||
"zh-CN": {
|
||||
"title": "如何使用 · 地球地理",
|
||||
"sections": [
|
||||
{
|
||||
"h": "开始使用(跟着做)",
|
||||
"lines": [
|
||||
"第 1 步:点右上「平面」,先看完整的世界地图,确认七大洲四大洋的位置。",
|
||||
"第 2 步:点「五带」,看回归线与极圈怎么把地球分成五个温度带。",
|
||||
"第 3 步:关掉「五带」,打开「六大板块」,记住六块板块的名字和范围。",
|
||||
"第 4 步:再打开「五大陆」,对比金色实线(大陆)与彩色虚线(板块)的差别。",
|
||||
"第 5 步:切回「3D 球面」,拖动转动地球,看背面会自动隐藏。",
|
||||
"看不清?滚轮放大;想重来点「复位」。每个图层都能单独开关,互不干扰。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "一、这个模型包含什么",
|
||||
"lines": [
|
||||
"五带:热带、南北温带、南北寒带(按回归线 23.5° 与极圈 66.5° 划分)。",
|
||||
"七大洲四大洋轮廓,以及洲与洲之间的分界线(苏伊士运河、巴拿马运河、白令海峡等)。",
|
||||
"六大板块:亚欧、非洲、美洲、太平洋、印度洋、南极洲板块。",
|
||||
"五块大陆:亚欧大陆、非洲大陆、美洲大陆、澳大利亚大陆、南极大陆。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "二、两种视图",
|
||||
"lines": [
|
||||
"「3D 球面」:正交投影球体,拖动旋转、滚轮缩放,背面自动裁掉。",
|
||||
"「平面」:等经纬矩形地图,课本地图样式,一次看全整幅。",
|
||||
"「复位」回到初始视角与缩放。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "三、图层开关(各自独立)",
|
||||
"lines": [
|
||||
"「五带」:叠加五带分界线与回归线、极圈。",
|
||||
"「大洲轮廓」:白色海岸线。",
|
||||
"「六大板块」:彩色虚线,是板块边界(不是大陆边界)。",
|
||||
"「五大陆」:金色实线,是大陆轮廓。",
|
||||
"「洲界」:分界点与分界线标签(如德雷克海峡、乌拉尔山…)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "四、颜色与图例",
|
||||
"lines": [
|
||||
"右侧图例说明三种线型:海岸线 / 板块边界 / 分界线。",
|
||||
"底部色块对应五个温度带。",
|
||||
"六大板块各一种颜色,标签放在板块中心附近。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "五、教学要点与易错点",
|
||||
"lines": [
|
||||
"「板块 ≠ 大陆」:美洲板块覆盖南北美大陆并向东到大西洋中脊;印度洋板块包含澳大利亚与印度次大陆。",
|
||||
"六大板块是全球一级板块,纳斯卡、阿拉伯等属于次级小板块,教材不列入。",
|
||||
"板块交界处多火山地震(环太平洋带、地中海—喜马拉雅带)。",
|
||||
"洲界是人为约定:亚欧以乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡为界;亚非以苏伊士运河为界;南北美以巴拿马运河为界;南美与南极以德雷克海峡为界。",
|
||||
"Esc 关闭窗口,F11 全屏。"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"en": {
|
||||
"title": "How to use · Earth Geography",
|
||||
"sections": [
|
||||
{
|
||||
"h": "Getting started (follow along)",
|
||||
"lines": [
|
||||
"Step 1: click Flat in the top right for the whole world map first.",
|
||||
"Step 2: turn on Climate zones to see how the tropics and polar circles split five belts.",
|
||||
"Step 3: switch zones off and turn on Six plates; learn the six names and extents.",
|
||||
"Step 4: turn on Five mainlands and compare solid gold lines (mainlands) with dashed colored lines (plates).",
|
||||
"Step 5: switch back to 3D globe, drag to rotate, and see back faces clip automatically.",
|
||||
"Hard to read? Scroll to zoom; press Reset to start over. Each layer toggles independently."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "1. What this model contains",
|
||||
"lines": [
|
||||
"Five climate zones split by the tropics (23.5°) and polar circles (66.5°).",
|
||||
"Seven continents, four oceans, and continental borders (Suez, Panama, Bering, etc.).",
|
||||
"Six major plates: Eurasian, African, American, Pacific, Indian Ocean, Antarctic.",
|
||||
"Five mainlands: Eurasia, Africa, America, Australia, Antarctica."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "2. Two views",
|
||||
"lines": [
|
||||
"3D globe: orthographic sphere; drag to rotate, scroll to zoom, back faces clipped.",
|
||||
"Flat: equirectangular textbook map, whole world at once.",
|
||||
"Reset restores the initial view and zoom."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "3. Independent layer toggles",
|
||||
"lines": [
|
||||
"Climate zones: tropics, polar circles and zone edges.",
|
||||
"Coastlines: white continental outlines.",
|
||||
"Six plates: dashed colored lines — plate BOUNDARIES, not continental edges.",
|
||||
"Five mainlands: solid gold lines — continental outlines.",
|
||||
"Borders: boundary dots and labels (Drake Passage, Ural Mts., ...)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "4. Colors & legend",
|
||||
"lines": [
|
||||
"The right legend explains the three line styles.",
|
||||
"The bottom strip maps the five climate zones.",
|
||||
"Each of the six plates has its own color, labelled near its center."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "5. Teaching notes & pitfalls",
|
||||
"lines": [
|
||||
"Plates are NOT mainlands: the American Plate spans both Americas to the Mid-Atlantic Ridge; the Indian Ocean Plate includes Australia and the Indian subcontinent.",
|
||||
"These six are the first-order plates; Nazca, Arabian, etc. are secondary and are not listed in textbooks.",
|
||||
"Volcanoes and earthquakes concentrate along plate boundaries (Pacific Ring, Mediterranean–Himalayan belt).",
|
||||
"Borders are conventions: Asia/Europe along the Urals–Ural River–Caspian–Caucasus–Black Sea–Turkish Straits; Asia/Africa at Suez; N/S America at Panama; S. America/Antarctica at Drake Passage.",
|
||||
"Esc closes, F11 toggles fullscreen."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"zones": "Zones",
|
||||
"coast": "Continents",
|
||||
"plates": "Plates",
|
||||
"borders": "Borders",
|
||||
"reset": "Reset"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"zones": "五带",
|
||||
"coast": "大洲轮廓",
|
||||
"plates": "板块",
|
||||
"borders": "洲界",
|
||||
"reset": "复位"
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
{
|
||||
"labels": [
|
||||
{
|
||||
"lat": 34,
|
||||
"lon": 90,
|
||||
"kind": "continent",
|
||||
"nameI18n": {
|
||||
"zh-CN": "亚洲",
|
||||
"en": "Asia"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": 2,
|
||||
"lon": 20,
|
||||
"kind": "continent",
|
||||
"nameI18n": {
|
||||
"zh-CN": "非洲",
|
||||
"en": "Africa"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": 48,
|
||||
"lon": -100,
|
||||
"kind": "continent",
|
||||
"nameI18n": {
|
||||
"zh-CN": "北美洲",
|
||||
"en": "North America"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": -15,
|
||||
"lon": -60,
|
||||
"kind": "continent",
|
||||
"nameI18n": {
|
||||
"zh-CN": "南美洲",
|
||||
"en": "South America"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": -78,
|
||||
"lon": 20,
|
||||
"kind": "continent",
|
||||
"nameI18n": {
|
||||
"zh-CN": "南极洲",
|
||||
"en": "Antarctica"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": 52,
|
||||
"lon": 18,
|
||||
"kind": "continent",
|
||||
"nameI18n": {
|
||||
"zh-CN": "欧洲",
|
||||
"en": "Europe"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": -24,
|
||||
"lon": 134,
|
||||
"kind": "continent",
|
||||
"nameI18n": {
|
||||
"zh-CN": "大洋洲",
|
||||
"en": "Oceania"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": 0,
|
||||
"lon": -155,
|
||||
"kind": "ocean",
|
||||
"nameI18n": {
|
||||
"zh-CN": "太平洋",
|
||||
"en": "Pacific Ocean"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": 12,
|
||||
"lon": -30,
|
||||
"kind": "ocean",
|
||||
"nameI18n": {
|
||||
"zh-CN": "大西洋",
|
||||
"en": "Atlantic Ocean"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": -22,
|
||||
"lon": 78,
|
||||
"kind": "ocean",
|
||||
"nameI18n": {
|
||||
"zh-CN": "印度洋",
|
||||
"en": "Indian Ocean"
|
||||
}
|
||||
},
|
||||
{
|
||||
"lat": 85,
|
||||
"lon": 0,
|
||||
"kind": "ocean",
|
||||
"nameI18n": {
|
||||
"zh-CN": "北冰洋",
|
||||
"en": "Arctic Ocean"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"plates": [
|
||||
{
|
||||
"id": "eurasian",
|
||||
"nameI18n": { "zh-CN": "亚欧板块", "en": "Eurasian Plate" },
|
||||
"label": [85, 55],
|
||||
"lines": [
|
||||
[[-10,36],[0,45],[15,55],[30,68],[60,72],[100,76],[140,70],[160,60],[140,42],[125,32],[110,28],[95,28],[80,30],[72,28],[60,25],[45,30],[32,32],[10,37],[-10,36]]
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "african",
|
||||
"nameI18n": { "zh-CN": "非洲板块", "en": "African Plate" },
|
||||
"label": [12, 2],
|
||||
"lines": [
|
||||
[[-20,35],[10,37],[32,32],[43,12],[51,10],[42,-8],[40,-25],[25,-35],[15,-30],[8,-5],[-8,5],[-17,15],[-20,35]]
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "american",
|
||||
"nameI18n": { "zh-CN": "美洲板块", "en": "American Plate" },
|
||||
"label": [-100, 12],
|
||||
"lines": [
|
||||
[[-168,72],[-140,70],[-115,70],[-90,72],[-60,60],[-52,45],[-60,30],[-80,25],[-82,8],[-78,0],[-70,-15],[-72,-40],[-75,-52],[-80,-55],[-95,-45],[-105,-25],[-95,-5],[-90,10],[-105,20],[-120,35],[-135,50],[-155,60],[-168,72]]
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "pacific",
|
||||
"nameI18n": { "zh-CN": "太平洋板块", "en": "Pacific Plate" },
|
||||
"label": [-150, 0],
|
||||
"lines": [
|
||||
[[-180,60],[-150,55],[-130,45],[-110,25],[-95,10],[-80,0],[-75,-15],[-90,-30],[-110,-45],[-130,-55],[-160,-60],[-180,-58],[-180,60]],
|
||||
[[145,55],[158,45],[152,30],[145,15],[140,0],[148,-15],[158,-30],[168,-45],[180,-55],[180,60],[165,60],[145,55]]
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "indian-ocean",
|
||||
"nameI18n": { "zh-CN": "印度洋板块", "en": "Indian Ocean Plate" },
|
||||
"label": [95, -8],
|
||||
"lines": [
|
||||
[[35,32],[50,30],[60,22],[68,24],[75,8],[88,5],[95,5],[115,10],[130,5],[145,-5],[150,-20],[145,-35],[130,-42],[115,-38],[105,-25],[95,-10],[80,-10],[65,-5],[55,10],[42,10],[35,20],[35,32]]
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "antarctic",
|
||||
"nameI18n": { "zh-CN": "南极洲板块", "en": "Antarctic Plate" },
|
||||
"label": [0, -76],
|
||||
"lines": [
|
||||
[[-180,-60],[-120,-62],[-60,-60],[0,-62],[60,-60],[120,-62],[180,-60],[180,-90],[-180,-90],[-180,-60]]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 196 KiB |
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"type": "geography",
|
||||
"defaultView": "zones",
|
||||
"views": [
|
||||
"zones",
|
||||
"coast",
|
||||
"plates"
|
||||
],
|
||||
"nameI18n": {
|
||||
"zh-CN": "地球地理",
|
||||
"en": "Earth Geography"
|
||||
},
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "五带划分 · 七大洲四大洋 · 六大板块 · 五大陆与洲界",
|
||||
"en": "Climate zones · continents & oceans · six plates · five mainlands & borders"
|
||||
},
|
||||
"tropicDeg": 23.5,
|
||||
"axialTiltDeg": 23.5,
|
||||
"oceanColor": "#0E2A4A",
|
||||
"zones": [
|
||||
{
|
||||
"id": "torrid",
|
||||
"latMin": -23.5,
|
||||
"latMax": 23.5,
|
||||
"nameI18n": {
|
||||
"zh-CN": "热带",
|
||||
"en": "Torrid zone"
|
||||
},
|
||||
"descI18n": {
|
||||
"zh-CN": "南北回归线之间,有太阳直射,终年高温。",
|
||||
"en": "Between the tropics; the Sun is overhead at some time each year."
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "north-temperate",
|
||||
"latMin": 23.5,
|
||||
"latMax": 66.5,
|
||||
"nameI18n": {
|
||||
"zh-CN": "北温带",
|
||||
"en": "North temperate"
|
||||
},
|
||||
"descI18n": {
|
||||
"zh-CN": "北回归线与北极圈之间,四季分明,无直射也无极昼极夜。",
|
||||
"en": "Between Tropic of Cancer and Arctic Circle; four distinct seasons."
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "south-temperate",
|
||||
"latMin": -66.5,
|
||||
"latMax": -23.5,
|
||||
"nameI18n": {
|
||||
"zh-CN": "南温带",
|
||||
"en": "South temperate"
|
||||
},
|
||||
"descI18n": {
|
||||
"zh-CN": "南回归线与南极圈之间,四季分明。",
|
||||
"en": "Between Tropic of Capricorn and Antarctic Circle; four seasons."
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "north-frigid",
|
||||
"latMin": 66.5,
|
||||
"latMax": 90,
|
||||
"nameI18n": {
|
||||
"zh-CN": "北寒带",
|
||||
"en": "North frigid zone"
|
||||
},
|
||||
"descI18n": {
|
||||
"zh-CN": "北极圈以北,有极昼极夜,终年寒冷。",
|
||||
"en": "North of the Arctic Circle; polar day/night, always cold."
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "south-frigid",
|
||||
"latMin": -90,
|
||||
"latMax": -66.5,
|
||||
"nameI18n": {
|
||||
"zh-CN": "南寒带",
|
||||
"en": "South frigid zone"
|
||||
},
|
||||
"descI18n": {
|
||||
"zh-CN": "南极圈以南,有极昼极夜,终年寒冷。",
|
||||
"en": "South of the Antarctic Circle; polar day/night, always cold."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "earth-revolution",
|
||||
"name": "Earth Revolution",
|
||||
"nameI18n": {
|
||||
"zh-CN": "地球公转",
|
||||
"en": "Earth Revolution"
|
||||
},
|
||||
"author": "Morris",
|
||||
"description": "四季更替、黄赤交角与二分二至",
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "地球绕太阳公转一年:地轴指向不变,太阳直射点南北往返,形成四季。",
|
||||
"en": "One year around the Sun: the fixed axial direction moves the subsolar point and creates the seasons."
|
||||
},
|
||||
"tags": [
|
||||
"astronomy",
|
||||
"geography",
|
||||
"revolution"
|
||||
],
|
||||
"entry": "scene.json",
|
||||
"license": "MIT",
|
||||
"assembly": "EarthRevolutionModel.dll",
|
||||
"type": "GC.EarthModels.RevolutionModelFactory",
|
||||
"preview": "preview.png",
|
||||
"apiVersion": 1,
|
||||
"version": "1.7",
|
||||
"chrome": {
|
||||
"titleBar": "#0C1828",
|
||||
"titleBorder": "#1B2740",
|
||||
"titleText": "#EAF2FF",
|
||||
"button": "#9FB4D4",
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "53b7a0fbc3",
|
||||
"updatedAt": "2026-11-21T10:55:36Z"
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
{
|
||||
"zh-CN": {
|
||||
"title": "如何使用 · 地球公转",
|
||||
"sections": [
|
||||
{
|
||||
"h": "开始使用(跟着做)",
|
||||
"lines": [
|
||||
"第 1 步:先按「1」定格到春分,看读数区「太阳直射」是多少度。",
|
||||
"第 2 步:再按「2」,直射纬度变成 23.5°N —— 这就是北半球夏至。",
|
||||
"第 3 步:依次按「3」「4」,对比四个节气的直射点位置。",
|
||||
"第 4 步:按「空格」播放,看地球绕太阳走完一圈要多久(有速度调节)。",
|
||||
"第 5 步:拖动鼠标换到「俯视」,能看到轨道是个椭圆,地轴始终指向同一方向。",
|
||||
"看不到变化?确认顶部「节气定位」已打开,且没有停在暂停状态。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "一、这个模型讲什么",
|
||||
"lines": [
|
||||
"地球绕太阳公转,周期约 365.25 天,轨道近似椭圆,地轴始终指向北极星附近。",
|
||||
"地轴与公转轨道面成 66.5° 夹角(赤道面与轨道面夹角 23.5°,即黄赤交角)。",
|
||||
"由于地轴倾斜方向不变,太阳直射点在南北回归线之间往返,形成四季更替。",
|
||||
"二分二至:春分 3/21、夏至 6/22、秋分 9/23、冬至 12/22(教材值)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "二、基本操作",
|
||||
"lines": [
|
||||
"「播放 / 暂停」控制公转动画;「速度」调节一年走完的快慢。",
|
||||
"「步进」让地球沿轨道前进一小格,便于逐段观察。",
|
||||
"拖动或滚轮改变观察角度与缩放;「俯视 / 侧视」切换视角。",
|
||||
"「重置」回到春分起点。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "三、节气定位(重点)",
|
||||
"lines": [
|
||||
"按 1–4 直接定格到春分、夏至、秋分、冬至。",
|
||||
"春分 / 秋分:太阳直射赤道(0°),全球昼夜平分。",
|
||||
"夏至:直射北回归线 23.5°N,北半球昼最长、北极圈内极昼。",
|
||||
"冬至:直射南回归线 23.5°S,北半球昼最短、北极圈内极夜。",
|
||||
"定格后读数区显示:公转角度、太阳直射纬度、教材日期、节气名称。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "四、读数与课堂卡",
|
||||
"lines": [
|
||||
"「太阳直射」读数来自模型数据里的 declinationDeg,不是近似公式。",
|
||||
"「节气定位」面板列出四个节气的日期与现象说明(中英双语)。",
|
||||
"「教学要点」解释:直射点移动 → 正午太阳高度与昼长变化 → 四季。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "五、易错点",
|
||||
"lines": [
|
||||
"四季成因是「地轴倾斜且方向不变」,不是「地球离太阳忽远忽近」。",
|
||||
"近日点在 1 月初(北半球冬天),远日点在 7 月初(北半球夏天)。",
|
||||
"南北半球季节相反:北半球夏至时南半球是冬至。",
|
||||
"Esc 关闭窗口,F11 全屏。"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"en": {
|
||||
"title": "How to use · Earth Revolution",
|
||||
"sections": [
|
||||
{
|
||||
"h": "Getting started (follow along)",
|
||||
"lines": [
|
||||
"Step 1: press 1 to freeze at the spring equinox and read the subsolar latitude.",
|
||||
"Step 2: press 2 — the subsolar point jumps to 23.5°N, the June solstice.",
|
||||
"Step 3: press 3 and 4 to compare all four key positions.",
|
||||
"Step 4: press Space to animate one full orbit; adjust Speed as needed.",
|
||||
"Step 5: drag to Top view to see the elliptical orbit and the fixed axis direction.",
|
||||
"Nothing changing? Make sure Seasons is on in the top bar and the model isn't paused."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "1. What this model shows",
|
||||
"lines": [
|
||||
"Earth orbits the Sun in ~365.25 days; the axis keeps pointing near Polaris.",
|
||||
"The axis is tilted 66.5° to the orbital plane (obliquity 23.5°).",
|
||||
"Because the tilt direction is fixed, the subsolar point migrates between the tropics, making seasons.",
|
||||
"Key dates: spring equinox 3/21, summer solstice 6/22, autumn equinox 9/23, winter solstice 12/22."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "2. Basic controls",
|
||||
"lines": [
|
||||
"Play/Pause runs the orbit; Speed sets how fast a year passes.",
|
||||
"Step advances one increment for close observation.",
|
||||
"Drag or scroll to change view/zoom; Top view / Side view switch perspective.",
|
||||
"Reset returns to the spring equinox."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "3. Solstices & equinoxes",
|
||||
"lines": [
|
||||
"Keys 1–4 freeze at spring equinox, summer solstice, autumn equinox, winter solstice.",
|
||||
"Equinoxes: subsolar at the equator (0°), equal day and night worldwide.",
|
||||
"June solstice: subsolar at 23.5°N; longest day in the north, polar day inside the Arctic Circle.",
|
||||
"December solstice: subsolar at 23.5°S; shortest day in the north, polar night.",
|
||||
"The readout shows orbit angle, subsolar latitude, textbook date and season name."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "4. Readouts & classroom cards",
|
||||
"lines": [
|
||||
"Subsolar latitude comes from declinationDeg in the model data, not an approximation.",
|
||||
"The seasons panel lists dates and phenomena for all four (bilingual).",
|
||||
"Teaching notes: migrating subsolar point → changing noon altitude and day length → seasons."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "5. Common mistakes",
|
||||
"lines": [
|
||||
"Seasons come from the fixed axial tilt, NOT from Earth being closer/farther to the Sun.",
|
||||
"Perihelion is early January (northern winter); aphelion is early July (northern summer).",
|
||||
"Seasons are opposite in the two hemispheres.",
|
||||
"Esc closes, F11 toggles fullscreen."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"title": "Earth Revolution",
|
||||
"view.rotation": "Rotation",
|
||||
"view.revolution": "Revolution",
|
||||
"play": "Play",
|
||||
"pause": "Pause",
|
||||
"speed": "Speed",
|
||||
"reset": "Reset",
|
||||
"labels": "Labels",
|
||||
"orbit": "Orbit",
|
||||
"grid": "Graticule",
|
||||
"tilt": "Exaggerate tilt",
|
||||
"lessons": "Teaching notes",
|
||||
"seasons": "Solstices & equinoxes",
|
||||
"close": "Close window",
|
||||
"loading": "Preparing scene…",
|
||||
"subsolar": "Subsolar point",
|
||||
"north": "North pole",
|
||||
"south": "South pole",
|
||||
"northShort": "N",
|
||||
"southShort": "S",
|
||||
"sun": "Sun",
|
||||
"earth": "Earth",
|
||||
"spinInfo": "Rotation {0}° · period {1} h",
|
||||
"orbitInfo": "Orbit {0}°",
|
||||
"declinationInfo": "Subsolar {0}",
|
||||
"dateInfo": "Date {0}",
|
||||
"season.springEquinox": "Spring equinox",
|
||||
"season.summerSolstice": "Summer solstice",
|
||||
"season.autumnEquinox": "Autumn equinox",
|
||||
"season.winterSolstice": "Winter solstice",
|
||||
"hint": "Pinch or scroll to zoom · drag to turn the Earth"
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"title": "地球自转",
|
||||
"view.rotation": "自转",
|
||||
"view.revolution": "公转",
|
||||
"play": "播放",
|
||||
"pause": "暂停",
|
||||
"speed": "速度",
|
||||
"reset": "重置",
|
||||
"labels": "标注",
|
||||
"orbit": "轨道",
|
||||
"grid": "经纬网",
|
||||
"tilt": "夸张倾角",
|
||||
"lessons": "教学要点",
|
||||
"seasons": "节气定位",
|
||||
"close": "关闭窗口",
|
||||
"loading": "正在准备场景…",
|
||||
"subsolar": "太阳直射点",
|
||||
"north": "北极",
|
||||
"south": "南极",
|
||||
"northShort": "N",
|
||||
"southShort": "S",
|
||||
"sun": "太阳",
|
||||
"earth": "地球",
|
||||
"spinInfo": "自转 {0}° · 周期 {1} 小时",
|
||||
"orbitInfo": "公转 {0}°",
|
||||
"declinationInfo": "太阳直射 {0}",
|
||||
"dateInfo": "日期 {0}",
|
||||
"season.springEquinox": "春分",
|
||||
"season.summerSolstice": "夏至",
|
||||
"season.autumnEquinox": "秋分",
|
||||
"season.winterSolstice": "冬至",
|
||||
"hint": "双指捏合或滚轮缩放 · 拖动可转动地球"
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"note": "简化大陆轮廓(经度,纬度),用于教学演示,非测绘精度",
|
||||
"polygons": [
|
||||
{
|
||||
"name": "north-america",
|
||||
"points": [[-168,66],[-164,70],[-155,71],[-145,70],[-133,69],[-120,69],[-110,68],[-100,69],[-92,68],[-85,70],[-80,73],[-72,71],[-64,66],[-60,60],[-56,52],[-60,47],[-66,45],[-70,42],[-74,40],[-76,35],[-81,31],[-80,25],[-83,29],[-88,30],[-94,29],[-97,26],[-97,21],[-92,19],[-87,21],[-88,16],[-83,9],[-78,9],[-84,14],[-90,14],[-96,16],[-105,20],[-112,25],[-117,32],[-122,37],[-124,42],[-125,48],[-131,54],[-140,59],[-150,59],[-158,56],[-165,60],[-166,64]]
|
||||
},
|
||||
{
|
||||
"name": "greenland",
|
||||
"points": [[-45,60],[-52,64],[-55,68],[-60,72],[-63,76],[-56,80],[-42,82],[-28,80],[-21,74],[-23,70],[-31,66],[-38,62]]
|
||||
},
|
||||
{
|
||||
"name": "south-america",
|
||||
"points": [[-78,8],[-72,11],[-64,10],[-60,8],[-52,5],[-50,0],[-44,-2],[-38,-5],[-35,-8],[-39,-13],[-41,-22],[-48,-25],[-53,-34],[-57,-38],[-62,-40],[-65,-45],[-68,-50],[-70,-55],[-75,-52],[-74,-45],[-73,-37],[-71,-30],[-70,-23],[-70,-18],[-76,-14],[-81,-6],[-80,-2],[-79,2],[-77,6]]
|
||||
},
|
||||
{
|
||||
"name": "africa",
|
||||
"points": [[-17,15],[-16,20],[-13,28],[-9,32],[-5,36],[10,37],[20,32],[32,31],[35,28],[39,15],[43,11],[51,12],[48,2],[41,-2],[40,-10],[35,-18],[32,-25],[27,-33],[20,-35],[15,-28],[12,-17],[9,-1],[5,4],[-4,5],[-8,4],[-13,8],[-16,12]]
|
||||
},
|
||||
{
|
||||
"name": "europe",
|
||||
"points": [[-9,38],[-9,43],[-2,44],[0,48],[2,51],[5,53],[8,54],[9,57],[12,56],[13,54],[20,54],[21,57],[24,58],[28,60],[30,60],[29,64],[25,66],[22,69],[30,70],[40,68],[46,66],[55,68],[60,70],[68,68],[62,62],[58,56],[52,50],[48,46],[40,45],[36,44],[30,45],[28,41],[24,40],[23,37],[19,40],[16,41],[12,44],[7,44],[3,42],[-2,37]]
|
||||
},
|
||||
{
|
||||
"name": "asia",
|
||||
"points": [[60,70],[75,73],[90,75],[105,77],[115,74],[130,73],[145,72],[160,70],[170,68],[180,65],[172,62],[163,58],[155,52],[143,54],[137,50],[130,43],[126,40],[122,40],[120,36],[122,31],[118,25],[110,21],[105,10],[100,13],[98,8],[95,17],[90,22],[88,21],[80,16],[77,8],[73,18],[68,23],[62,25],[57,24],[52,28],[48,30],[44,13],[43,17],[39,21],[35,28],[34,31],[36,36],[30,41],[28,41],[30,45],[34,45],[40,45],[48,46],[52,50],[58,56],[62,62],[68,68]]
|
||||
},
|
||||
{
|
||||
"name": "australia",
|
||||
"points": [[113,-22],[114,-27],[116,-35],[129,-32],[138,-35],[146,-39],[150,-37],[153,-28],[146,-19],[142,-11],[132,-11],[126,-14],[122,-18]]
|
||||
},
|
||||
{
|
||||
"name": "antarctica",
|
||||
"points": [[-180,-72],[-150,-76],[-120,-74],[-90,-73],[-60,-64],[-30,-70],[0,-70],[30,-69],[60,-67],[90,-66],[120,-66],[150,-70],[180,-72],[180,-90],[-180,-90]]
|
||||
},
|
||||
{
|
||||
"name": "madagascar",
|
||||
"points": [[43,-12],[50,-15],[50,-25],[45,-25],[43,-20]]
|
||||
},
|
||||
{
|
||||
"name": "japan",
|
||||
"points": [[130,32],[136,35],[141,40],[145,44],[142,39],[137,34],[133,33]]
|
||||
},
|
||||
{
|
||||
"name": "britain",
|
||||
"points": [[-6,50],[-2,53],[-2,58],[-5,58],[-6,54]]
|
||||
},
|
||||
{
|
||||
"name": "ireland",
|
||||
"points": [[-10,52],[-6,53],[-6,55],[-10,55]]
|
||||
},
|
||||
{
|
||||
"name": "iceland",
|
||||
"points": [[-24,65],[-14,66],[-14,64],[-22,63]]
|
||||
},
|
||||
{
|
||||
"name": "new-zealand",
|
||||
"points": [[166,-46],[170,-44],[174,-41],[177,-38],[174,-35],[170,-38],[167,-42]]
|
||||
},
|
||||
{
|
||||
"name": "sumatra",
|
||||
"points": [[95,5],[100,1],[105,-6],[100,-4],[96,2]]
|
||||
},
|
||||
{
|
||||
"name": "java",
|
||||
"points": [[105,-6],[114,-8],[114,-9],[106,-7]]
|
||||
},
|
||||
{
|
||||
"name": "borneo",
|
||||
"points": [[109,2],[117,4],[119,-2],[115,-4],[110,-2]]
|
||||
},
|
||||
{
|
||||
"name": "sulawesi",
|
||||
"points": [[119,1],[125,1],[123,-5],[120,-3]]
|
||||
},
|
||||
{
|
||||
"name": "new-guinea",
|
||||
"points": [[131,-1],[141,-3],[150,-6],[147,-9],[140,-9],[134,-5]]
|
||||
},
|
||||
{
|
||||
"name": "sri-lanka",
|
||||
"points": [[80,9],[82,7],[81,6],[79,7]]
|
||||
},
|
||||
{
|
||||
"name": "philippines",
|
||||
"points": [[120,18],[124,13],[126,8],[122,6],[120,12]]
|
||||
},
|
||||
{
|
||||
"name": "cuba",
|
||||
"points": [[-85,22],[-77,20],[-74,20],[-80,23]]
|
||||
},
|
||||
{
|
||||
"name": "taiwan",
|
||||
"points": [[120,25],[122,24],[121,22],[120,23]]
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 67 KiB |
@@ -0,0 +1,139 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"type": "planet",
|
||||
"defaultView": "revolution",
|
||||
"views": [
|
||||
"revolution"
|
||||
],
|
||||
"nameI18n": {
|
||||
"zh-CN": "地球公转",
|
||||
"en": "Earth Revolution"
|
||||
},
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "地球绕太阳公转一年:地轴指向不变,太阳直射点南北往返,形成四季。",
|
||||
"en": "One year around the Sun: the fixed axial direction moves the subsolar point and creates the seasons."
|
||||
},
|
||||
"star": {
|
||||
"name": "Sun",
|
||||
"nameI18n": {
|
||||
"zh-CN": "太阳",
|
||||
"en": "Sun"
|
||||
},
|
||||
"color": "#FFC24B",
|
||||
"radiusScale": 0.5
|
||||
},
|
||||
"planet": {
|
||||
"name": "Earth",
|
||||
"nameI18n": {
|
||||
"zh-CN": "地球",
|
||||
"en": "Earth"
|
||||
},
|
||||
"axialTiltDeg": 23.5,
|
||||
"tropicDeg": 23.5,
|
||||
"rotationHours": 23.93,
|
||||
"orbitDays": 365.26,
|
||||
"oceanColor": "#1C5FA8",
|
||||
"landColor": "#4E8C4C",
|
||||
"iceColor": "#E9EFF6",
|
||||
"landFile": "land.json",
|
||||
"showGraticule": false
|
||||
},
|
||||
"orbit": {
|
||||
"semiMajorAxis": 4.0,
|
||||
"eccentricity": 0.0167,
|
||||
"show": true,
|
||||
"seasonLayout": "springTopSummerLeft",
|
||||
"seasons": [
|
||||
{
|
||||
"angleDeg": 0,
|
||||
"key": "season.springEquinox",
|
||||
"date": "3/21",
|
||||
"declinationDeg": 0,
|
||||
"teachingI18n": {
|
||||
"zh-CN": "太阳直射赤道,全球昼夜平分。此后直射点由赤道向北移动。",
|
||||
"en": "The Sun is overhead at the equator and day equals night everywhere. The subsolar point now moves north."
|
||||
}
|
||||
},
|
||||
{
|
||||
"angleDeg": 90,
|
||||
"key": "season.summerSolstice",
|
||||
"date": "6/22",
|
||||
"declinationDeg": 23.5,
|
||||
"teachingI18n": {
|
||||
"zh-CN": "太阳直射北回归线 23.5°N。北半球昼最长、夜最短,北极圈内出现极昼。",
|
||||
"en": "The Sun is overhead at the Tropic of Cancer (23.5°N). The northern hemisphere has its longest day."
|
||||
}
|
||||
},
|
||||
{
|
||||
"angleDeg": 180,
|
||||
"key": "season.autumnEquinox",
|
||||
"date": "9/23",
|
||||
"declinationDeg": 0,
|
||||
"teachingI18n": {
|
||||
"zh-CN": "太阳再次直射赤道,全球昼夜平分。此后直射点向南移动。",
|
||||
"en": "The Sun is overhead at the equator again. The subsolar point now moves south."
|
||||
}
|
||||
},
|
||||
{
|
||||
"angleDeg": 270,
|
||||
"key": "season.winterSolstice",
|
||||
"date": "12/22",
|
||||
"declinationDeg": -23.5,
|
||||
"teachingI18n": {
|
||||
"zh-CN": "太阳直射南回归线 23.5°S。北半球昼最短、夜最长,北极圈内出现极夜。",
|
||||
"en": "The Sun is overhead at the Tropic of Capricorn (23.5°S). The northern hemisphere has its shortest day."
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"lessons": [
|
||||
{
|
||||
"titleI18n": {
|
||||
"zh-CN": "一年绕太阳一圈",
|
||||
"en": "One lap per year"
|
||||
},
|
||||
"bodyI18n": {
|
||||
"zh-CN": "公转方向与自转相同,周期约 365.26 天;轨道接近圆形。",
|
||||
"en": "The orbit takes about 365.26 days and runs the same direction as the spin."
|
||||
},
|
||||
"view": "revolution",
|
||||
"angleDeg": 0
|
||||
},
|
||||
{
|
||||
"titleI18n": {
|
||||
"zh-CN": "地轴指向不变",
|
||||
"en": "The axis keeps its direction"
|
||||
},
|
||||
"bodyI18n": {
|
||||
"zh-CN": "公转过程中地轴始终指向北极星附近,黄赤交角 23.5° 保持不变。",
|
||||
"en": "During the whole orbit the axis keeps pointing near Polaris, so the 23.5° tilt stays fixed in space."
|
||||
},
|
||||
"view": "revolution",
|
||||
"angleDeg": 90
|
||||
},
|
||||
{
|
||||
"titleI18n": {
|
||||
"zh-CN": "夏至与冬至",
|
||||
"en": "Solstices"
|
||||
},
|
||||
"bodyI18n": {
|
||||
"zh-CN": "夏至太阳直射北回归线 23.5°N,北半球昼最长;冬至直射南回归线 23.5°S。",
|
||||
"en": "At the June solstice the Sun is overhead at 23.5°N; at the December solstice at 23.5°S."
|
||||
},
|
||||
"view": "revolution",
|
||||
"angleDeg": 90
|
||||
},
|
||||
{
|
||||
"titleI18n": {
|
||||
"zh-CN": "春分与秋分",
|
||||
"en": "Equinoxes"
|
||||
},
|
||||
"bodyI18n": {
|
||||
"zh-CN": "春分、秋分太阳直射赤道,全球昼夜平分,是四季的转折点。",
|
||||
"en": "At the equinoxes the Sun is overhead at the equator and day equals night everywhere."
|
||||
},
|
||||
"view": "revolution",
|
||||
"angleDeg": 180
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "earth-rotation",
|
||||
"name": "Earth Rotation",
|
||||
"nameI18n": {
|
||||
"zh-CN": "地球自转",
|
||||
"en": "Earth Rotation"
|
||||
},
|
||||
"author": "Morris",
|
||||
"description": "昼夜交替、晨昏线与太阳直射点",
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "观察自转中的地球:昼夜半球、晨昏线与太阳直射点位置。",
|
||||
"en": "Watch a rotating Earth: day/night hemispheres, terminator and the subsolar point."
|
||||
},
|
||||
"tags": [
|
||||
"astronomy",
|
||||
"geography",
|
||||
"rotation"
|
||||
],
|
||||
"entry": "scene.json",
|
||||
"license": "MIT",
|
||||
"assembly": "EarthRotationModel.dll",
|
||||
"type": "GC.EarthModels.RotationModelFactory",
|
||||
"preview": "preview.png",
|
||||
"apiVersion": 1,
|
||||
"version": "1.7",
|
||||
"chrome": {
|
||||
"titleBar": "#0C1828",
|
||||
"titleBorder": "#1B2740",
|
||||
"titleText": "#EAF2FF",
|
||||
"button": "#9FB4D4",
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "ecd52665f9",
|
||||
"updatedAt": "2026-11-21T10:55:36Z"
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
{
|
||||
"zh-CN": {
|
||||
"title": "如何使用 · 地球自转",
|
||||
"sections": [
|
||||
{
|
||||
"h": "开始使用(跟着做)",
|
||||
"lines": [
|
||||
"第 1 步:窗口打开后先按「空格」暂停,动画停住才好观察。",
|
||||
"第 2 步:按住鼠标左键拖动地球,把晨昏线转到正对你。",
|
||||
"第 3 步:点顶部「经纬网」打开网格,能看清哪一段是夜半球。",
|
||||
"第 4 步:再按「空格」播放,盯住一个点,看它从黑夜转进白天。",
|
||||
"第 5 步:按住「←」「→」可以一格一格慢慢看昼夜交界线怎么移动。",
|
||||
"找不到按钮?所有开关都在窗口顶部那一排;转不动地球就点「复位」重来。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "一、这个模型讲什么",
|
||||
"lines": [
|
||||
"地球绕地轴自西向东自转,周期约 24 小时(一个太阳日)。",
|
||||
"自转产生三个可观察现象:昼夜交替、地方时差、地转偏向力。",
|
||||
"晨昏线( terminator )是把地球分成昼半球与夜半球的大圆,它随自转不断西移。",
|
||||
"太阳直射点是地表太阳高度为 90° 的点,正午太阳高度由它向南北两侧递减。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "二、基本操作",
|
||||
"lines": [
|
||||
"拖动地球:改变观察角度(经度/纬度),可从极地或赤道上空看。",
|
||||
"滚轮或双指捏合:缩放;右上角「放大」可切到地球特写。",
|
||||
"「播放 / 暂停」开始或停止自转动画;「速度」调节快慢。",
|
||||
"「重置」把角度、速度、缩放恢复到初始状态。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "三、图层开关",
|
||||
"lines": [
|
||||
"「经纬网」叠加经线与纬线,便于读出赤道、回归线、极圈。",
|
||||
"「标注」显示北极、南极、太阳直射点、赤道等关键标签。",
|
||||
"「轨道」显示自转轴与赤道面;「夸张倾角」把 23.5° 放大便于观察。",
|
||||
"「教学要点」展开课堂讲解文字,适合投屏授课。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "四、键盘快捷键",
|
||||
"lines": [
|
||||
"空格:播放 / 暂停。",
|
||||
"← →:逐帧步进(暂停时最有用)。",
|
||||
"Esc:关闭窗口;F11:全屏 / 退出全屏。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "五、课堂上怎么用",
|
||||
"lines": [
|
||||
"先暂停,把晨昏线转到与经线重合,说明「昼夜平分」只在二分日出现。",
|
||||
"再播放,让学生观察同一地点如何由夜入昼(晨线)与由昼入夜(昏线)。",
|
||||
"对比不同经度:东边地点先见到日出,引出「东早西晚」的地方时差。",
|
||||
"易错提醒:昼夜现象本身由「地球不发光、不透明」造成,自转只造成「交替」。"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"en": {
|
||||
"title": "How to use · Earth Rotation",
|
||||
"sections": [
|
||||
{
|
||||
"h": "Getting started (follow along)",
|
||||
"lines": [
|
||||
"Step 1: press Space to pause first — a still globe is easier to read.",
|
||||
"Step 2: hold the left mouse button and drag until the terminator faces you.",
|
||||
"Step 3: switch on Graticule in the top bar to see which side is night.",
|
||||
"Step 4: press Space to play and watch one point rotate from night into day.",
|
||||
"Step 5: use ← / → to step frame by frame and follow the day/night boundary.",
|
||||
"Can't find a control? Every toggle is in the top bar; if the globe gets twisted, press Reset."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "1. What this model shows",
|
||||
"lines": [
|
||||
"Earth spins west-to-east on its axis in about 24 hours (a solar day).",
|
||||
"Rotation causes the day/night cycle, local time differences and the Coriolis effect.",
|
||||
"The terminator is the great circle splitting day and night; it moves west as Earth turns.",
|
||||
"The subsolar point is where the Sun is overhead; noon altitude decreases away from it."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "2. Basic controls",
|
||||
"lines": [
|
||||
"Drag the globe to change the viewing angle (from pole or equator).",
|
||||
"Scroll or pinch to zoom; the close-up button gives an Earth detail view.",
|
||||
"Play/Pause starts or stops the spin; Speed changes the rate.",
|
||||
"Reset restores the initial angle, speed and zoom."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "3. Layer toggles",
|
||||
"lines": [
|
||||
"Graticule overlays meridians and parallels (equator, tropics, polar circles).",
|
||||
"Labels shows poles, subsolar point and the equator.",
|
||||
"Orbit shows the axis and equatorial plane; Exaggerate tilt magnifies the 23.5° tilt.",
|
||||
"Teaching notes expands classroom text, useful on a projector."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "4. Keyboard shortcuts",
|
||||
"lines": [
|
||||
"Space: play / pause. ← →: step one frame (best while paused).",
|
||||
"Esc: close window. F11: toggle fullscreen."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "5. In the classroom",
|
||||
"lines": [
|
||||
"Pause with the terminator along a meridian to show equal day/night at equinoxes.",
|
||||
"Play again and watch a site cross the dawn line and the dusk line.",
|
||||
"Compare longitudes: eastern places see sunrise earlier — local time runs ahead.",
|
||||
"Common mistake: day/night exists because Earth is opaque; rotation only makes it alternate."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"title": "Earth Rotation",
|
||||
"view.rotation": "Rotation",
|
||||
"view.revolution": "Revolution",
|
||||
"play": "Play",
|
||||
"pause": "Pause",
|
||||
"speed": "Speed",
|
||||
"reset": "Reset",
|
||||
"labels": "Labels",
|
||||
"orbit": "Orbit",
|
||||
"grid": "Graticule",
|
||||
"tilt": "Exaggerate tilt",
|
||||
"lessons": "Teaching notes",
|
||||
"seasons": "Solstices & equinoxes",
|
||||
"close": "Close window",
|
||||
"loading": "Preparing scene…",
|
||||
"subsolar": "Subsolar point",
|
||||
"north": "North pole",
|
||||
"south": "South pole",
|
||||
"northShort": "N",
|
||||
"southShort": "S",
|
||||
"sun": "Sun",
|
||||
"earth": "Earth",
|
||||
"spinInfo": "Rotation {0}° · period {1} h",
|
||||
"orbitInfo": "Orbit {0}°",
|
||||
"declinationInfo": "Subsolar {0}",
|
||||
"dateInfo": "Date {0}",
|
||||
"season.springEquinox": "Spring equinox",
|
||||
"season.summerSolstice": "Summer solstice",
|
||||
"season.autumnEquinox": "Autumn equinox",
|
||||
"season.winterSolstice": "Winter solstice",
|
||||
"hint": "Pinch or scroll to zoom · drag to turn the Earth"
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"title": "地球自转",
|
||||
"view.rotation": "自转",
|
||||
"view.revolution": "公转",
|
||||
"play": "播放",
|
||||
"pause": "暂停",
|
||||
"speed": "速度",
|
||||
"reset": "重置",
|
||||
"labels": "标注",
|
||||
"orbit": "轨道",
|
||||
"grid": "经纬网",
|
||||
"tilt": "夸张倾角",
|
||||
"lessons": "教学要点",
|
||||
"seasons": "节气定位",
|
||||
"close": "关闭窗口",
|
||||
"loading": "正在准备场景…",
|
||||
"subsolar": "太阳直射点",
|
||||
"north": "北极",
|
||||
"south": "南极",
|
||||
"northShort": "N",
|
||||
"southShort": "S",
|
||||
"sun": "太阳",
|
||||
"earth": "地球",
|
||||
"spinInfo": "自转 {0}° · 周期 {1} 小时",
|
||||
"orbitInfo": "公转 {0}°",
|
||||
"declinationInfo": "太阳直射 {0}",
|
||||
"dateInfo": "日期 {0}",
|
||||
"season.springEquinox": "春分",
|
||||
"season.summerSolstice": "夏至",
|
||||
"season.autumnEquinox": "秋分",
|
||||
"season.winterSolstice": "冬至",
|
||||
"hint": "双指捏合或滚轮缩放 · 拖动可转动地球"
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"note": "简化大陆轮廓(经度,纬度),用于教学演示,非测绘精度",
|
||||
"polygons": [
|
||||
{
|
||||
"name": "north-america",
|
||||
"points": [[-168,66],[-164,70],[-155,71],[-145,70],[-133,69],[-120,69],[-110,68],[-100,69],[-92,68],[-85,70],[-80,73],[-72,71],[-64,66],[-60,60],[-56,52],[-60,47],[-66,45],[-70,42],[-74,40],[-76,35],[-81,31],[-80,25],[-83,29],[-88,30],[-94,29],[-97,26],[-97,21],[-92,19],[-87,21],[-88,16],[-83,9],[-78,9],[-84,14],[-90,14],[-96,16],[-105,20],[-112,25],[-117,32],[-122,37],[-124,42],[-125,48],[-131,54],[-140,59],[-150,59],[-158,56],[-165,60],[-166,64]]
|
||||
},
|
||||
{
|
||||
"name": "greenland",
|
||||
"points": [[-45,60],[-52,64],[-55,68],[-60,72],[-63,76],[-56,80],[-42,82],[-28,80],[-21,74],[-23,70],[-31,66],[-38,62]]
|
||||
},
|
||||
{
|
||||
"name": "south-america",
|
||||
"points": [[-78,8],[-72,11],[-64,10],[-60,8],[-52,5],[-50,0],[-44,-2],[-38,-5],[-35,-8],[-39,-13],[-41,-22],[-48,-25],[-53,-34],[-57,-38],[-62,-40],[-65,-45],[-68,-50],[-70,-55],[-75,-52],[-74,-45],[-73,-37],[-71,-30],[-70,-23],[-70,-18],[-76,-14],[-81,-6],[-80,-2],[-79,2],[-77,6]]
|
||||
},
|
||||
{
|
||||
"name": "africa",
|
||||
"points": [[-17,15],[-16,20],[-13,28],[-9,32],[-5,36],[10,37],[20,32],[32,31],[35,28],[39,15],[43,11],[51,12],[48,2],[41,-2],[40,-10],[35,-18],[32,-25],[27,-33],[20,-35],[15,-28],[12,-17],[9,-1],[5,4],[-4,5],[-8,4],[-13,8],[-16,12]]
|
||||
},
|
||||
{
|
||||
"name": "europe",
|
||||
"points": [[-9,38],[-9,43],[-2,44],[0,48],[2,51],[5,53],[8,54],[9,57],[12,56],[13,54],[20,54],[21,57],[24,58],[28,60],[30,60],[29,64],[25,66],[22,69],[30,70],[40,68],[46,66],[55,68],[60,70],[68,68],[62,62],[58,56],[52,50],[48,46],[40,45],[36,44],[30,45],[28,41],[24,40],[23,37],[19,40],[16,41],[12,44],[7,44],[3,42],[-2,37]]
|
||||
},
|
||||
{
|
||||
"name": "asia",
|
||||
"points": [[60,70],[75,73],[90,75],[105,77],[115,74],[130,73],[145,72],[160,70],[170,68],[180,65],[172,62],[163,58],[155,52],[143,54],[137,50],[130,43],[126,40],[122,40],[120,36],[122,31],[118,25],[110,21],[105,10],[100,13],[98,8],[95,17],[90,22],[88,21],[80,16],[77,8],[73,18],[68,23],[62,25],[57,24],[52,28],[48,30],[44,13],[43,17],[39,21],[35,28],[34,31],[36,36],[30,41],[28,41],[30,45],[34,45],[40,45],[48,46],[52,50],[58,56],[62,62],[68,68]]
|
||||
},
|
||||
{
|
||||
"name": "australia",
|
||||
"points": [[113,-22],[114,-27],[116,-35],[129,-32],[138,-35],[146,-39],[150,-37],[153,-28],[146,-19],[142,-11],[132,-11],[126,-14],[122,-18]]
|
||||
},
|
||||
{
|
||||
"name": "antarctica",
|
||||
"points": [[-180,-72],[-150,-76],[-120,-74],[-90,-73],[-60,-64],[-30,-70],[0,-70],[30,-69],[60,-67],[90,-66],[120,-66],[150,-70],[180,-72],[180,-90],[-180,-90]]
|
||||
},
|
||||
{
|
||||
"name": "madagascar",
|
||||
"points": [[43,-12],[50,-15],[50,-25],[45,-25],[43,-20]]
|
||||
},
|
||||
{
|
||||
"name": "japan",
|
||||
"points": [[130,32],[136,35],[141,40],[145,44],[142,39],[137,34],[133,33]]
|
||||
},
|
||||
{
|
||||
"name": "britain",
|
||||
"points": [[-6,50],[-2,53],[-2,58],[-5,58],[-6,54]]
|
||||
},
|
||||
{
|
||||
"name": "ireland",
|
||||
"points": [[-10,52],[-6,53],[-6,55],[-10,55]]
|
||||
},
|
||||
{
|
||||
"name": "iceland",
|
||||
"points": [[-24,65],[-14,66],[-14,64],[-22,63]]
|
||||
},
|
||||
{
|
||||
"name": "new-zealand",
|
||||
"points": [[166,-46],[170,-44],[174,-41],[177,-38],[174,-35],[170,-38],[167,-42]]
|
||||
},
|
||||
{
|
||||
"name": "sumatra",
|
||||
"points": [[95,5],[100,1],[105,-6],[100,-4],[96,2]]
|
||||
},
|
||||
{
|
||||
"name": "java",
|
||||
"points": [[105,-6],[114,-8],[114,-9],[106,-7]]
|
||||
},
|
||||
{
|
||||
"name": "borneo",
|
||||
"points": [[109,2],[117,4],[119,-2],[115,-4],[110,-2]]
|
||||
},
|
||||
{
|
||||
"name": "sulawesi",
|
||||
"points": [[119,1],[125,1],[123,-5],[120,-3]]
|
||||
},
|
||||
{
|
||||
"name": "new-guinea",
|
||||
"points": [[131,-1],[141,-3],[150,-6],[147,-9],[140,-9],[134,-5]]
|
||||
},
|
||||
{
|
||||
"name": "sri-lanka",
|
||||
"points": [[80,9],[82,7],[81,6],[79,7]]
|
||||
},
|
||||
{
|
||||
"name": "philippines",
|
||||
"points": [[120,18],[124,13],[126,8],[122,6],[120,12]]
|
||||
},
|
||||
{
|
||||
"name": "cuba",
|
||||
"points": [[-85,22],[-77,20],[-74,20],[-80,23]]
|
||||
},
|
||||
{
|
||||
"name": "taiwan",
|
||||
"points": [[120,25],[122,24],[121,22],[120,23]]
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 178 KiB |
@@ -0,0 +1,138 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"type": "planet",
|
||||
"defaultView": "rotation",
|
||||
"views": [
|
||||
"rotation"
|
||||
],
|
||||
"nameI18n": {
|
||||
"zh-CN": "地球自转",
|
||||
"en": "Earth Rotation"
|
||||
},
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "观察自转中的地球:昼夜半球、晨昏线与太阳直射点位置。",
|
||||
"en": "Watch a rotating Earth: day/night hemispheres, terminator and the subsolar point."
|
||||
},
|
||||
"star": {
|
||||
"name": "Sun",
|
||||
"nameI18n": {
|
||||
"zh-CN": "太阳",
|
||||
"en": "Sun"
|
||||
},
|
||||
"color": "#FFC24B",
|
||||
"radiusScale": 0.5
|
||||
},
|
||||
"planet": {
|
||||
"name": "Earth",
|
||||
"nameI18n": {
|
||||
"zh-CN": "地球",
|
||||
"en": "Earth"
|
||||
},
|
||||
"axialTiltDeg": 23.5,
|
||||
"tropicDeg": 23.5,
|
||||
"rotationHours": 23.93,
|
||||
"orbitDays": 365.26,
|
||||
"oceanColor": "#1C5FA8",
|
||||
"landColor": "#4E8C4C",
|
||||
"iceColor": "#E9EFF6",
|
||||
"landFile": "land.json",
|
||||
"showGraticule": true
|
||||
},
|
||||
"orbit": {
|
||||
"semiMajorAxis": 4.0,
|
||||
"eccentricity": 0.0167,
|
||||
"show": true,
|
||||
"seasons": [
|
||||
{
|
||||
"angleDeg": 0,
|
||||
"key": "season.springEquinox",
|
||||
"date": "3/21",
|
||||
"declinationDeg": 0,
|
||||
"teachingI18n": {
|
||||
"zh-CN": "太阳直射赤道,全球昼夜平分。",
|
||||
"en": "The Sun is overhead at the equator and day equals night everywhere."
|
||||
}
|
||||
},
|
||||
{
|
||||
"angleDeg": 90,
|
||||
"key": "season.summerSolstice",
|
||||
"date": "6/22",
|
||||
"declinationDeg": 23.5,
|
||||
"teachingI18n": {
|
||||
"zh-CN": "太阳直射北回归线 23.5°N,北半球昼最长。",
|
||||
"en": "The Sun is overhead at 23.5°N; the northern hemisphere has its longest day."
|
||||
}
|
||||
},
|
||||
{
|
||||
"angleDeg": 180,
|
||||
"key": "season.autumnEquinox",
|
||||
"date": "9/23",
|
||||
"declinationDeg": 0,
|
||||
"teachingI18n": {
|
||||
"zh-CN": "太阳直射赤道,全球昼夜平分。",
|
||||
"en": "The Sun is overhead at the equator and day equals night everywhere."
|
||||
}
|
||||
},
|
||||
{
|
||||
"angleDeg": 270,
|
||||
"key": "season.winterSolstice",
|
||||
"date": "12/22",
|
||||
"declinationDeg": -23.5,
|
||||
"teachingI18n": {
|
||||
"zh-CN": "太阳直射南回归线 23.5°S,北半球昼最短。",
|
||||
"en": "The Sun is overhead at 23.5°S; the northern hemisphere has its shortest day."
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"lessons": [
|
||||
{
|
||||
"titleI18n": {
|
||||
"zh-CN": "自西向东的自转",
|
||||
"en": "Rotation from west to east"
|
||||
},
|
||||
"bodyI18n": {
|
||||
"zh-CN": "从北极上空看,地球逆时针转动;转一圈用 23 小时 56 分 4 秒。",
|
||||
"en": "Seen from above the north pole the Earth turns counter-clockwise, once every 23 h 56 min."
|
||||
},
|
||||
"view": "rotation",
|
||||
"angleDeg": 0
|
||||
},
|
||||
{
|
||||
"titleI18n": {
|
||||
"zh-CN": "昼夜交替",
|
||||
"en": "Day and night"
|
||||
},
|
||||
"bodyI18n": {
|
||||
"zh-CN": "晨昏线(白色虚线)把地球分成昼半球与夜半球,交替周期 24 小时。",
|
||||
"en": "The terminator (white dashes) splits the lit and dark hemispheres; one cycle takes 24 h."
|
||||
},
|
||||
"view": "rotation",
|
||||
"angleDeg": 60
|
||||
},
|
||||
{
|
||||
"titleI18n": {
|
||||
"zh-CN": "太阳直射点",
|
||||
"en": "Subsolar point"
|
||||
},
|
||||
"bodyI18n": {
|
||||
"zh-CN": "黄色圆环标出太阳光垂直照射的位置,它随季节在南北回归线之间往返。",
|
||||
"en": "The yellow ring marks where sunlight strikes vertically — it drifts between the tropics over a year."
|
||||
},
|
||||
"view": "rotation",
|
||||
"angleDeg": 120
|
||||
},
|
||||
{
|
||||
"titleI18n": {
|
||||
"zh-CN": "地轴倾斜 23.5°",
|
||||
"en": "Axial tilt 23.5°"
|
||||
},
|
||||
"bodyI18n": {
|
||||
"zh-CN": "地轴与黄道面法线成 23.5°,倾斜方向不变,这是四季与五带划分的根本原因。",
|
||||
"en": "The axis is tilted 23.5° from the ecliptic normal and keeps its direction — the root cause of seasons."
|
||||
},
|
||||
"view": "rotation",
|
||||
"angleDeg": 200
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "scale-calculator",
|
||||
"name": "Scale Calculator",
|
||||
"nameI18n": {
|
||||
"zh-CN": "比例尺计算器",
|
||||
"en": "Scale Calculator"
|
||||
},
|
||||
"author": "Morris GC",
|
||||
"description": "把比例尺变成可以拖、可以量的可视化标尺",
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "三种求解模式、图上/实地双条对比、线段式比例尺自动换挡、比例尺光谱、真实地标实地尺与练习闯关。",
|
||||
"en": "Three solve modes, dual map/real bars, auto-ranging graphic scale, scale spectrum, real-world landmarks and practice quizzes."
|
||||
},
|
||||
"tags": [
|
||||
"geography",
|
||||
"map",
|
||||
"scale",
|
||||
"calculator"
|
||||
],
|
||||
"entry": "scales.json",
|
||||
"license": "MIT",
|
||||
"assembly": "ScaleCalculatorModel.dll",
|
||||
"type": "GC.ScaleCalculator.ScaleCalculatorFactory",
|
||||
"preview": "preview.png",
|
||||
"apiVersion": 1,
|
||||
"version": "1.6",
|
||||
"chrome": {
|
||||
"titleBar": "#FFFFFF",
|
||||
"titleBorder": "#E3E8F3",
|
||||
"titleText": "#111A2E",
|
||||
"button": "#5B6A86",
|
||||
"frame": "#F4F6FB"
|
||||
},
|
||||
"build": "105653737d",
|
||||
"updatedAt": "2026-11-21T10:55:36Z"
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
{
|
||||
"zh-CN": {
|
||||
"title": "如何使用 · 比例尺计算器",
|
||||
"sections": [
|
||||
{
|
||||
"h": "开始使用(跟着做)",
|
||||
"lines": [
|
||||
"第 1 步:顶部选「求实地距离」,此时蓝色卡是答案,另外两个是输入。",
|
||||
"第 2 步:在「图上距离」里填 3,在「比例尺分母」里填 100000。",
|
||||
"第 3 步:看蓝色卡算出 3 千米 —— 再点「解题步骤」核对每一步。",
|
||||
"第 4 步:改成「求比例尺」,把实地距离填成 6 千米,看分母怎么翻倍。",
|
||||
"第 5 步:拖动中间标尺的滑块,观察蓝色条(图上)与绿色条(实地)的长度关系。",
|
||||
"第 6 步:滚到底部「练习闯关」,自己做一道,答错会自动展开步骤。",
|
||||
"算不出来?先检查单位:填了 km 就不要再按 cm 算,模型会自动换算。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "一、核心公式(先记住这一条)",
|
||||
"lines": [
|
||||
"比例尺 = 图上距离 ÷ 实地距离,写作 1 : N。",
|
||||
"N 是分母,含义是「实地距离是图上距离的 N 倍」,两句都必须统一成同一单位。",
|
||||
"三个变形:实地 = 图上 × N;图上 = 实地 ÷ N;N = 实地 ÷ 图上。",
|
||||
"单位换算:1 m = 100 cm,1 km = 1000 m = 100000 cm(km 化 cm 加 5 个 0)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "二、三种求解模式",
|
||||
"lines": [
|
||||
"顶部三个按钮选「求实地距离 / 求图上距离 / 求比例尺」。",
|
||||
"选中的那一项会变成蓝色结果卡(只读),另外两项留作输入。",
|
||||
"拖动滑块或直接输入数字,三栏读数与中栏标尺实时联动。",
|
||||
"「重置」回到 3 cm / 1:100000 / 3 km 的初始例子。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "三、中栏可视化标尺",
|
||||
"lines": [
|
||||
"上条(蓝)是图上距离,按真实厘米画刻度。",
|
||||
"下条(绿)是同一段实地距离按当前比例尺压缩后的长度,与上方同宽。",
|
||||
"线段式比例尺会按 1/2/5×10ⁿ 自动换挡,任何比例尺都画得下。",
|
||||
"比例尺光谱把 1:1千 到 1:10亿 排在对数轴上,当前值用指针标出。",
|
||||
"若超出图幅,会提示「需要更小的比例尺」——这正是选图幅的教学点。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "四、三种写法与解题步骤",
|
||||
"lines": [
|
||||
"数字式 1 : N;文字式「图上 1 厘米代表实地 …」;线段式(图形刻度)。",
|
||||
"右栏三者实时联动,可直接抄到作业里。",
|
||||
"「解题步骤」可展开:① 统一单位 → ② 列公式 → ③ 代入 → ④ 得数 → ⑤ 换算合适单位。",
|
||||
"「大小判读」卡:大 / 中 / 小比例尺 +「分母越大 → 比例尺越小 → 范围越大 → 越简略」。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "五、实地尺与练习",
|
||||
"lines": [
|
||||
"「实地尺」内置教室 10 m、操场 400 m、马拉松 42.195 km、京沪 1080 km、赤道 4 万 km。",
|
||||
"改变比例尺,看这段真实距离画到图上是多长(或画不下 / 几乎看不见)。",
|
||||
"「练习闯关」随机出三类题,填数字后回车或点「检查」,答错展开完整解题步骤。",
|
||||
"连对计数会一直累计,答错清零。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "六、易错点",
|
||||
"lines": [
|
||||
"忘记统一单位:km 必须 ×100000 变成 cm 才能代入。",
|
||||
"「放大 2 倍」是分母 ÷ 2(比例尺变大),不是 × 2。",
|
||||
"图上距离与实地距离别代反了;N 是「实地是图上的几倍」。",
|
||||
"比例尺是比值,没有单位;说「比例尺越大」指的是比值越大、分母越小。"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"en": {
|
||||
"title": "How to use · Scale Calculator",
|
||||
"sections": [
|
||||
{
|
||||
"h": "Getting started (follow along)",
|
||||
"lines": [
|
||||
"Step 1: choose Find real distance at the top — the blue card is the answer, the other two are inputs.",
|
||||
"Step 2: enter 3 as the map distance and 100000 as the scale denominator.",
|
||||
"Step 3: the blue card shows 3 km — open Worked steps and check each line.",
|
||||
"Step 4: switch to Find scale, set the real distance to 6 km, and watch the denominator change.",
|
||||
"Step 5: drag the ruler slider and compare the blue bar (map) with the green bar (real).",
|
||||
"Step 6: scroll to Practice and try one; a wrong answer expands the full solution.",
|
||||
"Stuck? Check your units first — the model converts automatically, so don't mix km and cm."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "1. The core formula",
|
||||
"lines": [
|
||||
"Scale = map distance ÷ real distance, written 1 : N.",
|
||||
"N is the denominator: the real distance is N times the map distance — both must share one unit.",
|
||||
"Three forms: real = map × N; map = real ÷ N; N = real ÷ map.",
|
||||
"Unit conversions: 1 m = 100 cm, 1 km = 1000 m = 100000 cm (add five zeros)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "2. Three solve modes",
|
||||
"lines": [
|
||||
"Pick Find real distance / Find map distance / Find scale at the top.",
|
||||
"The chosen one becomes the blue read-only result card; the other two stay as inputs.",
|
||||
"Drag a slider or type a number — all three columns and the ruler update live.",
|
||||
"Reset returns to the default 3 cm / 1:100000 / 3 km example."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "3. The visual ruler",
|
||||
"lines": [
|
||||
"The blue bar is the map distance in real centimetres.",
|
||||
"The green bar is the same real distance compressed by the current scale — same width.",
|
||||
"The graphic scale auto-ranges over 1/2/5×10ⁿ so it always fits.",
|
||||
"The spectrum places 1:1k … 1:1B on a log axis with a pointer at the current value.",
|
||||
"Overflow warns “use a smaller scale” — that IS the lesson on choosing a sheet size."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "4. Three notations & worked steps",
|
||||
"lines": [
|
||||
"Numeric 1:N; verbal “1 cm on the map = … on the ground”; graphic bar scale.",
|
||||
"All three stay in sync and can be copied straight into homework.",
|
||||
"Expand Worked steps: unify units → formula → substitute → result → convert unit.",
|
||||
"The grade card: large / medium / small scale and “bigger denominator → smaller scale → larger area → less detail”."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "5. Real-world ruler & practice",
|
||||
"lines": [
|
||||
"Built-in distances: classroom 10 m, track 400 m, marathon 42.195 km, Beijing–Shanghai 1080 km, equator 40,000 km.",
|
||||
"Change the scale to see how long each becomes on paper (or that it won't fit / is invisible).",
|
||||
"Practice generates three question types; type a number and press Enter or Check; wrong answers reveal full steps.",
|
||||
"The streak counter accumulates and resets on a wrong answer."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "6. Common mistakes",
|
||||
"lines": [
|
||||
"Forgetting to unify units: km ×100000 → cm before substituting.",
|
||||
"“Zoom 2×” means denominator ÷ 2 (a larger scale), not × 2.",
|
||||
"Don't swap map and real distance; N means “how many times the map length the real length is”.",
|
||||
"A scale is a ratio with no unit; “larger scale” means a larger ratio, i.e. a SMALLER denominator."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"app.title": "Scale Calculator",
|
||||
"app.subtitle": "Turn map-distance ÷ real-distance into a ruler you can drag and measure",
|
||||
"mode.real": "Find real distance",
|
||||
"mode.map": "Find map distance",
|
||||
"mode.scale": "Find scale",
|
||||
"mode.hint": "Pick what to solve; the blue card is the answer",
|
||||
"input.title": "Given",
|
||||
"input.map": "Map distance",
|
||||
"input.real": "Real distance",
|
||||
"input.scale": "Scale denominator N",
|
||||
"input.nPrefix": "1 :",
|
||||
"input.unit": "Unit",
|
||||
"input.reset": "Reset",
|
||||
"input.presets": "Common scales",
|
||||
"input.dragHint": "Drag the slider or type a number — everything updates live",
|
||||
"result.title": "Result",
|
||||
"result.real": "Real distance",
|
||||
"result.map": "Map distance",
|
||||
"result.scale": "Scale",
|
||||
"result.formula": "Formula",
|
||||
"forms.title": "Three ways to write a scale",
|
||||
"forms.digital": "Numeric",
|
||||
"forms.verbal": "Verbal",
|
||||
"forms.segment": "Graphic (bar)",
|
||||
"forms.verbalTpl": "1 cm on the map = {0} on the ground",
|
||||
"forms.segmentDesc": "Each division {0}, {1} divisions",
|
||||
"steps.title": "Worked solution",
|
||||
"steps.show": "Show steps",
|
||||
"steps.hide": "Hide steps",
|
||||
"steps.1.unify": "① Unify units: convert the real distance to cm (1 km = 100000 cm)",
|
||||
"steps.2.formulaReal": "② Real distance = map distance × scale denominator",
|
||||
"steps.2.formulaMap": "② Map distance = real distance ÷ scale denominator",
|
||||
"steps.2.formulaScale": "② Scale denominator = real distance ÷ map distance",
|
||||
"steps.3.substitute": "③ Substitute: {0}",
|
||||
"steps.4.result": "④ Result: {0}",
|
||||
"steps.5.convert": "⑤ Convert to a sensible unit (cm → m → km)",
|
||||
"grade.title": "Large / small scale",
|
||||
"grade.large": "Large scale",
|
||||
"grade.medium": "Medium scale",
|
||||
"grade.small": "Small scale",
|
||||
"grade.largeNote": "Small area · detailed · e.g. campus plan",
|
||||
"grade.mediumNote": "Medium area · e.g. city map",
|
||||
"grade.smallNote": "Large area · simplified · e.g. world map",
|
||||
"grade.rule": "Bigger denominator → smaller scale → larger area → less detail",
|
||||
"pit.title": "Common mistakes",
|
||||
"pit.1": "① Forgetting to unify units: km ×100000 = cm",
|
||||
"pit.2": "② \"Zoom 2×\" means denominator ÷ 2, not × 2",
|
||||
"pit.3": "③ Don't swap map distance and real distance",
|
||||
"field.title": "Real-world ruler · how long on the map",
|
||||
"field.hint": "Pick a real distance and change the scale to see its map length",
|
||||
"field.mapLength": "On map {0}",
|
||||
"field.tooLong": "too long",
|
||||
"field.tooShort": "barely visible",
|
||||
"quiz.title": "Practice",
|
||||
"quiz.promptReal": "Scale 1:{0}, map distance {1} cm — what is the real distance? (enter the number in the shown unit)",
|
||||
"quiz.promptMap": "Scale 1:{0}, real distance {1} — what is the map distance in cm?",
|
||||
"quiz.promptScale": "{0} cm on the map = {1} on the ground — what is the scale denominator?",
|
||||
"quiz.answer": "Your answer",
|
||||
"quiz.check": "Check",
|
||||
"quiz.next": "Next",
|
||||
"quiz.correct": "✓ Correct!",
|
||||
"quiz.wrong": "✗ Try again — read the steps",
|
||||
"quiz.streak": "{0} in a row",
|
||||
"quiz.showSteps": "Show solution",
|
||||
"quiz.unit": "Unit: {0}",
|
||||
"ruler.title": "Visual ruler",
|
||||
"ruler.mapBar": "Map distance (real cm)",
|
||||
"ruler.realBar": "Real distance (compressed by the same scale)",
|
||||
"ruler.sameWidth": "same width as above",
|
||||
"ruler.equals": "equals",
|
||||
"ruler.segment": "Graphic scale",
|
||||
"ruler.segmentHint": "auto-ranging ticks",
|
||||
"ruler.spectrum": "Scale spectrum",
|
||||
"ruler.scopeUp": "◀ larger area",
|
||||
"ruler.detailDown": "more detail ▶",
|
||||
"ruler.hint": "Blue is the real map length; green is the same real distance compressed by the scale",
|
||||
"ruler.overflowMap": "This map distance overflows the sheet — use a smaller scale",
|
||||
"ruler.overflowReal": "This real distance won't fit at this scale — use a smaller scale",
|
||||
"unit.cm": "cm",
|
||||
"unit.m": "m",
|
||||
"unit.km": "km",
|
||||
"unit.none": "(unitless)",
|
||||
"spec.campus": "Campus",
|
||||
"spec.city": "City",
|
||||
"spec.china": "China",
|
||||
"spec.world": "World",
|
||||
"preset.campus": "Campus 1:10k",
|
||||
"preset.campusNote": "Buildings clearly drawn",
|
||||
"preset.town": "Town 1:50k",
|
||||
"preset.townNote": "Villages and roads",
|
||||
"preset.city": "City 1:250k",
|
||||
"preset.cityNote": "Urban area and arterials",
|
||||
"preset.province": "Province 1:1M",
|
||||
"preset.provinceNote": "Cities and rivers",
|
||||
"preset.china": "China 1:10M",
|
||||
"preset.chinaNote": "Province outlines",
|
||||
"preset.world": "World 1:100M",
|
||||
"preset.worldNote": "Continents & oceans",
|
||||
"lm.classroom": "Classroom 10 m",
|
||||
"lm.track": "Running track 400 m",
|
||||
"lm.marathon": "Marathon 42.195 km",
|
||||
"lm.beijingShanghai": "Beijing–Shanghai 1080 km",
|
||||
"lm.equator": "Equator 40,000 km",
|
||||
"common.footer": "Scale = map distance ÷ real distance · unify units first · bigger denominator = smaller scale"
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"app.title": "比例尺计算器",
|
||||
"app.subtitle": "把「图上距离 ÷ 实地距离」变成可以拖、可以量的可视化标尺",
|
||||
"mode.real": "求实地距离",
|
||||
"mode.map": "求图上距离",
|
||||
"mode.scale": "求比例尺",
|
||||
"mode.hint": "选择要求什么,蓝色结果卡就是答案",
|
||||
"input.title": "已知量",
|
||||
"input.map": "图上距离",
|
||||
"input.real": "实地距离",
|
||||
"input.scale": "比例尺分母 N",
|
||||
"input.nPrefix": "1 :",
|
||||
"input.unit": "单位",
|
||||
"input.reset": "重置",
|
||||
"input.presets": "常用比例尺",
|
||||
"input.dragHint": "拖动滑块或直接输入数字,读数实时联动",
|
||||
"result.title": "计算结果",
|
||||
"result.real": "实地距离",
|
||||
"result.map": "图上距离",
|
||||
"result.scale": "比例尺",
|
||||
"result.formula": "计算公式",
|
||||
"forms.title": "比例尺的三种写法",
|
||||
"forms.digital": "数字式",
|
||||
"forms.verbal": "文字式",
|
||||
"forms.segment": "线段式",
|
||||
"forms.verbalTpl": "图上 1 厘米代表实地 {0}",
|
||||
"forms.segmentDesc": "每格 {0},共 {1} 格",
|
||||
"steps.title": "解题步骤",
|
||||
"steps.show": "展开步骤",
|
||||
"steps.hide": "收起步骤",
|
||||
"steps.1.unify": "① 统一单位:把实地距离化成厘米(1 km = 100000 cm,去掉 5 个 0)",
|
||||
"steps.2.formulaReal": "② 实地距离 = 图上距离 × 比例尺分母",
|
||||
"steps.2.formulaMap": "② 图上距离 = 实地距离 ÷ 比例尺分母",
|
||||
"steps.2.formulaScale": "② 比例尺分母 = 实地距离 ÷ 图上距离",
|
||||
"steps.3.substitute": "③ 代入数值:{0}",
|
||||
"steps.4.result": "④ 算出结果:{0}",
|
||||
"steps.5.convert": "⑤ 换算成合适单位(cm → m → km)",
|
||||
"grade.title": "大小判读",
|
||||
"grade.large": "大比例尺",
|
||||
"grade.medium": "中比例尺",
|
||||
"grade.small": "小比例尺",
|
||||
"grade.largeNote": "范围小 · 内容详细 · 如校园平面图",
|
||||
"grade.mediumNote": "范围中等 · 如城市交通图",
|
||||
"grade.smallNote": "范围大 · 内容简略 · 如世界地图",
|
||||
"grade.rule": "分母越大 → 比例尺越小 → 范围越大 → 越简略",
|
||||
"pit.title": "易错点",
|
||||
"pit.1": "① 忘记统一单位:km 要 ×100000 才成 cm",
|
||||
"pit.2": "② 「放大 2 倍」是分母 ÷ 2,不是 × 2",
|
||||
"pit.3": "③ 图上距离与实地距离别代反了",
|
||||
"field.title": "实地尺 · 这段距离画到图上多长",
|
||||
"field.hint": "选一个真实距离,改变比例尺看它在图上的长度",
|
||||
"field.mapLength": "图上 {0}",
|
||||
"field.tooLong": "画不下",
|
||||
"field.tooShort": "几乎看不见",
|
||||
"quiz.title": "练习闯关",
|
||||
"quiz.promptReal": "比例尺 1:{0},图上 {1} 厘米,实地距离是多少?(按提示单位填数字)",
|
||||
"quiz.promptMap": "比例尺 1:{0},实地 {1},图上距离是多少厘米?",
|
||||
"quiz.promptScale": "图上 {0} 厘米代表实地 {1},比例尺分母是多少?",
|
||||
"quiz.answer": "输入答案",
|
||||
"quiz.check": "检查",
|
||||
"quiz.next": "下一题",
|
||||
"quiz.correct": "✓ 答对了!",
|
||||
"quiz.wrong": "✗ 再想想,看看解题步骤",
|
||||
"quiz.streak": "连对 {0} 题",
|
||||
"quiz.showSteps": "查看解题步骤",
|
||||
"quiz.unit": "单位:{0}",
|
||||
"ruler.title": "可视化标尺",
|
||||
"ruler.mapBar": "图上距离(真实厘米)",
|
||||
"ruler.realBar": "实地距离(按同一比例尺压缩)",
|
||||
"ruler.sameWidth": "与上方同宽",
|
||||
"ruler.equals": "等于",
|
||||
"ruler.segment": "线段式比例尺",
|
||||
"ruler.segmentHint": "刻度自动换挡",
|
||||
"ruler.spectrum": "比例尺光谱",
|
||||
"ruler.scopeUp": "◀ 范围越大",
|
||||
"ruler.detailDown": "内容越详细 ▶",
|
||||
"ruler.hint": "蓝色是图上真实长度;绿色是同一段实地按比例尺压缩后的长度",
|
||||
"ruler.overflowMap": "这段图上距离超出图幅,需要更小的比例尺",
|
||||
"ruler.overflowReal": "这段实地距离在该比例尺下画不下,需要更小的比例尺",
|
||||
"unit.cm": "厘米",
|
||||
"unit.m": "米",
|
||||
"unit.km": "千米",
|
||||
"unit.none": "(无单位)",
|
||||
"spec.campus": "校园",
|
||||
"spec.city": "城市",
|
||||
"spec.china": "中国",
|
||||
"spec.world": "世界",
|
||||
"preset.campus": "校园 1:1万",
|
||||
"preset.campusNote": "操场、教学楼都画得清",
|
||||
"preset.town": "乡镇 1:5万",
|
||||
"preset.townNote": "村镇与道路",
|
||||
"preset.city": "城市 1:25万",
|
||||
"preset.cityNote": "城区与主干道",
|
||||
"preset.province": "省区 1:100万",
|
||||
"preset.provinceNote": "地级市与河流",
|
||||
"preset.china": "中国 1:1000万",
|
||||
"preset.chinaNote": "省级轮廓",
|
||||
"preset.world": "世界 1:1亿",
|
||||
"preset.worldNote": "大洲大洋",
|
||||
"lm.classroom": "教室 10 m",
|
||||
"lm.track": "操场一圈 400 m",
|
||||
"lm.marathon": "马拉松 42.195 km",
|
||||
"lm.beijingShanghai": "北京—上海 1080 km",
|
||||
"lm.equator": "赤道 4 万 km",
|
||||
"common.footer": "比例尺 = 图上距离 ÷ 实地距离 · 单位统一是第一步 · 分母越大,比例尺越小"
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"presets": [
|
||||
{ "n": 10000, "nameKey": "preset.campus", "noteKey": "preset.campusNote" },
|
||||
{ "n": 50000, "nameKey": "preset.town", "noteKey": "preset.townNote" },
|
||||
{ "n": 250000, "nameKey": "preset.city", "noteKey": "preset.cityNote" },
|
||||
{ "n": 1000000, "nameKey": "preset.province", "noteKey": "preset.provinceNote" },
|
||||
{ "n": 10000000, "nameKey": "preset.china", "noteKey": "preset.chinaNote" },
|
||||
{ "n": 100000000, "nameKey": "preset.world", "noteKey": "preset.worldNote" }
|
||||
],
|
||||
"spectrum": [
|
||||
{ "n": 10000, "labelKey": "spec.campus", "scopeKey": "spec.campusScope" },
|
||||
{ "n": 250000, "labelKey": "spec.city", "scopeKey": "spec.cityScope" },
|
||||
{ "n": 10000000, "labelKey": "spec.china", "scopeKey": "spec.chinaScope" },
|
||||
{ "n": 100000000, "labelKey": "spec.world", "scopeKey": "spec.worldScope" }
|
||||
],
|
||||
"landmarks": [
|
||||
{ "nameKey": "lm.classroom", "meters": 10 },
|
||||
{ "nameKey": "lm.track", "meters": 400 },
|
||||
{ "nameKey": "lm.marathon", "meters": 42195 },
|
||||
{ "nameKey": "lm.beijingShanghai", "meters": 1080000 },
|
||||
{ "nameKey": "lm.equator", "meters": 40000000 }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"generated": "2026-11-19T10:20:00Z",
|
||||
"repository": "https://git.xhmcl.com/Morris/GC",
|
||||
"branch": "main",
|
||||
"modelDir": "model",
|
||||
"launcher": {
|
||||
"version": "1.1.1",
|
||||
"revision": "",
|
||||
"packages": {
|
||||
"win-x64": {
|
||||
"path": "dist/win-amd64/GCL-1.1.1-win-amd64.zip",
|
||||
"dir": "dist/win-amd64",
|
||||
"name": "GCL-1.1.1-win-amd64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-amd64.zip",
|
||||
"sha256": "a03532606121280a1553ea73e56d6f9e8cc6cd9eefaf49f8c62857733199c10f",
|
||||
"size": 74993562
|
||||
},
|
||||
"win-arm64": {
|
||||
"path": "dist/win-arm64/GCL-1.1.1-win-arm64.zip",
|
||||
"dir": "dist/win-arm64",
|
||||
"name": "GCL-1.1.1-win-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-arm64.zip",
|
||||
"sha256": "0cd3e045fbc2415bb170e545bb720841eb4c5ebc01a98e03105618a2b7bace46",
|
||||
"size": 72535103
|
||||
},
|
||||
"osx-arm64": {
|
||||
"path": "dist/mac-arm64/GCL-1.1.1-mac-arm64.zip",
|
||||
"dir": "dist/mac-arm64",
|
||||
"name": "GCL-1.1.1-mac-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-arm64.zip"
|
||||
},
|
||||
"osx-x64": {
|
||||
"path": "dist/mac-x64/GCL-1.1.1-mac-x64.zip",
|
||||
"dir": "dist/mac-x64",
|
||||
"name": "GCL-1.1.1-mac-x64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-x64.zip"
|
||||
},
|
||||
"linux-arm64": {
|
||||
"path": "dist/linux-arm64/GCL-1.1.1-linux-arm64.zip",
|
||||
"dir": "dist/linux-arm64",
|
||||
"name": "GCL-1.1.1-linux-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-linux-arm64.zip"
|
||||
}
|
||||
}
|
||||
},
|
||||
"models": [
|
||||
{
|
||||
"id": "contour-map",
|
||||
"version": "1.1",
|
||||
"build": "773ab2161d",
|
||||
"manifestSha256": "ac3231d55175757b4c477ad6a3c398c041db9511061f0c650d2c10efca881103",
|
||||
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
|
||||
"files": 5,
|
||||
"dir": "model/contour-map"
|
||||
},
|
||||
{
|
||||
"id": "earth-geography",
|
||||
"version": "1.9",
|
||||
"build": "cc68b8863b",
|
||||
"manifestSha256": "f69ceb758c643701480af441da26dfa64e190c9e583073deba211bac3e2a6e1a",
|
||||
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
|
||||
"files": 11,
|
||||
"dir": "model/earth-geography"
|
||||
},
|
||||
{
|
||||
"id": "earth-revolution",
|
||||
"version": "1.7",
|
||||
"build": "53b7a0fbc3",
|
||||
"manifestSha256": "ab257669cd2bc57289d7e86b361064034d6040e85603b65069a93aec8d457b0b",
|
||||
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
|
||||
"files": 7,
|
||||
"dir": "model/earth-revolution"
|
||||
},
|
||||
{
|
||||
"id": "earth-rotation",
|
||||
"version": "1.7",
|
||||
"build": "ecd52665f9",
|
||||
"manifestSha256": "d463d85e08fd7f0525f8e08a5e9ec49c0005b3d8ca97a7f9497e95bdbb0697cb",
|
||||
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
|
||||
"files": 7,
|
||||
"dir": "model/earth-rotation"
|
||||
},
|
||||
{
|
||||
"id": "scale-calculator",
|
||||
"version": "1.6",
|
||||
"build": "105653737d",
|
||||
"manifestSha256": "2ac714eafb9acb4e4f11567b61848441de0f65ac41eb4260bc2d868c9500f56d",
|
||||
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
|
||||
"files": 6,
|
||||
"dir": "model/scale-calculator"
|
||||
}
|
||||
],
|
||||
"signature": {
|
||||
"alg": "ECDSA-P256-SHA256",
|
||||
"keyId": "gc-2026-12",
|
||||
"value": "U6j86/9PIUe5ZIqLRUlSIFf6EhODc7Dar1KvL7MecYujzNJ+ZnRrUg7aUT1rvktVwz4nyRacf9RYM2JQFb+qKw==",
|
||||
"contentSha256": "585f22236fa1a50d4e99581c676b8ad694c5e352b12fe1bfed30c342b1f38690",
|
||||
"signedAt": "2026-11-19T10:21:32Z"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
if exist "build\install\gc-java\bin\gc-java.bat" (
|
||||
call "build\install\gc-java\bin\gc-java.bat" %*
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
if exist "lib\gc-java-2.0.0.jar" (
|
||||
java -cp "lib\gc-java-2.0.0.jar" com.gc.Main %*
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
if exist "build\libs\gc-java-2.0.0.jar" (
|
||||
java -cp "build\libs\gc-java-2.0.0.jar" com.gc.Main %*
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
call gradlew.bat run --args="%*"
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# GC Java Launcher 启动脚本:优先使用已构建的发行目录,否则用 Gradle 直接运行。
|
||||
set -e
|
||||
DIR=$(cd "$(dirname "$0")" && pwd)
|
||||
cd "$DIR"
|
||||
if [ -x "$DIR/build/install/gc-java/bin/gc-java" ]; then
|
||||
exec "$DIR/build/install/gc-java/bin/gc-java" "$@"
|
||||
fi
|
||||
if [ -f "$DIR/lib/gc-java-2.0.0.jar" ]; then
|
||||
exec java ${JAVA_OPTS:-} -cp "$DIR/lib/gc-java-2.0.0.jar" com.gc.Main "$@"
|
||||
fi
|
||||
if [ -f "$DIR/build/libs/gc-java-2.0.0.jar" ]; then
|
||||
exec java ${JAVA_OPTS:-} -cp "$DIR/build/libs/gc-java-2.0.0.jar" com.gc.Main "$@"
|
||||
fi
|
||||
exec ./gradlew run --args="$*"
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = "gc-java"
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.gc;
|
||||
|
||||
import com.gc.core.*;
|
||||
|
||||
import java.awt.GraphicsEnvironment;
|
||||
|
||||
/** 单进程入口:无参数启动 GUI,其余走统一 CLI。 */
|
||||
public final class Main {
|
||||
public static void main(String[] args) {
|
||||
AppPaths paths = AppPaths.discover();
|
||||
paths.ensureCreated();
|
||||
Settings settings = Settings.load(paths.settingsFile());
|
||||
Log.init(paths.logsRoot());
|
||||
I18n.load(settings.language);
|
||||
Security.writeHealth(paths.updateRoot(), settings.launcherVersion);
|
||||
|
||||
// 环境变量可注入受信任公钥(测试 / 私有构建)
|
||||
String trusted = System.getenv("GC_TRUSTED_KEYS");
|
||||
if (trusted != null && !trusted.isBlank()) {
|
||||
for (String part : trusted.split(";")) {
|
||||
int idx = part.indexOf(':');
|
||||
if (idx > 0 && idx < part.length() - 1)
|
||||
Security.addKey(part.substring(0, idx).trim(), part.substring(idx + 1).trim());
|
||||
}
|
||||
}
|
||||
|
||||
if (args.length == 0) {
|
||||
if (GraphicsEnvironment.isHeadless()) {
|
||||
Cli.help();
|
||||
return;
|
||||
}
|
||||
com.gc.ui.MainWindow.launch(paths, settings);
|
||||
return;
|
||||
}
|
||||
int code = Cli.run(args, paths, settings);
|
||||
if (code != 0) System.exit(code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.*;
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* 运行目录:安装目录旁 .GC/{bin,config,model,cache,update,safedog,logs}。
|
||||
* 开发态自动使用项目根 model/ 并同步到 .GC/model。
|
||||
*/
|
||||
public final class AppPaths {
|
||||
public final Path appRoot;
|
||||
public final Path installDir;
|
||||
public final Path homeRoot;
|
||||
public final Path modelRoot;
|
||||
public final boolean development;
|
||||
public final boolean portableModelRoot;
|
||||
private volatile Thread syncThread;
|
||||
|
||||
private AppPaths(Path appRoot, Path installDir, Path homeRoot, Path modelRoot,
|
||||
boolean development, boolean portableModelRoot) {
|
||||
this.appRoot = appRoot;
|
||||
this.installDir = installDir;
|
||||
this.homeRoot = homeRoot;
|
||||
this.modelRoot = modelRoot;
|
||||
this.development = development;
|
||||
this.portableModelRoot = portableModelRoot;
|
||||
}
|
||||
|
||||
public static AppPaths discover() {
|
||||
Path cwd = Paths.get(System.getProperty("user.dir")).toAbsolutePath().normalize();
|
||||
Path explicitHome = envPath("EMS_HOME");
|
||||
Path repo = explicitHome != null && Files.isDirectory(explicitHome) ? explicitHome : findRepoRoot(cwd);
|
||||
boolean dev = repo != null;
|
||||
|
||||
Path install;
|
||||
if (dev) install = repo;
|
||||
else if (explicitHome != null && Files.isDirectory(explicitHome)) install = explicitHome;
|
||||
else {
|
||||
install = cwd;
|
||||
// 发行目录:<root>/{bin,lib,model,run.sh},从 bin 脚本启动时 cwd 就是根目录
|
||||
if (Files.isDirectory(cwd.resolve("lib")) && Files.isDirectory(cwd.resolve("bin"))) {
|
||||
install = cwd;
|
||||
} else {
|
||||
try {
|
||||
Path code = Paths.get(AppPaths.class.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
if (Files.isRegularFile(code)) code = code.getParent();
|
||||
if (code != null) {
|
||||
String s = code.toString().replace('\\', '/');
|
||||
if (s.contains(".app/Contents/")) {
|
||||
Path p = code;
|
||||
while (p != null && !p.getFileName().toString().endsWith(".app")) p = p.getParent();
|
||||
if (p != null && p.getParent() != null) install = p.getParent();
|
||||
} else if (code.getFileName() != null && code.getFileName().toString().equals("lib")
|
||||
&& code.getParent() != null) {
|
||||
install = code.getParent();
|
||||
} else install = code;
|
||||
}
|
||||
} catch (URISyntaxException | RuntimeException ignored) { }
|
||||
}
|
||||
}
|
||||
|
||||
Path explicitData = envPath("EMS_DATA");
|
||||
Path home;
|
||||
if (explicitData != null) home = explicitData;
|
||||
else {
|
||||
Path portable = install.resolve(".GC");
|
||||
home = canWrite(portable) ? portable
|
||||
: Paths.get(System.getProperty("user.home"), "Library", "Application Support", "GC", ".GC");
|
||||
}
|
||||
|
||||
Path envModels = envPath("EMS_MODELS");
|
||||
Path modelRoot = envModels != null ? envModels : home.resolve("model");
|
||||
return new AppPaths(install, install, home, modelRoot, dev, envModels == null);
|
||||
}
|
||||
|
||||
private static Path envPath(String key) {
|
||||
String v = System.getenv(key);
|
||||
return v == null || v.isBlank() ? null : Paths.get(v).toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
private static Path findRepoRoot(Path start) {
|
||||
Path dir = start;
|
||||
for (int i = 0; i < 10 && dir != null; i++, dir = dir.getParent()) {
|
||||
if (dir.getFileName() != null && dir.getFileName().toString().equalsIgnoreCase("dist")) return null;
|
||||
if (Files.exists(dir.resolve("settings.gradle.kts")) && Files.isDirectory(dir.resolve("src/main/java/com/gc")))
|
||||
return dir;
|
||||
// 兼容从仓库根启动
|
||||
if (Files.exists(dir.resolve("Java/settings.gradle.kts")) && Files.isDirectory(dir.resolve("Java/src/main/java/com/gc")))
|
||||
return dir.resolve("Java");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean canWrite(Path dir) {
|
||||
try {
|
||||
Files.createDirectories(dir);
|
||||
Path probe = dir.resolve(".write-test");
|
||||
Files.writeString(probe, "ok");
|
||||
Files.deleteIfExists(probe);
|
||||
return true;
|
||||
} catch (Exception e) { return false; }
|
||||
}
|
||||
|
||||
public Path configRoot() { return homeRoot.resolve("config"); }
|
||||
public Path cacheRoot() { return homeRoot.resolve("cache"); }
|
||||
public Path updateRoot() { return homeRoot.resolve("update"); }
|
||||
public Path logsRoot() { return homeRoot.resolve("logs"); }
|
||||
public Path safedogRoot() { return homeRoot.resolve("safedog"); }
|
||||
public Path binRoot() { return homeRoot.resolve("bin"); }
|
||||
public Path settingsFile() { return configRoot().resolve("settings.json"); }
|
||||
|
||||
/** 查找原始 HTML 课件目录(开发态、发行目录与仓库内 C# 前端均可)。 */
|
||||
public Path coursewareRoot() {
|
||||
String override = System.getProperty("gc.courseware", "");
|
||||
java.util.List<Path> candidates = new java.util.ArrayList<>();
|
||||
if (!override.isBlank()) candidates.add(Path.of(override));
|
||||
candidates.add(appRoot.resolve("courseware"));
|
||||
candidates.add(installDir.resolve("courseware"));
|
||||
candidates.add(java.nio.file.Paths.get(System.getProperty("user.dir", ".")).resolve("courseware"));
|
||||
candidates.add(appRoot.resolve("../C#/GC-UI/frontend/courseware").normalize());
|
||||
candidates.add(appRoot.resolve("../../C#/GC-UI/frontend/courseware").normalize());
|
||||
for (Path p : candidates) {
|
||||
try {
|
||||
if (p != null && Files.isRegularFile(p.resolve("index.html"))) return p.toAbsolutePath().normalize();
|
||||
} catch (Exception ignored) { }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void ensureCreated() {
|
||||
try {
|
||||
for (Path p : new Path[]{homeRoot, configRoot(), cacheRoot(), modelRoot, updateRoot(), logsRoot(), safedogRoot(), binRoot()})
|
||||
Files.createDirectories(p);
|
||||
Path legacy = homeRoot.resolve("settings.json");
|
||||
if (Files.exists(legacy) && !Files.exists(settingsFile())) {
|
||||
Files.createDirectories(configRoot());
|
||||
Files.move(legacy, settingsFile(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("[paths] 初始化目录失败: " + e.getMessage());
|
||||
}
|
||||
seedBundledModels();
|
||||
if (development && portableModelRoot && envPath("EMS_MODELS") == null) {
|
||||
Path source = appRoot.resolve("model");
|
||||
if (Files.isDirectory(source)) {
|
||||
syncThread = new Thread(() -> syncDevelopmentModels(modelRoot, source), "gc-model-sync");
|
||||
syncThread.setDaemon(true);
|
||||
syncThread.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 发行版把 model/ 放在主程序旁:首次启动时复制到 .GC/model,开箱即用。 */
|
||||
private void seedBundledModels() {
|
||||
try {
|
||||
Path source = appRoot.resolve("model");
|
||||
if (!Files.isDirectory(source)) return;
|
||||
try (DirectoryStream<Path> ds = Files.newDirectoryStream(source)) {
|
||||
for (Path dir : ds) {
|
||||
if (!Files.isDirectory(dir)) continue;
|
||||
String id = dir.getFileName().toString();
|
||||
if (id.startsWith("_") || id.startsWith(".")) continue;
|
||||
Path manifest = dir.resolve(id + ".json");
|
||||
if (!Files.isRegularFile(manifest)) continue;
|
||||
Path dest = modelRoot.resolve(id);
|
||||
if (Files.isRegularFile(dest.resolve(id + ".json"))) continue;
|
||||
Files.createDirectories(dest);
|
||||
Files.copy(manifest, dest.resolve(id + ".json"));
|
||||
Path data = dir.resolve(id + ".model");
|
||||
if (Files.isDirectory(data)) copyTree(data, dest.resolve(id + ".model"));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("[paths] 初始化内置模型失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void waitForDevelopmentModels() {
|
||||
Thread t = syncThread;
|
||||
if (t != null) try { t.join(15000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
|
||||
}
|
||||
|
||||
private static void syncDevelopmentModels(Path modelRoot, Path source) {
|
||||
try (DirectoryStream<Path> ds = Files.newDirectoryStream(source)) {
|
||||
for (Path dir : ds) {
|
||||
String id = dir.getFileName().toString();
|
||||
if (id.startsWith("_")) continue;
|
||||
Path manifest = dir.resolve(id + ".json");
|
||||
Path data = dir.resolve(id + ".model");
|
||||
if (!Files.isRegularFile(manifest) || !Files.isDirectory(data)) continue;
|
||||
Path dest = modelRoot.resolve(id);
|
||||
Files.createDirectories(dest);
|
||||
Files.copy(manifest, dest.resolve(id + ".json"), StandardCopyOption.REPLACE_EXISTING);
|
||||
copyTree(data, dest.resolve(id + ".model"));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("[paths] 同步开发模型失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void copyTree(Path src, Path dst) throws IOException {
|
||||
Files.createDirectories(dst);
|
||||
try (var walk = Files.walk(src)) {
|
||||
for (Path p : walk.toList()) {
|
||||
if (p.equals(src)) continue;
|
||||
String name = p.getFileName().toString();
|
||||
if (name.startsWith(".")) continue;
|
||||
Path target = dst.resolve(src.relativize(p).toString());
|
||||
if (Files.isDirectory(p)) Files.createDirectories(target);
|
||||
else {
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(p, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteTree(Path root) {
|
||||
if (!Files.exists(root)) return;
|
||||
try (var walk = Files.walk(root)) {
|
||||
walk.sorted(Comparator.reverseOrder()).forEach(p -> {
|
||||
try { Files.deleteIfExists(p); } catch (IOException ignored) { }
|
||||
});
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
public enum Platform { WIN_X64, WIN_ARM64, OSX_X64, OSX_ARM64, LINUX_X64, LINUX_ARM64 }
|
||||
|
||||
public static Platform platform() {
|
||||
String os = System.getProperty("os.name").toLowerCase();
|
||||
String arch = System.getProperty("os.arch").toLowerCase();
|
||||
boolean arm = arch.contains("aarch64") || arch.contains("arm64");
|
||||
if (os.contains("win")) return arm ? Platform.WIN_ARM64 : Platform.WIN_X64;
|
||||
if (os.contains("mac")) return arm ? Platform.OSX_ARM64 : Platform.OSX_X64;
|
||||
return arm ? Platform.LINUX_ARM64 : Platform.LINUX_X64;
|
||||
}
|
||||
|
||||
public static String rid() {
|
||||
return switch (platform()) {
|
||||
case WIN_X64 -> "win-x64";
|
||||
case WIN_ARM64 -> "win-arm64";
|
||||
case OSX_X64 -> "osx-x64";
|
||||
case OSX_ARM64 -> "osx-arm64";
|
||||
case LINUX_X64 -> "linux-x64";
|
||||
case LINUX_ARM64 -> "linux-arm64";
|
||||
};
|
||||
}
|
||||
|
||||
public static String displayPlatform() {
|
||||
String os = System.getProperty("os.name");
|
||||
String arch = System.getProperty("os.arch");
|
||||
return os + " / " + arch + " (" + rid() + ")";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Java 版内置的 5 个模型渲染器(原 C# dll 无法在 JVM 中加载)。 */
|
||||
public final class BuiltinModels {
|
||||
private BuiltinModels() {}
|
||||
|
||||
public static final List<String> IDS = List.of(
|
||||
"earth-rotation", "earth-revolution", "earth-geography", "contour-map", "scale-calculator");
|
||||
|
||||
public static final Map<String, String> FACTORY = Map.of(
|
||||
"earth-rotation", "com.gc.model.earth.RotationModel",
|
||||
"earth-revolution", "com.gc.model.earth.RevolutionModel",
|
||||
"earth-geography", "com.gc.model.earth.GeographyModel",
|
||||
"contour-map", "com.gc.model.contour.ContourModel",
|
||||
"scale-calculator", "com.gc.model.scale.ScaleCalculatorModel");
|
||||
|
||||
public static boolean supports(String id) { return IDS.contains(id); }
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.Locale;
|
||||
|
||||
/** 统一 CLI:核心工具 + 模型算法 + 更新守护。 */
|
||||
public final class Cli {
|
||||
private Cli() {}
|
||||
|
||||
public static int run(String[] args, AppPaths paths, Settings settings) {
|
||||
if (args.length == 0) { help(); return 0; }
|
||||
try {
|
||||
switch (args[0]) {
|
||||
case "help", "--help", "-h" -> { help(); return 0; }
|
||||
case "version", "--version" -> { System.out.println("GC Java 2.0.0"); return 0; }
|
||||
case "hash-file" -> {
|
||||
System.out.println(Hash.file(Path.of(args[1])));
|
||||
return 0;
|
||||
}
|
||||
case "hash-dir" -> {
|
||||
System.out.println(Hash.dir(Path.of(args[1])));
|
||||
return 0;
|
||||
}
|
||||
case "canonical" -> {
|
||||
String text = args.length > 1 && !args[1].equals("-")
|
||||
? Files.readString(Path.of(args[1]), StandardCharsets.UTF_8) : readStdin();
|
||||
String c = Json.canonical(text);
|
||||
if (c == null) { System.out.println("ERROR 无法解析 JSON"); return 2; }
|
||||
System.out.println(c);
|
||||
return 0;
|
||||
}
|
||||
case "version-normalize" -> { System.out.println(VersionUtil.normalize(args[1])); return 0; }
|
||||
case "version-compare" -> { System.out.println(VersionUtil.compare(args[1], args[2])); return 0; }
|
||||
case "paths" -> {
|
||||
Path root = args.length > 1 ? Path.of(args[1]).toAbsolutePath() : paths.homeRoot;
|
||||
printPaths(root);
|
||||
return 0;
|
||||
}
|
||||
case "settings-default" -> { System.out.println(Settings.defaultJson()); return 0; }
|
||||
case "model-scan" -> {
|
||||
Path root = args.length > 1 ? Path.of(args[1]) : paths.modelRoot;
|
||||
for (ModelManifest.Package p : ModelManifest.scan(root).models)
|
||||
System.out.printf(Locale.ROOT, "%s\t%s\t%s\t%d\t%s%n",
|
||||
p.id(), p.manifest.version, p.manifest.localizedName(), p.sizeBytes, p.directory);
|
||||
return 0;
|
||||
}
|
||||
case "safezip-name" -> { System.out.println(Security.safeZipName(args[1])); return 0; }
|
||||
case "human-size" -> { System.out.println(Hash.humanSize(Long.parseLong(args[1]))); return 0; }
|
||||
case "selftest" -> { return Selftest.run(); }
|
||||
case "model" -> {
|
||||
return ModelCommands.run(java.util.Arrays.copyOfRange(args, 1, args.length));
|
||||
}
|
||||
case "update-check" -> {
|
||||
UpdateService.Result r = new UpdateService(paths, settings).run(true,
|
||||
p -> System.out.println("[" + Math.round(p.value() * 100) + "%] " + p.message() + " " + p.detail()));
|
||||
System.out.println("outcome=" + r.outcome() + " message=" + r.message());
|
||||
if (r.error() != null) System.out.println("error=" + r.error());
|
||||
return r.outcome() == UpdateService.Outcome.UNAVAILABLE ? 2 : 0;
|
||||
}
|
||||
case "savedog" -> { return savedog(args, paths); }
|
||||
case "gui" -> {
|
||||
com.gc.ui.MainWindow.launch(paths, settings);
|
||||
return 0;
|
||||
}
|
||||
case "gui-selftest" -> {
|
||||
return com.gc.ui.UiSmoke.run(paths, Path.of("build/screenshots"));
|
||||
}
|
||||
default -> { help(); return 1; }
|
||||
}
|
||||
} catch (ArrayIndexOutOfBoundsException e) {
|
||||
System.out.println("缺少参数,使用 help 查看用法");
|
||||
return 1;
|
||||
} catch (Exception e) {
|
||||
System.out.println("ERROR " + e.getMessage());
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
private static int savedog(String[] a, AppPaths paths) {
|
||||
Updater u = new Updater(paths);
|
||||
if (a.length < 2) {
|
||||
System.out.println("savedog verify <manifest> | apply | status | keygen [dir] [keyId] | sign <file> <pem> <keyId>");
|
||||
return 1;
|
||||
}
|
||||
try {
|
||||
return switch (a[1]) {
|
||||
case "verify" -> u.verify(a[2]);
|
||||
case "apply" -> u.apply();
|
||||
case "status" -> { u.status(); yield 0; }
|
||||
case "keygen" -> u.keygen(Path.of(a.length > 2 ? a[2] : ".signing"),
|
||||
a.length > 3 ? a[3] : "gc-2026-12");
|
||||
case "sign" -> u.sign(Path.of(a[2]), Path.of(a[3]), a[4]);
|
||||
default -> { System.out.println("未知 savedog 命令"); yield 1; }
|
||||
};
|
||||
} catch (Exception e) {
|
||||
System.out.println("savedog 失败: " + e.getMessage());
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
private static void printPaths(Path root) {
|
||||
for (String p : new String[]{"bin", "config", "model", "cache", "update", "safedog", "logs"})
|
||||
System.out.println(root.resolve(p));
|
||||
System.out.println(root.resolve("config/settings.json"));
|
||||
}
|
||||
|
||||
private static String readStdin() throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try (BufferedReader r = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) sb.append(line).append('\n');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static void help() {
|
||||
System.out.println("""
|
||||
GC 天文教学模型启动器 · Java 版 2.0.0
|
||||
用法:
|
||||
gc 启动 HMCL 风格图形界面
|
||||
gc gui 显式启动图形界面
|
||||
gc selftest 运行全部内置断言
|
||||
gc hash-file <path> SHA-256
|
||||
gc hash-dir <path> 目录指纹
|
||||
gc canonical <file|-> 规范化 JSON
|
||||
gc version-normalize <tag>
|
||||
gc version-compare <a> <b>
|
||||
gc paths [root] 目录布局
|
||||
gc settings-default 默认设置
|
||||
gc model-scan [root] 扫描模型库
|
||||
gc safezip-name <name> 安全路径检查
|
||||
gc human-size <bytes> 人类可读体积
|
||||
gc update-check 检查模型 / 启动器更新
|
||||
gc savedog <cmd> 更新守护(verify/apply/status/keygen/sign)
|
||||
gc model <...> 5 个教学模型的算法命令(gc model 查看)
|
||||
""");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Gitea / GitHub 兼容的模型源。 */
|
||||
public final class GiteaRemote implements Remote {
|
||||
private final SourcePreset preset;
|
||||
private String rawText;
|
||||
|
||||
public GiteaRemote(SourcePreset preset) { this.preset = preset; }
|
||||
|
||||
@Override public String displayName() { return preset.name(); }
|
||||
@Override public String sourceId() { return preset.id(); }
|
||||
@Override public String rawManifestText() { return rawText; }
|
||||
@Override public java.nio.file.Path localRoot() { return null; }
|
||||
|
||||
@Override
|
||||
public String rawUrl(String path) { return preset.rawUrl(path); }
|
||||
|
||||
@Override
|
||||
public RepoVersion manifest() throws Exception {
|
||||
Exception last = null;
|
||||
for (String path : new String[]{"version.json", "model/version.json"}) {
|
||||
String url = preset.rawUrl(path);
|
||||
try {
|
||||
String text = Http.getString(url);
|
||||
if (!text.trim().startsWith("{")) continue;
|
||||
Security.Verification v = Security.verifyManifest(text, true);
|
||||
RepoVersion ver = RepoVersion.parse(text);
|
||||
ver.trust = v.trust().name();
|
||||
ver.keyId = v.keyId();
|
||||
ver.error = v.error();
|
||||
ver.trusted = v.trusted();
|
||||
rawText = text;
|
||||
if (v.trust() == Security.Trust.INVALID) {
|
||||
Log.warn("清单验签失败,已拒绝: " + v.error(), "Manifest signature verification failed: " + v.error());
|
||||
return null;
|
||||
}
|
||||
return ver;
|
||||
} catch (Exception e) { last = e; }
|
||||
}
|
||||
if (last != null) throw last;
|
||||
return null;
|
||||
}
|
||||
|
||||
private String contentsUrl(String path) {
|
||||
String p = path.replaceAll("^/+|/+$", "");
|
||||
String head = p.isEmpty() ? preset.apiBase() + "/repos/" + preset.owner() + "/" + preset.repo() + "/contents"
|
||||
: preset.apiBase() + "/repos/" + preset.owner() + "/" + preset.repo() + "/contents/" + p;
|
||||
return preset.kind().equals("github") ? head + "?ref=" + preset.branch() : head;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RepoEntry> listTree(String rootPath) throws Exception {
|
||||
List<RepoEntry> out = new ArrayList<>();
|
||||
walk(rootPath.replaceAll("^/+|/+$", ""), "", out, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
private void walk(String apiPath, String relPrefix, List<RepoEntry> out, int depth) throws Exception {
|
||||
if (depth > 8) return;
|
||||
String json;
|
||||
try { json = Http.getString(contentsUrl(apiPath)); }
|
||||
catch (Exception e) { Log.warn("读取目录失败 " + apiPath + ": " + e.getMessage()); return; }
|
||||
Object parsed;
|
||||
try { parsed = Json.parse(json); } catch (Exception e) { return; }
|
||||
List<Object> entries = parsed instanceof List ? Json.arr(parsed) : Json.list(parsed);
|
||||
for (Object o : entries) {
|
||||
Map<String, Object> e = Json.obj(o);
|
||||
String name = Json.str(e, "name", "");
|
||||
String path = Json.str(e, "path", "");
|
||||
String type = Json.str(e, "type", "file");
|
||||
String rel = relPrefix.isEmpty() ? name : relPrefix + "/" + name;
|
||||
boolean dir = type.equals("dir") || type.equals("directory");
|
||||
String download = Json.str(e, "download_url", "");
|
||||
if (download == null || download.isBlank() || download.equals("null"))
|
||||
download = dir ? "" : preset.rawUrl(path);
|
||||
long size = Json.l(e, "size", 0);
|
||||
out.add(new RepoEntry(name, path, rel, dir, download, size));
|
||||
if (dir) walk(path, rel, out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] download(RepoEntry entry) throws Exception {
|
||||
String url = entry.downloadUrl();
|
||||
if (url == null || url.isBlank()) url = preset.rawUrl(entry.path());
|
||||
return Http.getBytes(url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] downloadPackage(String url) throws Exception { return Http.getBytes(url); }
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** SHA-256 文件 / 目录指纹,算法与 C# ContentHash 完全一致。 */
|
||||
public final class Hash {
|
||||
private Hash() {}
|
||||
|
||||
public static String sha256(byte[] data) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(md.digest(data));
|
||||
} catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
|
||||
public static String sha256(String text) { return sha256(text.getBytes(StandardCharsets.UTF_8)); }
|
||||
|
||||
public static String file(Path path) throws IOException {
|
||||
try (InputStream in = Files.newInputStream(path)) {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
byte[] buf = new byte[16384];
|
||||
int n;
|
||||
while ((n = in.read(buf)) > 0) md.update(buf, 0, n);
|
||||
return HexFormat.of().formatHex(md.digest());
|
||||
} catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
|
||||
/** dirHash = SHA256(按相对路径 ordinal 升序 "<path>\0<fileHash>\n")。 */
|
||||
public static String dir(Path root) throws IOException {
|
||||
List<String> entries = new ArrayList<>();
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
walk.filter(Files::isRegularFile).forEach(p -> {
|
||||
String rel = root.relativize(p).toString().replace('\\', '/');
|
||||
if (skip(rel)) return;
|
||||
try {
|
||||
entries.add(rel + "\0" + file(p) + "\n");
|
||||
} catch (IOException e) { throw new RuntimeException(e); }
|
||||
});
|
||||
}
|
||||
entries.sort(String::compareTo);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String e : entries) sb.append(e);
|
||||
return sha256(sb.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** 与 C# 一致:跳过 . 开头、bin/、obj/、*.user。 */
|
||||
public static boolean skip(String rel) {
|
||||
for (String seg : rel.split("/")) {
|
||||
if (seg.startsWith(".") || seg.equals("bin") || seg.equals("obj")) return true;
|
||||
}
|
||||
return rel.toLowerCase(Locale.ROOT).endsWith(".user");
|
||||
}
|
||||
|
||||
/** 人类可读体积:1536 -> 1.5 KB。 */
|
||||
public static String humanSize(long bytes) {
|
||||
String[] units = {"B", "KB", "MB", "GB", "TB"};
|
||||
double value = bytes;
|
||||
int u = 0;
|
||||
while (value >= 1024 && u < units.length - 1) { value /= 1024; u++; }
|
||||
if (u == 0) return bytes + " B";
|
||||
String s = String.format(Locale.ROOT, "%.1f", value);
|
||||
if (s.endsWith(".0")) s = s.substring(0, s.length() - 2);
|
||||
return s + " " + units[u];
|
||||
}
|
||||
|
||||
/** 目录体积(忽略异常)。 */
|
||||
public static long dirSize(Path root) {
|
||||
if (!Files.isDirectory(root)) return 0;
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
return walk.filter(Files::isRegularFile).mapToLong(p -> {
|
||||
try { return Files.size(p); } catch (IOException e) { return 0; }
|
||||
}).sum();
|
||||
} catch (IOException e) { return 0; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
/** 轻量 HTTP 客户端(跟随重定向、超时、UA)。 */
|
||||
public final class Http {
|
||||
private static final HttpClient CLIENT = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.ALWAYS)
|
||||
.connectTimeout(Duration.ofSeconds(8))
|
||||
.build();
|
||||
|
||||
private Http() {}
|
||||
|
||||
public static String getString(String url) throws IOException, InterruptedException {
|
||||
HttpResponse<String> r = CLIENT.send(request(url).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (r.statusCode() >= 400) throw new IOException("HTTP " + r.statusCode() + " " + url);
|
||||
return r.body();
|
||||
}
|
||||
|
||||
public static byte[] getBytes(String url) throws IOException, InterruptedException {
|
||||
HttpResponse<byte[]> r = CLIENT.send(request(url).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
if (r.statusCode() >= 400) throw new IOException("HTTP " + r.statusCode() + " " + url);
|
||||
return r.body();
|
||||
}
|
||||
|
||||
public static java.io.InputStream open(String url) throws IOException, InterruptedException {
|
||||
HttpResponse<java.io.InputStream> r = CLIENT.send(request(url).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofInputStream());
|
||||
if (r.statusCode() >= 400) throw new IOException("HTTP " + r.statusCode() + " " + url);
|
||||
return r.body();
|
||||
}
|
||||
|
||||
private static HttpRequest.Builder request(String url) {
|
||||
return HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("User-Agent", "GC-Java/2.0 (Astronomy Model Launcher)")
|
||||
.header("Accept", "application/json, application/octet-stream, */*");
|
||||
}
|
||||
|
||||
public static String encode(String s) {
|
||||
return java.net.URLEncoder.encode(s, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
}
|
||||
|
||||
public static Map<String, String> noHeaders() { return Map.of(); }
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** 界面语言:auto / zh-CN / en,资源来自 resources/i18n。 */
|
||||
public final class I18n {
|
||||
private static Map<String, String> texts = new LinkedHashMap<>();
|
||||
private static Map<String, String> fallback = new LinkedHashMap<>();
|
||||
private static String language = "zh-CN";
|
||||
|
||||
private I18n() {}
|
||||
|
||||
public static void load(String setting) {
|
||||
String resolved = resolve(setting);
|
||||
fallback = read("/i18n/zh-CN.json");
|
||||
language = resolved;
|
||||
if (resolved.equals("zh-CN")) texts = fallback;
|
||||
else texts = read("/i18n/en.json");
|
||||
if (texts.isEmpty()) texts = fallback;
|
||||
}
|
||||
|
||||
public static String resolve(String setting) {
|
||||
if (setting != null && !setting.equals("auto") && !setting.isBlank()) return setting;
|
||||
String l = Locale.getDefault().getLanguage().toLowerCase();
|
||||
return l.startsWith("zh") ? "zh-CN" : "en";
|
||||
}
|
||||
|
||||
public static String language() { return language; }
|
||||
|
||||
public static String t(String key) {
|
||||
String v = texts.get(key);
|
||||
if (v != null) return v;
|
||||
v = fallback.get(key);
|
||||
return v != null ? v : key;
|
||||
}
|
||||
|
||||
public static String f(String key, Object... args) {
|
||||
String s = t(key);
|
||||
for (int i = 0; i < args.length; i++) s = s.replace("{" + i + "}", String.valueOf(args[i]));
|
||||
return s;
|
||||
}
|
||||
|
||||
private static Map<String, String> read(String resource) {
|
||||
Map<String, String> m = new LinkedHashMap<>();
|
||||
try (InputStream in = I18n.class.getResourceAsStream(resource)) {
|
||||
if (in == null) return m;
|
||||
String text = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
for (var e : Json.obj(Json.parse(text)).entrySet()) m.put(e.getKey(), String.valueOf(e.getValue()));
|
||||
} catch (Exception e) {
|
||||
System.err.println("[i18n] 读取 " + resource + " 失败: " + e.getMessage());
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* 零依赖 JSON 解析 / 序列化,并保留数字原始文本。
|
||||
* 规范化规则与 C# 原版一致:对象键按 Unicode 码点升序、无空白、非 ASCII 不转义、
|
||||
* 数字沿用源文本、签名时移除根级 signature。
|
||||
*/
|
||||
public final class Json {
|
||||
private Json() {}
|
||||
|
||||
/** 保留原始字面量的数字。 */
|
||||
public record Num(String raw) {
|
||||
public double asDouble() { return Double.parseDouble(raw); }
|
||||
public long asLong() { return (long) asDouble(); }
|
||||
public int asInt() { return (int) asDouble(); }
|
||||
@Override public String toString() { return raw; }
|
||||
}
|
||||
|
||||
public static Object parse(String text) {
|
||||
Parser p = new Parser(text);
|
||||
p.skipWs();
|
||||
Object v = p.value();
|
||||
p.skipWs();
|
||||
if (!p.eof()) throw new IllegalArgumentException("JSON 末尾有多余内容: " + p.pos);
|
||||
return v;
|
||||
}
|
||||
|
||||
public static Object parse(Path path) throws IOException {
|
||||
return parse(Files.readString(path, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map<String, Object> obj(Object o) {
|
||||
return o instanceof Map ? (Map<String, Object>) o : new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List<Object> arr(Object o) {
|
||||
return o instanceof List ? (List<Object>) o : new ArrayList<>();
|
||||
}
|
||||
|
||||
public static String str(Object o, String fallback) {
|
||||
return o == null ? fallback : String.valueOf(o);
|
||||
}
|
||||
|
||||
public static String str(Map<String, Object> m, String key, String fallback) {
|
||||
Object v = m.get(key);
|
||||
return v == null ? fallback : String.valueOf(v);
|
||||
}
|
||||
|
||||
public static int i(Map<String, Object> m, String key, int fallback) {
|
||||
Object v = m.get(key);
|
||||
if (v instanceof Num n) return n.asInt();
|
||||
if (v instanceof Number n) return n.intValue();
|
||||
return fallback;
|
||||
}
|
||||
|
||||
public static long l(Map<String, Object> m, String key, long fallback) {
|
||||
Object v = m.get(key);
|
||||
if (v instanceof Num n) return n.asLong();
|
||||
if (v instanceof Number n) return n.longValue();
|
||||
return fallback;
|
||||
}
|
||||
|
||||
public static double d(Map<String, Object> m, String key, double fallback) {
|
||||
Object v = m.get(key);
|
||||
if (v instanceof Num n) return n.asDouble();
|
||||
if (v instanceof Number n) return n.doubleValue();
|
||||
return fallback;
|
||||
}
|
||||
|
||||
public static boolean b(Map<String, Object> m, String key, boolean fallback) {
|
||||
Object v = m.get(key);
|
||||
return v instanceof Boolean bool ? bool : fallback;
|
||||
}
|
||||
|
||||
public static Map<String, Object> map(Object... kv) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
for (int i = 0; i + 1 < kv.length; i += 2) m.put(String.valueOf(kv[i]), kv[i + 1]);
|
||||
return m;
|
||||
}
|
||||
|
||||
public static List<Object> list(Object... values) {
|
||||
List<Object> l = new ArrayList<>();
|
||||
for (Object v : values) l.add(v);
|
||||
return l;
|
||||
}
|
||||
|
||||
public static String write(Object value) { return write(value, false, false); }
|
||||
|
||||
public static String writePretty(Object value) { return write(value, true, false); }
|
||||
|
||||
/** 规范化 JSON(移除根级 signature)。 */
|
||||
public static String canonical(String text) {
|
||||
Object v = parse(text);
|
||||
if (!(v instanceof Map)) return null;
|
||||
return write(v, false, true);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static String write(Object value, boolean pretty, boolean sortKeys) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
writeValue(sb, value, pretty, sortKeys, 0);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void writeValue(StringBuilder sb, Object value, boolean pretty, boolean sortKeys, int depth) {
|
||||
if (value == null) { sb.append("null"); return; }
|
||||
if (value instanceof String s) { quote(sb, s); return; }
|
||||
if (value instanceof Boolean bo) { sb.append(bo); return; }
|
||||
if (value instanceof Num n) { sb.append(n.raw()); return; }
|
||||
if (value instanceof Number n) {
|
||||
if (value instanceof Double || value instanceof Float) {
|
||||
double d = n.doubleValue();
|
||||
if (Double.isNaN(d) || Double.isInfinite(d)) sb.append("null");
|
||||
else if (d == Math.rint(d) && Math.abs(d) < 1e15) sb.append((long) d);
|
||||
else sb.append(n);
|
||||
} else sb.append(n);
|
||||
return;
|
||||
}
|
||||
if (value instanceof Map<?, ?> raw) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
for (Map.Entry<?, ?> e : raw.entrySet()) map.put(String.valueOf(e.getKey()), e.getValue());
|
||||
if (depth == 0 && sortKeys) map.remove("signature");
|
||||
Map<String, Object> ordered = map;
|
||||
if (sortKeys) {
|
||||
ordered = new TreeMap<>((a, b) -> compareCodePoints(a, b));
|
||||
ordered.putAll(map);
|
||||
}
|
||||
sb.append('{');
|
||||
boolean first = true;
|
||||
for (Map.Entry<String, Object> e : ordered.entrySet()) {
|
||||
if (!first) sb.append(',');
|
||||
first = false;
|
||||
if (pretty) { sb.append('\n'); indent(sb, depth + 1); }
|
||||
quote(sb, e.getKey());
|
||||
sb.append(pretty ? ": " : ":");
|
||||
writeValue(sb, e.getValue(), pretty, sortKeys, depth + 1);
|
||||
}
|
||||
if (pretty && !ordered.isEmpty()) { sb.append('\n'); indent(sb, depth); }
|
||||
sb.append('}');
|
||||
return;
|
||||
}
|
||||
if (value instanceof List<?> list) {
|
||||
sb.append('[');
|
||||
boolean first = true;
|
||||
for (Object item : list) {
|
||||
if (!first) sb.append(',');
|
||||
first = false;
|
||||
if (pretty) { sb.append('\n'); indent(sb, depth + 1); }
|
||||
writeValue(sb, item, pretty, sortKeys, depth + 1);
|
||||
}
|
||||
if (pretty && !list.isEmpty()) { sb.append('\n'); indent(sb, depth); }
|
||||
sb.append(']');
|
||||
return;
|
||||
}
|
||||
quote(sb, String.valueOf(value));
|
||||
}
|
||||
|
||||
private static void indent(StringBuilder sb, int depth) { sb.append(" ".repeat(Math.max(0, depth))); }
|
||||
|
||||
private static int compareCodePoints(String a, String b) {
|
||||
int i = 0, j = 0;
|
||||
while (i < a.length() && j < b.length()) {
|
||||
int ca = a.codePointAt(i), cb = b.codePointAt(j);
|
||||
if (ca != cb) return Integer.compare(ca, cb);
|
||||
i += Character.charCount(ca); j += Character.charCount(cb);
|
||||
}
|
||||
return Integer.compare(a.length(), b.length());
|
||||
}
|
||||
|
||||
private static void quote(StringBuilder sb, String s) {
|
||||
sb.append('"');
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
switch (c) {
|
||||
case '"' -> sb.append("\\\"");
|
||||
case '\\' -> sb.append("\\\\");
|
||||
case '\n' -> sb.append("\\n");
|
||||
case '\r' -> sb.append("\\r");
|
||||
case '\t' -> sb.append("\\t");
|
||||
case '\b' -> sb.append("\\b");
|
||||
case '\f' -> sb.append("\\f");
|
||||
default -> {
|
||||
if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
|
||||
else sb.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
sb.append('"');
|
||||
}
|
||||
|
||||
private static final class Parser {
|
||||
final String s; int pos;
|
||||
Parser(String s) { this.s = s; }
|
||||
boolean eof() { return pos >= s.length(); }
|
||||
void skipWs() { while (!eof() && Character.isWhitespace(s.charAt(pos))) pos++; }
|
||||
char peek() { return s.charAt(pos); }
|
||||
char next() { return s.charAt(pos++); }
|
||||
void expect(char c) {
|
||||
if (eof() || s.charAt(pos) != c) throw new IllegalArgumentException("JSON 位置 " + pos + " 期望 '" + c + "'");
|
||||
pos++;
|
||||
}
|
||||
Object value() {
|
||||
skipWs();
|
||||
if (eof()) throw new IllegalArgumentException("JSON 意外结束");
|
||||
char c = peek();
|
||||
return switch (c) {
|
||||
case '{' -> object();
|
||||
case '[' -> array();
|
||||
case '"' -> string();
|
||||
case 't' -> { literal("true"); yield Boolean.TRUE; }
|
||||
case 'f' -> { literal("false"); yield Boolean.FALSE; }
|
||||
case 'n' -> { literal("null"); yield null; }
|
||||
default -> number();
|
||||
};
|
||||
}
|
||||
void literal(String lit) {
|
||||
if (!s.startsWith(lit, pos)) throw new IllegalArgumentException("JSON 位置 " + pos + " 无效字面量");
|
||||
pos += lit.length();
|
||||
}
|
||||
Map<String, Object> object() {
|
||||
expect('{');
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
skipWs();
|
||||
if (!eof() && peek() == '}') { pos++; return m; }
|
||||
while (true) {
|
||||
skipWs();
|
||||
String key = string();
|
||||
skipWs(); expect(':');
|
||||
Object v = value();
|
||||
m.put(key, v);
|
||||
skipWs();
|
||||
if (eof()) throw new IllegalArgumentException("JSON 对象未闭合");
|
||||
char c = next();
|
||||
if (c == '}') break;
|
||||
if (c != ',') throw new IllegalArgumentException("JSON 位置 " + (pos - 1) + " 期望 ',' 或 '}'");
|
||||
}
|
||||
return m;
|
||||
}
|
||||
List<Object> array() {
|
||||
expect('[');
|
||||
List<Object> list = new ArrayList<>();
|
||||
skipWs();
|
||||
if (!eof() && peek() == ']') { pos++; return list; }
|
||||
while (true) {
|
||||
list.add(value());
|
||||
skipWs();
|
||||
if (eof()) throw new IllegalArgumentException("JSON 数组未闭合");
|
||||
char c = next();
|
||||
if (c == ']') break;
|
||||
if (c != ',') throw new IllegalArgumentException("JSON 位置 " + (pos - 1) + " 期望 ',' 或 ']'");
|
||||
}
|
||||
return list;
|
||||
}
|
||||
String string() {
|
||||
expect('"');
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (true) {
|
||||
if (eof()) throw new IllegalArgumentException("JSON 字符串未闭合");
|
||||
char c = next();
|
||||
if (c == '"') break;
|
||||
if (c == '\\') {
|
||||
char e = next();
|
||||
switch (e) {
|
||||
case '"' -> sb.append('"');
|
||||
case '\\' -> sb.append('\\');
|
||||
case '/' -> sb.append('/');
|
||||
case 'b' -> sb.append('\b');
|
||||
case 'f' -> sb.append('\f');
|
||||
case 'n' -> sb.append('\n');
|
||||
case 'r' -> sb.append('\r');
|
||||
case 't' -> sb.append('\t');
|
||||
case 'u' -> {
|
||||
if (pos + 4 > s.length()) throw new IllegalArgumentException("JSON unicode 转义不完整");
|
||||
sb.append((char) Integer.parseInt(s.substring(pos, pos + 4), 16));
|
||||
pos += 4;
|
||||
}
|
||||
default -> throw new IllegalArgumentException("JSON 非法转义 \\" + e);
|
||||
}
|
||||
} else sb.append(c);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
Num number() {
|
||||
int start = pos;
|
||||
if (!eof() && peek() == '-') pos++;
|
||||
while (!eof() && Character.isDigit(peek())) pos++;
|
||||
if (!eof() && peek() == '.') { pos++; while (!eof() && Character.isDigit(peek())) pos++; }
|
||||
if (!eof() && (peek() == 'e' || peek() == 'E')) {
|
||||
pos++;
|
||||
if (!eof() && (peek() == '+' || peek() == '-')) pos++;
|
||||
while (!eof() && Character.isDigit(peek())) pos++;
|
||||
}
|
||||
if (start == pos) throw new IllegalArgumentException("JSON 位置 " + start + " 不是数字");
|
||||
return new Num(s.substring(start, pos));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** 本地目录模型源(离线教室 / U 盘)。 */
|
||||
public final class LocalRemote implements Remote {
|
||||
private final Path root;
|
||||
|
||||
public LocalRemote(Path root) { this.root = root.toAbsolutePath().normalize(); }
|
||||
|
||||
@Override public String displayName() { return "本地目录 " + root; }
|
||||
@Override public String sourceId() { return "local"; }
|
||||
@Override public Path localRoot() { return root; }
|
||||
@Override public String rawManifestText() { return null; }
|
||||
@Override public String rawUrl(String path) { return root.resolve(path).toString(); }
|
||||
|
||||
@Override
|
||||
public RepoVersion manifest() throws Exception {
|
||||
for (String p : new String[]{"version.json", "model/version.json"}) {
|
||||
Path f = root.resolve(p);
|
||||
if (!Files.isRegularFile(f)) continue;
|
||||
String text = Files.readString(f);
|
||||
Security.Verification v = Security.verifyManifest(text, true);
|
||||
RepoVersion ver = RepoVersion.parse(text);
|
||||
ver.trust = v.trust().name();
|
||||
ver.keyId = v.keyId();
|
||||
ver.error = v.error();
|
||||
ver.trusted = v.trusted();
|
||||
if (v.trust() == Security.Trust.INVALID) return null;
|
||||
return ver;
|
||||
}
|
||||
// 没有 version.json:按目录扫描生成临时清单
|
||||
RepoVersion ver = new RepoVersion();
|
||||
ver.repository = root.toString();
|
||||
ver.trust = "SKIPPED";
|
||||
ver.trusted = true;
|
||||
Path modelRoot = Files.isDirectory(root.resolve("model")) ? root.resolve("model") : root;
|
||||
try (DirectoryStream<Path> ds = Files.newDirectoryStream(modelRoot)) {
|
||||
for (Path d : ds) {
|
||||
if (!Files.isDirectory(d)) continue;
|
||||
String id = d.getFileName().toString();
|
||||
Path mf = d.resolve(id + ".json");
|
||||
if (!Files.isRegularFile(mf)) continue;
|
||||
var mm = ModelManifest.parse(Json.obj(Json.parse(mf)));
|
||||
ver.models.add(new RepoModel(id, mm.version, modelRoot.relativize(d).toString(),
|
||||
"", Hash.file(mf), Hash.dir(d.resolve(id + ".model")), 0));
|
||||
}
|
||||
}
|
||||
return ver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RepoEntry> listTree(String rootPath) throws Exception {
|
||||
List<RepoEntry> out = new ArrayList<>();
|
||||
Path base = root.resolve(rootPath.replaceAll("^/+|/+$", ""));
|
||||
if (!Files.isDirectory(base)) return out;
|
||||
try (var walk = Files.walk(base)) {
|
||||
for (Path p : walk.toList()) {
|
||||
if (p.equals(base)) continue;
|
||||
String rel = base.relativize(p).toString().replace('\\', '/');
|
||||
out.add(new RepoEntry(p.getFileName().toString(),
|
||||
Path.of(rootPath).resolve(rel).toString().replace('\\', '/'), rel,
|
||||
Files.isDirectory(p), p.toUri().toString(), Files.size(p)));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] download(RepoEntry entry) throws Exception {
|
||||
Path p = root.resolve(entry.path());
|
||||
if (!Files.isRegularFile(p)) throw new java.io.IOException("文件不存在: " + p);
|
||||
return Files.readAllBytes(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] downloadPackage(String url) throws Exception {
|
||||
Path p = url.startsWith("file:") ? Path.of(java.net.URI.create(url)) : Path.of(url);
|
||||
return Files.readAllBytes(p);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.gc.core;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/** 仅监听 127.0.0.1 的静态文件服务,用于把离线 HTML 课件加载到 WebView。 */
|
||||
public final class LocalWebServer implements AutoCloseable {
|
||||
private final HttpServer server;
|
||||
private final Path root;
|
||||
private final int port;
|
||||
|
||||
public LocalWebServer(Path root) throws IOException {
|
||||
this.root = root.toAbsolutePath().normalize();
|
||||
server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
|
||||
port = server.getAddress().getPort();
|
||||
server.createContext("/", this::handle);
|
||||
server.setExecutor(Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "gc-courseware-http");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
}));
|
||||
server.start();
|
||||
}
|
||||
|
||||
public int port() { return port; }
|
||||
public String url() { return "http://127.0.0.1:" + port + "/index.html"; }
|
||||
|
||||
private void handle(HttpExchange ex) throws IOException {
|
||||
try {
|
||||
String raw = ex.getRequestURI().getPath();
|
||||
if (raw == null || raw.isEmpty() || raw.equals("/")) raw = "/index.html";
|
||||
Path file = root.resolve(raw.substring(1)).normalize();
|
||||
if (!file.startsWith(root) || !Files.isRegularFile(file)) {
|
||||
byte[] msg = "404 Not Found".getBytes();
|
||||
ex.sendResponseHeaders(404, msg.length);
|
||||
try (OutputStream os = ex.getResponseBody()) { os.write(msg); }
|
||||
return;
|
||||
}
|
||||
long length = Files.size(file);
|
||||
Headers h = ex.getResponseHeaders();
|
||||
h.set("Content-Type", mime(file));
|
||||
h.set("Accept-Ranges", "bytes");
|
||||
h.set("Cache-Control", "no-cache");
|
||||
h.set("X-Content-Type-Options", "nosniff");
|
||||
String range = ex.getRequestHeaders().getFirst("Range");
|
||||
if (range != null && range.startsWith("bytes=")) {
|
||||
String[] parts = range.substring(6).split("-", -1);
|
||||
long start = parse(parts.length > 0 ? parts[0] : "", 0);
|
||||
long end = parts.length > 1 ? parse(parts[1], -1) : -1;
|
||||
if (start < 0) start = 0;
|
||||
if (end < 0 || end >= length) end = length - 1;
|
||||
if (start >= length || start > end) {
|
||||
ex.sendResponseHeaders(416, -1);
|
||||
return;
|
||||
}
|
||||
long len = end - start + 1;
|
||||
h.set("Content-Range", "bytes " + start + "-" + end + "/" + length);
|
||||
ex.sendResponseHeaders(206, len);
|
||||
try (InputStream in = Files.newInputStream(file); OutputStream os = ex.getResponseBody()) {
|
||||
in.skipNBytes(start);
|
||||
byte[] buf = new byte[64 * 1024];
|
||||
long remaining = len;
|
||||
while (remaining > 0) {
|
||||
int n = in.read(buf, 0, (int) Math.min(buf.length, remaining));
|
||||
if (n < 0) break;
|
||||
os.write(buf, 0, n);
|
||||
remaining -= n;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
ex.sendResponseHeaders(200, length);
|
||||
try (OutputStream os = ex.getResponseBody()) {
|
||||
Files.copy(file, os);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
try { ex.sendResponseHeaders(500, -1); } catch (Exception ignored) { }
|
||||
} finally {
|
||||
ex.close();
|
||||
}
|
||||
}
|
||||
|
||||
private static long parse(String s, long fallback) {
|
||||
try { return s == null || s.isBlank() ? fallback : Long.parseLong(s.trim()); }
|
||||
catch (Exception e) { return fallback; }
|
||||
}
|
||||
|
||||
private static String mime(Path p) {
|
||||
String n = p.getFileName().toString().toLowerCase(Locale.ROOT);
|
||||
if (n.endsWith(".html") || n.endsWith(".htm")) return "text/html; charset=utf-8";
|
||||
if (n.endsWith(".css")) return "text/css; charset=utf-8";
|
||||
if (n.endsWith(".js")) return "text/javascript; charset=utf-8";
|
||||
if (n.endsWith(".json")) return "application/json; charset=utf-8";
|
||||
if (n.endsWith(".png")) return "image/png";
|
||||
if (n.endsWith(".jpg") || n.endsWith(".jpeg")) return "image/jpeg";
|
||||
if (n.endsWith(".gif")) return "image/gif";
|
||||
if (n.endsWith(".webp")) return "image/webp";
|
||||
if (n.endsWith(".svg")) return "image/svg+xml";
|
||||
if (n.endsWith(".mp4")) return "video/mp4";
|
||||
if (n.endsWith(".webm")) return "video/webm";
|
||||
if (n.endsWith(".woff2")) return "font/woff2";
|
||||
if (n.endsWith(".woff")) return "font/woff";
|
||||
if (n.endsWith(".ttf")) return "font/ttf";
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
try { server.stop(0); } catch (Exception ignored) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/** 按天分中英两份日志:.GC/logs/gc-YYYYMMDD.log 与 .en.log。 */
|
||||
public final class Log {
|
||||
private static final DateTimeFormatter TS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
private static Path dir;
|
||||
private static boolean enabled = true;
|
||||
|
||||
private Log() {}
|
||||
|
||||
public static void init(Path logsRoot) {
|
||||
dir = logsRoot;
|
||||
try { Files.createDirectories(dir); } catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
public static synchronized void info(String zh) { write("INFO", zh, null); }
|
||||
public static synchronized void info(String zh, String en) { write("INFO", zh, en); }
|
||||
public static synchronized void warn(String zh) { write("WARN", zh, null); }
|
||||
public static synchronized void warn(String zh, String en) { write("WARN", zh, en); }
|
||||
public static synchronized void error(String zh) { write("ERROR", zh, null); }
|
||||
public static synchronized void error(String zh, String en) { write("ERROR", zh, en); }
|
||||
|
||||
private static void write(String level, String zh, String en) {
|
||||
String line = "[" + LocalDateTime.now().format(TS) + "] [" + level + "] " + zh;
|
||||
System.out.println(line);
|
||||
if (!enabled || dir == null) return;
|
||||
String day = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
|
||||
try {
|
||||
Files.createDirectories(dir);
|
||||
Files.writeString(dir.resolve("gc-" + day + ".log"), line + System.lineSeparator(),
|
||||
StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
|
||||
if (en != null) {
|
||||
String eline = "[" + LocalDateTime.now().format(TS) + "] [" + level + "] " + en;
|
||||
Files.writeString(dir.resolve("gc-" + day + ".en.log"), eline + System.lineSeparator(),
|
||||
StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
|
||||
}
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
public static Path logsDir() { return dir; }
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.gc.core;
|
||||
|
||||
import com.gc.model.contour.*;
|
||||
import com.gc.model.earth.EarthMath;
|
||||
import com.gc.model.scale.ScaleMath;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** 5 个模型的命令行入口,GUI 与 CLI 共用同一套算法。 */
|
||||
public final class ModelCommands {
|
||||
private static final Map<String, TerrainField> CACHE = new HashMap<>();
|
||||
|
||||
private ModelCommands() {}
|
||||
|
||||
public static int run(String[] a) {
|
||||
if (a.length == 0) { help(); return 1; }
|
||||
try {
|
||||
return switch (a[0]) {
|
||||
case "scale" -> scale(a);
|
||||
case "contour" -> contour(a);
|
||||
case "rotation" -> rotation(a);
|
||||
case "revolution" -> revolution(a);
|
||||
case "geo" -> geo(a);
|
||||
default -> { help(); yield 1; }
|
||||
};
|
||||
} catch (Exception e) {
|
||||
System.out.println("error=" + e.getMessage());
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
private static void help() {
|
||||
System.out.println("""
|
||||
model scale solve <real|map|scale> <mapCm> <realCm> <N>
|
||||
model scale human <cm>
|
||||
model scale segment <N> <pxPerCm> <targetPx>
|
||||
model scale grade <N> | spectrum <N> | quiz <seed> | check <answer> <expect>
|
||||
model contour build <kind|landform> [size]
|
||||
model contour sample <kind> <u> <v> | levels <kind>
|
||||
model contour extract <kind> <level> | classify <kind> <u> <v>
|
||||
model contour color <height> | slope <kind> <u> <v>
|
||||
model rotation subsolar <orbitDeg> <tiltDeg> | date <orbitDeg> | angle <spinDeg> <orbitDeg>
|
||||
model revolution subsolar <orbitDeg> | season <orbitDeg> | step <spinDeg> <orbitDeg> <dt> <speed>
|
||||
model geo zones | declination <lat> | latlon <lat> <lon>
|
||||
""");
|
||||
}
|
||||
|
||||
private static int scale(String[] a) {
|
||||
if (a.length < 2) { help(); return 1; }
|
||||
switch (a[1]) {
|
||||
case "solve" -> {
|
||||
ScaleMath.State s = new ScaleMath.State();
|
||||
s.mode = switch (a[2].toLowerCase()) {
|
||||
case "real" -> ScaleMath.SolveMode.REAL;
|
||||
case "map" -> ScaleMath.SolveMode.MAP;
|
||||
case "scale" -> ScaleMath.SolveMode.SCALE;
|
||||
default -> throw new IllegalArgumentException("mode 必须是 real/map/scale");
|
||||
};
|
||||
s.mapCm = Double.parseDouble(a[3]);
|
||||
s.realCm = Double.parseDouble(a[4]);
|
||||
s.n = Double.parseDouble(a[5]);
|
||||
ScaleMath.solve(s);
|
||||
System.out.println("mapCm=" + plain(s.mapCm));
|
||||
System.out.println("realCm=" + plain(s.realCm));
|
||||
System.out.println("N=" + plain(s.n));
|
||||
return 0;
|
||||
}
|
||||
case "human" -> {
|
||||
ScaleMath.Human h = ScaleMath.humanReal(Double.parseDouble(a[2]));
|
||||
System.out.println(ScaleMath.num(h.value()) + " " + h.unitKey().replace("unit.", ""));
|
||||
return 0;
|
||||
}
|
||||
case "segment" -> {
|
||||
ScaleMath.Segment seg = ScaleMath.pickSegment(Double.parseDouble(a[2]),
|
||||
Double.parseDouble(a[3]), Double.parseDouble(a[4]));
|
||||
System.out.printf(Locale.ROOT, "metersPerDiv=%s divPx=%s divCount=%d%n",
|
||||
ScaleMath.num(seg.metersPerDiv()), ScaleMath.num(seg.divPx()), seg.divCount());
|
||||
return 0;
|
||||
}
|
||||
case "grade" -> {
|
||||
double n = Double.parseDouble(a[2]);
|
||||
System.out.println(ScaleMath.grade(n).name().toLowerCase());
|
||||
return 0;
|
||||
}
|
||||
case "spectrum" -> {
|
||||
System.out.printf(Locale.ROOT, "%.6f%n", ScaleMath.spectrumPosition(Double.parseDouble(a[2])));
|
||||
return 0;
|
||||
}
|
||||
case "quiz" -> {
|
||||
ScaleMath.Quiz q = ScaleMath.generateQuiz(new Random(Long.parseLong(a[2])));
|
||||
System.out.println("mode=" + q.mode.name().toLowerCase());
|
||||
System.out.println("answer=" + ScaleMath.num(q.answer));
|
||||
System.out.println("unit=" + q.answerUnitKey);
|
||||
return 0;
|
||||
}
|
||||
case "check" -> {
|
||||
double ans = Double.parseDouble(a[2]), expect = Double.parseDouble(a[3]);
|
||||
ScaleMath.Quiz q = new ScaleMath.Quiz();
|
||||
q.answer = expect;
|
||||
System.out.println(ScaleMath.checkAnswer(q, ans));
|
||||
return 0;
|
||||
}
|
||||
default -> { help(); return 1; }
|
||||
}
|
||||
}
|
||||
|
||||
private static String plain(double v) {
|
||||
String s = String.format(Locale.ROOT, "%.6f", v);
|
||||
s = s.replaceAll("0+$", "");
|
||||
if (s.endsWith(".")) s = s.substring(0, s.length() - 1);
|
||||
return s;
|
||||
}
|
||||
|
||||
private static TerrainField field(String kind, int size) {
|
||||
String key = kind + ":" + size;
|
||||
TerrainField f = CACHE.get(key);
|
||||
if (f != null) return f;
|
||||
String k = kind.toLowerCase();
|
||||
f = switch (k) {
|
||||
case "mountain", "basin", "hill", "plateau", "plain" ->
|
||||
new TerrainField(TerrainField.TerrainKind.valueOf(k.toUpperCase()), size);
|
||||
case "peak", "ridge", "valley", "saddle", "cliff" ->
|
||||
new TerrainField(TerrainField.LandformKind.valueOf(k.toUpperCase()), size);
|
||||
default -> throw new IllegalArgumentException("未知地形: " + kind);
|
||||
};
|
||||
CACHE.put(key, f);
|
||||
return f;
|
||||
}
|
||||
|
||||
private static int contour(String[] a) {
|
||||
if (a.length < 3) { help(); return 1; }
|
||||
switch (a[1]) {
|
||||
case "build" -> {
|
||||
int size = a.length > 3 ? Integer.parseInt(a[3]) : 192;
|
||||
TerrainField f = field(a[2], size);
|
||||
System.out.printf(Locale.ROOT, "kind=%s size=%d min=%.2f max=%.2f interval=%.1f%n",
|
||||
a[2], f.size, f.minHeight, f.maxHeight, f.effectiveInterval());
|
||||
return 0;
|
||||
}
|
||||
case "sample" -> {
|
||||
TerrainField f = field(a[2], 192);
|
||||
System.out.printf(Locale.ROOT, "%.2f%n", f.sampleSmooth(Double.parseDouble(a[3]), Double.parseDouble(a[4])));
|
||||
return 0;
|
||||
}
|
||||
case "levels" -> {
|
||||
TerrainField f = field(a[2], 192);
|
||||
StringJoiner sj = new StringJoiner(",");
|
||||
for (float l : f.contourLevels()) sj.add(ScaleMath.num(l));
|
||||
System.out.println(sj);
|
||||
return 0;
|
||||
}
|
||||
case "extract" -> {
|
||||
TerrainField f = field(a[2], 192);
|
||||
List<List<TerrainField.Point>> lines = f.extractContour(Float.parseFloat(a[3]));
|
||||
int points = lines.stream().mapToInt(List::size).sum();
|
||||
System.out.println("polylines=" + lines.size() + " points=" + points);
|
||||
return 0;
|
||||
}
|
||||
case "classify" -> {
|
||||
TerrainField f = field(a[2], 192);
|
||||
System.out.println(TerrainAnalyzer.classify(f, Double.parseDouble(a[3]), Double.parseDouble(a[4]))
|
||||
.name().toLowerCase());
|
||||
return 0;
|
||||
}
|
||||
case "color" -> {
|
||||
java.awt.Color c = TerrainAnalyzer.colorForHeight(Float.parseFloat(a[2]));
|
||||
System.out.printf("%02x%02x%02x%n", c.getRed(), c.getGreen(), c.getBlue());
|
||||
return 0;
|
||||
}
|
||||
case "slope" -> {
|
||||
TerrainField f = field(a[2], 192);
|
||||
System.out.printf(Locale.ROOT, "%.4f%n", f.slopeAt(Double.parseDouble(a[3]), Double.parseDouble(a[4])));
|
||||
return 0;
|
||||
}
|
||||
default -> { help(); return 1; }
|
||||
}
|
||||
}
|
||||
|
||||
private static int rotation(String[] a) {
|
||||
if (a.length < 3) { help(); return 1; }
|
||||
switch (a[1]) {
|
||||
case "subsolar" -> {
|
||||
double tilt = a.length > 3 ? Double.parseDouble(a[3]) : 23.5;
|
||||
System.out.println(ScaleMath.num(EarthMath.subsolarLatitude(Double.parseDouble(a[2]), tilt)));
|
||||
return 0;
|
||||
}
|
||||
case "date" -> {
|
||||
System.out.println(EarthMath.dateForAngle(Double.parseDouble(a[2])));
|
||||
return 0;
|
||||
}
|
||||
case "angle" -> {
|
||||
double spin = Double.parseDouble(a[2]), orbit = Double.parseDouble(a[3]);
|
||||
System.out.printf(Locale.ROOT, "spin=%.3f orbit=%.3f%n", spin, orbit);
|
||||
return 0;
|
||||
}
|
||||
default -> { help(); return 1; }
|
||||
}
|
||||
}
|
||||
|
||||
private static int revolution(String[] a) {
|
||||
if (a.length < 3) { help(); return 1; }
|
||||
switch (a[1]) {
|
||||
case "subsolar" -> {
|
||||
System.out.println(ScaleMath.num(EarthMath.subsolarLatitude(Double.parseDouble(a[2]))));
|
||||
return 0;
|
||||
}
|
||||
case "season" -> {
|
||||
String key = EarthMath.nearestSeason(Double.parseDouble(a[2])).key();
|
||||
System.out.println(key.substring(key.indexOf('.') + 1));
|
||||
return 0;
|
||||
}
|
||||
case "step" -> {
|
||||
double[] r = EarthMath.stepAngles(Double.parseDouble(a[2]), Double.parseDouble(a[3]),
|
||||
Double.parseDouble(a[4]), Double.parseDouble(a[5]));
|
||||
System.out.printf(Locale.ROOT, "spin=%.3f orbit=%.3f%n", r[0], r[1]);
|
||||
return 0;
|
||||
}
|
||||
default -> { help(); return 1; }
|
||||
}
|
||||
}
|
||||
|
||||
private static int geo(String[] a) {
|
||||
if (a.length < 2) { help(); return 1; }
|
||||
switch (a[1]) {
|
||||
case "zones" -> {
|
||||
for (EarthMath.Zone z : EarthMath.ZONES)
|
||||
System.out.printf(Locale.ROOT, "%s\t%.1f\t%.1f%n", z.id(), z.latMin(), z.latMax());
|
||||
return 0;
|
||||
}
|
||||
case "declination" -> {
|
||||
System.out.println(EarthMath.declination(Double.parseDouble(a[2])));
|
||||
return 0;
|
||||
}
|
||||
case "latlon" -> {
|
||||
double[] v = EarthMath.latLonToUnit(Double.parseDouble(a[2]), Double.parseDouble(a[3]));
|
||||
System.out.printf(Locale.ROOT, "%.6f,%.6f,%.6f%n", v[0], v[1], v[2]);
|
||||
return 0;
|
||||
}
|
||||
default -> { help(); return 1; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
|
||||
/** 把源里的模型目录复制进本地模型库(临时目录 + 原子替换)。 */
|
||||
public final class ModelInstaller {
|
||||
private ModelInstaller() {}
|
||||
|
||||
public static Path install(Path sourceDir, String id, Path modelRoot) throws IOException {
|
||||
String safe = Security.safeId(id);
|
||||
if (safe == null) throw new IOException("非法的模型标识: " + id);
|
||||
Path target = modelRoot.resolve(safe);
|
||||
Path staging = modelRoot.resolve(safe + ".installing");
|
||||
Path backup = modelRoot.resolve(safe + ".old");
|
||||
AppPaths.deleteTree(staging);
|
||||
AppPaths.deleteTree(backup);
|
||||
Files.createDirectories(staging);
|
||||
try {
|
||||
Path manifest = sourceDir.resolve(safe + ".json");
|
||||
if (!Files.isRegularFile(manifest)) throw new IOException("缺少模型清单 " + safe + ".json");
|
||||
Files.copy(manifest, staging.resolve(safe + ".json"), StandardCopyOption.REPLACE_EXISTING);
|
||||
Path data = sourceDir.resolve(safe + ".model");
|
||||
if (!Files.isDirectory(data)) throw new IOException("缺少模型数据 " + safe + ".model/");
|
||||
AppPaths.copyTree(data, staging.resolve(safe + ".model"));
|
||||
if (Files.exists(target)) Files.move(target, backup, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.move(staging, target);
|
||||
AppPaths.deleteTree(backup);
|
||||
return target;
|
||||
} catch (IOException e) {
|
||||
AppPaths.deleteTree(staging);
|
||||
if (!Files.exists(target) && Files.exists(backup)) Files.move(backup, target);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** 从包含 model/ 的本地根目录导入所有模型。 */
|
||||
public static int importLocal(Path root, Path modelRoot) throws IOException {
|
||||
Path sourceRoot = Files.isDirectory(root.resolve("model")) ? root.resolve("model") : root;
|
||||
int n = 0;
|
||||
try (DirectoryStream<Path> ds = Files.newDirectoryStream(sourceRoot)) {
|
||||
for (Path dir : ds) {
|
||||
if (!Files.isDirectory(dir)) continue;
|
||||
String id = dir.getFileName().toString();
|
||||
if (id.startsWith("_") || id.startsWith(".")) continue;
|
||||
if (!Files.isRegularFile(dir.resolve(id + ".json"))) continue;
|
||||
install(dir, id, modelRoot);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** model/<id>/<id>.json 的运行时模型。 */
|
||||
public final class ModelManifest {
|
||||
public int schemaVersion = 1;
|
||||
public String id = "";
|
||||
public String name = "";
|
||||
public Map<String, String> nameI18n = new LinkedHashMap<>();
|
||||
public String version = "1.0.0";
|
||||
public String author = "";
|
||||
public String description = "";
|
||||
public Map<String, String> descriptionI18n = new LinkedHashMap<>();
|
||||
public List<String> tags = new ArrayList<>();
|
||||
public String entry = "scene.json";
|
||||
public String assembly = "";
|
||||
public String type = "";
|
||||
public String preview = "preview.png";
|
||||
public int apiVersion = 1;
|
||||
public String license = "";
|
||||
public String updatedAt = "";
|
||||
public String minAppVersion = "";
|
||||
public Map<String, String> chrome = new LinkedHashMap<>();
|
||||
|
||||
public static ModelManifest parse(Map<String, Object> m) {
|
||||
ModelManifest x = new ModelManifest();
|
||||
x.schemaVersion = Json.i(m, "schemaVersion", 1);
|
||||
x.id = Json.str(m, "id", "");
|
||||
x.name = Json.str(m, "name", "");
|
||||
x.version = Json.str(m, "version", "1.0.0");
|
||||
x.author = Json.str(m, "author", "");
|
||||
x.description = Json.str(m, "description", "");
|
||||
x.entry = Json.str(m, "entry", "scene.json");
|
||||
x.assembly = Json.str(m, "assembly", "");
|
||||
x.type = Json.str(m, "type", "");
|
||||
x.preview = Json.str(m, "preview", "preview.png");
|
||||
x.apiVersion = Json.i(m, "apiVersion", 1);
|
||||
x.license = Json.str(m, "license", "");
|
||||
x.updatedAt = Json.str(m, "updatedAt", "");
|
||||
x.minAppVersion = Json.str(m, "minAppVersion", "");
|
||||
for (var e : Json.obj(m.get("nameI18n")).entrySet()) x.nameI18n.put(e.getKey(), String.valueOf(e.getValue()));
|
||||
for (var e : Json.obj(m.get("descriptionI18n")).entrySet()) x.descriptionI18n.put(e.getKey(), String.valueOf(e.getValue()));
|
||||
for (var e : Json.obj(m.get("chrome")).entrySet()) x.chrome.put(e.getKey(), String.valueOf(e.getValue()));
|
||||
for (Object o : Json.arr(m.get("tags"))) x.tags.add(String.valueOf(o));
|
||||
return x;
|
||||
}
|
||||
|
||||
public String localizedName() {
|
||||
String v = nameI18n.get(I18n.language());
|
||||
if (v == null) v = nameI18n.get("zh-CN");
|
||||
return v == null || v.isBlank() ? (name.isBlank() ? id : name) : v;
|
||||
}
|
||||
|
||||
public String localizedDescription() {
|
||||
String v = descriptionI18n.get(I18n.language());
|
||||
if (v == null) v = descriptionI18n.get("zh-CN");
|
||||
return v == null ? description : v;
|
||||
}
|
||||
|
||||
public static final class Package {
|
||||
public final ModelManifest manifest;
|
||||
public final Path directory;
|
||||
public long sizeBytes;
|
||||
public Package(ModelManifest manifest, Path directory) { this.manifest = manifest; this.directory = directory; }
|
||||
public String id() { return manifest.id; }
|
||||
public Path dataDir() { return directory.resolve(manifest.id + ".model"); }
|
||||
public Path previewPath() { return dataDir().resolve(manifest.preview.isBlank() ? "preview.png" : manifest.preview); }
|
||||
public Path scenePath() {
|
||||
Path p = Path.of(manifest.entry.isBlank() ? "scene.json" : manifest.entry);
|
||||
return p.isAbsolute() ? p : (manifest.entry.startsWith(manifest.id + ".model") ? directory.resolve(p) : dataDir().resolve(p));
|
||||
}
|
||||
public Path assemblyPath() {
|
||||
String f = manifest.assembly.isBlank() ? manifest.id + ".dll" : manifest.assembly;
|
||||
return dataDir().resolve(f);
|
||||
}
|
||||
public boolean hasBuiltinRenderer() {
|
||||
return BuiltinModels.supports(manifest.id);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Discovery {
|
||||
public final Path root;
|
||||
public final List<Package> models;
|
||||
public final List<String> errors;
|
||||
public Discovery(Path root, List<Package> models, List<String> errors) {
|
||||
this.root = root; this.models = models; this.errors = errors;
|
||||
}
|
||||
}
|
||||
|
||||
public static Discovery scan(Path root) {
|
||||
List<Package> list = new ArrayList<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
if (!Files.isDirectory(root)) return new Discovery(root, list, errors);
|
||||
try (var ds = Files.newDirectoryStream(root)) {
|
||||
for (Path dir : ds) {
|
||||
if (!Files.isDirectory(dir)) continue;
|
||||
String folder = dir.getFileName().toString();
|
||||
if (folder.startsWith(".") || folder.startsWith("_")) continue;
|
||||
Path manifestPath = dir.resolve(folder + ".json");
|
||||
if (!Files.isRegularFile(manifestPath)) {
|
||||
try (var fs = Files.list(dir)) {
|
||||
manifestPath = fs.filter(p -> p.getFileName().toString().endsWith(".json")).findFirst().orElse(null);
|
||||
}
|
||||
}
|
||||
if (manifestPath == null) continue;
|
||||
try {
|
||||
ModelManifest m = parse(Json.obj(Json.parse(manifestPath)));
|
||||
if (m.id == null || m.id.isBlank()) m.id = folder;
|
||||
Package pkg = new Package(m, dir);
|
||||
pkg.sizeBytes = Hash.dirSize(dir);
|
||||
list.add(pkg);
|
||||
} catch (Exception e) {
|
||||
errors.add(manifestPath + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
errors.add(root + ": " + e.getMessage());
|
||||
}
|
||||
list.sort(Comparator.comparing(p -> p.id().toLowerCase(Locale.ROOT)));
|
||||
return new Discovery(root, list, errors);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** 模型源抽象:Gitea/GitHub 仓库或本地目录。 */
|
||||
public interface Remote {
|
||||
String displayName();
|
||||
String sourceId();
|
||||
String rawManifestText() throws Exception;
|
||||
RepoVersion manifest() throws Exception;
|
||||
List<RepoEntry> listTree(String rootPath) throws Exception;
|
||||
byte[] download(RepoEntry entry) throws Exception;
|
||||
byte[] downloadPackage(String url) throws Exception;
|
||||
String rawUrl(String path);
|
||||
Path localRoot();
|
||||
|
||||
record RepoEntry(String name, String path, String relativePath, boolean directory,
|
||||
String downloadUrl, long size) {}
|
||||
|
||||
final class RepoVersion {
|
||||
public String repository = "";
|
||||
public String branch = "main";
|
||||
public String launcherVersion = "";
|
||||
public java.util.Map<String, RepoPackage> packages = new java.util.LinkedHashMap<>();
|
||||
public java.util.List<RepoModel> models = new java.util.ArrayList<>();
|
||||
public String trust = "";
|
||||
public String keyId = "";
|
||||
public String error = "";
|
||||
public String rawText = "";
|
||||
public boolean trusted;
|
||||
|
||||
public static RepoVersion parse(String text) {
|
||||
RepoVersion v = new RepoVersion();
|
||||
v.rawText = text;
|
||||
java.util.Map<String, Object> m = Json.obj(Json.parse(text));
|
||||
v.repository = Json.str(m, "repository", "");
|
||||
v.branch = Json.str(m, "branch", "main");
|
||||
java.util.Map<String, Object> launcher = Json.obj(m.get("launcher"));
|
||||
v.launcherVersion = Json.str(launcher, "version", "");
|
||||
for (var e : Json.obj(launcher.get("packages")).entrySet()) {
|
||||
java.util.Map<String, Object> p = Json.obj(e.getValue());
|
||||
v.packages.put(e.getKey(), new RepoPackage(
|
||||
Json.str(p, "url", ""), Json.str(p, "path", ""),
|
||||
Json.str(p, "sha256", ""), Json.l(p, "size", 0),
|
||||
Json.str(p, "dir", ""), Json.str(p, "name", ""), e.getKey()));
|
||||
}
|
||||
for (Object o : Json.arr(m.get("models"))) {
|
||||
java.util.Map<String, Object> x = Json.obj(o);
|
||||
v.models.add(new RepoModel(Json.str(x, "id", ""), Json.str(x, "version", ""),
|
||||
Json.str(x, "dir", ""), Json.str(x, "build", ""),
|
||||
Json.str(x, "manifestSha256", ""), Json.str(x, "filesSha256", ""),
|
||||
Json.i(x, "files", 0)));
|
||||
}
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
record RepoPackage(String url, String path, String sha256, long size, String dir, String name, String rid) {}
|
||||
record RepoModel(String id, String version, String dir, String build,
|
||||
String manifestSha256, String filesSha256, int files) {}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package com.gc.core;
|
||||
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/** 清单签名、公钥环、安全解压、模型完整性、启动健康标记。 */
|
||||
public final class Security {
|
||||
private Security() {}
|
||||
|
||||
public static final String ALGORITHM = "ECDSA-P256-SHA256";
|
||||
|
||||
public enum Trust { VERIFIED, SKIPPED, UNSIGNED, INVALID }
|
||||
|
||||
public record Verification(Trust trust, String keyId, String error) {
|
||||
public boolean trusted() { return trust == Trust.VERIFIED || trust == Trust.SKIPPED; }
|
||||
}
|
||||
|
||||
public record KeyEntry(String keyId, String publicKeyBase64, String note) {}
|
||||
|
||||
private static final List<KeyEntry> KEYS = new ArrayList<>(List.of(
|
||||
new KeyEntry("gc-2026-12",
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4R+R2Pvinsu/xdaUu5mATPyYoEpL6cyugSVKAVMz6yY15SjkgEvdosfWuQJBbrPOOgGulE6Jht6v7FZx1dQguQ==",
|
||||
"GC 主发布密钥"),
|
||||
new KeyEntry("gc-2026-11",
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xmPrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
|
||||
"已停用:私钥遗失")
|
||||
));
|
||||
|
||||
public static List<KeyEntry> keys() { return List.copyOf(KEYS); }
|
||||
|
||||
public static KeyEntry findKey(String keyId) {
|
||||
if (keyId == null || keyId.isBlank()) return KEYS.size() == 1 ? KEYS.get(0) : null;
|
||||
for (KeyEntry k : KEYS) if (k.keyId().equals(keyId)) return k;
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void addKey(String id, String b64) {
|
||||
if (id == null || id.isBlank() || b64 == null || b64.isBlank()) return;
|
||||
if (findKey(id) == null) KEYS.add(new KeyEntry(id, b64, "来自 GC_TRUSTED_KEYS"));
|
||||
}
|
||||
|
||||
public static Verification verifyManifest(String text, boolean requireSignature) {
|
||||
if (KEYS.isEmpty()) return new Verification(Trust.SKIPPED, null, "未配置受信任公钥,已跳过验签");
|
||||
if (text == null || text.isBlank()) return new Verification(Trust.INVALID, null, "清单内容为空");
|
||||
Map<String, Object> root;
|
||||
try { root = Json.obj(Json.parse(text)); }
|
||||
catch (Exception e) { return new Verification(Trust.INVALID, null, "清单不是合法 JSON: " + e.getMessage()); }
|
||||
Object sigObj = root.get("signature");
|
||||
if (!(sigObj instanceof Map)) {
|
||||
return new Verification(Trust.UNSIGNED, null, requireSignature ? "清单缺少签名" : "清单未签名");
|
||||
}
|
||||
Map<String, Object> sig = Json.obj(sigObj);
|
||||
String keyId = Json.str(sig, "keyId", "");
|
||||
String value = Json.str(sig, "value", "");
|
||||
String alg = Json.str(sig, "alg", ALGORITHM);
|
||||
if (!alg.equalsIgnoreCase(ALGORITHM)) return new Verification(Trust.INVALID, keyId, "不支持的签名算法: " + alg);
|
||||
if (value.isEmpty()) return new Verification(Trust.INVALID, keyId, "签名为空");
|
||||
KeyEntry key = findKey(keyId);
|
||||
if (key == null) return new Verification(Trust.INVALID, keyId, "未知签名密钥: " + keyId);
|
||||
String payload = Json.canonical(text);
|
||||
if (payload == null) return new Verification(Trust.INVALID, keyId, "无法规范化清单");
|
||||
try {
|
||||
byte[] sigBytes = Base64.getDecoder().decode(value);
|
||||
PublicKey pub = KeyFactory.getInstance("EC")
|
||||
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(key.publicKeyBase64())));
|
||||
Signature s = Signature.getInstance("SHA256withECDSAinP1363Format");
|
||||
s.initVerify(pub);
|
||||
s.update(payload.getBytes(StandardCharsets.UTF_8));
|
||||
return s.verify(sigBytes)
|
||||
? new Verification(Trust.VERIFIED, key.keyId(), null)
|
||||
: new Verification(Trust.INVALID, keyId, "签名与内容不符");
|
||||
} catch (Exception e) {
|
||||
return new Verification(Trust.INVALID, keyId, "验签异常: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static String signManifest(String text, PrivateKey key, String keyId) throws Exception {
|
||||
String payload = Json.canonical(text);
|
||||
if (payload == null) throw new IllegalArgumentException("清单不是合法 JSON,无法签名");
|
||||
Signature s = Signature.getInstance("SHA256withECDSAinP1363Format");
|
||||
s.initSign(key);
|
||||
s.update(payload.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] sig = s.sign();
|
||||
Map<String, Object> root = Json.obj(Json.parse(text));
|
||||
Map<String, Object> sigObj = new LinkedHashMap<>();
|
||||
sigObj.put("alg", ALGORITHM);
|
||||
sigObj.put("keyId", keyId);
|
||||
sigObj.put("value", Base64.getEncoder().encodeToString(sig));
|
||||
sigObj.put("contentSha256", Hash.sha256(payload.getBytes(StandardCharsets.UTF_8)));
|
||||
sigObj.put("signedAt", Instant.now().toString().substring(0, 19) + "Z");
|
||||
root.put("signature", sigObj);
|
||||
return Json.write(root, true, false) + "\n";
|
||||
}
|
||||
|
||||
public static PrivateKey loadPrivateKey(Path pem) throws Exception {
|
||||
String text = Files.readString(pem, StandardCharsets.UTF_8);
|
||||
String b64 = text.replaceAll("-----BEGIN [^-]+-----", "")
|
||||
.replaceAll("-----END [^-]+-----", "").replaceAll("\\s", "");
|
||||
byte[] der = Base64.getDecoder().decode(b64);
|
||||
return KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(der));
|
||||
}
|
||||
|
||||
public static String publicKeyBase64(PublicKey key) { return Base64.getEncoder().encodeToString(key.getEncoded()); }
|
||||
|
||||
public static String fingerprint(String publicKeyBase64) {
|
||||
return Hash.sha256(Base64.getDecoder().decode(publicKeyBase64)).substring(0, 16);
|
||||
}
|
||||
|
||||
/** 生成签名密钥对,写到目录;返回 keyId。 */
|
||||
public static String keygen(Path dir, String keyId) throws Exception {
|
||||
KeyPairGenerator gen = KeyPairGenerator.getInstance("EC");
|
||||
gen.initialize(new java.security.spec.ECGenParameterSpec("secp256r1"));
|
||||
KeyPair kp = gen.generateKeyPair();
|
||||
Files.createDirectories(dir);
|
||||
String priv = "-----BEGIN PRIVATE KEY-----\n" + wrap(Base64.getEncoder().encodeToString(kp.getPrivate().getEncoded()))
|
||||
+ "-----END PRIVATE KEY-----\n";
|
||||
String pub = "-----BEGIN PUBLIC KEY-----\n" + wrap(Base64.getEncoder().encodeToString(kp.getPublic().getEncoded()))
|
||||
+ "-----END PUBLIC KEY-----\n";
|
||||
Files.writeString(dir.resolve("gc-signing.pem"), priv, StandardCharsets.UTF_8);
|
||||
Files.writeString(dir.resolve("gc-signing.pub.pem"), pub, StandardCharsets.UTF_8);
|
||||
Files.writeString(dir.resolve("keyring.txt"),
|
||||
keyId + ":" + publicKeyBase64(kp.getPublic()) + " # fingerprint " + fingerprint(publicKeyBase64(kp.getPublic())) + "\n",
|
||||
StandardCharsets.UTF_8);
|
||||
return keyId;
|
||||
}
|
||||
|
||||
private static String wrap(String s) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < s.length(); i += 64) sb.append(s, i, Math.min(s.length(), i + 64)).append('\n');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 安全 zip
|
||||
|
||||
public static final long MAX_UNCOMPRESSED = 2L * 1024 * 1024 * 1024;
|
||||
public static final int MAX_ENTRIES = 20000;
|
||||
|
||||
public static String safeZipName(String name) {
|
||||
if (name == null) return "REJECT";
|
||||
String n = name.replace('\\', '/').trim();
|
||||
if (n.isEmpty()) return "REJECT";
|
||||
if (n.startsWith("/") || n.startsWith("//") || n.matches("^[A-Za-z]:.*") || n.startsWith("\\\\")) return "REJECT";
|
||||
for (String seg : n.split("/")) if (seg.equals("..")) return "REJECT";
|
||||
return "OK";
|
||||
}
|
||||
|
||||
public static boolean isSafeZipName(String name) { return safeZipName(name).equals("OK"); }
|
||||
|
||||
/** 解压不可信 zip 到目录,拒绝穿越 / 炸弹 / 链接。 */
|
||||
public static void extractZipSafe(Path zip, Path dest) throws IOException {
|
||||
Files.createDirectories(dest);
|
||||
Path destFull = dest.toAbsolutePath().normalize();
|
||||
int count = 0;
|
||||
long total = 0;
|
||||
try (ZipFile zf = new ZipFile(zip.toFile())) {
|
||||
Enumeration<? extends ZipEntry> en = zf.entries();
|
||||
while (en.hasMoreElements()) {
|
||||
ZipEntry e = en.nextElement();
|
||||
count++;
|
||||
if (count > MAX_ENTRIES) throw new IOException("zip 条目数超过限制");
|
||||
if (e.isDirectory()) continue;
|
||||
if (!isSafeZipName(e.getName())) throw new IOException("不安全的 zip 条目: " + e.getName());
|
||||
long size = e.getSize();
|
||||
if (size > 0 && total + size > MAX_UNCOMPRESSED) throw new IOException("zip 解压体积超过 2 GiB");
|
||||
long csize = Math.max(1, e.getCompressedSize());
|
||||
if (csize > 0 && size / csize > 200 && size > 10 * 1024 * 1024)
|
||||
throw new IOException("疑似 zip 炸弹: " + e.getName());
|
||||
Path out = destFull.resolve(e.getName()).normalize();
|
||||
if (!out.startsWith(destFull)) throw new IOException("zip 路径越界: " + e.getName());
|
||||
Files.createDirectories(out.getParent());
|
||||
long written = 0;
|
||||
try (InputStream in = zf.getInputStream(e);
|
||||
java.io.OutputStream os = Files.newOutputStream(out, StandardOpenOption.CREATE,
|
||||
StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
|
||||
byte[] buf = new byte[16384];
|
||||
int n;
|
||||
while ((n = in.read(buf)) > 0) {
|
||||
written += n;
|
||||
total += n;
|
||||
if (total > MAX_UNCOMPRESSED) throw new IOException("zip 解压体积超过 2 GiB");
|
||||
os.write(buf, 0, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 校验模型目录完整性,并写 .integrity.json。 */
|
||||
public static void writeIntegrity(Path modelDir, String id, String manifestSha, String filesSha) throws IOException {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("schema", 1);
|
||||
m.put("id", id);
|
||||
m.put("manifestSha256", manifestSha);
|
||||
m.put("filesSha256", filesSha);
|
||||
m.put("installedAt", Instant.now().toString());
|
||||
Files.writeString(modelDir.resolve(id + ".integrity.json"), Json.write(m, true, false) + "\n");
|
||||
}
|
||||
|
||||
public static boolean verifyModel(Path modelDir, String id, String expectedManifestSha, String expectedFilesSha) {
|
||||
try {
|
||||
Path manifest = modelDir.resolve(id + ".json");
|
||||
if (!Files.isRegularFile(manifest)) return false;
|
||||
if (expectedManifestSha != null && !expectedManifestSha.isBlank()
|
||||
&& !Hash.file(manifest).equalsIgnoreCase(expectedManifestSha)) return false;
|
||||
if (expectedFilesSha != null && !expectedFilesSha.isBlank()
|
||||
&& !Hash.dir(modelDir.resolve(id + ".model")).equalsIgnoreCase(expectedFilesSha)) return false;
|
||||
return true;
|
||||
} catch (Exception e) { return false; }
|
||||
}
|
||||
|
||||
/** 启动健康标记。 */
|
||||
public static void writeHealth(Path updateRoot, String version) {
|
||||
try {
|
||||
Files.createDirectories(updateRoot);
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("status", "ok");
|
||||
m.put("version", version);
|
||||
m.put("pid", ProcessHandle.current().pid());
|
||||
m.put("time", Instant.now().toString());
|
||||
Files.writeString(updateRoot.resolve("health.json"), Json.write(m, true, false) + "\n");
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
public static String safeId(String id) {
|
||||
if (id == null || !id.matches("^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")) return null;
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.gc.core;
|
||||
|
||||
import com.gc.model.contour.*;
|
||||
import com.gc.model.earth.EarthMath;
|
||||
import com.gc.model.scale.ScaleMath;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** 内置断言,全部 PASS 时退出码 0。 */
|
||||
public final class Selftest {
|
||||
private static int pass, fail;
|
||||
|
||||
private Selftest() {}
|
||||
|
||||
public static int run() {
|
||||
pass = fail = 0;
|
||||
try {
|
||||
Path tmp = Files.createTempDirectory("gc-selftest-");
|
||||
Path hello = tmp.resolve("hello.txt");
|
||||
Files.writeString(hello, "hello");
|
||||
check("hash-file", Hash.file(hello), "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824");
|
||||
|
||||
Path dir = tmp.resolve("d");
|
||||
Files.createDirectories(dir);
|
||||
Files.writeString(dir.resolve("a.txt"), "hello");
|
||||
check("hash-dir", Hash.dir(dir), "ed54360a4d7244bfcde6dca611fd00dbfbdf508c47ad104b711f8429a6d2604d");
|
||||
|
||||
check("version-normalize", VersionUtil.normalize("GCL-v1.0.6-beta"), "1.0.6");
|
||||
check("version-compare", String.valueOf(VersionUtil.compare("v1.0.6", "1.0.7")), "-1");
|
||||
check("canonical", Json.canonical("{\"b\":1,\"a\":\"中文\"}"), "{\"a\":\"中文\",\"b\":1}");
|
||||
check("safezip-name", Security.safeZipName("../x"), "REJECT");
|
||||
check("safezip-name", Security.safeZipName("a/b.txt"), "OK");
|
||||
check("human-size", Hash.humanSize(1536), "1.5 KB");
|
||||
|
||||
ScaleMath.State s = new ScaleMath.State();
|
||||
s.mode = ScaleMath.SolveMode.REAL;
|
||||
s.mapCm = 3; s.realCm = 0; s.n = 100000;
|
||||
ScaleMath.solve(s);
|
||||
check("scale-real", String.format(Locale.ROOT,"%.0f",s.realCm), "300000");
|
||||
check("scale-human", ScaleMath.num(ScaleMath.humanReal(300000).value()) + " " +
|
||||
ScaleMath.humanReal(300000).unitKey().replace("unit.", ""), "3 km");
|
||||
check("scale-grade", ScaleMath.grade(100000).name().toLowerCase(), "large");
|
||||
check("scale-grade", ScaleMath.grade(500000).name().toLowerCase(), "medium");
|
||||
check("scale-grade", ScaleMath.grade(10000000).name().toLowerCase(), "small");
|
||||
|
||||
TerrainField f = new TerrainField(TerrainField.TerrainKind.MOUNTAIN, 192);
|
||||
boolean has100 = false;
|
||||
for (float l : f.contourLevels()) if (Math.abs(l % 100) < 0.001) has100 = true;
|
||||
check("contour-levels", String.valueOf(has100), "true");
|
||||
int lines = f.extractContour(600).size();
|
||||
check("contour-extract", String.valueOf(lines > 0), "true");
|
||||
check("contour-color", rgb(TerrainAnalyzer.colorForHeight(450)), "a8c666");
|
||||
check("contour-classify-peak", TerrainAnalyzer.classify(f, 0.34, 0.34).name().toLowerCase(), "peak");
|
||||
|
||||
check("rotation-subsolar-90", ScaleMath.num(EarthMath.subsolarLatitude(90)), "23.5");
|
||||
check("rotation-subsolar-0", ScaleMath.num(EarthMath.subsolarLatitude(0)), "0");
|
||||
check("rotation-date", EarthMath.dateForAngle(0).toString(), "2025-03-21");
|
||||
check("revolution-season-90", EarthMath.nearestSeason(90).key().replace("season.", ""), "summerSolstice");
|
||||
check("revolution-season-270", EarthMath.nearestSeason(270).key().replace("season.", ""), "winterSolstice");
|
||||
check("revolution-step", String.format(Locale.ROOT, "%.3f", EarthMath.stepAngles(0, 0, 1, 1)[0]), "60.000");
|
||||
|
||||
check("geo-declination-40", EarthMath.declination(40), "northTemperate");
|
||||
check("geo-declination-0", EarthMath.declination(0), "tropics");
|
||||
double[] v = EarthMath.latLonToUnit(0, 90);
|
||||
check("geo-latlon", String.format(Locale.ROOT, "%.3f,%.3f,%.3f", v[0], v[1], v[2]), "1.000,0.000,0.000");
|
||||
|
||||
// 本地用户系统
|
||||
Path home = tmp.resolve("home");
|
||||
UserService us = new UserService(home);
|
||||
check("user-register", String.valueOf(us.register("student", "secret123").ok()), "true");
|
||||
check("user-login", String.valueOf(us.login("student", "secret123").ok()), "true");
|
||||
check("user-signin", String.valueOf(us.signIn().ok()), "true");
|
||||
check("user-points", String.valueOf(us.profile() != null
|
||||
&& us.profile().points() >= UserService.signInReward(1)), "true");
|
||||
// 主题色需要积分:把「昨天」写回存档,模拟连续签到累积积分
|
||||
for (int i = 0; i < 5; i++) backdateSignIn(home, "student", "secret123");
|
||||
UserService buyer = new UserService(home);
|
||||
buyer.login("student", "secret123");
|
||||
check("user-theme", String.valueOf(buyer.buyTheme("E74C3C", false).ok()), "true");
|
||||
buyer.logout();
|
||||
check("user-logout", String.valueOf(!buyer.loggedIn()), "true");
|
||||
|
||||
// 模型清单
|
||||
Path modelRoot = Path.of("model");
|
||||
if (Files.isDirectory(modelRoot)) {
|
||||
ModelManifest.Discovery d = ModelManifest.scan(modelRoot);
|
||||
check("model-scan", String.valueOf(d.models.size()), "5");
|
||||
}
|
||||
// 安全 zip
|
||||
check("safezip-abs", Security.safeZipName("/etc/passwd"), "REJECT");
|
||||
check("safezip-drive", Security.safeZipName("C:\\x"), "REJECT");
|
||||
AppPaths.deleteTree(tmp);
|
||||
} catch (Exception e) {
|
||||
fail++;
|
||||
System.out.println("FAIL exception: " + e);
|
||||
}
|
||||
System.out.println("\nSELFTEST " + (fail == 0 ? "PASS" : "FAIL") + " " + pass + " passed, " + fail + " failed");
|
||||
return fail == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/** 测试辅助:把最后签到日改成昨天,使下一次签到按连续天数发奖。 */
|
||||
private static void backdateSignIn(Path home, String username, String password) {
|
||||
try {
|
||||
Path file = home.resolve("user").resolve("users.json");
|
||||
Map<String, Object> all = Json.obj(Json.parse(file));
|
||||
Map<String, Object> u = Json.obj(all.get(username.toLowerCase(Locale.ROOT)));
|
||||
u.put("lastSignIn", java.time.LocalDate.now().minusDays(1).toString());
|
||||
Files.writeString(file, Json.write(all, true, false));
|
||||
UserService day = new UserService(home);
|
||||
day.login(username, password);
|
||||
day.signIn();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("模拟签到失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String rgb(java.awt.Color c) {
|
||||
return String.format("%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue());
|
||||
}
|
||||
|
||||
private static void check(String name, String actual, String expected) {
|
||||
if (Objects.equals(actual, expected)) { pass++; System.out.println("PASS " + name + " = " + actual); }
|
||||
else { fail++; System.out.println("FAIL " + name + " expected=" + expected + " actual=" + actual); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** 用户设置,持久化到 .GC/config/settings.json。 */
|
||||
public final class Settings {
|
||||
public String language = "auto";
|
||||
public String theme = "light";
|
||||
public String accentColor = "#8FB6FF";
|
||||
public int renderFps = 120;
|
||||
public int memoryMb = 2048;
|
||||
public boolean memoryAuto = true;
|
||||
public boolean checkSourceOnStartup = false;
|
||||
public String modelRootOverride = "";
|
||||
public List<Map<String, Object>> sources = new ArrayList<>();
|
||||
public List<String> recentModels = new ArrayList<>();
|
||||
|
||||
public boolean autoUpdateOnStartup = true;
|
||||
public String updateRepository = "https://git.xhmcl.com/Morris/GC";
|
||||
public String updateManifestUrl = "";
|
||||
public String updateLocalRoot = "";
|
||||
public boolean requireSignedManifest = true;
|
||||
public Map<String, String> installedModelVersions = new LinkedHashMap<>();
|
||||
public String launcherVersion = "2.0.0";
|
||||
public String pendingLauncherVersion = "";
|
||||
public String lastUpdateCheck = "";
|
||||
|
||||
private transient Path file;
|
||||
private transient boolean loading;
|
||||
|
||||
public static Settings load(Path file) {
|
||||
Settings s = new Settings();
|
||||
s.file = file;
|
||||
if (file != null && Files.isRegularFile(file)) {
|
||||
try {
|
||||
Map<String, Object> m = Json.obj(Json.parse(Files.readString(file, StandardCharsets.UTF_8)));
|
||||
s.apply(m);
|
||||
} catch (Exception e) {
|
||||
System.err.println("[settings] 读取设置失败,使用默认值: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
s.loading = false;
|
||||
return s;
|
||||
}
|
||||
|
||||
public static Settings defaults() {
|
||||
Settings s = new Settings();
|
||||
return s;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void apply(Map<String, Object> m) {
|
||||
language = Json.str(m, "language", language);
|
||||
theme = Json.str(m, "theme", theme);
|
||||
accentColor = Json.str(m, "accentColor", accentColor);
|
||||
renderFps = Json.i(m, "renderFps", renderFps);
|
||||
memoryMb = Json.i(m, "memoryMb", memoryMb);
|
||||
memoryAuto = Json.b(m, "memoryAuto", memoryAuto);
|
||||
checkSourceOnStartup = Json.b(m, "checkSourceOnStartup", checkSourceOnStartup);
|
||||
modelRootOverride = Json.str(m, "modelRootOverride", modelRootOverride);
|
||||
autoUpdateOnStartup = Json.b(m, "autoUpdateOnStartup", autoUpdateOnStartup);
|
||||
updateRepository = Json.str(m, "updateRepository", updateRepository);
|
||||
updateManifestUrl = Json.str(m, "updateManifestUrl", updateManifestUrl);
|
||||
updateLocalRoot = Json.str(m, "updateLocalRoot", updateLocalRoot);
|
||||
requireSignedManifest = Json.b(m, "requireSignedManifest", requireSignedManifest);
|
||||
launcherVersion = Json.str(m, "launcherVersion", launcherVersion);
|
||||
pendingLauncherVersion = Json.str(m, "pendingLauncherVersion", pendingLauncherVersion);
|
||||
lastUpdateCheck = Json.str(m, "lastUpdateCheck", lastUpdateCheck);
|
||||
sources = new ArrayList<>();
|
||||
for (Object o : Json.arr(m.get("sources"))) sources.add(new LinkedHashMap<>(Json.obj(o)));
|
||||
recentModels = new ArrayList<>();
|
||||
for (Object o : Json.arr(m.get("recentModels"))) recentModels.add(String.valueOf(o));
|
||||
installedModelVersions = new LinkedHashMap<>();
|
||||
Map<String, Object> im = Json.obj(m.get("installedModelVersions"));
|
||||
for (var e : im.entrySet()) installedModelVersions.put(e.getKey(), String.valueOf(e.getValue()));
|
||||
}
|
||||
|
||||
public synchronized void save() {
|
||||
if (loading || file == null) return;
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, Json.write(toMap(), true, false) + "\n", StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
System.err.println("[settings] 保存失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> toMap() {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("language", language);
|
||||
m.put("theme", theme);
|
||||
m.put("accentColor", accentColor);
|
||||
m.put("renderFps", renderFps);
|
||||
m.put("memoryMb", memoryMb);
|
||||
m.put("memoryAuto", memoryAuto);
|
||||
m.put("checkSourceOnStartup", checkSourceOnStartup);
|
||||
m.put("modelRootOverride", modelRootOverride);
|
||||
m.put("sources", sources);
|
||||
m.put("recentModels", recentModels);
|
||||
m.put("autoUpdateOnStartup", autoUpdateOnStartup);
|
||||
m.put("updateRepository", updateRepository);
|
||||
m.put("updateManifestUrl", updateManifestUrl);
|
||||
m.put("updateLocalRoot", updateLocalRoot);
|
||||
m.put("requireSignedManifest", requireSignedManifest);
|
||||
m.put("installedModelVersions", installedModelVersions);
|
||||
m.put("launcherVersion", launcherVersion);
|
||||
m.put("pendingLauncherVersion", pendingLauncherVersion);
|
||||
m.put("lastUpdateCheck", lastUpdateCheck);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** 有效内存预算:自动按物理内存 40% 取整到 256 MB。 */
|
||||
public int effectiveMemoryMb() {
|
||||
if (!memoryAuto) return Math.max(256, memoryMb);
|
||||
long total;
|
||||
try { total = ((com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean()).getTotalMemorySize(); }
|
||||
catch (Throwable t) { total = 8L * 1024 * 1024 * 1024; }
|
||||
long mb = (long) ((total / 1048576.0) * 0.4);
|
||||
mb = Math.max(1024, Math.min(8192, mb / 256 * 256));
|
||||
return (int) mb;
|
||||
}
|
||||
|
||||
public static String defaultJson() {
|
||||
return Json.write(Json.parse("""
|
||||
{"language":"auto","theme":"light","accentColor":"#8FB6FF","renderFps":120,
|
||||
"memoryMb":2048,"memoryAuto":true,"checkSourceOnStartup":false,
|
||||
"modelRootOverride":"","sources":[],"recentModels":[],
|
||||
"autoUpdateOnStartup":true,"updateRepository":"https://git.xhmcl.com/Morris/GC",
|
||||
"updateManifestUrl":"","updateLocalRoot":"","requireSignedManifest":true,
|
||||
"installedModelVersions":{},"launcherVersion":"2.0.0",
|
||||
"pendingLauncherVersion":"","lastUpdateCheck":""}
|
||||
"""), true, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 内置模型源,与原版一致:Xhmcl(Gitea)与 GitHub 镜像。 */
|
||||
public record SourcePreset(String id, String name, String homeUrl, String apiBase,
|
||||
String rawBase, String kind, String owner, String repo,
|
||||
String branch, String rawStyle) {
|
||||
public static final SourcePreset XHMCL = new SourcePreset(
|
||||
"xhmcl", "Xhmcl", "https://git.xhmcl.com/Morris/GC", "https://git.xhmcl.com/api/v1",
|
||||
"https://git.xhmcl.com", "gitea", "Morris", "GC", "main", "branch");
|
||||
public static final SourcePreset GITHUB = new SourcePreset(
|
||||
"github", "GitHub", "https://github.com/Morris-morris-cloud/GC", "https://api.github.com",
|
||||
"https://raw.githubusercontent.com", "github", "Morris-morris-cloud", "GC", "main", "raw");
|
||||
|
||||
public static final List<SourcePreset> ALL = List.of(XHMCL, GITHUB);
|
||||
|
||||
public static SourcePreset detect(String url) {
|
||||
if (url != null) {
|
||||
String u = url.toLowerCase();
|
||||
if (u.contains("github.com") || u.equals("github")) return GITHUB;
|
||||
if (u.contains("xhmcl.com") || u.equals("xhmcl")) return XHMCL;
|
||||
}
|
||||
return XHMCL;
|
||||
}
|
||||
|
||||
public String rawUrl(String path) {
|
||||
String p = path.startsWith("/") ? path.substring(1) : path;
|
||||
return switch (rawStyle) {
|
||||
case "raw" -> rawBase + "/" + owner + "/" + repo + "/" + branch + "/" + p;
|
||||
default -> rawBase + "/" + owner + "/" + repo + "/raw/branch/" + branch + "/" + p;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.awt.*;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryMXBean;
|
||||
import java.lang.management.MemoryPoolMXBean;
|
||||
import java.lang.management.MemoryUsage;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileStore;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** 百宝箱使用的系统信息采集(CPU / 内存 / GPU / 磁盘 / 网络 / OpenGL)。 */
|
||||
public final class SystemInfo {
|
||||
private SystemInfo() {}
|
||||
|
||||
public record Cpu(String model, int cores, double systemLoad, double processLoad) {}
|
||||
public record Memory(long total, long free, long used, long heapUsed, long heapMax) {}
|
||||
public record Gpu(String model, String driver, String vram, String opengl) {}
|
||||
public record Disk(long total, long free) {}
|
||||
public record Network(List<String> localIps, String publicIp, String location, String isp, long latencyMs) {}
|
||||
public record Snapshot(String os, String arch, String java, long uptimeMs, String screen, Cpu cpu,
|
||||
Memory memory, Gpu gpu, Disk disk) {}
|
||||
|
||||
public static Snapshot snapshot() {
|
||||
MemoryMXBean mm = ManagementFactory.getMemoryMXBean();
|
||||
MemoryUsage heap = mm.getHeapMemoryUsage();
|
||||
long total = 0, free = 0;
|
||||
try {
|
||||
com.sun.management.OperatingSystemMXBean os =
|
||||
(com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
|
||||
total = os.getTotalMemorySize();
|
||||
free = os.getFreeMemorySize();
|
||||
} catch (Throwable ignored) {
|
||||
total = Runtime.getRuntime().maxMemory();
|
||||
free = Runtime.getRuntime().freeMemory();
|
||||
}
|
||||
Memory mem = new Memory(total, free, total - free, heap.getUsed(), heap.getMax());
|
||||
|
||||
double sysLoad = -1, procLoad = -1;
|
||||
try {
|
||||
com.sun.management.OperatingSystemMXBean os =
|
||||
(com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
|
||||
sysLoad = os.getCpuLoad();
|
||||
procLoad = os.getProcessCpuLoad();
|
||||
} catch (Throwable ignored) { }
|
||||
Cpu cpu = new Cpu(cpuModel(), Runtime.getRuntime().availableProcessors(), sysLoad, procLoad);
|
||||
|
||||
String screen = "—";
|
||||
try {
|
||||
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
|
||||
DisplayMode dm = gd.getDisplayMode();
|
||||
screen = dm.getWidth() + " × " + dm.getHeight() + " @ " + dm.getRefreshRate() + " Hz";
|
||||
} catch (Throwable ignored) { }
|
||||
|
||||
return new Snapshot(System.getProperty("os.name", "?") + " " + System.getProperty("os.version", ""),
|
||||
System.getProperty("os.arch", "?"), System.getProperty("java.version", "?") + " / " +
|
||||
System.getProperty("java.vendor", ""), ManagementFactory.getRuntimeMXBean().getUptime(),
|
||||
screen + " · " + availableProcessorsText(), cpu, mem, gpu(), disk());
|
||||
}
|
||||
|
||||
private static String availableProcessorsText() {
|
||||
return Runtime.getRuntime().availableProcessors() + " 线程";
|
||||
}
|
||||
|
||||
public static String cpuModel() {
|
||||
String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
|
||||
try {
|
||||
if (os.contains("mac")) {
|
||||
String s = run(900, "sysctl", "-n", "machdep.cpu.brand_string");
|
||||
if (s != null && !s.isBlank()) return s.trim();
|
||||
} else if (os.contains("linux")) {
|
||||
Path p = Path.of("/proc/cpuinfo");
|
||||
if (Files.isRegularFile(p)) {
|
||||
for (String line : Files.readAllLines(p, StandardCharsets.UTF_8)) {
|
||||
if (line.toLowerCase(Locale.ROOT).startsWith("model name")) {
|
||||
return line.substring(line.indexOf(':') + 1).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (os.contains("win")) {
|
||||
String s = run(1200, "powershell", "-NoProfile", "-Command",
|
||||
"(Get-CimInstance Win32_Processor | Select-Object -First 1 -ExpandProperty Name)");
|
||||
if (s != null && !s.isBlank()) return s.trim();
|
||||
s = System.getenv("PROCESSOR_IDENTIFIER");
|
||||
if (s != null && !s.isBlank()) return s;
|
||||
}
|
||||
} catch (Throwable ignored) { }
|
||||
return System.getProperty("os.arch", "Unknown CPU");
|
||||
}
|
||||
|
||||
public static Gpu gpu() {
|
||||
String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
|
||||
String model = "—", driver = "—", vram = "—", opengl = "—";
|
||||
try {
|
||||
if (os.contains("mac")) {
|
||||
String s = run(2500, "system_profiler", "SPDisplaysDataType");
|
||||
if (s != null) {
|
||||
for (String line : s.split("\n")) {
|
||||
String t = line.trim();
|
||||
if (t.startsWith("Chipset Model:")) model = t.substring(t.indexOf(':') + 1).trim();
|
||||
else if (t.startsWith("Metal Support:")) driver = t.substring(t.indexOf(':') + 1).trim();
|
||||
else if (t.startsWith("Total Number of Cores:")) vram = t.substring(t.indexOf(':') + 1).trim() + " 核心";
|
||||
else if (t.startsWith("Resolution:") || t.startsWith("分辨率:")) {
|
||||
String v = t.substring(t.indexOf(':') + 1).trim();
|
||||
if (v.length() < 80) vram = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (os.contains("win")) {
|
||||
String s = run(1800, "powershell", "-NoProfile", "-Command",
|
||||
"Get-CimInstance Win32_VideoController | Select-Object -First 1 Name,DriverVersion,AdapterRAM | Format-List");
|
||||
if (s != null) {
|
||||
for (String line : s.split("\n")) {
|
||||
String t = line.trim();
|
||||
if (t.startsWith("Name")) model = afterColon(t);
|
||||
else if (t.startsWith("DriverVersion")) driver = afterColon(t);
|
||||
else if (t.startsWith("AdapterRAM")) vram = Hash.humanSize(parseLong(afterColon(t)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String s = run(1500, "sh", "-c", "lspci 2>/dev/null | grep -i -E 'vga|3d|display' | head -1");
|
||||
if (s != null && !s.isBlank()) model = s.trim();
|
||||
}
|
||||
} catch (Throwable ignored) { }
|
||||
try {
|
||||
Class<?> gp = Class.forName("com.jogamp.opengl.GLProfile");
|
||||
Object prof = gp.getMethod("getDefault").invoke(null);
|
||||
opengl = String.valueOf(prof);
|
||||
if (opengl.contains("GLProfile[")) opengl = opengl.substring(opengl.indexOf('[') + 1, opengl.length() - 1);
|
||||
} catch (Throwable t) {
|
||||
opengl = "JOGL 未加载";
|
||||
}
|
||||
return new Gpu(model.isBlank() ? "—" : model, driver, vram, opengl);
|
||||
}
|
||||
|
||||
private static String afterColon(String t) {
|
||||
int i = t.indexOf(':');
|
||||
return i < 0 ? t : t.substring(i + 1).trim();
|
||||
}
|
||||
|
||||
private static long parseLong(String s) {
|
||||
try { return Long.parseLong(s.replaceAll("[^0-9]", "")); } catch (Exception e) { return 0; }
|
||||
}
|
||||
|
||||
public static Disk disk() {
|
||||
try {
|
||||
Path home = Path.of(System.getProperty("user.home"));
|
||||
FileStore fs = Files.getFileStore(home);
|
||||
return new Disk(fs.getTotalSpace(), fs.getUsableSpace());
|
||||
} catch (Exception e) {
|
||||
return new Disk(0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static Network network() {
|
||||
List<String> ips = new ArrayList<>();
|
||||
try {
|
||||
for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
|
||||
if (!ni.isUp() || ni.isLoopback()) continue;
|
||||
for (InetAddress a : Collections.list(ni.getInetAddresses())) {
|
||||
if (a.getHostAddress().contains(":")) continue;
|
||||
ips.add(a.getHostAddress() + " (" + ni.getDisplayName() + ")");
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
if (ips.isEmpty()) ips.add("未检测到局域网地址");
|
||||
String pub = "—", loc = "—", isp = "—";
|
||||
long latency = -1;
|
||||
try {
|
||||
long start = System.nanoTime();
|
||||
String ip = Http.getString("https://api.ipify.org?format=json");
|
||||
latency = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
|
||||
pub = Json.str(Json.obj(Json.parse(ip)), "ip", "—");
|
||||
try {
|
||||
String detail = Http.getString("https://ipapi.co/" + pub + "/json/");
|
||||
var m = Json.obj(Json.parse(detail));
|
||||
String city = Json.str(m, "city", "");
|
||||
String region = Json.str(m, "region", "");
|
||||
String country = Json.str(m, "country_name", "");
|
||||
loc = (country + " " + region + " " + city).trim();
|
||||
isp = Json.str(m, "org", "—");
|
||||
} catch (Exception ignored) { }
|
||||
} catch (Exception e) {
|
||||
pub = "离线 / 无法访问";
|
||||
}
|
||||
return new Network(ips, pub, loc.isBlank() ? "—" : loc, isp, latency);
|
||||
}
|
||||
|
||||
public static long optimizeMemory() {
|
||||
MemoryUsage before = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
|
||||
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
|
||||
try { pool.resetPeakUsage(); } catch (Throwable ignored) { }
|
||||
}
|
||||
System.gc();
|
||||
System.runFinalization();
|
||||
System.gc();
|
||||
MemoryUsage after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
|
||||
return Math.max(0, before.getUsed() - after.getUsed());
|
||||
}
|
||||
|
||||
private static String run(long timeoutMs, String... cmd) {
|
||||
try {
|
||||
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
|
||||
if (!p.waitFor(timeoutMs, TimeUnit.MILLISECONDS)) { p.destroyForcibly(); return null; }
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) sb.append(line).append('\n');
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (Exception e) { return null; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** 读远端版本清单、验签、下载模型并原子安装;启动器包只下载待下次应用。 */
|
||||
public final class UpdateService {
|
||||
public enum Outcome { NO_CHANGE, APPLIED, PARTIAL, UNAVAILABLE, DISABLED }
|
||||
public record Progress(double value, String message, String detail) {}
|
||||
public record Result(Outcome outcome, String message, int updatedModels,
|
||||
List<String> modelNames, String error, String launcherPending,
|
||||
Remote.RepoVersion manifest) {}
|
||||
|
||||
private final AppPaths paths;
|
||||
private final Settings settings;
|
||||
|
||||
public UpdateService(AppPaths paths, Settings settings) {
|
||||
this.paths = paths;
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
public Remote createRemote() {
|
||||
if (settings.updateLocalRoot != null && !settings.updateLocalRoot.isBlank()
|
||||
&& Files.isDirectory(Path.of(settings.updateLocalRoot)))
|
||||
return new LocalRemote(Path.of(settings.updateLocalRoot));
|
||||
return new GiteaRemote(SourcePreset.detect(settings.updateRepository));
|
||||
}
|
||||
|
||||
public Result run(boolean force, Consumer<Progress> progress) {
|
||||
if (!force && !settings.autoUpdateOnStartup)
|
||||
return new Result(Outcome.DISABLED, I18n.t("update.disabled"), 0, List.of(), null, null, null);
|
||||
Remote remote = createRemote();
|
||||
progress.accept(new Progress(0.02, I18n.t("update.checking"), remote.displayName()));
|
||||
|
||||
Remote.RepoVersion rv;
|
||||
try {
|
||||
rv = remote.manifest();
|
||||
if (rv == null)
|
||||
return new Result(Outcome.UNAVAILABLE, I18n.t("update.noManifest"), 0, List.of(), null, null, null);
|
||||
} catch (Exception e) {
|
||||
Log.warn("更新检查失败: " + e.getMessage(), "Update check failed: " + e.getMessage());
|
||||
return new Result(Outcome.UNAVAILABLE, I18n.t("update.offline"), 0, List.of(), e.getMessage(), null, null);
|
||||
}
|
||||
|
||||
boolean allowUnsigned = paths.development || !settings.requireSignedManifest
|
||||
|| "1".equals(System.getenv("GC_ALLOW_UNSIGNED_MANIFEST"));
|
||||
if (!rv.trusted && !allowUnsigned) {
|
||||
String reason = rv.trust.equals("UNSIGNED") ? "清单未签名" : "清单签名无效(内容可能被篡改)";
|
||||
Log.warn(reason + ",已拒绝本次更新", reason + " — update rejected");
|
||||
return new Result(Outcome.UNAVAILABLE, reason + ",已拒绝更新", 0, List.of(), rv.error, null, rv);
|
||||
}
|
||||
settings.lastUpdateCheck = Instant.now().toString();
|
||||
settings.save();
|
||||
|
||||
List<Remote.RepoModel> needed = new ArrayList<>();
|
||||
for (Remote.RepoModel m : rv.models) if (needsModel(m)) needed.add(m);
|
||||
|
||||
List<String> updated = new ArrayList<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
for (int i = 0; i < needed.size(); i++) {
|
||||
Remote.RepoModel m = needed.get(i);
|
||||
progress.accept(new Progress(0.05 + 0.65 * i / Math.max(1, needed.size()),
|
||||
I18n.f("update.downloadingModel", m.id()), m.version()));
|
||||
try {
|
||||
installModel(remote, m, pk -> {});
|
||||
settings.installedModelVersions.put(m.id(), m.version());
|
||||
settings.save();
|
||||
updated.add(m.id());
|
||||
Log.info("模型已更新: " + m.id() + " " + m.version(), "Model updated: " + m.id() + " " + m.version());
|
||||
} catch (Exception e) {
|
||||
errors.add(m.id() + ": " + e.getMessage());
|
||||
Log.error("模型更新失败 " + m.id() + ": " + e.getMessage(), "Model update failed " + m.id() + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
String launcherPending = null;
|
||||
try {
|
||||
launcherPending = downloadLauncher(remote, rv, progress);
|
||||
} catch (Exception e) {
|
||||
Log.warn("启动器更新下载失败: " + e.getMessage(), "Launcher update download failed: " + e.getMessage());
|
||||
}
|
||||
|
||||
progress.accept(new Progress(1, I18n.t("update.done"), ""));
|
||||
Outcome outcome = !errors.isEmpty() ? Outcome.PARTIAL
|
||||
: (!updated.isEmpty() || launcherPending != null) ? Outcome.APPLIED : Outcome.NO_CHANGE;
|
||||
String msg = updated.isEmpty()
|
||||
? (launcherPending != null ? I18n.t("update.modelsLatest") : I18n.t("update.noChange"))
|
||||
: I18n.f("update.applied", updated.size());
|
||||
if (!errors.isEmpty()) msg += I18n.f("update.partial", errors.size());
|
||||
return new Result(outcome, msg, updated.size(), updated,
|
||||
errors.isEmpty() ? null : String.join("; ", errors), launcherPending, rv);
|
||||
}
|
||||
|
||||
private boolean needsModel(Remote.RepoModel m) {
|
||||
if (m.id() == null || m.id().isBlank() || m.version() == null || m.version().isBlank()) return false;
|
||||
Path dir = paths.modelRoot.resolve(m.id());
|
||||
Path mf = dir.resolve(m.id() + ".json");
|
||||
if (!Files.isRegularFile(mf) || !Files.isDirectory(dir.resolve(m.id() + ".model"))) return true;
|
||||
try {
|
||||
ModelManifest local = ModelManifest.parse(Json.obj(Json.parse(mf)));
|
||||
// 只在远端版本更高时更新;本地更高(离线改过的 Java 数据)绝不被旧版覆盖
|
||||
return VersionUtil.compare(m.version(), local.version) > 0;
|
||||
} catch (Exception e) { return true; }
|
||||
}
|
||||
|
||||
private void installModel(Remote remote, Remote.RepoModel model, Consumer<Progress> progress) throws Exception {
|
||||
String rootPath = model.dir() == null || model.dir().isBlank() ? "model/" + model.id() : model.dir();
|
||||
List<Remote.RepoEntry> tree = remote.listTree(rootPath);
|
||||
List<Remote.RepoEntry> files = new ArrayList<>();
|
||||
for (Remote.RepoEntry e : tree) {
|
||||
if (e.directory()) continue;
|
||||
if (isPayload(model.id(), e.relativePath())) files.add(e);
|
||||
}
|
||||
boolean hasManifest = files.stream().anyMatch(e -> e.relativePath().equalsIgnoreCase(model.id() + ".json"));
|
||||
if (!hasManifest) throw new IOException("远端缺少模型清单 " + model.id() + ".json");
|
||||
if (files.stream().noneMatch(e -> e.relativePath().toLowerCase().startsWith(model.id().toLowerCase() + ".model/")))
|
||||
throw new IOException("远端缺少模型数据 " + model.id() + ".model/");
|
||||
|
||||
Path staging = paths.cacheRoot().resolve("models").resolve(model.id() + "-" + safe(model.version()));
|
||||
AppPaths.deleteTree(staging);
|
||||
Files.createDirectories(staging);
|
||||
try {
|
||||
long total = Math.max(1, files.stream().mapToLong(f -> Math.max(1, f.size())).sum());
|
||||
long done = 0;
|
||||
for (Remote.RepoEntry f : files) {
|
||||
Path dest = staging.resolve(f.relativePath()).normalize();
|
||||
if (!dest.startsWith(staging)) throw new IOException("路径越界: " + f.relativePath());
|
||||
Files.createDirectories(dest.getParent());
|
||||
byte[] bytes = remote.download(f);
|
||||
Files.write(dest, bytes);
|
||||
done += Math.max(1, bytes.length);
|
||||
progress.accept(new Progress(0.05 + 0.6 * done / total, model.id(), f.relativePath()));
|
||||
}
|
||||
if (model.manifestSha256() != null && !model.manifestSha256().isBlank()) {
|
||||
String actual = Hash.file(staging.resolve(model.id() + ".json"));
|
||||
if (!actual.equalsIgnoreCase(model.manifestSha256()))
|
||||
throw new IOException("模型清单哈希不匹配");
|
||||
}
|
||||
if (model.filesSha256() != null && !model.filesSha256().isBlank()) {
|
||||
String actual = Hash.dir(staging.resolve(model.id() + ".model"));
|
||||
if (!actual.equalsIgnoreCase(model.filesSha256()))
|
||||
throw new IOException("模型文件哈希不匹配");
|
||||
}
|
||||
Path target = paths.modelRoot.resolve(model.id());
|
||||
Path backup = paths.modelRoot.resolve(model.id() + ".old");
|
||||
AppPaths.deleteTree(backup);
|
||||
if (Files.exists(target)) Files.move(target, backup, StandardCopyOption.REPLACE_EXISTING);
|
||||
try { Files.move(staging, target); }
|
||||
catch (IOException e) {
|
||||
if (!Files.exists(target) && Files.exists(backup)) Files.move(backup, target);
|
||||
throw e;
|
||||
}
|
||||
AppPaths.deleteTree(backup);
|
||||
Security.writeIntegrity(target, model.id(), model.manifestSha256(), model.filesSha256());
|
||||
} catch (Exception e) {
|
||||
AppPaths.deleteTree(staging);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isPayload(String id, String rel) {
|
||||
String r = rel.replace('\\', '/');
|
||||
if (r.startsWith("/") || r.contains("..")) return false;
|
||||
return r.equalsIgnoreCase(id + ".json") || r.toLowerCase().startsWith(id.toLowerCase() + ".model/");
|
||||
}
|
||||
|
||||
private String safe(String s) { return s.replaceAll("[^A-Za-z0-9._-]", "_"); }
|
||||
|
||||
private String downloadLauncher(Remote remote, Remote.RepoVersion rv, Consumer<Progress> progress) throws Exception {
|
||||
if (rv.launcherVersion == null || rv.launcherVersion.isBlank()) return null;
|
||||
if (VersionUtil.compare(rv.launcherVersion, settings.launcherVersion) <= 0) return null;
|
||||
String rid = AppPaths.rid();
|
||||
Remote.RepoPackage pkg = rv.packages.get(rid);
|
||||
if (pkg == null) {
|
||||
Log.warn(I18n.f("update.noRidPackage", rv.launcherVersion, rid));
|
||||
return null;
|
||||
}
|
||||
String url = pkg.url();
|
||||
if (url == null || url.isBlank()) {
|
||||
if (pkg.path() == null || pkg.path().isBlank()) return null;
|
||||
url = remote.rawUrl(pkg.path());
|
||||
}
|
||||
progress.accept(new Progress(0.8, I18n.f("update.downloadingLauncher", rv.launcherVersion), url));
|
||||
byte[] bytes = remote.downloadPackage(url);
|
||||
if (pkg.sha256() != null && !pkg.sha256().isBlank()
|
||||
&& !Hash.sha256(bytes).equalsIgnoreCase(pkg.sha256()))
|
||||
throw new IOException("启动器包 sha256 不匹配");
|
||||
Files.createDirectories(paths.updateRoot());
|
||||
String name = pkg.name() == null || pkg.name().isBlank()
|
||||
? "GCL-" + rv.launcherVersion + "-" + rid + ".zip" : pkg.name();
|
||||
Path zip = paths.updateRoot().resolve(name);
|
||||
Files.write(zip, bytes);
|
||||
Map<String, Object> req = new LinkedHashMap<>();
|
||||
req.put("package", zip.toAbsolutePath().toString());
|
||||
req.put("version", rv.launcherVersion);
|
||||
req.put("installDir", paths.installDir.toAbsolutePath().toString());
|
||||
req.put("sha256", Hash.sha256(bytes));
|
||||
req.put("createdAt", Instant.now().toString());
|
||||
Files.writeString(paths.updateRoot().resolve("apply-request.json"), Json.write(req, true, false) + "\n");
|
||||
settings.pendingLauncherVersion = rv.launcherVersion;
|
||||
settings.save();
|
||||
return rv.launcherVersion;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 更新守护进程(对应 C# GC-SAVEDOG):验签 / 验哈希 / 安全解压 / 备份替换 / 回滚。
|
||||
* 用法:gc savedog verify <manifest> | apply <request.json> | status | keygen | sign。
|
||||
*/
|
||||
public final class Updater {
|
||||
private final AppPaths paths;
|
||||
|
||||
public Updater(AppPaths paths) { this.paths = paths; }
|
||||
|
||||
public int verify(String manifest) {
|
||||
try {
|
||||
String text = Files.readString(Path.of(manifest), StandardCharsets.UTF_8);
|
||||
Security.Verification v = Security.verifyManifest(text, true);
|
||||
System.out.println("trust=" + v.trust() + " keyId=" + (v.keyId() == null ? "" : v.keyId())
|
||||
+ (v.error() == null ? "" : " error=" + v.error()));
|
||||
return v.trust() == Security.Trust.VERIFIED || v.trust() == Security.Trust.SKIPPED ? 0 : 2;
|
||||
} catch (Exception e) {
|
||||
System.out.println("trust=INVALID error=" + e.getMessage());
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
public int apply() {
|
||||
Path request = paths.updateRoot().resolve("apply-request.json");
|
||||
if (!Files.isRegularFile(request)) { System.out.println("没有待应用的更新"); return 1; }
|
||||
try {
|
||||
Map<String, Object> req = Json.obj(Json.parse(request));
|
||||
Path zip = Path.of(Json.str(req, "package", ""));
|
||||
Path installDir = Path.of(Json.str(req, "installDir", paths.installDir.toString()));
|
||||
String expectedSha = Json.str(req, "sha256", "");
|
||||
String version = Json.str(req, "version", "");
|
||||
if (!Files.isRegularFile(zip)) throw new IOException("更新包不存在: " + zip);
|
||||
if (!expectedSha.isBlank() && !Hash.file(zip).equalsIgnoreCase(expectedSha))
|
||||
throw new IOException("更新包哈希不匹配");
|
||||
|
||||
Path stage = paths.updateRoot().resolve("stage");
|
||||
Path backup = paths.updateRoot().resolve("backup");
|
||||
AppPaths.deleteTree(stage);
|
||||
AppPaths.deleteTree(backup);
|
||||
Security.extractZipSafe(zip, stage);
|
||||
Path source = stage;
|
||||
// 如果压缩包只有一个顶层目录,替换目录内容
|
||||
try (DirectoryStream<Path> ds = Files.newDirectoryStream(stage)) {
|
||||
List<Path> top = new ArrayList<>();
|
||||
for (Path p : ds) top.add(p);
|
||||
if (top.size() == 1 && Files.isDirectory(top.get(0))) source = top.get(0);
|
||||
}
|
||||
List<Path> replaced = new ArrayList<>();
|
||||
try {
|
||||
try (var walk = Files.walk(source)) {
|
||||
for (Path p : walk.toList()) {
|
||||
if (p.equals(source)) continue;
|
||||
String rel = source.relativize(p).toString().replace('\\', '/');
|
||||
if (rel.isEmpty()) continue;
|
||||
String first = rel.split("/")[0];
|
||||
if (first.equals(".GC") || first.equals("config") || first.equals("model")
|
||||
|| first.equals("cache") || first.equals("logs") || first.equals("update")
|
||||
|| first.equals("safedog") || first.equals("user")) continue;
|
||||
Path target = installDir.resolve(rel).normalize();
|
||||
if (!target.startsWith(installDir)) throw new IOException("路径越界: " + rel);
|
||||
if (Files.isDirectory(p)) { Files.createDirectories(target); continue; }
|
||||
if (Files.exists(target)) {
|
||||
Path bak = backup.resolve(rel);
|
||||
Files.createDirectories(bak.getParent());
|
||||
Files.copy(target, bak, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(p, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
replaced.add(target);
|
||||
}
|
||||
}
|
||||
writeState("applied", version, null);
|
||||
writeLastGood(version);
|
||||
System.out.println("更新已应用: " + version + "(替换 " + replaced.size() + " 个文件)");
|
||||
Files.deleteIfExists(request);
|
||||
return 0;
|
||||
} catch (Exception e) {
|
||||
// 回滚
|
||||
try (var walk = Files.walk(backup)) {
|
||||
for (Path p : walk.toList()) {
|
||||
if (Files.isDirectory(p)) continue;
|
||||
Path target = installDir.resolve(backup.relativize(p).toString());
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(p, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
writeState("rolledback", version, e.getMessage());
|
||||
System.err.println("更新失败,已回滚: " + e.getMessage());
|
||||
return 3;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("应用更新失败: " + e.getMessage());
|
||||
writeState("failed", "", e.getMessage());
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeState(String state, String version, String error) {
|
||||
try {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("state", state);
|
||||
m.put("version", version);
|
||||
m.put("error", error);
|
||||
m.put("time", Instant.now().toString());
|
||||
Files.createDirectories(paths.updateRoot());
|
||||
Files.writeString(paths.updateRoot().resolve("state.json"), Json.write(m, true, false) + "\n");
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
private void writeLastGood(String version) throws IOException {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("version", version);
|
||||
m.put("time", Instant.now().toString());
|
||||
Files.writeString(paths.updateRoot().resolve("last-good.json"), Json.write(m, true, false) + "\n");
|
||||
}
|
||||
|
||||
public void status() {
|
||||
for (String f : new String[]{"apply-request.json", "state.json", "last-good.json", "health.json"}) {
|
||||
Path p = paths.updateRoot().resolve(f);
|
||||
System.out.println("== " + f + (Files.isRegularFile(p) ? "" : " (无)"));
|
||||
if (Files.isRegularFile(p)) {
|
||||
try { System.out.println(Files.readString(p).trim()); } catch (IOException ignored) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int keygen(Path dir, String keyId) {
|
||||
try {
|
||||
Security.keygen(dir, keyId);
|
||||
System.out.println("已生成密钥: " + dir + " keyId=" + keyId);
|
||||
return 0;
|
||||
} catch (Exception e) {
|
||||
System.err.println("生成密钥失败: " + e.getMessage());
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
public int sign(Path manifest, Path key, String keyId) {
|
||||
try {
|
||||
String text = Files.readString(manifest, StandardCharsets.UTF_8);
|
||||
String signed = Security.signManifest(text, Security.loadPrivateKey(key), keyId);
|
||||
Files.writeString(manifest, signed, StandardCharsets.UTF_8);
|
||||
System.out.println("已签名: " + manifest);
|
||||
return 0;
|
||||
} catch (Exception e) {
|
||||
System.err.println("签名失败: " + e.getMessage());
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package com.gc.core;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 本地用户系统,完整复刻原 GC.UI.Server.UserService 的业务规则:
|
||||
* 注册 / 登录 / 30 天周期签到 / 积分 / 每日人品值(阶梯计费)/
|
||||
* 二选一(自定义选项、阶梯计费)/ 主题色购买与 1 小时 80% 退款。
|
||||
*
|
||||
* <p>密码只保存 SHA-512(salt + ":" + password),不保存明文;数据位于
|
||||
* {@code .GC/user/users.json},会话位于 {@code .GC/user/session.json}。</p>
|
||||
*/
|
||||
public final class UserService {
|
||||
public static final String DEFAULT_THEME_COLOR = "4A90D9";
|
||||
public static final int PRESET_COLOR_COST = 50;
|
||||
public static final int CUSTOM_COLOR_COST = 150;
|
||||
public static final int SIGN_IN_CYCLE = 30;
|
||||
public static final double REFUND_RATE = 0.8;
|
||||
|
||||
public static final String[] PRESET_COLORS = {
|
||||
"4A90D9", "E74C3C", "27AE60", "9B59B6", "F39C12", "1ABC9C", "E91E63", "2C3E50"
|
||||
};
|
||||
public static final String[] PRESET_NAMES = {
|
||||
"蓝色", "红色", "绿色", "紫色", "橙色", "青色", "粉色", "深蓝"
|
||||
};
|
||||
|
||||
public record Result(boolean ok, String message) {}
|
||||
public record FortuneResult(boolean ok, String message, int value, String comment, double cost) {}
|
||||
public record PickResult(boolean ok, String message, String choice, double cost) {}
|
||||
public record Profile(String username, double points, int consecutiveDays, int cycleDay, int cycleDays,
|
||||
int nextReward, String themeColor, boolean signedToday, boolean fortuneToday,
|
||||
boolean pickToday, int refundSeconds, double fortuneCost, double pickCost,
|
||||
int fortuneCount, int pickCount) {}
|
||||
|
||||
private final Path dir;
|
||||
private final Path usersFile;
|
||||
private final Path sessionFile;
|
||||
private final Map<String, Map<String, Object>> users = new LinkedHashMap<>();
|
||||
private String current;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
public UserService(Path homeRoot) {
|
||||
dir = homeRoot.resolve("user");
|
||||
usersFile = dir.resolve("users.json");
|
||||
sessionFile = dir.resolve("session.json");
|
||||
try { Files.createDirectories(dir); } catch (Exception ignored) { }
|
||||
load();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 持久化
|
||||
|
||||
private synchronized void load() {
|
||||
try {
|
||||
if (Files.isRegularFile(usersFile)) {
|
||||
Map<String, Object> m = Json.obj(Json.parse(usersFile));
|
||||
for (var e : m.entrySet()) users.put(e.getKey(), new LinkedHashMap<>(Json.obj(e.getValue())));
|
||||
}
|
||||
} catch (Exception e) { System.err.println("[user] 读取用户失败: " + e.getMessage()); }
|
||||
try {
|
||||
if (Files.isRegularFile(sessionFile))
|
||||
current = Json.str(Json.obj(Json.parse(sessionFile)), "user", "");
|
||||
} catch (Exception ignored) { }
|
||||
if (current != null && !users.containsKey(current)) current = null;
|
||||
}
|
||||
|
||||
private synchronized void save() {
|
||||
try {
|
||||
Files.createDirectories(dir);
|
||||
Files.writeString(usersFile, Json.write(new LinkedHashMap<>(users), true, false) + "\n", StandardCharsets.UTF_8);
|
||||
Map<String, Object> s = new LinkedHashMap<>();
|
||||
s.put("user", current == null ? "" : current);
|
||||
Files.writeString(sessionFile, Json.write(s, true, false) + "\n", StandardCharsets.UTF_8);
|
||||
} catch (Exception e) { System.err.println("[user] 保存用户失败: " + e.getMessage()); }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 会话
|
||||
|
||||
public synchronized boolean loggedIn() { return current != null; }
|
||||
public synchronized String currentUser() { return current; }
|
||||
|
||||
public synchronized Profile profile() {
|
||||
Map<String, Object> u = me();
|
||||
if (u == null) return null;
|
||||
LocalDate today = LocalDate.now();
|
||||
int streak = Json.i(u, "consecutiveDays", 0);
|
||||
boolean signed = today.toString().equals(Json.str(u, "lastSignIn", ""));
|
||||
int nextConsecutive = signed ? streak + 1 : nextStreak(u, today);
|
||||
int fortuneCount = countToday(u, "fortuneDate", "fortuneCount");
|
||||
int pickCount = countToday(u, "pickDate", "pickCount");
|
||||
return new Profile(Json.str(u, "username", current), round2(Json.d(u, "points", 0)), streak,
|
||||
cycleDay(streak), SIGN_IN_CYCLE, signInReward(cycleDay(nextConsecutive)),
|
||||
normalizeHex(Json.str(u, "themeColor", DEFAULT_THEME_COLOR)).isEmpty()
|
||||
? DEFAULT_THEME_COLOR : normalizeHex(Json.str(u, "themeColor", DEFAULT_THEME_COLOR)),
|
||||
signed, fortuneCount > 0, pickCount > 0, refundSeconds(u),
|
||||
fortuneCost(fortuneCount), pickCost(pickCount), fortuneCount, pickCount);
|
||||
}
|
||||
|
||||
private int nextStreak(Map<String, Object> u, LocalDate today) {
|
||||
LocalDate last = date(Json.str(u, "lastSignIn", ""));
|
||||
return last != null && last.plusDays(1).equals(today)
|
||||
? Json.i(u, "consecutiveDays", 0) + 1 : 1;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 账号
|
||||
|
||||
public synchronized Result register(String username, String password) {
|
||||
String name = username == null ? "" : username.trim();
|
||||
if (name.length() < 1 || name.length() > 20) return new Result(false, "用户名需为 1–20 个字符");
|
||||
if (name.matches(".*\\s.*")) return new Result(false, "用户名不能包含空格");
|
||||
if (!name.matches("^[A-Za-z0-9_\\u4e00-\\u9fa5]+$")) return new Result(false, "用户名只能包含字母、数字、下划线或汉字");
|
||||
if (password == null || password.length() < 6) return new Result(false, "密码至少 6 位");
|
||||
String key = name.toLowerCase(Locale.ROOT);
|
||||
if (users.containsKey(key)) return new Result(false, "用户名已存在,请换一个");
|
||||
String salt = newSalt();
|
||||
Map<String, Object> u = new LinkedHashMap<>();
|
||||
u.put("username", name);
|
||||
u.put("salt", salt);
|
||||
u.put("hash", hash(salt, password));
|
||||
u.put("points", 0);
|
||||
u.put("consecutiveDays", 0);
|
||||
u.put("lastSignIn", "");
|
||||
u.put("themeColor", DEFAULT_THEME_COLOR);
|
||||
u.put("themePaid", 0);
|
||||
u.put("themePaidAt", "");
|
||||
u.put("fortuneDate", "");
|
||||
u.put("fortuneCount", 0);
|
||||
u.put("pickDate", "");
|
||||
u.put("pickCount", 0);
|
||||
users.put(key, u);
|
||||
current = key;
|
||||
save();
|
||||
return new Result(true, "注册成功,已自动登录");
|
||||
}
|
||||
|
||||
public synchronized Result login(String username, String password) {
|
||||
String key = username == null ? "" : username.trim().toLowerCase(Locale.ROOT);
|
||||
Map<String, Object> u = users.get(key);
|
||||
if (u == null) return new Result(false, "用户名或密码错误");
|
||||
if (!hash(Json.str(u, "salt", ""), password == null ? "" : password).equals(Json.str(u, "hash", "")))
|
||||
return new Result(false, "用户名或密码错误");
|
||||
current = key;
|
||||
save();
|
||||
return new Result(true, "欢迎回来," + Json.str(u, "username", key));
|
||||
}
|
||||
|
||||
public synchronized void logout() { current = null; save(); }
|
||||
|
||||
// ---------------------------------------------------------------- 签到
|
||||
|
||||
public static int cycleDay(int consecutiveDays) {
|
||||
if (consecutiveDays < 1) return 1;
|
||||
return ((consecutiveDays - 1) % SIGN_IN_CYCLE) + 1;
|
||||
}
|
||||
|
||||
public static int signInReward(int cycleDay) {
|
||||
int d = Math.max(1, Math.min(SIGN_IN_CYCLE, cycleDay));
|
||||
return switch (d) {
|
||||
case 7 -> 30;
|
||||
case 14 -> 40;
|
||||
case 21 -> 50;
|
||||
case 28 -> 60;
|
||||
case 30 -> 100;
|
||||
default -> d <= 6 ? 10 : d <= 13 ? 15 : d <= 20 ? 20 : d <= 27 ? 25 : 40;
|
||||
};
|
||||
}
|
||||
|
||||
public synchronized Result signIn() {
|
||||
Map<String, Object> u = me();
|
||||
if (u == null) return new Result(false, "请先登录");
|
||||
LocalDate today = LocalDate.now();
|
||||
LocalDate last = date(Json.str(u, "lastSignIn", ""));
|
||||
if (last != null && last.equals(today)) return new Result(false, "今日已签到");
|
||||
int streak;
|
||||
if (last != null) {
|
||||
long diff = Duration.between(last.atStartOfDay(), today.atStartOfDay()).toDays();
|
||||
streak = diff == 1 ? Json.i(u, "consecutiveDays", 0) + 1 : 1;
|
||||
} else streak = 1;
|
||||
int reward = signInReward(cycleDay(streak));
|
||||
u.put("consecutiveDays", streak);
|
||||
u.put("lastSignIn", today.toString());
|
||||
u.put("points", round2(Json.d(u, "points", 0) + reward));
|
||||
save();
|
||||
return new Result(true, "签到成功 +" + reward + " 积分(连续 " + streak + " 天)");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 人品值 / 二选一
|
||||
|
||||
public static double fortuneCost(int paidIndexToday) {
|
||||
if (paidIndexToday <= 0) return 0;
|
||||
if (paidIndexToday <= 5) return 0.1;
|
||||
if (paidIndexToday <= 10) return 0.2;
|
||||
if (paidIndexToday <= 25) return 0.5;
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static double pickCost(int paidIndexToday) {
|
||||
return paidIndexToday <= 0 ? 0 : 0.5;
|
||||
}
|
||||
|
||||
public synchronized FortuneResult fortune() {
|
||||
Map<String, Object> u = me();
|
||||
if (u == null) return new FortuneResult(false, "请先登录", 0, "", 0);
|
||||
int count = countToday(u, "fortuneDate", "fortuneCount");
|
||||
double cost = fortuneCost(count);
|
||||
double points = Json.d(u, "points", 0);
|
||||
if (points < cost) return new FortuneResult(false, "积分不足,本次需要 " + fmt(cost) + " 积分", 0, "", cost);
|
||||
points = round2(points - cost);
|
||||
int value = random.nextInt(101);
|
||||
u.put("points", points);
|
||||
u.put("fortuneDate", LocalDate.now().toString());
|
||||
u.put("fortuneCount", count + 1);
|
||||
save();
|
||||
return new FortuneResult(true, cost > 0 ? "本次消耗 " + fmt(cost) + " 积分" : "今日首次免费",
|
||||
value, fortuneComment(value), cost);
|
||||
}
|
||||
|
||||
public static String fortuneComment(int value) {
|
||||
if (value >= 96) return "欧皇附体,今天买彩票吧";
|
||||
if (value >= 90) return "运气爆棚,适合干大事";
|
||||
if (value >= 80) return "手气不错,稳";
|
||||
if (value >= 65) return "中上水平,稍微努一下";
|
||||
if (value >= 50) return "普普通通,够用";
|
||||
if (value >= 35) return "有点背,低调点";
|
||||
if (value >= 20) return "今天别赌任何东西";
|
||||
if (value >= 8) return "极差,建议躺平";
|
||||
return "非酋之王,明天再来";
|
||||
}
|
||||
|
||||
public synchronized PickResult pick(String optionA, String optionB) {
|
||||
Map<String, Object> u = me();
|
||||
if (u == null) return new PickResult(false, "请先登录", "", 0);
|
||||
String a = optionA == null ? "" : optionA.trim();
|
||||
String b = optionB == null ? "" : optionB.trim();
|
||||
if (a.isEmpty() || b.isEmpty()) return new PickResult(false, "两个选项都不能为空", "", 0);
|
||||
int count = countToday(u, "pickDate", "pickCount");
|
||||
double cost = pickCost(count);
|
||||
double points = Json.d(u, "points", 0);
|
||||
if (points < cost) return new PickResult(false, "积分不足,本次需要 " + fmt(cost) + " 积分", "", cost);
|
||||
points = round2(points - cost);
|
||||
String choice = random.nextBoolean() ? a : b;
|
||||
u.put("points", points);
|
||||
u.put("pickDate", LocalDate.now().toString());
|
||||
u.put("pickCount", count + 1);
|
||||
save();
|
||||
return new PickResult(true, cost > 0 ? "本次消耗 " + fmt(cost) + " 积分" : "今日首次免费", choice, cost);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 主题色
|
||||
|
||||
public static String normalizeHex(String hex) {
|
||||
if (hex == null) return "";
|
||||
String h = hex.trim();
|
||||
if (h.startsWith("#")) h = h.substring(1);
|
||||
if (h.startsWith("0x") || h.startsWith("0X")) h = h.substring(2);
|
||||
if (h.length() != 6) return "";
|
||||
for (char c : h.toCharArray()) if (!isHex(c)) return "";
|
||||
return h.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private static boolean isHex(char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||
}
|
||||
|
||||
public static int themeCost(String hex) {
|
||||
String h = normalizeHex(hex);
|
||||
if (h.isEmpty()) return -1;
|
||||
if (h.equals(DEFAULT_THEME_COLOR)) return 0;
|
||||
for (String c : PRESET_COLORS) if (c.equalsIgnoreCase(h)) return PRESET_COLOR_COST;
|
||||
return CUSTOM_COLOR_COST;
|
||||
}
|
||||
|
||||
public synchronized Result buyTheme(String color) {
|
||||
return buyTheme(color, false);
|
||||
}
|
||||
|
||||
public synchronized Result buyTheme(String color, boolean ignoredCustom) {
|
||||
Map<String, Object> u = me();
|
||||
if (u == null) return new Result(false, "请先登录");
|
||||
String hex = normalizeHex(color);
|
||||
if (hex.isEmpty()) return new Result(false, "颜色格式应为 #RRGGBB");
|
||||
int cost = themeCost(hex);
|
||||
String old = normalizeHex(Json.str(u, "themeColor", DEFAULT_THEME_COLOR));
|
||||
if (hex.equals(old)) return new Result(false, "当前已经是这个颜色");
|
||||
double points = Json.d(u, "points", 0);
|
||||
double refunded = 0;
|
||||
double paid = Json.d(u, "themePaid", 0);
|
||||
String paidAt = Json.str(u, "themePaidAt", "");
|
||||
if (paid > 0 && !paidAt.isBlank()) {
|
||||
try {
|
||||
LocalDateTime t = LocalDateTime.parse(paidAt);
|
||||
if (Duration.between(t, LocalDateTime.now()).compareTo(Duration.ofHours(1)) <= 0) {
|
||||
refunded = round2(paid * REFUND_RATE);
|
||||
points += refunded;
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
}
|
||||
if (points < cost) {
|
||||
return new Result(false, refunded > 0
|
||||
? "积分不足(含可退 " + fmt(refunded) + ",需 " + cost + ")"
|
||||
: "积分不足,需要 " + cost + " 积分");
|
||||
}
|
||||
points = round2(points - cost);
|
||||
u.put("points", points);
|
||||
u.put("themeColor", hex);
|
||||
u.put("themePaid", cost);
|
||||
u.put("themePaidAt", cost > 0 ? LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) : "");
|
||||
save();
|
||||
String msg = "已购买并应用主题色 #" + hex;
|
||||
if (refunded > 0) msg = "旧主题退款 +" + fmt(refunded) + " 积分;" + msg;
|
||||
return new Result(true, msg);
|
||||
}
|
||||
|
||||
public synchronized void applySavedTheme(Settings settings) {
|
||||
Map<String, Object> u = me();
|
||||
if (u == null) return;
|
||||
String c = normalizeHex(Json.str(u, "themeColor", DEFAULT_THEME_COLOR));
|
||||
if (!c.isEmpty()) {
|
||||
settings.accentColor = "#" + c;
|
||||
settings.save();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具
|
||||
|
||||
public static String formatPoints(double v) {
|
||||
String s = String.format(Locale.ROOT, "%.2f", v);
|
||||
if (s.endsWith(".00")) return s.substring(0, s.length() - 3);
|
||||
if (s.endsWith("0")) return s.substring(0, s.length() - 1);
|
||||
return s;
|
||||
}
|
||||
|
||||
private static String fmt(double v) { return formatPoints(v); }
|
||||
|
||||
private static double round2(double v) { return Math.round(v * 100.0) / 100.0; }
|
||||
|
||||
private Map<String, Object> me() { return current == null ? null : users.get(current); }
|
||||
|
||||
private int countToday(Map<String, Object> u, String dateKey, String countKey) {
|
||||
return LocalDate.now().toString().equals(Json.str(u, dateKey, "")) ? Json.i(u, countKey, 0) : 0;
|
||||
}
|
||||
|
||||
private int refundSeconds(Map<String, Object> u) {
|
||||
double paid = Json.d(u, "themePaid", 0);
|
||||
if (paid <= 0) return 0;
|
||||
try {
|
||||
LocalDateTime t = LocalDateTime.parse(Json.str(u, "themePaidAt", ""));
|
||||
long left = Duration.ofHours(1).getSeconds()
|
||||
- Duration.between(t, LocalDateTime.now()).getSeconds();
|
||||
return (int) Math.max(0, left);
|
||||
} catch (Exception e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDate date(String s) {
|
||||
try { return s == null || s.isBlank() ? null : LocalDate.parse(s); }
|
||||
catch (Exception e) { return null; }
|
||||
}
|
||||
|
||||
private String newSalt() {
|
||||
byte[] bytes = new byte[16];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getEncoder().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private static String hash(String salt, String password) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-512");
|
||||
return HexFormat.of().formatHex(md.digest((password + ":" + salt).getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.gc.core;
|
||||
|
||||
/** 版本规整与比较,等价于原 GC.Services.VersionUtil。 */
|
||||
public final class VersionUtil {
|
||||
private VersionUtil() {}
|
||||
|
||||
public static String normalize(String tag) {
|
||||
if (tag == null) return "";
|
||||
String s = tag.trim();
|
||||
String lower = s.toLowerCase();
|
||||
if (lower.startsWith("gcl-")) s = s.substring(4);
|
||||
else if (lower.startsWith("gc-")) s = s.substring(3);
|
||||
else if (lower.startsWith("release-")) s = s.substring(8);
|
||||
int i = 0;
|
||||
while (i < s.length() && (s.charAt(i) == 'v' || s.charAt(i) == 'V')) i++;
|
||||
s = s.substring(i);
|
||||
int end = 0;
|
||||
while (end < s.length() && (Character.isDigit(s.charAt(end)) || s.charAt(end) == '.')) end++;
|
||||
s = s.substring(0, end);
|
||||
while (s.endsWith(".")) s = s.substring(0, s.length() - 1);
|
||||
return s;
|
||||
}
|
||||
|
||||
/** 返回 -1 / 0 / 1。 */
|
||||
public static int compare(String a, String b) {
|
||||
int[] aa = parts(normalize(a));
|
||||
int[] bb = parts(normalize(b));
|
||||
int n = Math.max(aa.length, bb.length);
|
||||
for (int i = 0; i < n; i++) {
|
||||
int x = i < aa.length ? aa[i] : 0;
|
||||
int y = i < bb.length ? bb[i] : 0;
|
||||
if (x != y) return Integer.compare(x, y);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int[] parts(String v) {
|
||||
if (v == null || v.isEmpty()) return new int[]{0};
|
||||
String[] p = v.split("\\.");
|
||||
int[] out = new int[p.length];
|
||||
for (int i = 0; i < p.length; i++) {
|
||||
try { out[i] = Integer.parseInt(p[i]); } catch (NumberFormatException e) { out[i] = 0; }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.gc.model.contour;
|
||||
|
||||
import java.awt.Color;
|
||||
|
||||
/** 等高线判读:坡度、局部最高、鞍部、曲率与分层设色。 */
|
||||
public final class TerrainAnalyzer {
|
||||
private TerrainAnalyzer() {}
|
||||
|
||||
public static TerrainField.Feature classify(TerrainField f, double u, double v) {
|
||||
TerrainField.Feature tagged = f.tagAt(u, v);
|
||||
if (tagged != TerrainField.Feature.NONE) return tagged;
|
||||
double[] grad = gradient(f, u, v);
|
||||
double slope = Math.sqrt(grad[0] * grad[0] + grad[1] * grad[1]);
|
||||
if (slope > 8.5) return TerrainField.Feature.CLIFF;
|
||||
if (isLocalMax(f, u, v)) return TerrainField.Feature.PEAK;
|
||||
if (isSaddle(f, u, v)) return TerrainField.Feature.SADDLE;
|
||||
double curvature = crossCurvature(f, u, v, grad);
|
||||
if (curvature < -0.55) return TerrainField.Feature.RIDGE;
|
||||
if (curvature > 0.55) return TerrainField.Feature.VALLEY;
|
||||
return TerrainField.Feature.SLOPE;
|
||||
}
|
||||
|
||||
private static double[] gradient(TerrainField f, double u, double v) {
|
||||
final double h = 0.004;
|
||||
double du = (f.sampleSmooth(u + h, v) - f.sampleSmooth(u - h, v)) / (2 * h) / 1000.0;
|
||||
double dv = (f.sampleSmooth(u, v + h) - f.sampleSmooth(u, v - h)) / (2 * h) / 1000.0;
|
||||
return new double[]{du, dv};
|
||||
}
|
||||
|
||||
private static boolean isLocalMax(TerrainField f, double u, double v) {
|
||||
double c = f.sampleSmooth(u, v);
|
||||
final double r = 0.035;
|
||||
double[][] pts = {{r, 0}, {-r, 0}, {0, r}, {0, -r}};
|
||||
for (double[] d : pts) {
|
||||
if (u + d[0] < 0 || u + d[0] > 1 || v + d[1] < 0 || v + d[1] > 1) return false;
|
||||
if (f.sampleSmooth(u + d[0], v + d[1]) >= c - 4) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isSaddle(TerrainField f, double u, double v) {
|
||||
final double r = 0.05;
|
||||
if (u - r < 0 || u + r > 1 || v - r < 0 || v + r > 1) return false;
|
||||
double c = f.sampleSmooth(u, v);
|
||||
double l = f.sampleSmooth(u - r, v), rt = f.sampleSmooth(u + r, v);
|
||||
double t = f.sampleSmooth(u, v - r), b = f.sampleSmooth(u, v + r);
|
||||
boolean horizHigh = l > c + 8 && rt > c + 8;
|
||||
boolean vertLow = t < c - 8 && b < c - 8;
|
||||
boolean vertHigh = t > c + 8 && b > c + 8;
|
||||
boolean horizLow = l < c - 8 && rt < c - 8;
|
||||
return (horizHigh && vertLow) || (vertHigh && horizLow);
|
||||
}
|
||||
|
||||
private static double crossCurvature(TerrainField f, double u, double v, double[] grad) {
|
||||
double len = Math.sqrt(grad[0] * grad[0] + grad[1] * grad[1]);
|
||||
if (len < 1e-6) return 0;
|
||||
double nU = -grad[1] / len, nV = grad[0] / len;
|
||||
final double r = 0.045;
|
||||
double c = f.sampleSmooth(u, v);
|
||||
if (u + nU * r < 0 || u + nU * r > 1 || v + nV * r < 0 || v + nV * r > 1) return 0;
|
||||
if (u - nU * r < 0 || u - nU * r > 1 || v - nV * r < 0 || v - nV * r > 1) return 0;
|
||||
double a = f.sampleSmooth(u + nU * r, v + nV * r);
|
||||
double b = f.sampleSmooth(u - nU * r, v - nV * r);
|
||||
return (a + b - 2 * c) / 1000.0 * 6.0;
|
||||
}
|
||||
|
||||
public static Color colorForHeight(float h) {
|
||||
if (h < 200) return new Color(0x1E, 0x6B, 0x3A);
|
||||
if (h < 400) return new Color(0x4E, 0x9E, 0x4E);
|
||||
if (h < 600) return new Color(0xA8, 0xC6, 0x66);
|
||||
if (h < 800) return new Color(0xE8, 0xE2, 0x9A);
|
||||
if (h < 1000) return new Color(0xE0, 0xC0, 0x5A);
|
||||
if (h < 1200) return new Color(0xC8, 0x9A, 0x63);
|
||||
if (h < 1400) return new Color(0xA8, 0x74, 0x4C);
|
||||
if (h < 1600) return new Color(0xC8, 0xA8, 0x8C);
|
||||
return new Color(0xF5, 0xF5, 0xF0);
|
||||
}
|
||||
|
||||
public static Color colorSmooth(float h) {
|
||||
Color[] stops = {
|
||||
new Color(0x1E, 0x6B, 0x3A), new Color(0x4E, 0x9E, 0x4E), new Color(0xA8, 0xC6, 0x66),
|
||||
new Color(0xE8, 0xE2, 0x9A), new Color(0xE0, 0xC0, 0x5A), new Color(0xC8, 0x9A, 0x63),
|
||||
new Color(0xA8, 0x74, 0x4C), new Color(0xC8, 0xA8, 0x8C), new Color(0xF5, 0xF5, 0xF0)};
|
||||
double p = Math.max(0, Math.min(stops.length - 1, h / 200.0 - 0.5));
|
||||
int i = (int) Math.floor(p), j = Math.min(i + 1, stops.length - 1);
|
||||
double t = p - i;
|
||||
t = t * t * (3 - 2 * t);
|
||||
return new Color(lerp(stops[i].getRed(), stops[j].getRed(), t),
|
||||
lerp(stops[i].getGreen(), stops[j].getGreen(), t),
|
||||
lerp(stops[i].getBlue(), stops[j].getBlue(), t));
|
||||
}
|
||||
|
||||
private static int lerp(int a, int b, double k) { return (int) Math.max(0, Math.min(255, a + (b - a) * k)); }
|
||||
|
||||
public static String bandName(float h) {
|
||||
if (h < 200) return "200 米以下";
|
||||
if (h < 400) return "200–400 米";
|
||||
if (h < 600) return "400–600 米";
|
||||
if (h < 800) return "600–800 米";
|
||||
if (h < 1000) return "800–1000 米";
|
||||
if (h < 1200) return "1000–1200 米";
|
||||
if (h < 1400) return "1200–1400 米";
|
||||
if (h < 1600) return "1400–1600 米";
|
||||
return "1600 米以上";
|
||||
}
|
||||
|
||||
public static String featureLabel(TerrainField.Feature f) {
|
||||
return switch (f) {
|
||||
case PEAK -> "山峰";
|
||||
case RIDGE -> "山脊";
|
||||
case VALLEY -> "山谷";
|
||||
case SADDLE -> "鞍部";
|
||||
case CLIFF -> "陡崖";
|
||||
case SLOPE -> "坡面";
|
||||
case NONE -> "—";
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
package com.gc.model.contour;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 地形高度场:5 种基本地形 + 5 种典型地貌部位,算法与 C# TerrainField 等价。
|
||||
* 高度单位米,网格正方形,u 向东、v 向南,均为 [0,1]。
|
||||
*/
|
||||
public final class TerrainField {
|
||||
public enum TerrainKind { MOUNTAIN, BASIN, HILL, PLATEAU, PLAIN }
|
||||
public enum LandformKind { PEAK, RIDGE, VALLEY, SADDLE, CLIFF }
|
||||
public enum Feature { NONE, PEAK, RIDGE, VALLEY, SADDLE, CLIFF, SLOPE }
|
||||
|
||||
public record Tag(double u, double v, double radius, Feature feature) {}
|
||||
public record Point(double u, double v) {}
|
||||
public record PeakPoint(double u, double v, float height) {}
|
||||
|
||||
public final int size;
|
||||
public final float[][] heights;
|
||||
public final TerrainKind kind;
|
||||
public final LandformKind landform;
|
||||
public float minHeight, maxHeight;
|
||||
public final List<Tag> tags = new ArrayList<>();
|
||||
public final List<Point> river = new ArrayList<>();
|
||||
public final List<PeakPoint> peaks = new ArrayList<>();
|
||||
public final List<Point> cliffs = new ArrayList<>();
|
||||
|
||||
public TerrainField(TerrainKind kind, int size) {
|
||||
this.size = size;
|
||||
this.kind = kind;
|
||||
this.landform = null;
|
||||
heights = new float[size][size];
|
||||
build(kind);
|
||||
}
|
||||
|
||||
public TerrainField(LandformKind landform, int size) {
|
||||
this.size = size;
|
||||
this.kind = TerrainKind.MOUNTAIN;
|
||||
this.landform = landform;
|
||||
heights = new float[size][size];
|
||||
buildLandform(landform);
|
||||
}
|
||||
|
||||
public float effectiveInterval() {
|
||||
return switch (kind) {
|
||||
case PLAIN -> 5f;
|
||||
case HILL -> 10f;
|
||||
default -> 100f;
|
||||
};
|
||||
}
|
||||
|
||||
public float heightAt(double u, double v) {
|
||||
int x = clamp((int) Math.round(u * (size - 1)), 0, size - 1);
|
||||
int y = clamp((int) Math.round(v * (size - 1)), 0, size - 1);
|
||||
return heights[y][x];
|
||||
}
|
||||
|
||||
public float sampleSmooth(double u, double v) {
|
||||
double fx = clamp(u, 0, 1) * (size - 1);
|
||||
double fy = clamp(v, 0, 1) * (size - 1);
|
||||
int x0 = (int) Math.floor(fx), y0 = (int) Math.floor(fy);
|
||||
int x1 = Math.min(x0 + 1, size - 1), y1 = Math.min(y0 + 1, size - 1);
|
||||
double tx = fx - x0, ty = fy - y0;
|
||||
float h00 = heights[y0][x0], h10 = heights[y0][x1], h01 = heights[y1][x0], h11 = heights[y1][x1];
|
||||
double a = h00 * (1 - tx) + h10 * tx;
|
||||
double b = h01 * (1 - tx) + h11 * tx;
|
||||
return (float) (a * (1 - ty) + b * ty);
|
||||
}
|
||||
|
||||
private void build(TerrainKind k) {
|
||||
switch (k) {
|
||||
case MOUNTAIN -> buildMountain();
|
||||
case BASIN -> buildBasin();
|
||||
case HILL -> buildHill();
|
||||
case PLATEAU -> buildPlateau();
|
||||
case PLAIN -> buildPlain();
|
||||
}
|
||||
buildFeatures();
|
||||
}
|
||||
|
||||
private void buildMountain() {
|
||||
double[][] peaks = {
|
||||
{0.34, 0.34, 1180, 0.26, 0.24}, {0.66, 0.52, 860, 0.20, 0.20},
|
||||
{0.22, 0.70, 520, 0.18, 0.16}, {0.78, 0.22, 430, 0.16, 0.15}};
|
||||
float min = Float.MAX_VALUE, max = -Float.MAX_VALUE;
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double h = 120;
|
||||
for (double[] p : peaks) {
|
||||
double du = (u - p[0]) / p[3], dv = (v - p[1]) / p[4];
|
||||
h += p[2] * Math.exp(-(du * du + dv * dv) * 1.15);
|
||||
}
|
||||
double valley = Math.abs((u - 0.5) * 0.8 + (v - 0.44) * 0.6);
|
||||
h -= 210 * Math.exp(-valley * valley / 0.0016);
|
||||
if (u > 0.86 && v > 0.18 && v < 0.72) h += 260 * smoothStep(0.86, 0.895, u);
|
||||
if (u < 0.3 && v > 0.6) h += 90 * (1 - u / 0.3) * ((v - 0.6) / 0.4);
|
||||
h += 18 * Math.sin(u * 9.1) * Math.cos(v * 7.7);
|
||||
float hf = (float) Math.max(0, h);
|
||||
heights[y][x] = hf; min = Math.min(min, hf); max = Math.max(max, hf);
|
||||
}
|
||||
minHeight = min; maxHeight = max;
|
||||
tags.clear();
|
||||
tags.add(new Tag(0.34, 0.34, 0.045, Feature.PEAK));
|
||||
tags.add(new Tag(0.66, 0.52, 0.042, Feature.PEAK));
|
||||
tags.add(new Tag(0.50, 0.44, 0.055, Feature.SADDLE));
|
||||
tags.add(new Tag(0.90, 0.45, 0.035, Feature.CLIFF));
|
||||
tags.add(new Tag(0.22, 0.70, 0.045, Feature.RIDGE));
|
||||
tags.add(new Tag(0.50, 0.22, 0.040, Feature.VALLEY));
|
||||
}
|
||||
|
||||
private void buildBasin() {
|
||||
float min = Float.MAX_VALUE, max = -Float.MAX_VALUE;
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double du = u - 0.5, dv = v - 0.5, r = Math.sqrt(du * du + dv * dv) * 2.0;
|
||||
double h = 160 + 900 * Math.pow(clamp(r, 0, 1.15), 2.2);
|
||||
double gap = Math.abs(Math.atan2(dv, du) - 0.5);
|
||||
if (gap < 0.35) h -= 320 * (1 - gap / 0.35) * (1 - clamp(r, 0, 1));
|
||||
h += 14 * Math.sin(u * 7.3) * Math.cos(v * 6.1);
|
||||
float hf = (float) Math.max(0, h);
|
||||
heights[y][x] = hf; min = Math.min(min, hf); max = Math.max(max, hf);
|
||||
}
|
||||
minHeight = min; maxHeight = max;
|
||||
tags.clear();
|
||||
tags.add(new Tag(0.50, 0.50, 0.10, Feature.SLOPE));
|
||||
}
|
||||
|
||||
private void buildHill() {
|
||||
double[][] bumps = {{0.30, 0.32, 120, 0.20}, {0.66, 0.28, 95, 0.17}, {0.52, 0.62, 140, 0.22},
|
||||
{0.22, 0.72, 88, 0.16}, {0.78, 0.70, 110, 0.18}};
|
||||
float min = Float.MAX_VALUE, max = -Float.MAX_VALUE;
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double h = 60;
|
||||
for (double[] b : bumps) {
|
||||
double du = (u - b[0]) / b[3], dv = (v - b[1]) / b[3];
|
||||
h += b[2] * Math.exp(-(du * du + dv * dv) * 1.3);
|
||||
}
|
||||
h += 10 * Math.sin(u * 11.0) * Math.cos(v * 9.0);
|
||||
float hf = (float) Math.max(0, h);
|
||||
heights[y][x] = hf; min = Math.min(min, hf); max = Math.max(max, hf);
|
||||
}
|
||||
minHeight = min; maxHeight = max;
|
||||
}
|
||||
|
||||
private void buildPlateau() {
|
||||
float min = Float.MAX_VALUE, max = -Float.MAX_VALUE;
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double du = u - 0.5, dv = v - 0.5, r = Math.sqrt(du * du + dv * dv) * 2.0;
|
||||
double h = r < 0.55 ? 1250 : 1250 - 1000 * smoothStep(0.55, 0.78, r);
|
||||
if (r < 0.55) h += 25 * Math.sin(u * 6.0) * Math.cos(v * 5.0);
|
||||
h += 30 * (1 - clamp(r, 0, 1));
|
||||
float hf = (float) Math.max(0, h);
|
||||
heights[y][x] = hf; min = Math.min(min, hf); max = Math.max(max, hf);
|
||||
}
|
||||
minHeight = min; maxHeight = max;
|
||||
tags.clear();
|
||||
tags.add(new Tag(0.50, 0.50, 0.15, Feature.SLOPE));
|
||||
}
|
||||
|
||||
private void buildPlain() {
|
||||
float min = Float.MAX_VALUE, max = -Float.MAX_VALUE;
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double h = 40 + 22 * u + 8 * Math.sin(u * 4.2) * Math.cos(v * 3.6);
|
||||
float hf = (float) Math.max(0, h);
|
||||
heights[y][x] = hf; min = Math.min(min, hf); max = Math.max(max, hf);
|
||||
}
|
||||
minHeight = min; maxHeight = max;
|
||||
}
|
||||
|
||||
private void buildLandform(LandformKind landform) {
|
||||
switch (landform) {
|
||||
case PEAK -> buildPeak();
|
||||
case RIDGE -> buildRidge();
|
||||
case VALLEY -> buildValley();
|
||||
case SADDLE -> buildSaddle();
|
||||
case CLIFF -> buildCliff();
|
||||
}
|
||||
buildFeatures();
|
||||
}
|
||||
|
||||
private void buildPeak() {
|
||||
float min = Float.MAX_VALUE;
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double du = u - 0.5, dv = (v - 0.5) / 0.94;
|
||||
double r = Math.sqrt(du * du + dv * dv);
|
||||
double core = Math.exp(-Math.pow(r / 0.36, 1.85));
|
||||
double rim = 1 - smoothStep(0.36, 0.50, r);
|
||||
double 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;
|
||||
setAndTrack((float) Math.max(0, h), x, y);
|
||||
}
|
||||
tags.clear();
|
||||
tags.add(new Tag(0.5, 0.5, 0.09, Feature.PEAK));
|
||||
}
|
||||
|
||||
private void buildRidge() {
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double crestV = 0.5 + 0.10 * Math.sin(u * 3.1);
|
||||
double across = v - crestV;
|
||||
double crest = 1150 - 380 * u;
|
||||
double lateral = Math.exp(-Math.pow(Math.abs(across) / 0.27, 1.55));
|
||||
double 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);
|
||||
setAndTrack((float) Math.max(0, h), x, y);
|
||||
}
|
||||
tags.clear();
|
||||
tags.add(new Tag(0.30, 0.50, 0.09, Feature.RIDGE));
|
||||
tags.add(new Tag(0.70, 0.50, 0.09, Feature.RIDGE));
|
||||
}
|
||||
|
||||
private void buildValley() {
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double side = Math.pow(Math.abs(u - 0.5) / 0.5, 1.5);
|
||||
double downhill = 1 - v;
|
||||
double 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);
|
||||
setAndTrack((float) Math.max(0, h), x, y);
|
||||
}
|
||||
tags.clear();
|
||||
tags.add(new Tag(0.50, 0.40, 0.075, Feature.VALLEY));
|
||||
tags.add(new Tag(0.50, 0.68, 0.075, Feature.VALLEY));
|
||||
}
|
||||
|
||||
private void buildSaddle() {
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double d1 = Math.sqrt(Math.pow((u - 0.27) / 0.30, 2) + Math.pow((v - 0.52) / 0.28, 2));
|
||||
double d2 = Math.sqrt(Math.pow((u - 0.73) / 0.30, 2) + Math.pow((v - 0.48) / 0.28, 2));
|
||||
double p1 = 1140 * Math.exp(-Math.pow(d1, 2.2));
|
||||
double p2 = 1060 * Math.exp(-Math.pow(d2, 2.2));
|
||||
double bench = 330 * Math.exp(-Math.pow((v - 0.5) / 0.34, 2));
|
||||
double h = 65 + bench + Math.max(p1, p2);
|
||||
h += 20 * Math.sin(u * 8.0) * Math.cos(v * 7.0);
|
||||
setAndTrack((float) Math.max(0, h), x, y);
|
||||
}
|
||||
tags.clear();
|
||||
tags.add(new Tag(0.28, 0.50, 0.05, Feature.PEAK));
|
||||
tags.add(new Tag(0.72, 0.50, 0.05, Feature.PEAK));
|
||||
tags.add(new Tag(0.50, 0.50, 0.045, Feature.SADDLE));
|
||||
}
|
||||
|
||||
private void buildCliff() {
|
||||
for (int y = 0; y < size; y++) for (int x = 0; x < size; x++) {
|
||||
double u = (double) x / (size - 1), v = (double) y / (size - 1);
|
||||
double edge = smoothStep(0.50, 0.62, u + 0.045 * Math.sin(v * 5.2) + 0.02 * Math.sin(v * 11.0));
|
||||
double 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);
|
||||
setAndTrack((float) Math.max(0, h), x, y);
|
||||
}
|
||||
tags.clear();
|
||||
tags.add(new Tag(0.50, 0.50, 0.035, Feature.CLIFF));
|
||||
}
|
||||
|
||||
private void setAndTrack(float h, int x, int y) {
|
||||
heights[y][x] = h;
|
||||
if (h < minHeight) minHeight = h;
|
||||
if (h > maxHeight) maxHeight = h;
|
||||
}
|
||||
|
||||
public Feature tagAt(double u, double v) {
|
||||
for (Tag t : tags) {
|
||||
double du = u - t.u(), dv = v - t.v();
|
||||
if (du * du + dv * dv <= t.radius() * t.radius()) return t.feature();
|
||||
}
|
||||
return Feature.NONE;
|
||||
}
|
||||
|
||||
private void buildFeatures() {
|
||||
heights[0][0] = heights[0][0]; // ensure arrays initialized
|
||||
computeMinMax();
|
||||
final int step = 4;
|
||||
for (int y = step; y < size - step; y += step) for (int x = step; x < size - step; x += step) {
|
||||
float h = heights[y][x];
|
||||
if (h < maxHeight * 0.55f) continue;
|
||||
boolean isMax = true;
|
||||
for (int dy = -step; dy <= step && isMax; dy += step)
|
||||
for (int dx = -step; dx <= step; dx += step) {
|
||||
if (dx == 0 && dy == 0) continue;
|
||||
if (heights[y + dy][x + dx] > h) { isMax = false; break; }
|
||||
}
|
||||
if (isMax) peaks.add(new PeakPoint((double) x / (size - 1), (double) y / (size - 1), h));
|
||||
}
|
||||
peaks.sort((a, b) -> Float.compare(b.height(), a.height()));
|
||||
final int cstep = 3;
|
||||
double h = 0.004;
|
||||
for (int y = cstep; y < size - cstep; y += cstep) for (int x = cstep; x < size - cstep; x += cstep) {
|
||||
double du = (heights[y][x + 2] - heights[y][x - 2]) / (2 * h * (size - 1)) / 1000;
|
||||
double dv = (heights[y + 2][x] - heights[y - 2][x]) / (2 * h * (size - 1)) / 1000;
|
||||
if (Math.sqrt(du * du + dv * dv) > 0.11)
|
||||
cliffs.add(new Point((double) x / (size - 1), (double) y / (size - 1)));
|
||||
}
|
||||
if (!peaks.isEmpty()) {
|
||||
PeakPoint start = peaks.get(0);
|
||||
double cu = start.u(), cv = start.v();
|
||||
river.add(new Point(cu, cv));
|
||||
for (int i = 0; i < 400; i++) {
|
||||
double h0 = sampleSmooth(cu, cv), bestU = 0, bestV = 0, bestH = h0;
|
||||
boolean found = false;
|
||||
for (int a = 0; a < 16; a++) {
|
||||
double ang = a * Math.PI * 2 / 16;
|
||||
double nu = cu + Math.cos(ang) * 0.012, nv = cv + Math.sin(ang) * 0.012;
|
||||
if (nu < 0 || nu > 1 || nv < 0 || nv > 1) continue;
|
||||
double nh = sampleSmooth(nu, nv);
|
||||
if (nh < bestH) { bestH = nh; bestU = nu; bestV = nv; found = true; }
|
||||
}
|
||||
if (!found) break;
|
||||
cu = bestU; cv = bestV;
|
||||
river.add(new Point(cu, cv));
|
||||
if (cu <= 0.001 || cu >= 0.999 || cv <= 0.001 || cv >= 0.999 || bestH < minHeight + 20) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void computeMinMax() {
|
||||
float min = Float.MAX_VALUE, max = -Float.MAX_VALUE;
|
||||
for (float[] row : heights) for (float v : row) { min = Math.min(min, v); max = Math.max(max, v); }
|
||||
minHeight = min; maxHeight = max;
|
||||
}
|
||||
|
||||
public List<Float> contourLevels() {
|
||||
List<Float> levels = new ArrayList<>();
|
||||
float iv = effectiveInterval();
|
||||
float top = (float) (Math.floor(maxHeight / iv) * iv);
|
||||
float bottom = (float) (Math.ceil(minHeight / iv) * iv);
|
||||
for (float h = bottom; h <= top + 0.01f; h += iv) levels.add(h);
|
||||
return levels;
|
||||
}
|
||||
|
||||
public List<List<Point>> extractContour(float level) {
|
||||
List<double[]> segs = new ArrayList<>();
|
||||
for (int y = 0; y < size - 1; y++) for (int x = 0; x < size - 1; x++) {
|
||||
float h00 = heights[y][x], h10 = heights[y][x + 1], h11 = heights[y + 1][x + 1], h01 = heights[y + 1][x];
|
||||
int idx = 0;
|
||||
if (h00 >= level) idx |= 1;
|
||||
if (h10 >= level) idx |= 2;
|
||||
if (h11 >= level) idx |= 4;
|
||||
if (h01 >= level) idx |= 8;
|
||||
if (idx == 0 || idx == 15) continue;
|
||||
double u0 = (double) x / (size - 1), u1 = (double) (x + 1) / (size - 1);
|
||||
double v0 = (double) y / (size - 1), v1 = (double) (y + 1) / (size - 1);
|
||||
double[] top = {lerp(u0, u1, (level - h00) / (h10 - h00)), v0};
|
||||
double[] bottom = {lerp(u0, u1, (level - h01) / (h11 - h01)), v1};
|
||||
double[] left = {u0, lerp(v0, v1, (level - h00) / (h01 - h00))};
|
||||
double[] right = {u1, lerp(v0, v1, (level - h10) / (h11 - h10))};
|
||||
switch (idx) {
|
||||
case 1, 14 -> addSeg(segs, left, top);
|
||||
case 2, 13 -> addSeg(segs, top, right);
|
||||
case 3, 12 -> addSeg(segs, left, right);
|
||||
case 4, 11 -> addSeg(segs, right, bottom);
|
||||
case 6, 9 -> addSeg(segs, top, bottom);
|
||||
case 7, 8 -> addSeg(segs, left, bottom);
|
||||
case 5 -> { addSeg(segs, left, top); addSeg(segs, right, bottom); }
|
||||
case 10 -> { addSeg(segs, top, right); addSeg(segs, left, bottom); }
|
||||
}
|
||||
}
|
||||
return chain(segs);
|
||||
}
|
||||
|
||||
private static void addSeg(List<double[]> segs, double[] a, double[] b) {
|
||||
segs.add(new double[]{a[0], a[1], b[0], b[1]});
|
||||
}
|
||||
|
||||
private static List<List<Point>> chain(List<double[]> segments) {
|
||||
final double Q = 1e4;
|
||||
Map<Long, List<Integer>> index = new HashMap<>();
|
||||
for (int i = 0; i < segments.size(); i++) {
|
||||
double[] s = segments.get(i);
|
||||
register(index, s[0], s[1], i, Q);
|
||||
register(index, s[2], s[3], i, Q);
|
||||
}
|
||||
boolean[] used = new boolean[segments.size()];
|
||||
List<List<Point>> result = new ArrayList<>();
|
||||
for (int i = 0; i < segments.size(); i++) {
|
||||
if (used[i]) continue;
|
||||
used[i] = true;
|
||||
double[] s = segments.get(i);
|
||||
LinkedList<Point> line = new LinkedList<>();
|
||||
line.add(new Point(s[0], s[1])); line.add(new Point(s[2], s[3]));
|
||||
while (true) {
|
||||
Point tail = line.getLast();
|
||||
int j = next(index, used, tail.u(), tail.v(), Q);
|
||||
if (j < 0) break;
|
||||
used[j] = true;
|
||||
double[] n = segments.get(j);
|
||||
line.add(key(n[0], n[1], Q) == key(tail.u(), tail.v(), Q)
|
||||
? new Point(n[2], n[3]) : new Point(n[0], n[1]));
|
||||
}
|
||||
while (true) {
|
||||
Point head = line.getFirst();
|
||||
int j = next(index, used, head.u(), head.v(), Q);
|
||||
if (j < 0) break;
|
||||
used[j] = true;
|
||||
double[] n = segments.get(j);
|
||||
line.addFirst(key(n[0], n[1], Q) == key(head.u(), head.v(), Q)
|
||||
? new Point(n[2], n[3]) : new Point(n[0], n[1]));
|
||||
}
|
||||
if (line.size() >= 3) result.add(new ArrayList<>(line));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void register(Map<Long, List<Integer>> index, double u, double v, int seg, double q) {
|
||||
index.computeIfAbsent(key(u, v, q), k -> new ArrayList<>()).add(seg);
|
||||
}
|
||||
private static long key(double u, double v, double q) {
|
||||
long a = Math.round(u * q), b = Math.round(v * q);
|
||||
return (a << 32) ^ (b & 0xffffffffL);
|
||||
}
|
||||
private static int next(Map<Long, List<Integer>> index, boolean[] used, double u, double v, double q) {
|
||||
List<Integer> list = index.get(key(u, v, q));
|
||||
if (list == null) return -1;
|
||||
for (int j : list) if (!used[j]) return j;
|
||||
return -1;
|
||||
}
|
||||
|
||||
public double slopeAt(double u, double v) {
|
||||
double h = 0.006;
|
||||
double du = (sampleSmooth(u + h, v) - sampleSmooth(u - h, v)) / (2 * h);
|
||||
double dv = (sampleSmooth(u, v + h) - sampleSmooth(u, v - h)) / (2 * h);
|
||||
double grad = Math.sqrt(du * du + dv * dv);
|
||||
double span = Math.max(60, maxHeight - minHeight);
|
||||
return clamp(grad / (span * 2.6), 0, 1);
|
||||
}
|
||||
|
||||
private static double smoothStep(double a, double b, double x) {
|
||||
double t = clamp((x - a) / (b - a), 0, 1);
|
||||
return t * t * (3 - 2 * t);
|
||||
}
|
||||
private static double lerp(double a, double b, double t) {
|
||||
if (Double.isNaN(t)) t = 0.5;
|
||||
return a + (b - a) * clamp(t, 0, 1);
|
||||
}
|
||||
private static double clamp(double v, double lo, double hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
private static int clamp(int v, int lo, int hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.gc.model.earth;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/** 地球自转 / 公转 / 地理的共享公式,与 C# CelestialView、GeoModels 一致。 */
|
||||
public final class EarthMath {
|
||||
public static final double TILT = 23.5;
|
||||
public static final double TROPIC = 23.5;
|
||||
public static final double POLAR = 90 - 23.5;
|
||||
|
||||
public record Season(double angleDeg, String key, String date, double declinationDeg, String zh, String en) {}
|
||||
public record Zone(String id, double latMin, double latMax, String nameZh, String nameEn) {}
|
||||
|
||||
public static final List<Season> SEASONS = List.of(
|
||||
new Season(0, "season.springEquinox", "3/21", 0,
|
||||
"太阳直射赤道,全球昼夜平分。", "The Sun is overhead at the equator; day equals night everywhere."),
|
||||
new Season(90, "season.summerSolstice", "6/22", 23.5,
|
||||
"太阳直射北回归线 23.5°N,北半球昼最长。", "The Sun is overhead at 23.5°N; the northern hemisphere has its longest day."),
|
||||
new Season(180, "season.autumnEquinox", "9/23", 0,
|
||||
"太阳直射赤道,全球昼夜平分。", "The Sun is overhead at the equator; day equals night everywhere."),
|
||||
new Season(270, "season.winterSolstice", "12/22", -23.5,
|
||||
"太阳直射南回归线 23.5°S,北半球昼最短。", "The Sun is overhead at 23.5°S; the northern hemisphere has its shortest day.")
|
||||
);
|
||||
|
||||
public static final List<Zone> ZONES = List.of(
|
||||
new Zone("torrid", -23.5, 23.5, "热带", "Torrid zone"),
|
||||
new Zone("northTemperate", 23.5, 66.5, "北温带", "North temperate zone"),
|
||||
new Zone("southTemperate", -66.5, -23.5, "南温带", "South temperate zone"),
|
||||
new Zone("northFrigid", 66.5, 90, "北寒带", "North frigid zone"),
|
||||
new Zone("southFrigid", -90, -66.5, "南寒带", "South frigid zone")
|
||||
);
|
||||
|
||||
private EarthMath() {}
|
||||
|
||||
public static double subsolarLatitude(double orbitDeg) { return subsolarLatitude(orbitDeg, TILT); }
|
||||
|
||||
public static double subsolarLatitude(double orbitDeg, double tiltDeg) {
|
||||
double o = Math.toRadians(orbitDeg);
|
||||
double t = Math.toRadians(tiltDeg);
|
||||
return Math.toDegrees(Math.asin(Math.sin(t) * Math.sin(o)));
|
||||
}
|
||||
|
||||
public static LocalDate dateForAngle(double deg) {
|
||||
double days = 79 + deg / 360.0 * 365.2422;
|
||||
return LocalDate.of(2025, 1, 1).plusDays(Math.round(days));
|
||||
}
|
||||
|
||||
public static String dateText(double deg) {
|
||||
LocalDate d = dateForAngle(deg);
|
||||
return d.getMonthValue() + "/" + d.getDayOfMonth();
|
||||
}
|
||||
|
||||
public static Season nearestSeason(double orbitDeg) {
|
||||
double o = ((orbitDeg % 360) + 360) % 360;
|
||||
Season best = SEASONS.get(0);
|
||||
double bestDiff = 360;
|
||||
for (Season s : SEASONS) {
|
||||
double diff = Math.abs(o - s.angleDeg());
|
||||
diff = Math.min(diff, 360 - diff);
|
||||
if (diff < bestDiff) { bestDiff = diff; best = s; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** 返回 {spin, orbit}。 */
|
||||
public static double[] stepAngles(double spinDeg, double orbitDeg, double dtSeconds, double speed) {
|
||||
double spin = (spinDeg + dtSeconds * speed * 60) % 360;
|
||||
double orbit = (orbitDeg + dtSeconds * speed * 12) % 360;
|
||||
if (spin < 0) spin += 360;
|
||||
if (orbit < 0) orbit += 360;
|
||||
return new double[]{spin, orbit};
|
||||
}
|
||||
|
||||
public static double[] latLonToUnit(double latDeg, double lonDeg) {
|
||||
double lat = Math.toRadians(latDeg), lon = Math.toRadians(lonDeg);
|
||||
return new double[]{Math.cos(lat) * Math.sin(lon), Math.sin(lat), Math.cos(lat) * Math.cos(lon)};
|
||||
}
|
||||
|
||||
public static String zoneId(double lat) {
|
||||
double a = Math.abs(lat);
|
||||
if (a < 23.5) return "torrid";
|
||||
if (a < 66.5) return lat >= 0 ? "northTemperate" : "southTemperate";
|
||||
return lat >= 0 ? "northFrigid" : "southFrigid";
|
||||
}
|
||||
|
||||
public static Zone zone(double lat) {
|
||||
String id = zoneId(lat);
|
||||
for (Zone z : ZONES) if (z.id().equals(id)) return z;
|
||||
return ZONES.get(0);
|
||||
}
|
||||
|
||||
public static String zoneName(double lat) {
|
||||
Zone z = zone(lat);
|
||||
return "zh".equals(com.gc.core.I18n.language().substring(0, 2)) ? z.nameZh() : z.nameEn();
|
||||
}
|
||||
|
||||
public static String declination(double lat) {
|
||||
String id = zoneId(lat);
|
||||
if (id.equals("torrid")) return "tropics";
|
||||
String[] p = id.split("-");
|
||||
StringBuilder sb = new StringBuilder(p[0]);
|
||||
for (int i = 1; i < p.length; i++) sb.append(Character.toUpperCase(p[i].charAt(0))).append(p[i].substring(1));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** 地理模型:把某纬度投影到画布 y。 */
|
||||
public static double latToY(double lat, double height) {
|
||||
return (90 - lat) / 180.0 * height;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.gc.model.scale;
|
||||
|
||||
import com.gc.core.Json;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** scales.json 预设 / 光谱 / 地标;文件缺失时用与 C# 相同的兜底数据。 */
|
||||
public final class ScaleData {
|
||||
public record Preset(double n, String nameKey, String noteKey) {}
|
||||
public record Spectrum(double n, String labelKey, String scopeKey) {}
|
||||
public record Landmark(String nameKey, double meters) {}
|
||||
|
||||
public final List<Preset> presets = new ArrayList<>();
|
||||
public final List<Spectrum> spectrum = new ArrayList<>();
|
||||
public final List<Landmark> landmarks = new ArrayList<>();
|
||||
|
||||
public static ScaleData load(Path dataDir) {
|
||||
ScaleData d = fallback();
|
||||
Path p = dataDir.resolve("scales.json");
|
||||
if (!Files.isRegularFile(p)) return d;
|
||||
try {
|
||||
Map<String, Object> m = Json.obj(Json.parse(p));
|
||||
List<Preset> ps = new ArrayList<>();
|
||||
for (Object o : Json.arr(m.get("presets"))) {
|
||||
Map<String, Object> x = Json.obj(o);
|
||||
ps.add(new Preset(Json.d(x, "n", 0), Json.str(x, "nameKey", ""), Json.str(x, "noteKey", "")));
|
||||
}
|
||||
if (ps.isEmpty()) return d;
|
||||
d.presets.clear(); d.presets.addAll(ps);
|
||||
d.spectrum.clear();
|
||||
for (Object o : Json.arr(m.get("spectrum"))) {
|
||||
Map<String, Object> x = Json.obj(o);
|
||||
d.spectrum.add(new Spectrum(Json.d(x, "n", 0), Json.str(x, "labelKey", ""), Json.str(x, "scopeKey", "")));
|
||||
}
|
||||
d.landmarks.clear();
|
||||
for (Object o : Json.arr(m.get("landmarks"))) {
|
||||
Map<String, Object> x = Json.obj(o);
|
||||
d.landmarks.add(new Landmark(Json.str(x, "nameKey", ""), Json.d(x, "meters", 0)));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("[scale] 读取 scales.json 失败: " + e.getMessage());
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
public static ScaleData fallback() {
|
||||
ScaleData d = new ScaleData();
|
||||
d.presets.add(new Preset(10000, "preset.campus", "preset.campusNote"));
|
||||
d.presets.add(new Preset(50000, "preset.town", "preset.townNote"));
|
||||
d.presets.add(new Preset(250000, "preset.city", "preset.cityNote"));
|
||||
d.presets.add(new Preset(1000000, "preset.province", "preset.provinceNote"));
|
||||
d.presets.add(new Preset(10000000, "preset.china", "preset.chinaNote"));
|
||||
d.presets.add(new Preset(100000000, "preset.world", "preset.worldNote"));
|
||||
d.spectrum.add(new Spectrum(10000, "spec.campus", "spec.campusScope"));
|
||||
d.spectrum.add(new Spectrum(250000, "spec.city", "spec.cityScope"));
|
||||
d.spectrum.add(new Spectrum(10000000, "spec.china", "spec.chinaScope"));
|
||||
d.spectrum.add(new Spectrum(100000000, "spec.world", "spec.worldScope"));
|
||||
d.landmarks.add(new Landmark("lm.classroom", 10));
|
||||
d.landmarks.add(new Landmark("lm.track", 400));
|
||||
d.landmarks.add(new Landmark("lm.marathon", 42195));
|
||||
d.landmarks.add(new Landmark("lm.beijingShanghai", 1080000));
|
||||
d.landmarks.add(new Landmark("lm.equator", 40000000));
|
||||
return d;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.gc.model.scale;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Random;
|
||||
|
||||
/** 比例尺算法,逐字对应 C# GC.ScaleCalculator.ScaleMath。 */
|
||||
public final class ScaleMath {
|
||||
public static final double CM_PER_M = 100.0;
|
||||
public static final double CM_PER_KM = 100000.0;
|
||||
|
||||
public enum SolveMode { REAL, MAP, SCALE }
|
||||
public enum Grade { LARGE, MEDIUM, SMALL }
|
||||
|
||||
public static final class State {
|
||||
public double mapCm = 3.0;
|
||||
public double realCm = 300000.0;
|
||||
public double n = 100000.0;
|
||||
public SolveMode mode = SolveMode.REAL;
|
||||
public State copy() {
|
||||
State s = new State(); s.mapCm = mapCm; s.realCm = realCm; s.n = n; s.mode = mode; return s;
|
||||
}
|
||||
}
|
||||
|
||||
public record Segment(double metersPerDiv, double divPx, int divCount) {}
|
||||
public record Human(double value, String unitKey) {}
|
||||
public static final class Quiz {
|
||||
public SolveMode mode;
|
||||
public String promptKey = "";
|
||||
public Object[] promptArgs = new Object[0];
|
||||
public double answer;
|
||||
public double tolerance = 0.02;
|
||||
public String answerUnitKey = "unit.cm";
|
||||
public String[] stepKeys = new String[0];
|
||||
}
|
||||
|
||||
private ScaleMath() {}
|
||||
|
||||
public static void solve(State s) {
|
||||
if (s.mapCm < 0) s.mapCm = 0;
|
||||
if (s.realCm < 0) s.realCm = 0;
|
||||
if (s.n < 1) s.n = 1;
|
||||
switch (s.mode) {
|
||||
case REAL -> s.realCm = s.mapCm * s.n;
|
||||
case MAP -> s.mapCm = s.n > 0 ? s.realCm / s.n : 0;
|
||||
case SCALE -> {
|
||||
s.n = s.mapCm > 1e-9 ? s.realCm / s.mapCm : 1;
|
||||
if (s.n < 1) s.n = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Human humanReal(double cm) {
|
||||
if (cm < CM_PER_M) return new Human(cm, "unit.cm");
|
||||
if (cm < CM_PER_KM) return new Human(cm / CM_PER_M, "unit.m");
|
||||
return new Human(cm / CM_PER_KM, "unit.km");
|
||||
}
|
||||
|
||||
public static String num(double v) {
|
||||
if (Double.isNaN(v) || Double.isInfinite(v)) return "—";
|
||||
double a = Math.abs(v);
|
||||
if (a >= 1000) return String.format(Locale.ROOT, "%,.0f", v);
|
||||
if (a >= 10) return trim(v, "%.1f");
|
||||
if (a >= 1) return trim(v, "%.2f");
|
||||
if (a >= 0.01) return trim(v, "%.3f");
|
||||
if (a == 0) return "0";
|
||||
return trim(v, "%.4f");
|
||||
}
|
||||
|
||||
private static String trim(double v, String fmt) {
|
||||
String s = String.format(Locale.ROOT, fmt, v);
|
||||
if (s.contains(".")) {
|
||||
s = s.replaceAll("0+$", "");
|
||||
if (s.endsWith(".")) s = s.substring(0, s.length() - 1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String formatRealCm(double cm) {
|
||||
Human h = humanReal(cm);
|
||||
return num(h.value()) + " " + h.unitKey();
|
||||
}
|
||||
|
||||
public static String formatN(double n) { return num(Math.round(n)); }
|
||||
|
||||
public static String digital(double n) { return "1 : " + formatN(n); }
|
||||
|
||||
public static String verbalDistance(double n) {
|
||||
Human h = humanReal(n);
|
||||
return num(h.value()) + " " + h.unitKey();
|
||||
}
|
||||
|
||||
public static double realToMapCm(double realCm, double n) { return n > 0 ? realCm / n : 0; }
|
||||
public static double cmToPx(double cm, double pxPerCm) { return cm * pxPerCm; }
|
||||
public static double realToMapPx(double realCm, double n, double pxPerCm) {
|
||||
return realToMapCm(realCm, n) * pxPerCm;
|
||||
}
|
||||
|
||||
public static Segment pickSegment(double n, double pxPerCm, double targetPx) {
|
||||
if (n < 1) n = 1;
|
||||
if (pxPerCm < 1) pxPerCm = 1;
|
||||
double idealMeters = targetPx * n / (100.0 * pxPerCm);
|
||||
if (idealMeters <= 0) idealMeters = 1;
|
||||
double best = 1, bestErr = Double.MAX_VALUE;
|
||||
double logIdeal = Math.log10(idealMeters);
|
||||
for (int k = -3; k <= 9; k++) {
|
||||
for (double m : new double[]{1, 2, 5}) {
|
||||
double cand = m * Math.pow(10, k);
|
||||
double err = Math.abs(Math.log10(cand) - logIdeal);
|
||||
if (err < bestErr) { bestErr = err; best = cand; }
|
||||
}
|
||||
}
|
||||
double divPx = best * 100.0 / n * pxPerCm;
|
||||
int count = 5;
|
||||
double total = divPx * count;
|
||||
if (total > targetPx * 9) count = 4;
|
||||
else if (total < targetPx * 2.5) count = 6;
|
||||
return new Segment(best, divPx, count);
|
||||
}
|
||||
|
||||
public static String segmentLabel(double meters) {
|
||||
if (meters < 1) return num(meters * 100) + " cm";
|
||||
if (meters < 1000) return num(meters) + " m";
|
||||
return num(meters / 1000) + " km";
|
||||
}
|
||||
|
||||
public static Grade grade(double n) {
|
||||
if (n <= 100000) return Grade.LARGE;
|
||||
if (n <= 1000000) return Grade.MEDIUM;
|
||||
return Grade.SMALL;
|
||||
}
|
||||
|
||||
public static String gradeKey(double n) {
|
||||
return switch (grade(n)) {
|
||||
case LARGE -> "grade.large";
|
||||
case MEDIUM -> "grade.medium";
|
||||
default -> "grade.small";
|
||||
};
|
||||
}
|
||||
|
||||
public static double spectrumPosition(double n) {
|
||||
if (n < 1) n = 1;
|
||||
double p = (Math.log10(n) - 3.0) / 6.0;
|
||||
return p < 0 ? 0 : Math.min(p, 1);
|
||||
}
|
||||
|
||||
public static Double tryParseReal(String text, String unitKey) {
|
||||
try {
|
||||
double v = Double.parseDouble(text.replace(",", "").trim());
|
||||
if (v < 0 || Double.isNaN(v) || Double.isInfinite(v)) return null;
|
||||
return switch (unitKey) {
|
||||
case "unit.m" -> v * CM_PER_M;
|
||||
case "unit.km" -> v * CM_PER_KM;
|
||||
default -> v;
|
||||
};
|
||||
} catch (Exception e) { return null; }
|
||||
}
|
||||
|
||||
public static double toUnit(double cm, String unitKey) {
|
||||
return switch (unitKey) {
|
||||
case "unit.m" -> cm / CM_PER_M;
|
||||
case "unit.km" -> cm / CM_PER_KM;
|
||||
default -> cm;
|
||||
};
|
||||
}
|
||||
|
||||
public static Quiz generateQuiz(Random rnd) {
|
||||
SolveMode mode = SolveMode.values()[rnd.nextInt(3)];
|
||||
double[] maps = {1, 2, 2.5, 3, 4, 5, 6, 8, 10, 12};
|
||||
double[] ns = {1000, 5000, 10000, 25000, 50000, 100000, 500000, 1000000, 5000000, 10000000};
|
||||
double mapCm = maps[rnd.nextInt(maps.length)];
|
||||
double n = ns[rnd.nextInt(ns.length)];
|
||||
Quiz q = new Quiz();
|
||||
q.mode = mode;
|
||||
switch (mode) {
|
||||
case REAL -> {
|
||||
double realCm = mapCm * n;
|
||||
Human h = humanReal(realCm);
|
||||
q.promptKey = "quiz.promptReal";
|
||||
q.promptArgs = new Object[]{formatN(n), num(mapCm)};
|
||||
q.answer = h.value();
|
||||
q.answerUnitKey = h.unitKey();
|
||||
q.stepKeys = new String[]{"steps.2.formulaReal", "steps.4.result"};
|
||||
}
|
||||
case MAP -> {
|
||||
double realCm = mapCm * n;
|
||||
Human h = humanReal(realCm);
|
||||
q.promptKey = "quiz.promptMap";
|
||||
q.promptArgs = new Object[]{formatN(n), num(h.value())};
|
||||
q.answer = mapCm;
|
||||
q.answerUnitKey = "unit.cm";
|
||||
q.stepKeys = new String[]{"steps.2.formulaMap", "steps.4.result"};
|
||||
}
|
||||
case SCALE -> {
|
||||
double realCm = mapCm * n;
|
||||
Human h = humanReal(realCm);
|
||||
q.promptKey = "quiz.promptScale";
|
||||
q.promptArgs = new Object[]{num(mapCm), num(h.value())};
|
||||
q.answer = n;
|
||||
q.answerUnitKey = "unit.none";
|
||||
q.stepKeys = new String[]{"steps.1.unify", "steps.2.formulaScale", "steps.4.result"};
|
||||
}
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
public static boolean checkAnswer(Quiz q, double input) {
|
||||
if (q.answer <= 0) return false;
|
||||
return Math.abs(input - q.answer) / q.answer <= q.tolerance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.*;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
|
||||
/** 关于页:版本、运行环境、源码语言、构建工具、内置模型与许可。 */
|
||||
public final class AboutPage extends JPanel {
|
||||
private final MainWindow app;
|
||||
|
||||
public AboutPage(MainWindow app) {
|
||||
this.app = app;
|
||||
setLayout(new BorderLayout());
|
||||
setOpaque(false);
|
||||
JPanel page = UI.page();
|
||||
page.add(UI.pageHeader(I18n.t("about.title"), I18n.t("about.desc"), null), BorderLayout.NORTH);
|
||||
JPanel body = new JPanel();
|
||||
body.setOpaque(false);
|
||||
body.setLayout(new UI.VStackLayout());
|
||||
|
||||
UI.Card hero = new UI.Card(new BorderLayout(18, 0));
|
||||
hero.setBorder(new EmptyBorder(22, 24, 22, 24));
|
||||
hero.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
hero.setMaximumSize(new Dimension(Integer.MAX_VALUE, 120));
|
||||
JLabel logo = new JLabel("G") {
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
GradientPaint gp = new GradientPaint(0, 0, Theme.ACCENT, getWidth(), getHeight(), new Color(0x8B5CF6));
|
||||
g2.setPaint(gp);
|
||||
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);
|
||||
g2.setColor(Color.WHITE);
|
||||
g2.setFont(Theme.bold(38));
|
||||
FontMetrics fm = g2.getFontMetrics();
|
||||
g2.drawString("G", (getWidth() - fm.stringWidth("G")) / 2, (getHeight() + fm.getAscent() - fm.getDescent()) / 2);
|
||||
g2.dispose();
|
||||
}
|
||||
};
|
||||
logo.setPreferredSize(new Dimension(82, 82));
|
||||
hero.add(logo, BorderLayout.WEST);
|
||||
JPanel info = new JPanel();
|
||||
info.setOpaque(false);
|
||||
info.setLayout(new UI.VStackLayout());
|
||||
info.add(Theme.boldLabel("GC · Astronomy Model Launcher", 21, Theme.INK));
|
||||
info.add(Box.createVerticalStrut(4));
|
||||
info.add(Theme.label("Java 2.0.0 · " + I18n.t("about.ui.value"), 13, Theme.DIM));
|
||||
info.add(Box.createVerticalStrut(4));
|
||||
info.add(Theme.label("Copyright © 2026 Morris GC · MIT", 11, Theme.FAINT));
|
||||
hero.add(info, BorderLayout.CENTER);
|
||||
body.add(hero);
|
||||
body.add(Box.createVerticalStrut(16));
|
||||
|
||||
UI.Card env = new UI.Card();
|
||||
env.setLayout(new UI.VStackLayout());
|
||||
env.setBorder(new EmptyBorder(18, 20, 18, 20));
|
||||
env.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JLabel envTitle = Theme.boldLabel(I18n.t("set.general"), 15, Theme.INK);
|
||||
envTitle.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
env.add(envTitle);
|
||||
env.add(Box.createVerticalStrut(12));
|
||||
env.add(row(I18n.t("about.language"), "Java 17+ / Swing"));
|
||||
env.add(row(I18n.t("about.ui"), I18n.t("about.ui.value")));
|
||||
env.add(row(I18n.t("about.build"), I18n.t("about.build.value")));
|
||||
env.add(row(I18n.t("app.version"), "2.0.0"));
|
||||
env.add(row(I18n.t("app.platform"), AppPaths.displayPlatform()));
|
||||
env.add(row(I18n.t("about.license"), "MIT"));
|
||||
env.add(row(I18n.t("about.thanks"), "https://git.xhmcl.com/Morris/GC"));
|
||||
body.add(env);
|
||||
body.add(Box.createVerticalStrut(16));
|
||||
|
||||
UI.Card models = new UI.Card();
|
||||
models.setLayout(new UI.VStackLayout());
|
||||
models.setBorder(new EmptyBorder(18, 20, 18, 20));
|
||||
models.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JLabel mt = Theme.boldLabel(I18n.t("about.models"), 15, Theme.INK);
|
||||
mt.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
models.add(mt);
|
||||
models.add(Box.createVerticalStrut(10));
|
||||
for (String id : BuiltinModels.IDS) models.add(row(id, BuiltinModels.FACTORY.get(id)));
|
||||
body.add(models);
|
||||
body.add(Box.createVerticalStrut(16));
|
||||
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
actions.setOpaque(false);
|
||||
UI.RoundButton repo = UI.primary(I18n.t("dl.openRepo"));
|
||||
repo.addActionListener(e -> {
|
||||
try { Desktop.getDesktop().browse(URI.create("https://git.xhmcl.com/Morris/GC")); }
|
||||
catch (Exception ex) { UI.error(this, ex.getMessage()); }
|
||||
});
|
||||
UI.RoundButton data = UI.button(I18n.t("set.openData"));
|
||||
data.addActionListener(e -> MainWindow.openFolder(this, app.paths.homeRoot));
|
||||
UI.RoundButton logs = UI.button(I18n.t("nav.logs"));
|
||||
logs.addActionListener(e -> MainWindow.openFolder(this, app.paths.logsRoot()));
|
||||
actions.add(repo);
|
||||
actions.add(data);
|
||||
actions.add(logs);
|
||||
body.add(actions);
|
||||
body.add(Box.createVerticalStrut(20));
|
||||
page.add(UI.scroll(body), BorderLayout.CENTER);
|
||||
add(page, BorderLayout.CENTER);
|
||||
}
|
||||
|
||||
public void onShow() { }
|
||||
|
||||
private JComponent row(String k, String v) {
|
||||
JPanel p = new JPanel(new BorderLayout(20, 0));
|
||||
p.setOpaque(false);
|
||||
p.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30));
|
||||
p.add(Theme.label(k, 12, Theme.DIM), BorderLayout.WEST);
|
||||
JLabel val = Theme.label(v, 12, Theme.INK);
|
||||
val.setHorizontalAlignment(SwingConstants.RIGHT);
|
||||
p.add(val, BorderLayout.EAST);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.I18n;
|
||||
import com.gc.core.ModelManifest;
|
||||
import com.gc.model.contour.TerrainAnalyzer;
|
||||
import com.gc.model.contour.TerrainField;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.awt.geom.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
|
||||
/** 等高线地形图:5 种地形 / 5 种地貌、分层设色、Marching Squares 等高线、悬停判读、3D 旋转。 */
|
||||
public final class ContourPanel extends JPanel {
|
||||
private final TerrainCanvas canvas = new ContourCanvas();
|
||||
private final JLabel stats = Theme.label("", 11, new Color(0x9FB4D4));
|
||||
private final JLabel hover = Theme.label("", 12.5f, new Color(0xEAF2FF));
|
||||
private final JLabel modeTitle = Theme.boldLabel("", 15, new Color(0xEAF2FF));
|
||||
private final JPanel kindRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
|
||||
private final JPanel landRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
|
||||
private final JPanel legend = new JPanel();
|
||||
private final JLabel loading = Theme.label("", 12, new Color(0x9FB4D4));
|
||||
private final UI.Switch contours = new UI.Switch("等高线", true);
|
||||
private final UI.Switch labels = new UI.Switch("标注", true);
|
||||
private final UI.Switch threeD = new UI.Switch("3D", false);
|
||||
private TerrainField.TerrainKind kind = TerrainField.TerrainKind.MOUNTAIN;
|
||||
private TerrainField.LandformKind landform = null;
|
||||
private final Map<String, JComponent> chips = new LinkedHashMap<>();
|
||||
private javax.swing.Timer anim;
|
||||
private double contourReveal = 1;
|
||||
|
||||
public ContourPanel(ModelManifest.Package pkg) {
|
||||
setLayout(new BorderLayout());
|
||||
setBackground(new Color(0x0A1524));
|
||||
add(header(), BorderLayout.NORTH);
|
||||
JPanel main = new JPanel(new BorderLayout(12, 0));
|
||||
main.setOpaque(false);
|
||||
main.setBorder(new EmptyBorder(0, 14, 12, 14));
|
||||
main.add(canvas, BorderLayout.CENTER);
|
||||
main.add(sidebar(), BorderLayout.EAST);
|
||||
add(main, BorderLayout.CENTER);
|
||||
add(footer(), BorderLayout.SOUTH);
|
||||
load(new TerrainField(kind, 160));
|
||||
selectChips();
|
||||
}
|
||||
|
||||
private JComponent header() {
|
||||
kindRow.setOpaque(false);
|
||||
landRow.setOpaque(false);
|
||||
JPanel h = new JPanel();
|
||||
h.setBackground(new Color(0x0C1828));
|
||||
h.setLayout(new UI.VStackLayout());
|
||||
h.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x1B2740)),
|
||||
new EmptyBorder(12, 18, 10, 18)));
|
||||
JPanel top = new JPanel(new BorderLayout());
|
||||
top.setOpaque(false);
|
||||
JPanel t = new JPanel();
|
||||
t.setOpaque(false);
|
||||
t.setLayout(new UI.VStackLayout());
|
||||
t.add(Theme.boldLabel("等高线地形 · 五大典型地貌判读", 20, new Color(0xEAF2FF)));
|
||||
t.add(Theme.label("等高线、等高距、山峰/山脊/山谷/鞍部/陡崖 · 拖动 3D 可旋转", 11, new Color(0x9FB4D4)));
|
||||
top.add(t, BorderLayout.WEST);
|
||||
top.add(modeTitle, BorderLayout.EAST);
|
||||
h.add(top);
|
||||
h.add(Box.createVerticalStrut(10));
|
||||
h.add(kindRow);
|
||||
h.add(Box.createVerticalStrut(5));
|
||||
h.add(landRow);
|
||||
return h;
|
||||
}
|
||||
|
||||
private JComponent sidebar() {
|
||||
JPanel p = new JPanel();
|
||||
p.setOpaque(false);
|
||||
p.setLayout(new UI.VStackLayout());
|
||||
p.setPreferredSize(new Dimension(300, 0));
|
||||
|
||||
UI.Card info = darkCard();
|
||||
info.setLayout(new UI.VStackLayout());
|
||||
info.add(Theme.boldLabel("实时读数", 13, new Color(0xEAF2FF)));
|
||||
info.add(Box.createVerticalStrut(6));
|
||||
info.add(stats);
|
||||
info.add(Box.createVerticalStrut(8));
|
||||
hover.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
info.add(hover);
|
||||
info.add(Box.createVerticalStrut(8));
|
||||
JPanel opts = new JPanel(new GridLayout(1, 3, 6, 0));
|
||||
opts.setOpaque(false);
|
||||
opts.setMaximumSize(new Dimension(Integer.MAX_VALUE, 28));
|
||||
for (UI.Switch s : new UI.Switch[]{contours, labels, threeD}) {
|
||||
s.addActionListener(e -> canvas.repaint());
|
||||
opts.add(s);
|
||||
}
|
||||
info.add(opts);
|
||||
p.add(info);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
|
||||
UI.Card leg = darkCard();
|
||||
leg.setLayout(new UI.VStackLayout());
|
||||
leg.add(Theme.boldLabel("分层设色 / 海拔", 13, new Color(0xEAF2FF)));
|
||||
leg.add(Box.createVerticalStrut(8));
|
||||
legend.setOpaque(false);
|
||||
legend.setLayout(new UI.VStackLayout());
|
||||
for (int i = 0; i < 9; i++) {
|
||||
int low = i * 200;
|
||||
Color c = TerrainAnalyzer.colorForHeight(low + 10);
|
||||
JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 2));
|
||||
row.setOpaque(false);
|
||||
JLabel chip = new JLabel();
|
||||
chip.setOpaque(true);
|
||||
chip.setBackground(c);
|
||||
chip.setPreferredSize(new Dimension(26, 14));
|
||||
row.add(chip);
|
||||
row.add(Theme.label(i == 8 ? "1600 m 以上" : low + "–" + (low + 200) + " m", 10.5f, new Color(0xC6D5EC)));
|
||||
legend.add(row);
|
||||
}
|
||||
leg.add(legend);
|
||||
p.add(leg);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
|
||||
UI.Card read = darkCard();
|
||||
read.setLayout(new UI.VStackLayout());
|
||||
read.add(Theme.boldLabel("判读口诀", 13, new Color(0xEAF2FF)));
|
||||
read.add(Box.createVerticalStrut(6));
|
||||
for (String s : new String[]{
|
||||
"山峰:闭合等高线,数值向内升高",
|
||||
"山脊:等高线凸向低处,凸低为脊",
|
||||
"山谷:等高线凸向高处,凸高为谷",
|
||||
"鞍部:两峰之间,俯视收腰",
|
||||
"陡崖:等高线密集甚至重合",
|
||||
"坡陡:等高线密;坡缓:等高线疏"}) {
|
||||
JLabel l = Theme.label("· " + s, 10.5f, new Color(0xA9BBD8));
|
||||
read.add(l);
|
||||
}
|
||||
p.add(read);
|
||||
p.add(Box.createVerticalGlue());
|
||||
return p;
|
||||
}
|
||||
|
||||
private UI.Card darkCard() {
|
||||
UI.Card c = new UI.Card();
|
||||
c.setBorder(new EmptyBorder(12, 14, 12, 14));
|
||||
c.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1000));
|
||||
c.alt = true;
|
||||
c.bgOverride = new Color(0x121D2E);
|
||||
c.borderOverride = new Color(0x24324A);
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent footer() {
|
||||
JPanel f = new JPanel(new BorderLayout());
|
||||
f.setBackground(new Color(0x0C1828));
|
||||
f.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(0x1B2740)),
|
||||
new EmptyBorder(8, 18, 8, 18)));
|
||||
loading.setText("就绪 · 移动鼠标查看海拔与地形判读");
|
||||
loading.setForeground(new Color(0x9FB4D4));
|
||||
f.add(loading, BorderLayout.WEST);
|
||||
JPanel r = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 0));
|
||||
r.setOpaque(false);
|
||||
UI.RoundButton anim = UI.primary("演示等高线");
|
||||
anim.addActionListener(e -> animateContours());
|
||||
UI.RoundButton reset = UI.button("重置视角");
|
||||
reset.addActionListener(e -> { canvas.resetView(); });
|
||||
r.add(anim);
|
||||
r.add(reset);
|
||||
f.add(r, BorderLayout.EAST);
|
||||
return f;
|
||||
}
|
||||
|
||||
private void animateContours() {
|
||||
if (anim != null) anim.stop();
|
||||
contourReveal = 0;
|
||||
contours.setSelected(true);
|
||||
anim = new javax.swing.Timer(30, e -> {
|
||||
contourReveal += 0.025;
|
||||
if (contourReveal >= 1) { contourReveal = 1; ((javax.swing.Timer) e.getSource()).stop(); }
|
||||
canvas.repaint();
|
||||
});
|
||||
anim.start();
|
||||
}
|
||||
|
||||
private void selectChips() {
|
||||
kindRow.removeAll();
|
||||
landRow.removeAll();
|
||||
String[] kinds = {"mountain", "basin", "hill", "plateau", "plain"};
|
||||
String[] lands = {"peak", "ridge", "valley", "saddle", "cliff"};
|
||||
JLabel kl = Theme.label("基本地形", 10.5f, new Color(0x9FB4D4));
|
||||
kindRow.add(kl);
|
||||
for (int i = 0; i < kinds.length; i++) {
|
||||
final TerrainField.TerrainKind k = TerrainField.TerrainKind.valueOf(kinds[i].toUpperCase());
|
||||
UI.RoundButton b = chip(I18n.t("contour.kind." + kinds[i]), landform == null && kind == k);
|
||||
b.addActionListener(e -> {
|
||||
landform = null; kind = k; selectChips(); load(new TerrainField(kind, 160));
|
||||
});
|
||||
kindRow.add(b);
|
||||
}
|
||||
JLabel ll = Theme.label("典型地貌", 10.5f, new Color(0x9FB4D4));
|
||||
landRow.add(ll);
|
||||
for (String s : lands) {
|
||||
final TerrainField.LandformKind lf = TerrainField.LandformKind.valueOf(s.toUpperCase());
|
||||
UI.RoundButton b = chip(I18n.t("contour.landform." + s), landform == lf);
|
||||
b.addActionListener(e -> {
|
||||
landform = lf; selectChips(); load(new TerrainField(lf, 160));
|
||||
});
|
||||
landRow.add(b);
|
||||
}
|
||||
kindRow.revalidate(); kindRow.repaint();
|
||||
landRow.revalidate(); landRow.repaint();
|
||||
modeTitle.setText(landform != null ? I18n.t("contour.landform." + landform.name().toLowerCase())
|
||||
: I18n.t("contour.kind." + kind.name().toLowerCase()));
|
||||
}
|
||||
|
||||
private UI.RoundButton chip(String text, boolean active) {
|
||||
UI.RoundButton b = UI.button(text);
|
||||
b.setFont(Theme.font(10.5f));
|
||||
b.setBorder(new EmptyBorder(4, 10, 4, 10));
|
||||
b.primary = active;
|
||||
b.ghost = !active;
|
||||
return b;
|
||||
}
|
||||
|
||||
private void load(TerrainField field) {
|
||||
loading.setText("正在生成地形高度场与等高线…");
|
||||
loading.setForeground(new Color(0xE9B25B));
|
||||
canvas.setLoading(true);
|
||||
new SwingWorker<Data, Void>() {
|
||||
@Override protected Data doInBackground() {
|
||||
return prepare(field);
|
||||
}
|
||||
@Override protected void done() {
|
||||
try {
|
||||
Data d = get();
|
||||
canvas.setData(d);
|
||||
stats.setText(String.format(Locale.ROOT, "海拔 %.0f – %.0f m · 等高距 %.0f m · %d 格",
|
||||
field.minHeight, field.maxHeight, field.effectiveInterval(), field.size));
|
||||
loading.setText("就绪 · 移动鼠标查看海拔与地形判读");
|
||||
loading.setForeground(new Color(0x9FB4D4));
|
||||
canvas.setLoading(false);
|
||||
} catch (Exception e) {
|
||||
loading.setText("生成失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
private final class ContourCanvas extends TerrainCanvas {
|
||||
ContourCanvas() {
|
||||
addMouseMotionListener(new MouseMotionAdapter() {
|
||||
@Override public void mouseMoved(MouseEvent e) { updateHover(e.getX(), e.getY()); }
|
||||
@Override public void mouseDragged(MouseEvent e) {
|
||||
if (threeD.isSelected()) { yaw += (e.getX() - lastX) * 0.01; lastX = e.getX(); repaint(); }
|
||||
}
|
||||
});
|
||||
addMouseListener(new MouseAdapter() {
|
||||
@Override public void mousePressed(MouseEvent e) { lastX = e.getX(); }
|
||||
@Override public void mouseExited(MouseEvent e) { hoverU = -1; repaint(); }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void updateHover(int mx, int my) {
|
||||
ContourCanvas c = (ContourCanvas) canvas;
|
||||
c.hoverX = mx; c.hoverY = my;
|
||||
Rectangle r = c.mapRect();
|
||||
if (r == null || !r.contains(mx, my) || c.data == null) { hover.setText(" "); c.repaint(); return; }
|
||||
double u = (mx - r.x) / (double) r.width, v = (my - r.y) / (double) r.height;
|
||||
TerrainField f = c.data.field;
|
||||
float h = f.sampleSmooth(u, v);
|
||||
TerrainField.Feature feat = TerrainAnalyzer.classify(f, u, v);
|
||||
double slope = f.slopeAt(u, v);
|
||||
c.hoverU = u; c.hoverV = v;
|
||||
hover.setText(String.format(Locale.ROOT, "海拔 %.0f m · %s · 坡度 %.0f%%",
|
||||
h, TerrainAnalyzer.featureLabel(feat), slope * 100));
|
||||
hover.setForeground(new Color(0xEAF2FF));
|
||||
c.repaint();
|
||||
}
|
||||
|
||||
private static final class Data {
|
||||
final TerrainField field;
|
||||
final List<Float> levels;
|
||||
final Map<Float, List<List<TerrainField.Point>>> contours = new LinkedHashMap<>();
|
||||
final BufferedImage relief;
|
||||
Data(TerrainField f, List<Float> levels, List<List<List<TerrainField.Point>>> lines, BufferedImage relief) {
|
||||
this.field = f; this.levels = levels; this.relief = relief;
|
||||
for (int i = 0; i < levels.size(); i++) contours.put(levels.get(i), lines.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
private static Data prepare(TerrainField f) {
|
||||
List<Float> levels = f.contourLevels();
|
||||
List<List<List<TerrainField.Point>>> lines = new ArrayList<>();
|
||||
for (float l : levels) lines.add(f.extractContour(l));
|
||||
BufferedImage img = new BufferedImage(f.size, f.size, BufferedImage.TYPE_INT_RGB);
|
||||
for (int y = 0; y < f.size; y++) for (int x = 0; x < f.size; x++) {
|
||||
float h = f.heights[y][x];
|
||||
Color c = TerrainAnalyzer.colorForHeight(h);
|
||||
int x1 = Math.min(f.size - 1, x + 1), y1 = Math.min(f.size - 1, y + 1);
|
||||
double dz = (f.heights[y1][x] - h) * 0.6 + (f.heights[y][x1] - h) * 0.4;
|
||||
double shade = Math.max(-0.35, Math.min(0.35, dz / 80.0));
|
||||
int r = clampColor((int) (c.getRed() * (1 + shade)));
|
||||
int g = clampColor((int) (c.getGreen() * (1 + shade)));
|
||||
int b = clampColor((int) (c.getBlue() * (1 + shade)));
|
||||
img.setRGB(x, y, (r << 16) | (g << 8) | b);
|
||||
}
|
||||
return new Data(f, levels, lines, img);
|
||||
}
|
||||
|
||||
private static int clampColor(int v) { return Math.max(0, Math.min(255, v)); }
|
||||
|
||||
/** 地形画布:俯视分层设色 + 等高线;3D 轴测 + 拖动旋转。 */
|
||||
private class TerrainCanvas extends JPanel {
|
||||
Data data;
|
||||
boolean loading;
|
||||
double yaw = 0.7;
|
||||
double hoverU = -1, hoverV = -1;
|
||||
int hoverX, hoverY, lastX;
|
||||
|
||||
TerrainCanvas() { setOpaque(false); }
|
||||
|
||||
void setData(Data d) { data = d; repaint(); }
|
||||
void setLoading(boolean b) { loading = b; repaint(); }
|
||||
void resetView() { yaw = 0.7; hoverU = -1; repaint(); }
|
||||
|
||||
Rectangle mapRect() {
|
||||
if (data == null) return null;
|
||||
int pad = 26;
|
||||
int avail = Math.min(getWidth() - pad * 2, getHeight() - pad * 2);
|
||||
if (avail <= 10) return null;
|
||||
return new Rectangle(pad + (getWidth() - pad * 2 - avail) / 2,
|
||||
pad + (getHeight() - pad * 2 - avail) / 2, avail, avail);
|
||||
}
|
||||
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g2.setColor(new Color(0x0F1E33));
|
||||
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 14, 14);
|
||||
g2.setColor(new Color(0x1B2740));
|
||||
g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 14, 14);
|
||||
if (loading || data == null) {
|
||||
g2.setColor(new Color(0x9FB4D4));
|
||||
g2.setFont(Theme.font(13));
|
||||
String s = "正在生成地形与等高线…";
|
||||
g2.drawString(s, (getWidth() - g2.getFontMetrics().stringWidth(s)) / 2, getHeight() / 2);
|
||||
g2.dispose();
|
||||
return;
|
||||
}
|
||||
if (threeDSelected()) paint3D(g2); else paintTop(g2);
|
||||
g2.dispose();
|
||||
}
|
||||
|
||||
private boolean threeDSelected() { return threeD.isSelected(); }
|
||||
private boolean contoursSelected() { return contours.isSelected(); }
|
||||
private boolean labelsSelected() { return labels.isSelected(); }
|
||||
|
||||
private void paintTop(Graphics2D g2) {
|
||||
Rectangle r = mapRect();
|
||||
if (r == null) return;
|
||||
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||
Shape clip = new RoundRectangle2D.Float(r.x, r.y, r.width, r.height, 10, 10);
|
||||
g2.clip(clip);
|
||||
g2.drawImage(data.relief, r.x, r.y, r.width, r.height, null);
|
||||
g2.setClip(null);
|
||||
g2.setColor(new Color(0x1B2740));
|
||||
g2.drawRoundRect(r.x, r.y, r.width, r.height, 10, 10);
|
||||
|
||||
// contours
|
||||
if (contoursSelected()) {
|
||||
g2.setStroke(new BasicStroke(1f));
|
||||
for (float level : data.levels) {
|
||||
float t = (level - data.levels.get(0)) / Math.max(1, data.levels.get(data.levels.size() - 1) - data.levels.get(0));
|
||||
if (t > contourReveal) continue;
|
||||
boolean major = Math.abs(level % 500) < 1;
|
||||
g2.setColor(major ? new Color(255, 255, 255, 210) : new Color(255, 255, 255, 120));
|
||||
g2.setStroke(new BasicStroke(major ? 1.5f : 0.9f));
|
||||
for (List<TerrainField.Point> line : data.contours.get(level)) {
|
||||
Path2D p = new Path2D.Double();
|
||||
boolean first = true;
|
||||
for (TerrainField.Point pt : line) {
|
||||
double x = r.x + pt.u() * r.width, y = r.y + pt.v() * r.height;
|
||||
if (first) { p.moveTo(x, y); first = false; } else p.lineTo(x, y);
|
||||
}
|
||||
g2.draw(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
// river
|
||||
if (data.field.river.size() > 2) {
|
||||
Path2D p = new Path2D.Double();
|
||||
boolean first = true;
|
||||
for (TerrainField.Point pt : data.field.river) {
|
||||
double x = r.x + pt.u() * r.width, y = r.y + pt.v() * r.height;
|
||||
if (first) { p.moveTo(x, y); first = false; } else p.lineTo(x, y);
|
||||
}
|
||||
g2.setColor(new Color(0x6FD3FF));
|
||||
g2.setStroke(new BasicStroke(1.8f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
|
||||
g2.draw(p);
|
||||
}
|
||||
// peaks
|
||||
for (TerrainField.PeakPoint pk : data.field.peaks.subList(0, Math.min(6, data.field.peaks.size()))) {
|
||||
double x = r.x + pk.u() * r.width, y = r.y + pk.v() * r.height;
|
||||
g2.setColor(new Color(0x111A2E));
|
||||
Path2D tri = new Path2D.Double();
|
||||
tri.moveTo(x, y - 7); tri.lineTo(x - 6, y + 4); tri.lineTo(x + 6, y + 4); tri.closePath();
|
||||
g2.fill(tri);
|
||||
if (labelsSelected()) {
|
||||
g2.setFont(Theme.bold(9));
|
||||
g2.setColor(new Color(0x111A2E));
|
||||
g2.drawString(String.format(Locale.ROOT, "%.0f", pk.height()), (float) x + 7, (float) y + 2);
|
||||
}
|
||||
}
|
||||
// cliff hatching
|
||||
g2.setColor(new Color(0x5A2D1A));
|
||||
for (TerrainField.Point c : data.field.cliffs) {
|
||||
double x = r.x + c.u() * r.width, y = r.y + c.v() * r.height;
|
||||
g2.drawLine((int) x, (int) y, (int) x + 4, (int) y + 4);
|
||||
}
|
||||
// hover crosshair
|
||||
if (hoverU >= 0) {
|
||||
double x = r.x + hoverU * r.width, y = r.y + hoverV * r.height;
|
||||
g2.setColor(new Color(255, 255, 255, 200));
|
||||
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{3, 4}, 0));
|
||||
g2.drawLine((int) x - 10, (int) y, (int) x + 10, (int) y);
|
||||
g2.drawLine((int) x, (int) y - 10, (int) x, (int) y + 10);
|
||||
g2.setColor(new Color(0xFFD166));
|
||||
g2.fillOval((int) x - 3, (int) y - 3, 6, 6);
|
||||
}
|
||||
// labels (features)
|
||||
if (labelsSelected()) {
|
||||
g2.setFont(Theme.bold(10));
|
||||
for (TerrainField.Tag tag : data.field.tags) {
|
||||
double x = r.x + tag.u() * r.width, y = r.y + tag.v() * r.height;
|
||||
String label = TerrainAnalyzer.featureLabel(tag.feature());
|
||||
g2.setColor(new Color(10, 20, 36, 190));
|
||||
int tw = g2.getFontMetrics().stringWidth(label);
|
||||
g2.fillRoundRect((int) x + 8, (int) y - 20, tw + 10, 16, 8, 8);
|
||||
g2.setColor(Color.WHITE);
|
||||
g2.drawString(label, (int) x + 13, (int) y - 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void paint3D(Graphics2D g2) {
|
||||
int n = Math.min(76, data.field.size - 1);
|
||||
int step = Math.max(1, data.field.size / n);
|
||||
List<int[]> cells = new ArrayList<>();
|
||||
double scale = Math.min(getWidth(), getHeight()) * 0.58;
|
||||
double cx = getWidth() / 2.0, cy = getHeight() * 0.56;
|
||||
double range = Math.max(1, data.field.maxHeight - data.field.minHeight);
|
||||
for (int y = 0; y < data.field.size - step; y += step)
|
||||
for (int x = 0; x < data.field.size - step; x += step) {
|
||||
double u0 = (double) x / (data.field.size - 1), v0 = (double) y / (data.field.size - 1);
|
||||
double u1 = (double) (x + step) / (data.field.size - 1), v1 = (double) (y + step) / (data.field.size - 1);
|
||||
double h = data.field.heightAt((u0 + u1) / 2, (v0 + v1) / 2);
|
||||
double[] p = project((u0 + u1) / 2 - 0.5, (v0 + v1) / 2 - 0.5, h / range, scale, cx, cy);
|
||||
cells.add(new int[]{x, y, (int) Math.round(p[2] * 1000)});
|
||||
}
|
||||
cells.sort(Comparator.comparingInt(a -> a[2]));
|
||||
for (int[] cell : cells) {
|
||||
int x = cell[0], y = cell[1];
|
||||
double u0 = (double) x / (data.field.size - 1), v0 = (double) y / (data.field.size - 1);
|
||||
double u1 = (double) (x + step) / (data.field.size - 1), v1 = (double) (y + step) / (data.field.size - 1);
|
||||
float h = data.field.heightAt((u0 + u1) / 2, (v0 + v1) / 2);
|
||||
Color c = TerrainAnalyzer.colorSmooth(h);
|
||||
Polygon poly = new Polygon();
|
||||
addProj(poly, u0, v0, h / range, scale, cx, cy);
|
||||
addProj(poly, u1, v0, data.field.heightAt(u1, v0) / range, scale, cx, cy);
|
||||
addProj(poly, u1, v1, data.field.heightAt(u1, v1) / range, scale, cx, cy);
|
||||
addProj(poly, u0, v1, data.field.heightAt(u0, v1) / range, scale, cx, cy);
|
||||
g2.setColor(c);
|
||||
g2.fillPolygon(poly);
|
||||
g2.setColor(new Color(0, 0, 0, 22));
|
||||
g2.drawPolygon(poly);
|
||||
}
|
||||
g2.setColor(new Color(0x9FB4D4));
|
||||
g2.setFont(Theme.font(11));
|
||||
g2.drawString("3D 轴测视图 · 拖动旋转", 20, getHeight() - 18);
|
||||
}
|
||||
|
||||
private double[] project(double x, double y, double z, double scale, double cx, double cy) {
|
||||
double cos = Math.cos(yaw), sin = Math.sin(yaw);
|
||||
double xr = x * cos - y * sin, yr = x * sin + y * cos;
|
||||
double sx = (xr - yr) * 0.86;
|
||||
double sy = (xr + yr) * 0.48 - z * 0.72;
|
||||
return new double[]{cx + sx * scale * 0.5, cy + sy * scale * 0.5, yr};
|
||||
}
|
||||
|
||||
private void addProj(Polygon p, double x, double y, double z, double scale, double cx, double cy) {
|
||||
double[] q = project(x - 0.5, y - 0.5, z, scale, cx, cy);
|
||||
p.addPoint((int) q[0], (int) q[1]);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.AppPaths;
|
||||
import com.gc.core.LocalWebServer;
|
||||
import javafx.application.Platform;
|
||||
import javafx.concurrent.Worker;
|
||||
import javafx.embed.swing.JFXPanel;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.paint.Color;
|
||||
import javafx.scene.web.WebEngine;
|
||||
import javafx.scene.web.WebView;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.Desktop;
|
||||
import java.io.File;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* 原始 HTML 课件页:用 JavaFX WebView 加载 C# 版本内置的离线课件。
|
||||
*
|
||||
* <p>课件目录通过 127.0.0.1 的临时静态服务器提供,从而保留相对路径、
|
||||
* 视频 HTTP Range 拖动与 Three.js 资源加载;不联网、不暴露到局域网。</p>
|
||||
*/
|
||||
public final class CoursewarePage extends JPanel {
|
||||
private final MainWindow app;
|
||||
private final JLabel status = Theme.label("正在准备课件…", 11, Theme.FAINT);
|
||||
private final JPanel stage = new JPanel(new BorderLayout());
|
||||
private JFXPanel fxPanel;
|
||||
private WebView webView;
|
||||
private LocalWebServer server;
|
||||
private Path root;
|
||||
|
||||
public CoursewarePage(MainWindow app) {
|
||||
this.app = app;
|
||||
setLayout(new BorderLayout());
|
||||
setOpaque(false);
|
||||
JPanel page = UI.page();
|
||||
page.add(header(), BorderLayout.NORTH);
|
||||
stage.setOpaque(false);
|
||||
stage.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createLineBorder(Theme.LINE, 1, true),
|
||||
new EmptyBorder(1, 1, 1, 1)));
|
||||
page.add(stage, BorderLayout.CENTER);
|
||||
page.add(footer(), BorderLayout.SOUTH);
|
||||
add(page, BorderLayout.CENTER);
|
||||
root = app.paths.coursewareRoot();
|
||||
if (root == null) {
|
||||
showFallback("未找到原始 HTML 课件目录(courseware/index.html)。\n"
|
||||
+ "开发态请确认 Java/courseware 存在;发行版请确认 courseware/ 与程序同级。");
|
||||
} else if (GraphicsEnvironment.isHeadless()) {
|
||||
showFallback("当前为无头环境,课件不会创建 WebView。\n课件目录:" + root);
|
||||
} else {
|
||||
initFx();
|
||||
}
|
||||
}
|
||||
|
||||
private JComponent header() {
|
||||
JPanel wrap = new JPanel(new BorderLayout());
|
||||
wrap.setOpaque(false);
|
||||
JPanel left = new JPanel();
|
||||
left.setOpaque(false);
|
||||
left.setLayout(new UI.VStackLayout());
|
||||
left.add(Theme.boldLabel("等高线地形 · 五大典型地貌判读", 25, Theme.INK));
|
||||
left.add(Theme.label("原始离线 HTML 课件 · JavaFX WebView · 视频 / Three.js / 交互式实验", 12.5f, Theme.DIM));
|
||||
wrap.add(left, BorderLayout.WEST);
|
||||
JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 0));
|
||||
right.setOpaque(false);
|
||||
UI.RoundButton reload = UI.button("刷新");
|
||||
reload.addActionListener(e -> reload());
|
||||
UI.RoundButton browser = UI.button("用浏览器打开");
|
||||
browser.addActionListener(e -> openBrowser());
|
||||
UI.RoundButton full = UI.primary("全屏");
|
||||
full.addActionListener(e -> toggleFullScreen());
|
||||
right.add(reload);
|
||||
right.add(browser);
|
||||
right.add(full);
|
||||
wrap.add(right, BorderLayout.EAST);
|
||||
wrap.setBorder(new EmptyBorder(0, 0, 16, 0));
|
||||
return wrap;
|
||||
}
|
||||
|
||||
private JComponent footer() {
|
||||
JPanel p = new JPanel(new BorderLayout());
|
||||
p.setOpaque(false);
|
||||
p.setBorder(new EmptyBorder(10, 2, 0, 2));
|
||||
status.setForeground(Theme.DIM);
|
||||
p.add(status, BorderLayout.WEST);
|
||||
JLabel hint = Theme.label("课件完全离线运行 · 数据来源:C#/GC-UI/frontend/courseware", 10.5f, Theme.FAINT);
|
||||
p.add(hint, BorderLayout.EAST);
|
||||
return p;
|
||||
}
|
||||
|
||||
private void initFx() {
|
||||
try {
|
||||
fxPanel = new JFXPanel();
|
||||
stage.add(fxPanel, BorderLayout.CENTER);
|
||||
server = new LocalWebServer(root);
|
||||
String url = server.url();
|
||||
Platform.setImplicitExit(false);
|
||||
Platform.runLater(() -> {
|
||||
try {
|
||||
webView = new WebView();
|
||||
webView.setContextMenuEnabled(true);
|
||||
webView.setStyle("-fx-font-smoothing-type: gray;");
|
||||
WebEngine engine = webView.getEngine();
|
||||
engine.setJavaScriptEnabled(true);
|
||||
try {
|
||||
Path userData = app.paths.cacheRoot().resolve("webview");
|
||||
java.nio.file.Files.createDirectories(userData);
|
||||
engine.setUserDataDirectory(userData.toFile());
|
||||
// 用用户样式表设置中文字体,避免在 LoadWorker 回调里执行 JS
|
||||
//(JavaFX 21 WebKit 在 JDK 26 上executeScript 会触发 JNI 崩溃)。
|
||||
Path css = userData.resolve("gc-courseware.css");
|
||||
java.nio.file.Files.writeString(css,
|
||||
"html,body,input,button,div,span,p,h1,h2,h3,h4,text { "
|
||||
+ "font-family: 'PingFang SC','Microsoft YaHei','Noto Sans CJK SC','Segoe UI',sans-serif !important; }",
|
||||
java.nio.charset.StandardCharsets.UTF_8);
|
||||
engine.setUserStyleSheetLocation(css.toUri().toString());
|
||||
} catch (Exception ignored) { }
|
||||
engine.getLoadWorker().stateProperty().addListener((obs, old, now) -> {
|
||||
if (now == Worker.State.RUNNING) setStatus("正在加载课件 " + url);
|
||||
else if (now == Worker.State.SUCCEEDED) {
|
||||
setStatus("课件加载完成 · 可直接操作");
|
||||
} else if (now == Worker.State.FAILED) {
|
||||
setStatus("课件加载失败:" + engine.getLoadWorker().getException());
|
||||
}
|
||||
});
|
||||
engine.setOnError(e -> setStatus("WebView 错误:" + e.getMessage()));
|
||||
engine.load(url);
|
||||
fxPanel.setScene(new Scene(webView, Color.web("#eef4fc")));
|
||||
} catch (Throwable t) {
|
||||
showFallback("JavaFX WebView 初始化失败:" + t.getMessage());
|
||||
}
|
||||
});
|
||||
} catch (Throwable t) {
|
||||
showFallback("JavaFX WebView 不可用:" + t.getMessage() + "\n可以点击「用浏览器打开」查看原始 HTML。");
|
||||
}
|
||||
}
|
||||
|
||||
private void reload() {
|
||||
if (webView != null) {
|
||||
Platform.runLater(() -> webView.getEngine().reload());
|
||||
setStatus("正在重新加载…");
|
||||
} else if (root != null) {
|
||||
openBrowser();
|
||||
}
|
||||
}
|
||||
|
||||
private void openBrowser() {
|
||||
try {
|
||||
if (root == null) return;
|
||||
File f = root.resolve("index.html").toFile();
|
||||
Desktop.getDesktop().browse(f.toURI());
|
||||
setStatus("已在系统浏览器打开原始 HTML");
|
||||
} catch (Exception e) {
|
||||
UI.error(this, "无法打开浏览器:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void toggleFullScreen() {
|
||||
Window w = SwingUtilities.getWindowAncestor(this);
|
||||
if (!(w instanceof JFrame f)) return;
|
||||
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
|
||||
if (gd.getFullScreenWindow() == f) gd.setFullScreenWindow(null);
|
||||
else gd.setFullScreenWindow(f);
|
||||
}
|
||||
|
||||
private void setStatus(String s) {
|
||||
SwingUtilities.invokeLater(() -> status.setText(s));
|
||||
}
|
||||
|
||||
private void showFallback(String message) {
|
||||
stage.removeAll();
|
||||
JPanel box = new JPanel(new GridBagLayout());
|
||||
box.setOpaque(false);
|
||||
UI.Card card = new UI.Card();
|
||||
card.setLayout(new UI.VStackLayout());
|
||||
card.setBorder(new EmptyBorder(30, 34, 30, 34));
|
||||
card.add(Theme.boldLabel("原始 HTML 课件", 19, Theme.INK));
|
||||
card.add(Box.createVerticalStrut(8));
|
||||
JLabel l = Theme.label("<html><body style='width:620px'>" + message.replace("\n", "<br>") + "</body></html>", 12.5f, Theme.DIM);
|
||||
card.add(l);
|
||||
card.add(Box.createVerticalStrut(16));
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
actions.setOpaque(false);
|
||||
UI.RoundButton b = UI.primary("用系统浏览器打开");
|
||||
b.addActionListener(e -> openBrowser());
|
||||
actions.add(b);
|
||||
card.add(actions);
|
||||
box.add(card);
|
||||
stage.add(box, BorderLayout.CENTER);
|
||||
status.setText(message.replace("\n", " · "));
|
||||
stage.revalidate();
|
||||
stage.repaint();
|
||||
}
|
||||
|
||||
public void disposePanel() {
|
||||
try { if (server != null) server.close(); } catch (Exception ignored) { }
|
||||
try {
|
||||
if (webView != null) Platform.runLater(() -> {
|
||||
try { webView.getEngine().load(null); } catch (Exception ignored) { }
|
||||
});
|
||||
} catch (Throwable ignored) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.*;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** 下载 / 更新页:更新源、检查更新、进度、远端模型列表、本地导入。 */
|
||||
public final class DownloadPage extends JPanel {
|
||||
private final MainWindow app;
|
||||
private final UI.TextField repo = new UI.TextField();
|
||||
private final UI.TextField local = new UI.TextField();
|
||||
private final UI.Switch auto = new UI.Switch(I18n.t("update.auto"), true);
|
||||
private final UI.Switch signed = new UI.Switch(I18n.t("set.requireSigned"), true);
|
||||
private final UI.Progress progress = new UI.Progress();
|
||||
private final JLabel status = Theme.label("", 12, Theme.DIM);
|
||||
private final JPanel remoteList = new JPanel();
|
||||
private final JLabel remoteTitle = Theme.boldLabel("", 14, Theme.INK);
|
||||
private UI.RoundButton checkBtn;
|
||||
|
||||
public DownloadPage(MainWindow app) {
|
||||
this.app = app;
|
||||
setLayout(new BorderLayout());
|
||||
setOpaque(false);
|
||||
JPanel page = UI.page();
|
||||
page.add(UI.pageHeader(I18n.t("dl.title"), I18n.t("dl.subtitle"), null), BorderLayout.NORTH);
|
||||
|
||||
JPanel cols = new JPanel(new GridLayout(1, 2, 16, 0));
|
||||
cols.setOpaque(false);
|
||||
cols.add(left());
|
||||
cols.add(right());
|
||||
page.add(cols, BorderLayout.CENTER);
|
||||
add(page, BorderLayout.CENTER);
|
||||
}
|
||||
|
||||
private JComponent left() {
|
||||
JPanel col = new JPanel();
|
||||
col.setOpaque(false);
|
||||
col.setLayout(new UI.VStackLayout());
|
||||
|
||||
UI.Card src = new UI.Card();
|
||||
src.setLayout(new UI.VStackLayout());
|
||||
src.setBorder(new EmptyBorder(18, 20, 18, 20));
|
||||
src.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
src.setMaximumSize(new Dimension(Integer.MAX_VALUE, 340));
|
||||
JLabel srcTitle = Theme.boldLabel(I18n.t("dl.source"), 15, Theme.INK);
|
||||
srcTitle.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
src.add(srcTitle);
|
||||
src.add(Box.createVerticalStrut(12));
|
||||
src.add(UI.labeled(I18n.t("set.updateRepo"), repo));
|
||||
src.add(Box.createVerticalStrut(10));
|
||||
JPanel localRow = new JPanel(new BorderLayout(6, 0));
|
||||
localRow.setOpaque(false);
|
||||
localRow.add(local, BorderLayout.CENTER);
|
||||
UI.RoundButton browse = UI.button(I18n.t("common.browse"));
|
||||
browse.addActionListener(e -> {
|
||||
JFileChooser fc = new JFileChooser();
|
||||
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
|
||||
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) local.setText(fc.getSelectedFile().getAbsolutePath());
|
||||
});
|
||||
localRow.add(browse, BorderLayout.EAST);
|
||||
src.add(UI.labeled(I18n.t("set.updateLocal"), localRow));
|
||||
src.add(Box.createVerticalStrut(12));
|
||||
auto.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
signed.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
src.add(auto);
|
||||
src.add(signed);
|
||||
src.add(Box.createVerticalStrut(12));
|
||||
checkBtn = UI.primary(I18n.t("dl.check"));
|
||||
checkBtn.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
checkBtn.addActionListener(e -> check());
|
||||
src.add(checkBtn);
|
||||
src.add(Box.createVerticalStrut(12));
|
||||
progress.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
progress.setMaximumSize(new Dimension(Integer.MAX_VALUE, 8));
|
||||
src.add(progress);
|
||||
src.add(Box.createVerticalStrut(6));
|
||||
status.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
src.add(status);
|
||||
col.add(src);
|
||||
col.add(Box.createVerticalStrut(16));
|
||||
|
||||
UI.Card imp = new UI.Card();
|
||||
imp.setLayout(new UI.VStackLayout());
|
||||
imp.setBorder(new EmptyBorder(18, 20, 18, 20));
|
||||
imp.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
imp.setMaximumSize(new Dimension(Integer.MAX_VALUE, 160));
|
||||
JLabel impTitle = Theme.boldLabel(I18n.t("dl.import"), 15, Theme.INK);
|
||||
impTitle.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
imp.add(impTitle);
|
||||
imp.add(Box.createVerticalStrut(5));
|
||||
imp.add(Theme.label(I18n.t("dl.hint"), 11.5f, Theme.DIM));
|
||||
imp.add(Box.createVerticalStrut(12));
|
||||
UI.RoundButton doImport = UI.button(I18n.t("dl.import"));
|
||||
doImport.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
doImport.addActionListener(e -> {
|
||||
JFileChooser fc = new JFileChooser();
|
||||
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
|
||||
if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
|
||||
Path root = fc.getSelectedFile().toPath();
|
||||
try {
|
||||
int n = ModelInstaller.importLocal(root, app.modelRoot());
|
||||
app.refreshModels();
|
||||
UI.toast(this, I18n.f("dl.imported", n));
|
||||
} catch (Exception ex) {
|
||||
UI.error(this, I18n.f("dl.importFailed", ex.getMessage()));
|
||||
}
|
||||
});
|
||||
imp.add(doImport);
|
||||
col.add(imp);
|
||||
col.add(Box.createVerticalGlue());
|
||||
return col;
|
||||
}
|
||||
|
||||
private JComponent right() {
|
||||
UI.Card card = new UI.Card(new BorderLayout(0, 10));
|
||||
card.setBorder(new EmptyBorder(18, 20, 18, 20));
|
||||
card.add(remoteTitle, BorderLayout.NORTH);
|
||||
remoteList.setOpaque(false);
|
||||
remoteList.setLayout(new UI.VStackLayout());
|
||||
card.add(UI.scroll(remoteList), BorderLayout.CENTER);
|
||||
return card;
|
||||
}
|
||||
|
||||
public void onShow() {
|
||||
repo.setText(app.settings.updateRepository);
|
||||
local.setText(app.settings.updateLocalRoot);
|
||||
auto.setSelected(app.settings.autoUpdateOnStartup);
|
||||
signed.setSelected(app.settings.requireSignedManifest);
|
||||
remoteTitle.setText(I18n.t("dl.available"));
|
||||
if (remoteList.getComponentCount() == 0) refreshLocalList();
|
||||
}
|
||||
|
||||
private void refreshLocalList() {
|
||||
remoteList.removeAll();
|
||||
for (ModelManifest.Package p : app.models()) {
|
||||
remoteList.add(row(p.id(), "v" + p.manifest.version,
|
||||
p.manifest.localizedName(), Theme.SUCCESS, I18n.t("dl.installed")));
|
||||
remoteList.add(Box.createVerticalStrut(6));
|
||||
}
|
||||
if (app.models().isEmpty()) remoteList.add(Theme.label(I18n.t("dl.empty"), 12, Theme.DIM));
|
||||
remoteList.revalidate();
|
||||
remoteList.repaint();
|
||||
}
|
||||
|
||||
private JComponent row(String id, String ver, String name, Color color, String tag) {
|
||||
JPanel p = new JPanel(new BorderLayout(8, 0));
|
||||
p.setOpaque(false);
|
||||
p.setMaximumSize(new Dimension(Integer.MAX_VALUE, 46));
|
||||
JPanel l = new JPanel();
|
||||
l.setOpaque(false);
|
||||
l.setLayout(new UI.VStackLayout());
|
||||
l.add(Theme.boldLabel(name, 12.5f, Theme.INK));
|
||||
l.add(Theme.label(id + " · " + ver, 10, Theme.FAINT));
|
||||
p.add(l, BorderLayout.CENTER);
|
||||
p.add(Theme.label(tag, 10.5f, color), BorderLayout.EAST);
|
||||
return p;
|
||||
}
|
||||
|
||||
private void check() {
|
||||
app.settings.updateRepository = repo.getText().trim();
|
||||
app.settings.updateLocalRoot = local.getText().trim();
|
||||
app.settings.autoUpdateOnStartup = auto.isSelected();
|
||||
app.settings.requireSignedManifest = signed.isSelected();
|
||||
app.settings.save();
|
||||
checkBtn.setEnabled(false);
|
||||
progress.setValue(0.02);
|
||||
status.setForeground(Theme.DIM);
|
||||
status.setText(I18n.t("dl.checking"));
|
||||
remoteList.removeAll();
|
||||
remoteTitle.setText(I18n.t("dl.checking"));
|
||||
remoteList.revalidate();
|
||||
|
||||
new Thread(() -> {
|
||||
UpdateService.Result r = new UpdateService(app.paths, app.settings).run(true, p -> SwingUtilities.invokeLater(() -> {
|
||||
progress.setValue(p.value());
|
||||
status.setText(p.message() + (p.detail() == null || p.detail().isBlank() ? "" : " " + p.detail()));
|
||||
}));
|
||||
SwingUtilities.invokeLater(() -> {
|
||||
checkBtn.setEnabled(true);
|
||||
progress.setValue(1);
|
||||
status.setText(r.message());
|
||||
status.setForeground(r.outcome() == UpdateService.Outcome.UNAVAILABLE ? Theme.WARN : Theme.SUCCESS);
|
||||
remoteTitle.setText(I18n.t("dl.available"));
|
||||
remoteList.removeAll();
|
||||
if (r.manifest() != null && !r.manifest().models.isEmpty()) {
|
||||
for (Remote.RepoModel m : r.manifest().models) {
|
||||
ModelManifest.Package localPkg = app.findModel(m.id());
|
||||
boolean installed = localPkg != null && localPkg.manifest.version.equals(m.version());
|
||||
remoteList.add(row(m.id(), "v" + m.version(), m.id(), installed ? Theme.SUCCESS : Theme.ACCENT,
|
||||
installed ? I18n.t("dl.installed") : m.version()));
|
||||
remoteList.add(Box.createVerticalStrut(6));
|
||||
}
|
||||
} else refreshLocalList();
|
||||
if (r.error() != null) {
|
||||
remoteList.add(Theme.label(r.error(), 10.5f, Theme.DANGER));
|
||||
}
|
||||
app.refreshModels();
|
||||
remoteList.revalidate();
|
||||
remoteList.repaint();
|
||||
});
|
||||
}, "gc-download-check").start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.I18n;
|
||||
import com.gc.core.Json;
|
||||
import com.gc.core.ModelManifest;
|
||||
import com.gc.model.earth.EarthMath;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.awt.geom.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
|
||||
/** 地球自转 / 公转:球体、晨昏线、直射点、轨道与四季;播放、拖动、缩放、节气定位。 */
|
||||
public final class EarthPanel extends JPanel {
|
||||
private final boolean revolution;
|
||||
private final EarthData data;
|
||||
private final JComponent canvas;
|
||||
private final javax.swing.Timer timer;
|
||||
private double spin = 0, orbit = 0, speed = 1;
|
||||
private boolean playing = true;
|
||||
private boolean labels = true, grid;
|
||||
private double viewYaw = 18, viewPitch = 22, zoom = 1;
|
||||
private final JLabel spinInfo = Theme.label("", 11.5f, new Color(0xC6D5EC));
|
||||
private final JLabel orbitInfo = Theme.label("", 11.5f, new Color(0xC6D5EC));
|
||||
private final JLabel declInfo = Theme.boldLabel("", 17, new Color(0xEAF2FF));
|
||||
private final JLabel dateInfo = Theme.label("", 11.5f, new Color(0x9FB4D4));
|
||||
private final JLabel seasonInfo = Theme.label("", 11.5f, new Color(0xE9B25B));
|
||||
private final JLabel speedLabel = Theme.label("1.0×", 11, new Color(0x9FB4D4));
|
||||
private final JLabel lessonTitle = Theme.boldLabel("", 12.5f, new Color(0xEAF2FF));
|
||||
private final JLabel lessonBody = Theme.label("", 11, new Color(0xA9BBD8));
|
||||
|
||||
public EarthPanel(ModelManifest.Package pkg, boolean revolution) {
|
||||
this.revolution = revolution;
|
||||
this.data = EarthData.load(pkg.dataDir());
|
||||
setLayout(new BorderLayout());
|
||||
setBackground(new Color(0x080F1C));
|
||||
canvas = createCanvas();
|
||||
installViewControls();
|
||||
add(header(), BorderLayout.NORTH);
|
||||
JPanel main = new JPanel(new BorderLayout(12, 0));
|
||||
main.setOpaque(false);
|
||||
main.setBorder(new EmptyBorder(0, 12, 10, 14));
|
||||
main.add(canvas, BorderLayout.CENTER);
|
||||
main.add(sidebar(), BorderLayout.EAST);
|
||||
add(main, BorderLayout.CENTER);
|
||||
JComponent footer = footer();
|
||||
add(footer, BorderLayout.SOUTH);
|
||||
timer = new javax.swing.Timer(16, e -> tick());
|
||||
timer.start();
|
||||
updateHud();
|
||||
updateLesson(0);
|
||||
}
|
||||
|
||||
/** 优先使用 JOGL OpenGL 场景;无显示环境或驱动不可用时回退 Java2D。 */
|
||||
private JComponent createCanvas() {
|
||||
try {
|
||||
if (GlEarthView.available()) {
|
||||
return new GlEarthView(new GlEarthView.Scene() {
|
||||
@Override public boolean revolution() { return revolution; }
|
||||
@Override public double spin() { return spin; }
|
||||
@Override public double orbit() { return orbit; }
|
||||
@Override public boolean labels() { return labels; }
|
||||
@Override public boolean grid() { return grid; }
|
||||
@Override public List<List<double[]>> land() { return data.land; }
|
||||
});
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
System.err.println("[earth] OpenGL 初始化失败,回退 Java2D: " + t.getMessage());
|
||||
}
|
||||
return new EarthCanvas();
|
||||
}
|
||||
|
||||
/** Java2D 回退画布的拖动控制;OpenGL 画布自身已实现同样的交互。 */
|
||||
private void installViewControls() {
|
||||
if (!(canvas instanceof EarthCanvas)) return;
|
||||
java.awt.event.MouseAdapter ma = new java.awt.event.MouseAdapter() {
|
||||
private int x, y;
|
||||
@Override public void mousePressed(MouseEvent e) { x = e.getX(); y = e.getY(); }
|
||||
@Override public void mouseDragged(MouseEvent e) {
|
||||
viewYaw += (e.getX() - x) * 0.45;
|
||||
viewPitch = Math.max(-78, Math.min(78, viewPitch - (e.getY() - y) * 0.35));
|
||||
x = e.getX(); y = e.getY();
|
||||
canvas.repaint();
|
||||
}
|
||||
};
|
||||
canvas.addMouseListener(ma);
|
||||
canvas.addMouseMotionListener(ma);
|
||||
canvas.addMouseWheelListener(e -> {
|
||||
zoom = Math.max(0.55, Math.min(2.2, zoom * (e.getWheelRotation() < 0 ? 1.12 : 0.89)));
|
||||
canvas.repaint();
|
||||
});
|
||||
}
|
||||
|
||||
private JComponent header() {
|
||||
JPanel h = new JPanel(new BorderLayout());
|
||||
h.setBackground(new Color(0x0C1828));
|
||||
h.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x1B2740)),
|
||||
new EmptyBorder(12, 18, 10, 18)));
|
||||
JPanel t = new JPanel();
|
||||
t.setOpaque(false);
|
||||
t.setLayout(new UI.VStackLayout());
|
||||
t.add(Theme.boldLabel(revolution ? "地球公转 · 四季成因" : "地球自转 · 昼夜交替", 20, new Color(0xEAF2FF)));
|
||||
t.add(Theme.label(revolution ? "地轴指向不变,太阳直射点在南北回归线之间往返"
|
||||
: "自西向东转动 · 晨昏线分割昼夜 · 太阳直射点随季节移动", 11, new Color(0x9FB4D4)));
|
||||
h.add(t, BorderLayout.WEST);
|
||||
return h;
|
||||
}
|
||||
|
||||
private JComponent footer() {
|
||||
JPanel f = new JPanel(new BorderLayout());
|
||||
f.setBackground(new Color(0x0C1828));
|
||||
f.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(0x1B2740)),
|
||||
new EmptyBorder(8, 16, 8, 16)));
|
||||
JPanel l = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
l.setOpaque(false);
|
||||
UI.RoundButton play = UI.primary("⏸ 暂停");
|
||||
play.addActionListener(e -> { playing = !playing; play.setText(playing ? "⏸ 暂停" : "▶ 播放"); });
|
||||
l.add(play);
|
||||
UI.RoundButton reset = UI.button("重置");
|
||||
reset.addActionListener(e -> {
|
||||
spin = 0; orbit = 0; playing = true;
|
||||
zoom = 1; viewYaw = 18; viewPitch = 22;
|
||||
if (canvas instanceof GlEarthView gl) gl.resetView();
|
||||
updateHud(); canvas.repaint();
|
||||
});
|
||||
l.add(reset);
|
||||
l.add(Theme.label("速度", 11, new Color(0x9FB4D4)));
|
||||
UI.Slider sp = new UI.Slider(1, 50, 10, false);
|
||||
sp.setPreferredSize(new Dimension(150, 28));
|
||||
sp.addChangeListener(e -> {
|
||||
speed = sp.getValue() / 10.0;
|
||||
speedLabel.setText(String.format(Locale.ROOT, "%.1f×", speed));
|
||||
});
|
||||
l.add(sp);
|
||||
l.add(speedLabel);
|
||||
UI.Switch lab = new UI.Switch("标注", true);
|
||||
lab.addActionListener(e -> { labels = lab.isSelected(); canvas.repaint(); });
|
||||
UI.Switch gr = new UI.Switch("经纬网", !revolution);
|
||||
gr.addActionListener(e -> { grid = gr.isSelected(); canvas.repaint(); });
|
||||
grid = gr.isSelected();
|
||||
l.add(lab); l.add(gr);
|
||||
f.add(l, BorderLayout.WEST);
|
||||
JLabel hint = Theme.label("拖动旋转视角(上下/左右) · 滚轮缩放", 10.5f, new Color(0x71819A));
|
||||
f.add(hint, BorderLayout.EAST);
|
||||
return f;
|
||||
}
|
||||
|
||||
private JComponent sidebar() {
|
||||
JPanel p = new JPanel();
|
||||
p.setOpaque(false);
|
||||
p.setLayout(new UI.VStackLayout());
|
||||
p.setPreferredSize(new Dimension(320, 0));
|
||||
|
||||
UI.Card hud = card();
|
||||
hud.setLayout(new UI.VStackLayout());
|
||||
hud.add(Theme.label(I18n.t("player.subsolar"), 11, new Color(0x9FB4D4)));
|
||||
hud.add(Box.createVerticalStrut(3));
|
||||
declInfo.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
hud.add(declInfo);
|
||||
hud.add(Box.createVerticalStrut(4));
|
||||
dateInfo.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
hud.add(dateInfo);
|
||||
hud.add(Box.createVerticalStrut(2));
|
||||
seasonInfo.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
hud.add(seasonInfo);
|
||||
hud.add(Box.createVerticalStrut(10));
|
||||
spinInfo.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
orbitInfo.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
hud.add(spinInfo);
|
||||
hud.add(Box.createVerticalStrut(3));
|
||||
hud.add(orbitInfo);
|
||||
p.add(hud);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
|
||||
UI.Card seasons = card();
|
||||
seasons.setLayout(new UI.VStackLayout());
|
||||
seasons.add(Theme.boldLabel(I18n.t("player.seasons"), 12.5f, new Color(0xEAF2FF)));
|
||||
seasons.add(Box.createVerticalStrut(6));
|
||||
JPanel sg = new JPanel(new GridLayout(2, 2, 6, 6));
|
||||
sg.setOpaque(false);
|
||||
for (EarthMath.Season s : EarthMath.SEASONS) {
|
||||
UI.RoundButton b = UI.button(I18n.t(s.key()));
|
||||
b.setFont(Theme.font(11));
|
||||
b.setBorder(new EmptyBorder(5, 8, 5, 8));
|
||||
b.addActionListener(e -> { orbit = s.angleDeg(); playing = false; updateHud(); updateSeason(s); canvas.repaint(); });
|
||||
sg.add(b);
|
||||
}
|
||||
seasons.add(sg);
|
||||
p.add(seasons);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
|
||||
UI.Card lesson = card();
|
||||
lesson.setLayout(new UI.VStackLayout());
|
||||
lesson.add(Theme.boldLabel(I18n.t("player.lessons"), 12.5f, new Color(0xEAF2FF)));
|
||||
lesson.add(Box.createVerticalStrut(8));
|
||||
JPanel list = new JPanel();
|
||||
list.setOpaque(false);
|
||||
list.setLayout(new UI.VStackLayout());
|
||||
for (int i = 0; i < data.lessons.size(); i++) {
|
||||
final int idx = i;
|
||||
UI.RoundButton b = UI.button(data.lessons.get(i).title());
|
||||
b.setFont(Theme.font(10.5f));
|
||||
b.setBorder(new EmptyBorder(4, 8, 4, 8));
|
||||
b.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
b.addActionListener(e -> {
|
||||
EarthData.Lesson l = data.lessons.get(idx);
|
||||
orbit = l.angleDeg;
|
||||
playing = false;
|
||||
updateLesson(idx);
|
||||
updateHud();
|
||||
canvas.repaint();
|
||||
});
|
||||
list.add(b);
|
||||
list.add(Box.createVerticalStrut(3));
|
||||
}
|
||||
lesson.add(list);
|
||||
p.add(lesson);
|
||||
p.add(Box.createVerticalGlue());
|
||||
return p;
|
||||
}
|
||||
|
||||
private UI.Card card() {
|
||||
UI.Card c = new UI.Card();
|
||||
c.setBorder(new EmptyBorder(12, 14, 12, 14));
|
||||
c.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.setMaximumSize(new Dimension(Integer.MAX_VALUE, 900));
|
||||
c.alt = true;
|
||||
c.bgOverride = new Color(0x121D2E);
|
||||
c.borderOverride = new Color(0x24324A);
|
||||
return c;
|
||||
}
|
||||
|
||||
private void updateLesson(int i) {
|
||||
if (data.lessons.isEmpty()) return;
|
||||
EarthData.Lesson l = data.lessons.get(i);
|
||||
lessonTitle.setText(l.title());
|
||||
lessonBody.setText("<html><body style='width:250px'>" + l.body() + "</body></html>");
|
||||
}
|
||||
|
||||
private void updateSeason(EarthMath.Season s) {
|
||||
seasonInfo.setText(I18n.t(s.key()) + " · " + s.date());
|
||||
}
|
||||
|
||||
private void updatePlayText() { }
|
||||
|
||||
public void disposePanel() {
|
||||
if (timer != null) timer.stop();
|
||||
}
|
||||
|
||||
private void tick() {
|
||||
if (!playing) return;
|
||||
double dt = 1.0 / 60;
|
||||
double[] r = EarthMath.stepAngles(spin, orbit, dt, speed);
|
||||
spin = r[0]; orbit = r[1];
|
||||
updateHud();
|
||||
canvas.repaint();
|
||||
}
|
||||
|
||||
private void updateHud() {
|
||||
double decl = EarthMath.subsolarLatitude(orbit);
|
||||
declInfo.setText(String.format(Locale.ROOT, "%+.1f° %s", decl, decl >= 0 ? "N" : "S"));
|
||||
dateInfo.setText(I18n.f("player.dateInfo", EarthMath.dateText(orbit)));
|
||||
EarthMath.Season season = EarthMath.nearestSeason(orbit);
|
||||
seasonInfo.setText(I18n.t(season.key()) + " · " + season.date());
|
||||
spinInfo.setText(I18n.f("player.spinInfo", String.format(Locale.ROOT, "%.0f", spin), "23.93"));
|
||||
orbitInfo.setText(I18n.f("player.orbitInfo", String.format(Locale.ROOT, "%.0f", orbit)));
|
||||
}
|
||||
|
||||
private final class EarthCanvas extends JComponent {
|
||||
EarthCanvas() { setOpaque(false); }
|
||||
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
paintSpace(g2);
|
||||
Graphics2D scene = (Graphics2D) g2.create();
|
||||
int w = getWidth(), h = getHeight();
|
||||
double squash = Math.max(0.35, Math.cos(Math.toRadians(viewPitch)) / Math.cos(Math.toRadians(22)));
|
||||
scene.translate(w / 2.0, h / 2.0);
|
||||
scene.scale(1, squash);
|
||||
scene.translate(-w / 2.0, -h / 2.0);
|
||||
if (revolution) paintOrbit(scene); else paintGlobeScene(scene);
|
||||
scene.dispose();
|
||||
g2.dispose();
|
||||
}
|
||||
|
||||
private void paintSpace(Graphics2D g2) {
|
||||
g2.setColor(new Color(0x080F1C));
|
||||
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 14, 14);
|
||||
Random rnd = new Random(42);
|
||||
for (int i = 0; i < 130; i++) {
|
||||
int x = rnd.nextInt(Math.max(1, getWidth())), y = rnd.nextInt(Math.max(1, getHeight()));
|
||||
g2.setColor(new Color(255, 255, 255, 25 + rnd.nextInt(100)));
|
||||
g2.fillOval(x, y, 1 + rnd.nextInt(2), 1 + rnd.nextInt(2));
|
||||
}
|
||||
}
|
||||
|
||||
private void paintGlobeScene(Graphics2D g2) {
|
||||
int w = getWidth(), h = getHeight();
|
||||
double r = Math.min(w, h) * 0.34 * zoom;
|
||||
double cx = w * 0.46, cy = h * 0.50;
|
||||
drawGlobe(g2, cx, cy, r, spin + viewYaw, EarthMath.TILT, labels);
|
||||
// mini orbit
|
||||
drawOrbitInset(g2, w - 190, h - 150, 150, 120);
|
||||
// caption
|
||||
g2.setColor(new Color(0x9FB4D4));
|
||||
g2.setFont(Theme.font(11));
|
||||
g2.drawString("自西向东 · 从北极上空看逆时针", 20, h - 20);
|
||||
}
|
||||
|
||||
private void paintOrbit(Graphics2D g2) {
|
||||
int w = getWidth(), h = getHeight();
|
||||
double cx = w * 0.47, cy = h * 0.52;
|
||||
double rx = Math.min(w * 0.33, 380), ry = Math.min(h * 0.32, 250);
|
||||
// orbit ellipse
|
||||
g2.setColor(new Color(0x2B3E60));
|
||||
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{6, 8}, 0));
|
||||
g2.draw(new Ellipse2D.Double(cx - rx, cy - ry, rx * 2, ry * 2));
|
||||
g2.setStroke(new BasicStroke(1));
|
||||
// sun
|
||||
RadialGradientPaint sun = new RadialGradientPaint(new Point2D.Double(cx, cy), 70,
|
||||
new float[]{0, 1}, new Color[]{new Color(0xFFE3A3), new Color(255, 194, 75, 40)});
|
||||
g2.setPaint(sun);
|
||||
g2.fillOval((int) (cx - 70), (int) (cy - 70), 140, 140);
|
||||
g2.setColor(new Color(0xFFC24B));
|
||||
g2.fillOval((int) (cx - 26), (int) (cy - 26), 52, 52);
|
||||
if (labels) {
|
||||
g2.setColor(new Color(0xEAF2FF));
|
||||
g2.setFont(Theme.bold(12));
|
||||
g2.drawString(I18n.t("star.sun"), (int) cx - 12, (int) cy + 5);
|
||||
}
|
||||
// seasons labels
|
||||
String[] order = {"season.springEquinox", "season.summerSolstice", "season.autumnEquinox", "season.winterSolstice"};
|
||||
double[] angles = {0, 90, 180, 270};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
double a = Math.toRadians(angles[i]);
|
||||
double x = cx - rx * Math.sin(a), y = cy - ry * Math.cos(a);
|
||||
boolean near = Math.abs(((orbit - angles[i] + 540) % 360) - 180) > 160;
|
||||
g2.setColor(near ? new Color(0xFFD166) : new Color(0x71819A));
|
||||
g2.setFont(near ? Theme.bold(11) : Theme.font(11));
|
||||
String s = I18n.t(order[i]);
|
||||
g2.drawString(s, (float) x - g2.getFontMetrics().stringWidth(s) / 2f, (float) (y - 12));
|
||||
if (near) {
|
||||
g2.setColor(new Color(0xFFD166));
|
||||
g2.fillOval((int) x - 3, (int) y - 3, 6, 6);
|
||||
}
|
||||
}
|
||||
// earth on orbit
|
||||
double a = Math.toRadians(orbit);
|
||||
double ex = cx - rx * Math.sin(a), ey = cy - ry * Math.cos(a);
|
||||
drawGlobe(g2, ex, ey, 34 * zoom, spin + viewYaw, EarthMath.TILT, labels);
|
||||
// axis line
|
||||
g2.setColor(new Color(255, 255, 255, 130));
|
||||
g2.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{3, 4}, 0));
|
||||
g2.drawLine((int) (ex + 12), (int) (ey - 58), (int) (ex - 12), (int) (ey + 58));
|
||||
// sun->earth line
|
||||
g2.setColor(new Color(255, 200, 90, 70));
|
||||
g2.setStroke(new BasicStroke(1f));
|
||||
g2.drawLine((int) cx, (int) cy, (int) ex, (int) ey);
|
||||
if (labels) {
|
||||
g2.setColor(new Color(0xEAF2FF));
|
||||
g2.setFont(Theme.bold(10.5f));
|
||||
String s = EarthMath.dateText(orbit);
|
||||
g2.drawString(s, (float) ex + 42, (float) ey + 4);
|
||||
g2.setColor(new Color(0xFFD166));
|
||||
g2.drawString(String.format(Locale.ROOT, "%.1f°%s", Math.abs(EarthMath.subsolarLatitude(orbit)),
|
||||
EarthMath.subsolarLatitude(orbit) >= 0 ? "N" : "S"), (float) ex + 42, (float) ey + 20);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawOrbitInset(Graphics2D g2, double x, double y, double w, double h) {
|
||||
g2.setColor(new Color(0x0F1E33));
|
||||
g2.fillRoundRect((int) x, (int) y, (int) w, (int) h, 10, 10);
|
||||
g2.setColor(new Color(0x1B2740));
|
||||
g2.drawRoundRect((int) x, (int) y, (int) w - 1, (int) h - 1, 10, 10);
|
||||
double cx = x + w / 2, cy = y + h / 2 + 6, rx = w * 0.35, ry = h * 0.30;
|
||||
g2.setColor(new Color(0x2B3E60));
|
||||
g2.draw(new Ellipse2D.Double(cx - rx, cy - ry, rx * 2, ry * 2));
|
||||
g2.setColor(new Color(0xFFC24B));
|
||||
g2.fillOval((int) cx - 8, (int) cy - 8, 16, 16);
|
||||
double a = Math.toRadians(orbit);
|
||||
double ex = cx - rx * Math.sin(a), ey = cy - ry * Math.cos(a);
|
||||
g2.setColor(new Color(0x3D7BD9));
|
||||
g2.fillOval((int) ex - 6, (int) ey - 6, 12, 12);
|
||||
g2.setColor(new Color(0x9FB4D4));
|
||||
g2.setFont(Theme.font(9));
|
||||
g2.drawString("轨道", (int) x + 10, (int) y + 16);
|
||||
}
|
||||
|
||||
private void drawGlobe(Graphics2D g2, double cx, double cy, double r, double spinDeg, double tilt, boolean showLabels) {
|
||||
Shape clip = new Ellipse2D.Double(cx - r, cy - r, r * 2, r * 2);
|
||||
RadialGradientPaint ocean = new RadialGradientPaint(new Point2D.Double(cx - r * 0.25, cy - r * 0.25), (float) (r * 1.5),
|
||||
new float[]{0, 1}, new Color[]{new Color(0x3D7BD9), new Color(0x10264D)});
|
||||
g2.setPaint(ocean);
|
||||
g2.fill(clip);
|
||||
g2.setClip(clip);
|
||||
// graticule
|
||||
if (grid && r > 50) {
|
||||
g2.setColor(new Color(255, 255, 255, 36));
|
||||
g2.setStroke(new BasicStroke(0.7f));
|
||||
for (int lat = -60; lat <= 60; lat += 30) drawLatLine(g2, cx, cy, r, lat, spinDeg, tilt);
|
||||
for (int lon = -180; lon < 180; lon += 30) drawLonLine(g2, cx, cy, r, lon, spinDeg, tilt);
|
||||
}
|
||||
// land
|
||||
for (List<double[]> poly : data.land) drawLand(g2, cx, cy, r, poly, spinDeg, tilt);
|
||||
// terminator / night
|
||||
double sunLat = EarthMath.subsolarLatitude(orbit);
|
||||
double sunLon = orbit;
|
||||
double[] sv = unitView(sunLon, sunLat, tilt);
|
||||
double antx = cx - sv[0] * r * 1.05, anty = cy + sv[1] * r * 1.05;
|
||||
RadialGradientPaint night = new RadialGradientPaint(new Point2D.Double(antx, anty), (float) (r * 2.2),
|
||||
new float[]{0f, 0.45f, 1f},
|
||||
new Color[]{new Color(0, 0, 10, 175), new Color(0, 0, 10, 120), new Color(0, 0, 10, 0)});
|
||||
g2.setPaint(night);
|
||||
g2.fill(clip);
|
||||
g2.setClip(null);
|
||||
g2.setColor(new Color(255, 255, 255, 90));
|
||||
g2.setStroke(new BasicStroke(1f));
|
||||
g2.draw(clip);
|
||||
// axis
|
||||
double[] np = unit(0, 90, tilt), sp = unit(0, -90, tilt);
|
||||
g2.setColor(new Color(255, 255, 255, 120));
|
||||
g2.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{4, 5}, 0));
|
||||
g2.draw(new Line2D.Double(cx - np[0] * r * 0.0, cy + np[1] * r * 1.12, cx - sp[0] * r, cy + sp[1] * r * 1.12));
|
||||
if (showLabels && r > 50) {
|
||||
g2.setFont(Theme.bold(10));
|
||||
g2.setColor(new Color(0xEAF2FF));
|
||||
g2.drawString(I18n.t("player.north"), (float) (cx + np[0] * r * 0.0 - 12), (float) (cy - r * 1.05));
|
||||
g2.drawString(I18n.t("player.south"), (float) (cx - 12), (float) (cy + r * 1.08));
|
||||
// subsolar marker
|
||||
double[] p = projectView(sunLon, sunLat, tilt);
|
||||
if (p[2] > 0) {
|
||||
double x = cx + p[0] * r, y = cy - p[1] * r;
|
||||
g2.setColor(new Color(0xFFD166));
|
||||
g2.setStroke(new BasicStroke(1.5f));
|
||||
g2.drawOval((int) x - 6, (int) y - 6, 12, 12);
|
||||
g2.drawLine((int) x - 10, (int) y, (int) x + 10, (int) y);
|
||||
g2.drawLine((int) x, (int) y - 10, (int) x, (int) y + 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void drawLand(Graphics2D g2, double cx, double cy, double r, List<double[]> poly,
|
||||
double spinDeg, double tilt) {
|
||||
Path2D path = new Path2D.Double();
|
||||
boolean first = true;
|
||||
boolean allVisible = true;
|
||||
int visible = 0;
|
||||
for (double[] p : poly) {
|
||||
double[] q = projectPoint(p[0], p[1], spinDeg, tilt);
|
||||
if (q[2] <= 0) { allVisible = false; continue; }
|
||||
visible++;
|
||||
double x = cx + q[0] * r, y = cy - q[1] * r;
|
||||
if (first) { path.moveTo(x, y); first = false; } else path.lineTo(x, y);
|
||||
}
|
||||
if (visible < 3) return;
|
||||
if (allVisible) {
|
||||
path.closePath();
|
||||
g2.setColor(new Color(0x4E8C4C));
|
||||
g2.fill(path);
|
||||
g2.setColor(new Color(0xBFE3B0));
|
||||
g2.setStroke(new BasicStroke(0.6f));
|
||||
g2.draw(path);
|
||||
} else {
|
||||
g2.setColor(new Color(0x4E8C4C));
|
||||
g2.setStroke(new BasicStroke(0.9f));
|
||||
g2.draw(path);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawLatLine(Graphics2D g2, double cx, double cy, double r, double lat, double spinDeg, double tilt) {
|
||||
Path2D p = new Path2D.Double();
|
||||
boolean first = true;
|
||||
for (int lon = -180; lon <= 180; lon += 4) {
|
||||
double[] q = projectPoint(lon, lat, spinDeg, tilt);
|
||||
if (q[2] <= 0) { first = true; continue; }
|
||||
double x = cx + q[0] * r, y = cy - q[1] * r;
|
||||
if (first) { p.moveTo(x, y); first = false; } else p.lineTo(x, y);
|
||||
}
|
||||
g2.draw(p);
|
||||
}
|
||||
|
||||
private void drawLonLine(Graphics2D g2, double cx, double cy, double r, double lon, double spinDeg, double tilt) {
|
||||
Path2D p = new Path2D.Double();
|
||||
boolean first = true;
|
||||
for (int lat = -90; lat <= 90; lat += 4) {
|
||||
double[] q = projectPoint(lon, lat, spinDeg, tilt);
|
||||
if (q[2] <= 0) { first = true; continue; }
|
||||
double x = cx + q[0] * r, y = cy - q[1] * r;
|
||||
if (first) { p.moveTo(x, y); first = false; } else p.lineTo(x, y);
|
||||
}
|
||||
g2.draw(p);
|
||||
}
|
||||
|
||||
private double[] unit(double lon, double lat, double tilt) {
|
||||
double la = Math.toRadians(lat), lo = Math.toRadians(lon);
|
||||
double x = Math.cos(la) * Math.sin(lo), y = Math.sin(la), z = Math.cos(la) * Math.cos(lo);
|
||||
double t = Math.toRadians(tilt);
|
||||
return new double[]{x, y * Math.cos(t) - z * Math.sin(t), y * Math.sin(t) + z * Math.cos(t)};
|
||||
}
|
||||
|
||||
private double[] unitView(double lon, double lat, double tilt) { return unit(lon, lat, tilt); }
|
||||
|
||||
private double[] projectPoint(double lon, double lat, double spinDeg, double tilt) {
|
||||
double la = Math.toRadians(lat), lo = Math.toRadians(lon + spinDeg);
|
||||
double x = Math.cos(la) * Math.sin(lo), y = Math.sin(la), z = Math.cos(la) * Math.cos(lo);
|
||||
double t = Math.toRadians(tilt);
|
||||
double yy = y * Math.cos(t) - z * Math.sin(t);
|
||||
double zz = y * Math.sin(t) + z * Math.cos(t);
|
||||
return new double[]{x, yy, zz};
|
||||
}
|
||||
|
||||
private double[] projectView(double lon, double lat, double tilt) {
|
||||
return projectPoint(lon, lat, 0, tilt);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 数据
|
||||
|
||||
private static final class EarthData {
|
||||
final List<List<double[]>> land = new ArrayList<>();
|
||||
final List<Lesson> lessons = new ArrayList<>();
|
||||
|
||||
record Lesson(String title, String body, String view, double angleDeg) {}
|
||||
|
||||
static EarthData load(Path dir) {
|
||||
EarthData d = new EarthData();
|
||||
try {
|
||||
Path landFile = dir.resolve("land.json");
|
||||
if (Files.isRegularFile(landFile)) {
|
||||
Map<String, Object> m = Json.obj(Json.parse(landFile));
|
||||
for (Object po : Json.arr(m.get("polygons"))) {
|
||||
Map<String, Object> p = Json.obj(po);
|
||||
List<double[]> pts = new ArrayList<>();
|
||||
for (Object pt : Json.arr(p.get("points"))) {
|
||||
List<Object> pair = Json.arr(pt);
|
||||
if (pair.size() >= 2) pts.add(new double[]{num(pair.get(0)), num(pair.get(1))});
|
||||
}
|
||||
if (pts.size() > 2) d.land.add(pts);
|
||||
}
|
||||
}
|
||||
Path sceneFile = dir.resolve("scene.json");
|
||||
if (Files.isRegularFile(sceneFile)) {
|
||||
Map<String, Object> scene = Json.obj(Json.parse(sceneFile));
|
||||
String lang = I18n.language();
|
||||
for (Object lo : Json.arr(scene.get("lessons"))) {
|
||||
Map<String, Object> l = Json.obj(lo);
|
||||
String title = pick(Json.obj(l.get("titleI18n")), lang);
|
||||
String body = pick(Json.obj(l.get("bodyI18n")), lang);
|
||||
d.lessons.add(new Lesson(title, body, Json.str(l, "view", ""), Json.d(l, "angleDeg", 0)));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("[earth] 读取场景失败: " + e.getMessage());
|
||||
}
|
||||
if (d.land.isEmpty()) {
|
||||
d.land.add(List.of(new double[]{-100, 40}, new double[]{-80, 10}, new double[]{-40, -20},
|
||||
new double[]{-70, -50}, new double[]{-120, 20}));
|
||||
d.land.add(List.of(new double[]{10, 60}, new double[]{40, 60}, new double[]{120, 30},
|
||||
new double[]{100, -10}, new double[]{20, -30}, new double[]{-10, 10}));
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static String pick(Map<String, Object> m, String lang) {
|
||||
Object v = m.get(lang);
|
||||
if (v == null) v = m.get("zh-CN");
|
||||
if (v == null) v = m.values().stream().findFirst().orElse("");
|
||||
return String.valueOf(v);
|
||||
}
|
||||
|
||||
static double num(Object o) {
|
||||
return o instanceof Json.Num n ? n.asDouble() : Double.parseDouble(String.valueOf(o));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.I18n;
|
||||
import com.gc.core.Json;
|
||||
import com.gc.core.ModelManifest;
|
||||
import com.gc.model.earth.EarthMath;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.awt.geom.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
|
||||
/** 地球地理:五带划分、海陆轮廓、大洲大洋、六大板块与洲界,悬停判读温度带。 */
|
||||
public final class GeographyPanel extends JPanel {
|
||||
private final GeoData data;
|
||||
private final MapCanvas canvas = new MapCanvas();
|
||||
private final JLabel hover = Theme.label("", 12.5f, new Color(0xEAF2FF));
|
||||
private final JLabel zoneInfo = Theme.boldLabel("", 16, new Color(0xEAF2FF));
|
||||
private final JLabel coord = Theme.label("", 11, new Color(0x9FB4D4));
|
||||
private final JPanel zoneList = new JPanel();
|
||||
private final JLabel modeTitle = Theme.boldLabel("", 14, new Color(0xEAF2FF));
|
||||
private final Map<String, UI.RoundButton> tabButtons = new LinkedHashMap<>();
|
||||
private String view = "zones";
|
||||
private double hoverLat = 0, hoverLon = 0;
|
||||
private boolean hovering;
|
||||
|
||||
public GeographyPanel(ModelManifest.Package pkg) {
|
||||
this.data = GeoData.load(pkg.dataDir());
|
||||
setLayout(new BorderLayout());
|
||||
setBackground(new Color(0x080F1C));
|
||||
add(header(), BorderLayout.NORTH);
|
||||
JPanel main = new JPanel(new BorderLayout(12, 0));
|
||||
main.setOpaque(false);
|
||||
main.setBorder(new EmptyBorder(0, 12, 12, 14));
|
||||
main.add(canvas, BorderLayout.CENTER);
|
||||
main.add(sidebar(), BorderLayout.EAST);
|
||||
add(main, BorderLayout.CENTER);
|
||||
add(footer(), BorderLayout.SOUTH);
|
||||
}
|
||||
|
||||
private JComponent header() {
|
||||
JPanel h = new JPanel(new BorderLayout());
|
||||
h.setBackground(new Color(0x0C1828));
|
||||
h.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x1B2740)),
|
||||
new EmptyBorder(12, 18, 10, 18)));
|
||||
JPanel t = new JPanel();
|
||||
t.setOpaque(false);
|
||||
t.setLayout(new UI.VStackLayout());
|
||||
t.add(Theme.boldLabel("地球地理 · 五带与海陆", 20, new Color(0xEAF2FF)));
|
||||
t.add(Theme.label("五带划分 · 七大洲四大洋 · 六大板块 · 洲界(纯线稿)", 11, new Color(0x9FB4D4)));
|
||||
h.add(t, BorderLayout.WEST);
|
||||
JPanel tabRow = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0));
|
||||
tabRow.setOpaque(false);
|
||||
for (String[] v : new String[][]{{"zones", "五带划分"}, {"coast", "海陆轮廓"}, {"plates", "六大板块"}}) {
|
||||
UI.RoundButton b = UI.button(v[1]);
|
||||
b.setFont(Theme.font(11));
|
||||
b.setBorder(new EmptyBorder(5, 12, 5, 12));
|
||||
b.primary = v[0].equals(view);
|
||||
b.ghost = !b.primary;
|
||||
b.addActionListener(e -> { view = v[0]; refreshTabs(); canvas.repaint(); modeTitle.setText(v[1]); });
|
||||
tabButtons.put(v[0], b);
|
||||
tabRow.add(b);
|
||||
}
|
||||
h.add(tabRow, BorderLayout.EAST);
|
||||
return h;
|
||||
}
|
||||
|
||||
private void refreshTabs() {
|
||||
tabButtons.forEach((k, b) -> {
|
||||
b.primary = k.equals(view);
|
||||
b.ghost = !b.primary;
|
||||
b.repaint();
|
||||
});
|
||||
}
|
||||
|
||||
private JComponent sidebar() {
|
||||
JPanel p = new JPanel();
|
||||
p.setOpaque(false);
|
||||
p.setLayout(new UI.VStackLayout());
|
||||
p.setPreferredSize(new Dimension(310, 0));
|
||||
|
||||
UI.Card read = card();
|
||||
read.setLayout(new UI.VStackLayout());
|
||||
read.add(Theme.boldLabel("实时判读", 12.5f, new Color(0xEAF2FF)));
|
||||
read.add(Box.createVerticalStrut(6));
|
||||
zoneInfo.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
read.add(zoneInfo);
|
||||
coord.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
read.add(Box.createVerticalStrut(3));
|
||||
read.add(coord);
|
||||
hover.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
read.add(Box.createVerticalStrut(6));
|
||||
read.add(hover);
|
||||
p.add(read);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
|
||||
UI.Card zones = card();
|
||||
zones.setLayout(new UI.VStackLayout());
|
||||
zones.add(Theme.boldLabel("五带", 12.5f, new Color(0xEAF2FF)));
|
||||
zones.add(Box.createVerticalStrut(6));
|
||||
zoneList.setOpaque(false);
|
||||
zoneList.setLayout(new UI.VStackLayout());
|
||||
for (EarthMath.Zone z : EarthMath.ZONES) {
|
||||
JPanel row = new JPanel(new BorderLayout(8, 0));
|
||||
row.setOpaque(false);
|
||||
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30));
|
||||
JLabel chip = new JLabel();
|
||||
chip.setOpaque(true);
|
||||
chip.setBackground(zoneColor(z.id()));
|
||||
chip.setPreferredSize(new Dimension(12, 12));
|
||||
row.add(chip, BorderLayout.WEST);
|
||||
row.add(Theme.label(z.nameZh() + " / " + z.nameEn(), 10.5f, new Color(0xC6D5EC)), BorderLayout.CENTER);
|
||||
row.add(Theme.label(String.format(Locale.ROOT, "%.1f°~%.1f°", z.latMin(), z.latMax()), 9.5f, new Color(0x71819A)), BorderLayout.EAST);
|
||||
zoneList.add(row);
|
||||
zoneList.add(Box.createVerticalStrut(4));
|
||||
}
|
||||
zones.add(zoneList);
|
||||
p.add(zones);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
|
||||
UI.Card facts = card();
|
||||
facts.setLayout(new UI.VStackLayout());
|
||||
facts.add(Theme.boldLabel("判读要点", 12.5f, new Color(0xEAF2FF)));
|
||||
facts.add(Box.createVerticalStrut(6));
|
||||
for (String s : new String[]{
|
||||
"热带:有太阳直射,终年炎热",
|
||||
"温带:四季分明,无直射无极昼",
|
||||
"寒带:有极昼极夜,终年寒冷",
|
||||
"回归线 23.5°;极圈 66.5°",
|
||||
"大陆:亚欧、非洲、北美、南美、南极、大洋洲",
|
||||
"四大洋:太平洋、大西洋、印度洋、北冰洋",
|
||||
"六大板块:亚欧、非洲、印度洋、太平洋、美洲、南极洲"}) {
|
||||
JLabel l = Theme.label("· " + s, 10.5f, new Color(0xA9BBD8));
|
||||
l.setToolTipText(s);
|
||||
facts.add(l);
|
||||
}
|
||||
p.add(facts);
|
||||
p.add(Box.createVerticalGlue());
|
||||
return p;
|
||||
}
|
||||
|
||||
private UI.Card card() {
|
||||
UI.Card c = new UI.Card();
|
||||
c.setBorder(new EmptyBorder(12, 14, 12, 14));
|
||||
c.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.setMaximumSize(new Dimension(Integer.MAX_VALUE, 900));
|
||||
c.alt = true;
|
||||
c.bgOverride = new Color(0x121D2E);
|
||||
c.borderOverride = new Color(0x24324A);
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent footer() {
|
||||
JPanel f = new JPanel(new BorderLayout());
|
||||
f.setBackground(new Color(0x0C1828));
|
||||
f.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(0x1B2740)),
|
||||
new EmptyBorder(8, 16, 8, 16)));
|
||||
modeTitle.setText("五带划分");
|
||||
f.add(modeTitle, BorderLayout.WEST);
|
||||
f.add(Theme.label("移动鼠标读取经纬度与所属温度带", 10.5f, new Color(0x71819A)), BorderLayout.EAST);
|
||||
return f;
|
||||
}
|
||||
|
||||
private static Color zoneColor(String id) {
|
||||
return switch (id) {
|
||||
case "torrid" -> new Color(0xE08A4B);
|
||||
case "northTemperate", "southTemperate" -> new Color(0x5FAF6A);
|
||||
default -> new Color(0x6FA8D8);
|
||||
};
|
||||
}
|
||||
|
||||
private final class MapCanvas extends JComponent {
|
||||
MapCanvas() {
|
||||
addMouseMotionListener(new MouseMotionAdapter() {
|
||||
@Override public void mouseMoved(MouseEvent e) {
|
||||
Rectangle r = mapRect();
|
||||
if (r == null || !r.contains(e.getX(), e.getY())) { hovering = false; repaint(); return; }
|
||||
hovering = true;
|
||||
hoverLon = (e.getX() - r.x) / (double) r.width * 360 - 180;
|
||||
hoverLat = 90 - (e.getY() - r.y) / (double) r.height * 180;
|
||||
EarthMath.Zone z = EarthMath.zone(hoverLat);
|
||||
zoneInfo.setText(String.format(Locale.ROOT, "%s %s", z.nameZh(), z.nameEn()));
|
||||
zoneInfo.setForeground(zoneColor(z.id()));
|
||||
coord.setText(String.format(Locale.ROOT, "纬度 %+.1f° 经度 %+.1f°", hoverLat, hoverLon));
|
||||
hover.setText("直射/极昼: " + (Math.abs(hoverLat) < 23.5 ? "有太阳直射"
|
||||
: Math.abs(hoverLat) >= 66.5 ? "有极昼极夜" : "四季分明"));
|
||||
repaint();
|
||||
}
|
||||
});
|
||||
addMouseListener(new MouseAdapter() {
|
||||
@Override public void mouseExited(MouseEvent e) { hovering = false; repaint(); }
|
||||
});
|
||||
}
|
||||
|
||||
Rectangle mapRect() {
|
||||
int pad = 22;
|
||||
int availW = Math.max(10, getWidth() - pad * 2);
|
||||
int availH = Math.max(10, getHeight() - pad * 2);
|
||||
double ratio = 2.0;
|
||||
int w = (int) Math.min(availW, availH * ratio);
|
||||
int h = (int) (w / ratio);
|
||||
return new Rectangle(pad + (availW - w) / 2, pad + (availH - h) / 2, w, h);
|
||||
}
|
||||
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g2.setColor(new Color(0x080F1C));
|
||||
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 14, 14);
|
||||
Rectangle r = mapRect();
|
||||
if (r == null) { g2.dispose(); return; }
|
||||
Shape clip = new RoundRectangle2D.Float(r.x, r.y, r.width, r.height, 12, 12);
|
||||
g2.setClip(clip);
|
||||
g2.setColor(new Color(0x0E2A4A));
|
||||
g2.fillRect(r.x, r.y, r.width, r.height);
|
||||
if (view.equals("zones")) paintZones(g2, r);
|
||||
if (view.equals("coast") || view.equals("zones")) paintCoast(g2, r);
|
||||
if (view.equals("plates")) paintPlates(g2, r);
|
||||
paintGraticule(g2, r);
|
||||
if (hovering) {
|
||||
int x = (int) (r.x + (hoverLon + 180) / 360 * r.width);
|
||||
int y = (int) (r.y + (90 - hoverLat) / 180 * r.height);
|
||||
g2.setColor(new Color(255, 209, 102));
|
||||
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{4, 4}, 0));
|
||||
g2.drawLine(x, r.y, x, r.y + r.height);
|
||||
g2.drawLine(r.x, y, r.x + r.width, y);
|
||||
g2.fillOval(x - 3, y - 3, 6, 6);
|
||||
EarthMath.Zone z = EarthMath.zone(hoverLat);
|
||||
if (view.equals("zones")) {
|
||||
int y1 = (int) (r.y + (90 - z.latMax()) / 180 * r.height);
|
||||
int y2 = (int) (r.y + (90 - z.latMin()) / 180 * r.height);
|
||||
g2.setColor(new Color(zoneColor(z.id()).getRed(), zoneColor(z.id()).getGreen(), zoneColor(z.id()).getBlue(), 46));
|
||||
g2.fillRect(r.x, y1, r.width, y2 - y1);
|
||||
}
|
||||
}
|
||||
g2.setClip(null);
|
||||
g2.setColor(new Color(0x1B2740));
|
||||
g2.drawRoundRect(r.x, r.y, r.width, r.height, 12, 12);
|
||||
g2.dispose();
|
||||
}
|
||||
|
||||
private void paintZones(Graphics2D g2, Rectangle r) {
|
||||
for (EarthMath.Zone z : EarthMath.ZONES) {
|
||||
int y1 = (int) (r.y + (90 - z.latMax()) / 180 * r.height);
|
||||
int y2 = (int) (r.y + (90 - z.latMin()) / 180 * r.height);
|
||||
Color c = zoneColor(z.id());
|
||||
g2.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 52));
|
||||
g2.fillRect(r.x, y1, r.width, y2 - y1);
|
||||
g2.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 120));
|
||||
g2.setStroke(new BasicStroke(0.8f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{5, 4}, 0));
|
||||
g2.drawLine(r.x, y1, r.x + r.width, y1);
|
||||
g2.setStroke(new BasicStroke(1));
|
||||
g2.setFont(Theme.bold(9.5f));
|
||||
g2.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 230));
|
||||
g2.drawString(z.nameZh(), r.x + 8, (y1 + y2) / 2 + 3);
|
||||
}
|
||||
// tropics/polar labels
|
||||
g2.setFont(Theme.font(9));
|
||||
g2.setColor(new Color(0x9FB4D4));
|
||||
g2.drawString("北回归线 23.5°N", r.x + 8, (int) (r.y + (90 - 23.5) / 180 * r.height) - 3);
|
||||
g2.drawString("南回归线 23.5°S", r.x + 8, (int) (r.y + (90 + 23.5) / 180 * r.height) - 3);
|
||||
g2.drawString("北极圈 66.5°N", r.x + 8, (int) (r.y + (90 - 66.5) / 180 * r.height) - 3);
|
||||
g2.drawString("南极圈 66.5°S", r.x + 8, (int) (r.y + (90 + 66.5) / 180 * r.height) - 3);
|
||||
}
|
||||
|
||||
private void paintCoast(Graphics2D g2, Rectangle r) {
|
||||
g2.setColor(new Color(0xB8D8F0, true));
|
||||
g2.setStroke(new BasicStroke(0.85f));
|
||||
for (List<double[]> line : data.coastline) drawLine(g2, r, line, new Color(0xB8D8F0));
|
||||
if (!data.continents.isEmpty()) {
|
||||
g2.setStroke(new BasicStroke(1.2f));
|
||||
for (GeoData.Shape s : data.continents) {
|
||||
for (List<double[]> line : s.lines) drawLine(g2, r, line, new Color(0x7FC4A0));
|
||||
}
|
||||
}
|
||||
g2.setFont(Theme.bold(9.5f));
|
||||
for (GeoData.Label l : data.labels) {
|
||||
int x = (int) (r.x + (l.lon + 180) / 360 * r.width);
|
||||
int y = (int) (r.y + (90 - l.lat) / 180 * r.height);
|
||||
g2.setColor(l.kind.equals("ocean") ? new Color(0x7FB6E8) : new Color(0xB8E0C0));
|
||||
g2.drawString(l.name, x - g2.getFontMetrics().stringWidth(l.name) / 2, y);
|
||||
}
|
||||
for (GeoData.Border b : data.borders) {
|
||||
for (List<double[]> line : b.lines) drawLine(g2, r, line, new Color(0xE9B25B));
|
||||
}
|
||||
}
|
||||
|
||||
private void paintPlates(Graphics2D g2, Rectangle r) {
|
||||
g2.setStroke(new BasicStroke(1.4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{6, 5}, 0));
|
||||
Color[] colors = {new Color(0xE08A4B), new Color(0x6FA8D8), new Color(0x7FC4A0),
|
||||
new Color(0xD97C9A), new Color(0xC9B06A), new Color(0xA88CE0)};
|
||||
int i = 0;
|
||||
for (GeoData.Shape p : data.plates) {
|
||||
Color c = colors[i++ % colors.length];
|
||||
g2.setColor(c);
|
||||
for (List<double[]> line : p.lines) drawLine(g2, r, line, c);
|
||||
if (p.label != null) {
|
||||
int x = (int) (r.x + (p.label[0] + 180) / 360 * r.width);
|
||||
int y = (int) (r.y + (90 - p.label[1]) / 180 * r.height);
|
||||
g2.setFont(Theme.bold(9.5f));
|
||||
String name = p.name;
|
||||
g2.drawString(name, x - g2.getFontMetrics().stringWidth(name) / 2, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void drawLine(Graphics2D g2, Rectangle r, List<double[]> line, Color c) {
|
||||
g2.setColor(c);
|
||||
Path2D p = new Path2D.Double();
|
||||
boolean first = true;
|
||||
double lastLon = 0;
|
||||
for (double[] pt : line) {
|
||||
double lon = pt[0], lat = pt[1];
|
||||
if (first) { p.moveTo(r.x + (lon + 180) / 360 * r.width, r.y + (90 - lat) / 180 * r.height); first = false; }
|
||||
else if (Math.abs(lon - lastLon) > 180) {
|
||||
p.moveTo(r.x + (lon + 180) / 360 * r.width, r.y + (90 - lat) / 180 * r.height);
|
||||
} else p.lineTo(r.x + (lon + 180) / 360 * r.width, r.y + (90 - lat) / 180 * r.height);
|
||||
lastLon = lon;
|
||||
}
|
||||
g2.draw(p);
|
||||
}
|
||||
|
||||
private void paintGraticule(Graphics2D g2, Rectangle r) {
|
||||
g2.setColor(new Color(255, 255, 255, 22));
|
||||
g2.setStroke(new BasicStroke(0.6f));
|
||||
for (int lon = -180; lon <= 180; lon += 30) {
|
||||
int x = (int) (r.x + (lon + 180) / 360 * r.width);
|
||||
g2.drawLine(x, r.y, x, r.y + r.height);
|
||||
}
|
||||
for (int lat = -60; lat <= 60; lat += 30) {
|
||||
int y = (int) (r.y + (90 - lat) / 180 * r.height);
|
||||
g2.drawLine(r.x, y, r.x + r.width, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 数据
|
||||
|
||||
private static final class GeoData {
|
||||
record Shape(String id, String name, double[] label, List<List<double[]>> lines) {}
|
||||
record Label(double lat, double lon, String kind, String name) {}
|
||||
record Border(String name, List<List<double[]>> lines) {}
|
||||
|
||||
List<List<double[]>> coastline = new ArrayList<>();
|
||||
List<Shape> continents = new ArrayList<>();
|
||||
List<Shape> plates = new ArrayList<>();
|
||||
List<Border> borders = new ArrayList<>();
|
||||
List<Label> labels = new ArrayList<>();
|
||||
Map<String, Object> scene = new LinkedHashMap<>();
|
||||
|
||||
static GeoData load(Path dir) {
|
||||
GeoData d = new GeoData();
|
||||
try {
|
||||
d.coastline = readLines(dir.resolve("coastline.json"), "lines");
|
||||
d.scene = Json.obj(Json.parse(dir.resolve("scene.json")));
|
||||
d.continents = readShapes(dir.resolve("continents.json"), "continents");
|
||||
d.plates = readShapes(dir.resolve("plates.json"), "plates");
|
||||
d.borders = readBorders(dir.resolve("borders.json"));
|
||||
d.labels = readLabels(dir.resolve("labels.json"));
|
||||
} catch (Exception e) {
|
||||
System.err.println("[geo] 读取数据失败: " + e.getMessage());
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static List<List<double[]>> readLines(Path p, String key) throws IOException {
|
||||
List<List<double[]>> out = new ArrayList<>();
|
||||
if (!Files.isRegularFile(p)) return out;
|
||||
Map<String, Object> m = Json.obj(Json.parse(p));
|
||||
for (Object lo : Json.arr(m.get(key))) {
|
||||
List<double[]> line = new ArrayList<>();
|
||||
for (Object po : Json.arr(lo)) {
|
||||
List<Object> pair = Json.arr(po);
|
||||
if (pair.size() >= 2) line.add(new double[]{num(pair.get(0)), num(pair.get(1))});
|
||||
}
|
||||
if (line.size() > 1) out.add(line);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static List<Shape> readShapes(Path p, String key) throws IOException {
|
||||
List<Shape> out = new ArrayList<>();
|
||||
if (!Files.isRegularFile(p)) return out;
|
||||
Map<String, Object> m = Json.obj(Json.parse(p));
|
||||
String lang = I18n.language();
|
||||
for (Object so : Json.arr(m.get(key))) {
|
||||
Map<String, Object> s = Json.obj(so);
|
||||
String id = Json.str(s, "id", "");
|
||||
String name = pick(Json.obj(s.get("nameI18n")), lang);
|
||||
if (name.isBlank()) name = Json.str(s, "name", id);
|
||||
double[] label = null;
|
||||
List<Object> pair = Json.arr(s.get("label"));
|
||||
if (pair.size() >= 2) label = new double[]{num(pair.get(0)), num(pair.get(1))};
|
||||
List<List<double[]>> lines = new ArrayList<>();
|
||||
for (Object lo : Json.arr(s.get("lines"))) {
|
||||
List<double[]> line = new ArrayList<>();
|
||||
for (Object po : Json.arr(lo)) {
|
||||
List<Object> pt = Json.arr(po);
|
||||
if (pt.size() >= 2) line.add(new double[]{num(pt.get(0)), num(pt.get(1))});
|
||||
}
|
||||
if (line.size() > 1) lines.add(line);
|
||||
}
|
||||
out.add(new Shape(id, name, label, lines));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static List<Border> readBorders(Path p) throws IOException {
|
||||
List<Border> out = new ArrayList<>();
|
||||
if (!Files.isRegularFile(p)) return out;
|
||||
Map<String, Object> m = Json.obj(Json.parse(p));
|
||||
String lang = I18n.language();
|
||||
for (Object bo : Json.arr(m.get("borders"))) {
|
||||
Map<String, Object> b = Json.obj(bo);
|
||||
String name = pick(Json.obj(b.get("nameI18n")), lang);
|
||||
if (name.isBlank()) name = Json.str(b, "name", "");
|
||||
List<List<double[]>> lines = new ArrayList<>();
|
||||
for (Object lo : Json.arr(b.get("lines"))) {
|
||||
List<double[]> line = new ArrayList<>();
|
||||
for (Object po : Json.arr(lo)) {
|
||||
List<Object> pt = Json.arr(po);
|
||||
if (pt.size() >= 2) line.add(new double[]{num(pt.get(0)), num(pt.get(1))});
|
||||
}
|
||||
if (line.size() > 1) lines.add(line);
|
||||
}
|
||||
out.add(new Border(name, lines));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static List<Label> readLabels(Path p) throws IOException {
|
||||
List<Label> out = new ArrayList<>();
|
||||
if (!Files.isRegularFile(p)) return out;
|
||||
Map<String, Object> m = Json.obj(Json.parse(p));
|
||||
String lang = I18n.language();
|
||||
for (Object lo : Json.arr(m.get("labels"))) {
|
||||
Map<String, Object> l = Json.obj(lo);
|
||||
String name = pick(Json.obj(l.get("nameI18n")), lang);
|
||||
out.add(new Label(Json.d(l, "lat", 0), Json.d(l, "lon", 0), Json.str(l, "kind", "continent"), name));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static String pick(Map<String, Object> m, String lang) {
|
||||
Object v = m.get(lang);
|
||||
if (v == null) v = m.get("zh-CN");
|
||||
if (v == null) return "";
|
||||
return String.valueOf(v);
|
||||
}
|
||||
|
||||
static double num(Object o) {
|
||||
return o instanceof Json.Num n ? n.asDouble() : Double.parseDouble(String.valueOf(o));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.jogamp.opengl.GL;
|
||||
import com.jogamp.opengl.GL2;
|
||||
import com.jogamp.opengl.GLAutoDrawable;
|
||||
import com.jogamp.opengl.GLCapabilities;
|
||||
import com.jogamp.opengl.GLEventListener;
|
||||
import com.jogamp.opengl.GLProfile;
|
||||
import com.jogamp.opengl.awt.GLJPanel;
|
||||
import com.jogamp.opengl.glu.GLU;
|
||||
|
||||
import java.awt.event.MouseAdapter;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.awt.event.MouseMotionAdapter;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* OpenGL 地球场景:JOGL / GLJPanel 固定管线渲染。
|
||||
*
|
||||
* <p>自转与公转共用同一个 3D 场景:球体经纬网细分、按太阳方向逐顶点明暗、晨昏线、
|
||||
* 大陆轮廓、地轴、公转轨道与四季标记。鼠标拖动改变视角 yaw/pitch,滚轮缩放;
|
||||
* 与原 Java2D 画布相比,这里的观察方向是真正的三维相机。</p>
|
||||
*/
|
||||
public final class GlEarthView extends GLJPanel implements GLEventListener {
|
||||
/** 场景数据由 EarthPanel 提供,避免 OpenGL 组件持有 UI 状态。 */
|
||||
public interface Scene {
|
||||
boolean revolution();
|
||||
double spin();
|
||||
double orbit();
|
||||
boolean labels();
|
||||
boolean grid();
|
||||
List<List<double[]>> land();
|
||||
}
|
||||
|
||||
private static final double TILT = Math.toRadians(23.44);
|
||||
private final Scene scene;
|
||||
private final GLU glu = new GLU();
|
||||
private final double[][] stars;
|
||||
private double yaw = 18, pitch = 22, zoom = 1;
|
||||
private double dragX = -1, dragY = -1;
|
||||
private boolean dragging;
|
||||
private boolean ready;
|
||||
|
||||
public GlEarthView(Scene scene) {
|
||||
super(capabilities());
|
||||
this.scene = scene;
|
||||
this.stars = makeStars();
|
||||
setBackground(new java.awt.Color(0x080F1C));
|
||||
addGLEventListener(this);
|
||||
addMouseListener(new MouseAdapter() {
|
||||
@Override public void mousePressed(MouseEvent e) {
|
||||
if (e.getButton() == MouseEvent.BUTTON1) {
|
||||
dragX = e.getX(); dragY = e.getY(); dragging = true;
|
||||
}
|
||||
}
|
||||
@Override public void mouseReleased(MouseEvent e) { dragging = false; dragX = -1; }
|
||||
});
|
||||
addMouseMotionListener(new MouseMotionAdapter() {
|
||||
@Override public void mouseDragged(MouseEvent e) {
|
||||
if (!dragging) return;
|
||||
yaw += (e.getX() - dragX) * 0.45;
|
||||
pitch = clamp(pitch - (e.getY() - dragY) * 0.35, -78, 78);
|
||||
dragX = e.getX(); dragY = e.getY();
|
||||
repaint();
|
||||
}
|
||||
});
|
||||
addMouseWheelListener(e -> {
|
||||
zoom = clamp(zoom * (e.getWheelRotation() < 0 ? 1.12 : 0.89), 0.55, 2.2);
|
||||
repaint();
|
||||
});
|
||||
}
|
||||
|
||||
private static GLCapabilities capabilities() {
|
||||
GLProfile profile = GLProfile.get(GLProfile.GL2);
|
||||
GLCapabilities caps = new GLCapabilities(profile);
|
||||
caps.setDoubleBuffered(true);
|
||||
caps.setHardwareAccelerated(true);
|
||||
return caps;
|
||||
}
|
||||
|
||||
/** 构建失败或 OpenGL 不可用时由 EarthPanel 回退到 Java2D。 */
|
||||
public static boolean available() {
|
||||
try {
|
||||
return !java.awt.GraphicsEnvironment.isHeadless() && GLProfile.isAvailable(GLProfile.GL2);
|
||||
} catch (Throwable t) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void resetView() {
|
||||
yaw = 18; pitch = 22; zoom = 1;
|
||||
repaint();
|
||||
}
|
||||
|
||||
@Override public void init(GLAutoDrawable d) {
|
||||
GL2 gl = d.getGL().getGL2();
|
||||
gl.glEnable(GL.GL_DEPTH_TEST);
|
||||
gl.glDepthFunc(GL.GL_LEQUAL);
|
||||
gl.glEnable(GL.GL_BLEND);
|
||||
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
|
||||
gl.glClearColor(0.031f, 0.059f, 0.11f, 1f);
|
||||
gl.glPointSize(1.6f);
|
||||
ready = true;
|
||||
}
|
||||
|
||||
@Override public void dispose(GLAutoDrawable d) { ready = false; }
|
||||
|
||||
@Override public void reshape(GLAutoDrawable d, int x, int y, int w, int h) {
|
||||
GL2 gl = d.getGL().getGL2();
|
||||
gl.glViewport(0, 0, Math.max(1, w), Math.max(1, h));
|
||||
gl.glMatrixMode(GL2.GL_PROJECTION);
|
||||
gl.glLoadIdentity();
|
||||
glu.gluPerspective(45.0, Math.max(1, w) / (double) Math.max(1, h), 0.05, 120.0);
|
||||
gl.glMatrixMode(GL2.GL_MODELVIEW);
|
||||
gl.glLoadIdentity();
|
||||
}
|
||||
|
||||
@Override public void display(GLAutoDrawable d) {
|
||||
if (!ready) return;
|
||||
GL2 gl = d.getGL().getGL2();
|
||||
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
|
||||
gl.glMatrixMode(GL2.GL_MODELVIEW);
|
||||
gl.glLoadIdentity();
|
||||
|
||||
boolean revolution = scene.revolution();
|
||||
double dist = (revolution ? 8.6 : 3.7) / zoom;
|
||||
double yr = Math.toRadians(yaw), pr = Math.toRadians(pitch);
|
||||
double cp = Math.cos(pr);
|
||||
glu.gluLookAt(dist * Math.sin(yr) * cp, dist * Math.sin(pr), dist * Math.cos(yr) * cp,
|
||||
0, 0, 0, 0, 1, 0);
|
||||
|
||||
drawStars(gl);
|
||||
if (revolution) drawRevolution(gl);
|
||||
else drawRotation(gl);
|
||||
gl.glFlush();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 场景
|
||||
|
||||
private void drawRevolution(GL2 gl) {
|
||||
double orbitR = 2.65;
|
||||
double a = Math.toRadians(scene.orbit());
|
||||
double earthX = orbitR * Math.sin(a);
|
||||
double earthZ = orbitR * Math.cos(a);
|
||||
double[] sunDir = norm(new double[]{-earthX, 0, -earthZ});
|
||||
|
||||
drawSun(gl);
|
||||
drawOrbit(gl, orbitR);
|
||||
drawEarth(gl, earthX, 0, earthZ, 0.38, sunDir, true);
|
||||
// 太阳光方向线
|
||||
line(gl, new double[]{0, 0, 0}, new double[]{earthX, 0, earthZ}, 0.55, 0.46, 0.22, 0.45);
|
||||
}
|
||||
|
||||
private void drawRotation(GL2 gl) {
|
||||
double[] sunDir = norm(new double[]{0.85, 0.25, 0.45});
|
||||
drawEarth(gl, 0, 0, 0, 1.05, sunDir, false);
|
||||
}
|
||||
|
||||
private void drawSun(GL2 gl) {
|
||||
solidSphere(gl, 0, 0, 0, 0.32, 1.0, 0.79, 0.30, 1);
|
||||
additiveSphere(gl, 0, 0, 0, 0.52, 1.0, 0.72, 0.25, 0.16);
|
||||
additiveSphere(gl, 0, 0, 0, 0.82, 1.0, 0.64, 0.18, 0.07);
|
||||
}
|
||||
|
||||
private void drawOrbit(GL2 gl, double r) {
|
||||
gl.glDisable(GL.GL_DEPTH_TEST);
|
||||
gl.glBegin(GL.GL_LINE_LOOP);
|
||||
gl.glColor4d(0.36, 0.55, 0.86, 0.8);
|
||||
for (int i = 0; i < 180; i++) {
|
||||
double t = i * Math.PI * 2 / 180;
|
||||
gl.glVertex3d(r * Math.sin(t), 0, r * Math.cos(t));
|
||||
}
|
||||
gl.glEnd();
|
||||
if (scene.labels()) {
|
||||
double[] angles = {0, 90, 180, 270};
|
||||
double[][] colors = {{0.48, 0.88, 0.55}, {1.0, 0.78, 0.32},
|
||||
{0.96, 0.56, 0.38}, {0.58, 0.82, 1.0}};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
double t = Math.toRadians(angles[i]);
|
||||
solidSphere(gl, r * Math.sin(t), 0, r * Math.cos(t), 0.055,
|
||||
colors[i][0], colors[i][1], colors[i][2], 1);
|
||||
}
|
||||
}
|
||||
gl.glEnable(GL.GL_DEPTH_TEST);
|
||||
}
|
||||
|
||||
private void drawEarth(GL2 gl, double cx, double cy, double cz, double r,
|
||||
double[] sunDir, boolean orbitView) {
|
||||
double spin = Math.toRadians(scene.spin());
|
||||
double s = Math.sin(spin), c = Math.cos(spin);
|
||||
double ct = Math.cos(TILT), st = Math.sin(TILT);
|
||||
|
||||
// 球面网格:逐顶点按太阳方向着色,晨昏线由明暗过渡自然形成。
|
||||
int latSteps = 24, lonSteps = 48;
|
||||
for (int i = 0; i < latSteps; i++) {
|
||||
double lat0 = -90 + 180.0 * i / latSteps;
|
||||
double lat1 = -90 + 180.0 * (i + 1) / latSteps;
|
||||
gl.glBegin(GL.GL_TRIANGLE_STRIP);
|
||||
for (int j = 0; j <= lonSteps; j++) {
|
||||
double lon = -180 + 360.0 * j / lonSteps;
|
||||
earthVertex(gl, lon, lat1, cx, cy, cz, r, sunDir, s, c, ct, st, false);
|
||||
earthVertex(gl, lon, lat0, cx, cy, cz, r, sunDir, s, c, ct, st, false);
|
||||
}
|
||||
gl.glEnd();
|
||||
}
|
||||
|
||||
// 大陆:经纬度多边形按球面三角形扇填充,略高于海平面避免 z-fighting。
|
||||
for (List<double[]> poly : scene.land()) {
|
||||
if (poly == null || poly.size() < 3) continue;
|
||||
double[][] pts = unwrap(poly);
|
||||
double midLon = 0, midLat = 0;
|
||||
for (double[] p : pts) { midLon += p[0]; midLat += p[1]; }
|
||||
midLon /= pts.length; midLat /= pts.length;
|
||||
gl.glBegin(GL.GL_TRIANGLES);
|
||||
for (int i = 0; i < pts.length; i++) {
|
||||
double[] p0 = pts[i], p1 = pts[(i + 1) % pts.length];
|
||||
earthVertex(gl, midLon, midLat, cx, cy, cz, r * 1.006, sunDir, s, c, ct, st, true);
|
||||
earthVertex(gl, p0[0], p0[1], cx, cy, cz, r * 1.006, sunDir, s, c, ct, st, true);
|
||||
earthVertex(gl, p1[0], p1[1], cx, cy, cz, r * 1.006, sunDir, s, c, ct, st, true);
|
||||
}
|
||||
gl.glEnd();
|
||||
}
|
||||
|
||||
// 经纬网
|
||||
if (scene.grid() && (!orbitView || r > 0.5)) {
|
||||
gl.glColor4d(1, 1, 1, 0.22);
|
||||
for (int lat = -60; lat <= 60; lat += 30) {
|
||||
gl.glBegin(GL.GL_LINE_LOOP);
|
||||
for (int lon = -180; lon < 180; lon += 6)
|
||||
earthPos(gl, lon, lat, cx, cy, cz, r * 1.012, s, c, ct, st);
|
||||
gl.glEnd();
|
||||
}
|
||||
for (int lon = -180; lon < 180; lon += 30) {
|
||||
gl.glBegin(GL.GL_LINE_STRIP);
|
||||
for (int lat = -90; lat <= 90; lat += 6)
|
||||
earthPos(gl, lon, lat, cx, cy, cz, r * 1.012, s, c, ct, st);
|
||||
gl.glEnd();
|
||||
}
|
||||
}
|
||||
|
||||
// 地轴:空间方向固定(倾角不变),与自转角度无关。
|
||||
double[] north = worldFromLocal(new double[]{0, 1, 0}, s, c, ct, st);
|
||||
line(gl, new double[]{cx - north[0] * r * 1.35, cy - north[1] * r * 1.35, cz - north[2] * r * 1.35},
|
||||
new double[]{cx + north[0] * r * 1.35, cy + north[1] * r * 1.35, cz + north[2] * r * 1.35},
|
||||
1, 1, 1, 0.55);
|
||||
|
||||
// 大气层
|
||||
additiveSphereAt(gl, cx, cy, cz, r * 1.045, 0.24, 0.55, 1.0, 0.055);
|
||||
}
|
||||
|
||||
private void earthVertex(GL2 gl, double lon, double lat, double cx, double cy, double cz,
|
||||
double r, double[] sunDir, double s, double c, double ct, double st,
|
||||
boolean land) {
|
||||
double[] local = localNormal(lon, lat);
|
||||
double[] n = worldFromLocal(local, s, c, ct, st);
|
||||
gl.glVertex3d(cx + n[0] * r, cy + n[1] * r, cz + n[2] * r);
|
||||
double light = smoothstep(-0.18, 0.32, dot(n, sunDir));
|
||||
double base = 0.18 + 0.82 * light;
|
||||
if (land) {
|
||||
gl.glColor3d(0.10 + 0.32 * base, 0.16 + 0.48 * base, 0.10 + 0.26 * base);
|
||||
} else {
|
||||
gl.glColor3d(0.015 + 0.13 * base, 0.045 + 0.32 * base, 0.12 + 0.62 * base);
|
||||
}
|
||||
}
|
||||
|
||||
private void earthPos(GL2 gl, double lon, double lat, double cx, double cy, double cz,
|
||||
double r, double s, double c, double ct, double st) {
|
||||
double[] n = worldFromLocal(localNormal(lon, lat), s, c, ct, st);
|
||||
gl.glVertex3d(cx + n[0] * r, cy + n[1] * r, cz + n[2] * r);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 基础图元
|
||||
|
||||
private void drawStars(GL2 gl) {
|
||||
gl.glDisable(GL.GL_DEPTH_TEST);
|
||||
gl.glBegin(GL.GL_POINTS);
|
||||
for (double[] p : stars) {
|
||||
gl.glColor4d(0.75, 0.84, 1.0, p[3]);
|
||||
gl.glVertex3d(p[0], p[1], p[2]);
|
||||
}
|
||||
gl.glEnd();
|
||||
gl.glEnable(GL.GL_DEPTH_TEST);
|
||||
}
|
||||
|
||||
private void solidSphere(GL2 gl, double cx, double cy, double cz, double r,
|
||||
double red, double green, double blue, double alpha) {
|
||||
gl.glColor4d(red, green, blue, alpha);
|
||||
sphereMesh(gl, cx, cy, cz, r);
|
||||
}
|
||||
|
||||
private void additiveSphere(GL2 gl, double cx, double cy, double cz, double r,
|
||||
double red, double green, double blue, double alpha) {
|
||||
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);
|
||||
additiveSphereAt(gl, cx, cy, cz, r, red, green, blue, alpha);
|
||||
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
|
||||
}
|
||||
|
||||
private void additiveSphereAt(GL2 gl, double cx, double cy, double cz, double r,
|
||||
double red, double green, double blue, double alpha) {
|
||||
gl.glColor4d(red, green, blue, alpha);
|
||||
sphereMesh(gl, cx, cy, cz, r);
|
||||
}
|
||||
|
||||
private void sphereMesh(GL2 gl, double cx, double cy, double cz, double r) {
|
||||
int lat = 16, lon = 32;
|
||||
for (int i = 0; i < lat; i++) {
|
||||
double a = Math.PI * i / lat, b = Math.PI * (i + 1) / lat;
|
||||
gl.glBegin(GL.GL_TRIANGLE_STRIP);
|
||||
for (int j = 0; j <= lon; j++) {
|
||||
double t = 2 * Math.PI * j / lon;
|
||||
gl.glVertex3d(cx + r * Math.sin(a) * Math.cos(t), cy + r * Math.cos(a),
|
||||
cz + r * Math.sin(a) * Math.sin(t));
|
||||
gl.glVertex3d(cx + r * Math.sin(b) * Math.cos(t), cy + r * Math.cos(b),
|
||||
cz + r * Math.sin(b) * Math.sin(t));
|
||||
}
|
||||
gl.glEnd();
|
||||
}
|
||||
}
|
||||
|
||||
private void line(GL2 gl, double[] a, double[] b, double red, double green, double blue, double alpha) {
|
||||
gl.glColor4d(red, green, blue, alpha);
|
||||
gl.glBegin(GL.GL_LINES);
|
||||
gl.glVertex3d(a[0], a[1], a[2]);
|
||||
gl.glVertex3d(b[0], b[1], b[2]);
|
||||
gl.glEnd();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 数学
|
||||
|
||||
/** 本地球坐标(Y 为北极)经自转和地轴倾斜变换到世界坐标。 */
|
||||
private static double[] worldFromLocal(double[] v, double s, double c, double ct, double st) {
|
||||
double x = v[0] * c + v[2] * s;
|
||||
double y = v[1];
|
||||
double z = -v[0] * s + v[2] * c;
|
||||
return new double[]{x * ct - y * st, x * st + y * ct, z};
|
||||
}
|
||||
|
||||
private static double[] localNormal(double lon, double lat) {
|
||||
double la = Math.toRadians(lat), lo = Math.toRadians(lon);
|
||||
return new double[]{Math.cos(la) * Math.sin(lo), Math.sin(la), Math.cos(la) * Math.cos(lo)};
|
||||
}
|
||||
|
||||
private static double[][] unwrap(List<double[]> poly) {
|
||||
double[][] out = new double[poly.size()][2];
|
||||
double prev = poly.get(0)[0];
|
||||
for (int i = 0; i < poly.size(); i++) {
|
||||
double lon = poly.get(i)[0];
|
||||
while (lon - prev > 180) lon -= 360;
|
||||
while (lon - prev < -180) lon += 360;
|
||||
out[i][0] = lon; out[i][1] = poly.get(i)[1];
|
||||
prev = lon;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static double[] norm(double[] v) {
|
||||
double len = Math.sqrt(dot(v, v));
|
||||
return len < 1e-9 ? new double[]{0, 0, 1} : new double[]{v[0] / len, v[1] / len, v[2] / len};
|
||||
}
|
||||
|
||||
private static double dot(double[] a, double[] b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
|
||||
|
||||
private static double smoothstep(double a, double b, double x) {
|
||||
double t = clamp((x - a) / (b - a), 0, 1);
|
||||
return t * t * (3 - 2 * t);
|
||||
}
|
||||
|
||||
private static double clamp(double v, double lo, double hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
|
||||
private static double[][] makeStars() {
|
||||
Random rnd = new Random(20261126);
|
||||
double[][] out = new double[220][4];
|
||||
for (int i = 0; i < out.length; i++) {
|
||||
double z = rnd.nextDouble() * 2 - 1;
|
||||
double t = rnd.nextDouble() * Math.PI * 2;
|
||||
double r = Math.sqrt(1 - z * z) * 30;
|
||||
out[i][0] = r * Math.cos(t);
|
||||
out[i][1] = z * 30;
|
||||
out[i][2] = r * Math.sin(t);
|
||||
out[i][3] = 0.25 + rnd.nextDouble() * 0.6;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.I18n;
|
||||
import com.gc.core.ModelManifest;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.geom.*;
|
||||
import java.util.List;
|
||||
|
||||
/** HMCL 风格首页:Hero、统计、已安装模型网格、公告。 */
|
||||
public final class HomePage extends JPanel {
|
||||
private final MainWindow app;
|
||||
private final JPanel body = new JPanel();
|
||||
private UI.Select selector;
|
||||
private final JLabel heroMeta = Theme.label("", 12, new Color(0xC9D8F5));
|
||||
private final JPanel modelGrid = new JPanel(new GridLayout(0, 3, 14, 14));
|
||||
private final JLabel statModels = Theme.boldLabel("0", 24, Theme.INK);
|
||||
private final JLabel statMemory = Theme.boldLabel("", 24, Theme.INK);
|
||||
private final JLabel statSource = Theme.boldLabel("2", 24, Theme.INK);
|
||||
|
||||
public HomePage(MainWindow app) {
|
||||
this.app = app;
|
||||
setLayout(new BorderLayout());
|
||||
setOpaque(false);
|
||||
JScrollPane sp = UI.scroll(body);
|
||||
add(sp, BorderLayout.CENTER);
|
||||
build();
|
||||
}
|
||||
|
||||
private void build() {
|
||||
body.setOpaque(false);
|
||||
body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS));
|
||||
body.setBorder(new EmptyBorder(26, 30, 26, 30));
|
||||
|
||||
HeroPanel hero = new HeroPanel();
|
||||
hero.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
hero.setMaximumSize(new Dimension(Integer.MAX_VALUE, 248));
|
||||
hero.setPreferredSize(new Dimension(800, 248));
|
||||
hero.setLayout(new BorderLayout());
|
||||
hero.setBorder(new EmptyBorder(30, 34, 26, 34));
|
||||
|
||||
JPanel left = new JPanel();
|
||||
left.setOpaque(false);
|
||||
left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
|
||||
JLabel kicker = Theme.label("GC · ASTRONOMY CLASSROOM", 11, new Color(0x9FB8E8));
|
||||
kicker.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JLabel title = Theme.boldLabel(I18n.t("home.hero.title"), 30, Color.WHITE);
|
||||
title.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JLabel sub = Theme.label(I18n.t("home.hero.subtitle"), 13, new Color(0xC9D8F5));
|
||||
sub.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
left.add(kicker);
|
||||
left.add(Box.createVerticalStrut(8));
|
||||
left.add(title);
|
||||
left.add(Box.createVerticalStrut(6));
|
||||
left.add(sub);
|
||||
left.add(Box.createVerticalStrut(20));
|
||||
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
|
||||
actions.setOpaque(false);
|
||||
actions.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
selector = new UI.Select();
|
||||
selector.setPreferredSize(new Dimension(210, 38));
|
||||
selector.setFocusable(false);
|
||||
actions.add(selector);
|
||||
UI.RoundButton launch = UI.primary(I18n.t("home.hero.launch"));
|
||||
launch.setFont(Theme.bold(13.5f));
|
||||
launch.setBorder(new EmptyBorder(10, 22, 10, 22));
|
||||
launch.addActionListener(e -> {
|
||||
int i = selector.getSelectedIndex();
|
||||
List<ModelManifest.Package> ms = app.models();
|
||||
if (i >= 0 && i < ms.size()) app.openModel(ms.get(i));
|
||||
else app.navigate("download");
|
||||
});
|
||||
actions.add(launch);
|
||||
UI.RoundButton more = UI.button(I18n.t("home.download"));
|
||||
more.setBorder(new EmptyBorder(10, 16, 10, 16));
|
||||
more.addActionListener(e -> app.navigate("download"));
|
||||
actions.add(more);
|
||||
left.add(actions);
|
||||
left.add(Box.createVerticalStrut(14));
|
||||
heroMeta.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
left.add(heroMeta);
|
||||
hero.add(left, BorderLayout.WEST);
|
||||
body.add(hero);
|
||||
body.add(Box.createVerticalStrut(18));
|
||||
|
||||
JPanel stats = new JPanel(new GridLayout(1, 3, 14, 0));
|
||||
stats.setOpaque(false);
|
||||
stats.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
stats.setMaximumSize(new Dimension(Integer.MAX_VALUE, 94));
|
||||
stats.add(statCard(statModels, I18n.t("home.installed"), "\u25A0"));
|
||||
stats.add(statCard(statSource, I18n.t("home.stats.sources"), "\u25C7"));
|
||||
stats.add(statCard(statMemory, I18n.t("home.stats.memory"), "\u26A1"));
|
||||
body.add(stats);
|
||||
body.add(Box.createVerticalStrut(22));
|
||||
|
||||
JPanel section = new JPanel(new BorderLayout());
|
||||
section.setOpaque(false);
|
||||
section.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JLabel h = Theme.boldLabel(I18n.t("home.section.models"), 17, Theme.INK);
|
||||
section.add(h, BorderLayout.WEST);
|
||||
UI.RoundButton getMore = UI.button(I18n.t("home.getMore") + " \u2192");
|
||||
getMore.ghost();
|
||||
getMore.addActionListener(e -> app.navigate("download"));
|
||||
JPanel r = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
|
||||
r.setOpaque(false);
|
||||
r.add(getMore);
|
||||
section.add(r, BorderLayout.EAST);
|
||||
section.setMaximumSize(new Dimension(Integer.MAX_VALUE, 34));
|
||||
body.add(section);
|
||||
body.add(Box.createVerticalStrut(12));
|
||||
|
||||
modelGrid.setOpaque(false);
|
||||
modelGrid.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
body.add(modelGrid);
|
||||
body.add(Box.createVerticalStrut(20));
|
||||
|
||||
UI.Card news = new UI.Card(new BorderLayout(12, 0));
|
||||
news.setBorder(new EmptyBorder(16, 18, 16, 18));
|
||||
news.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
news.setMaximumSize(new Dimension(Integer.MAX_VALUE, 92));
|
||||
JLabel dot = Theme.label("\u25CF", 10, Theme.ACCENT);
|
||||
news.add(dot, BorderLayout.WEST);
|
||||
JPanel nt = new JPanel();
|
||||
nt.setOpaque(false);
|
||||
nt.setLayout(new BoxLayout(nt, BoxLayout.Y_AXIS));
|
||||
nt.add(Theme.boldLabel(I18n.t("home.section.news"), 12.5f, Theme.INK));
|
||||
nt.add(Box.createVerticalStrut(4));
|
||||
JLabel nb = Theme.label(I18n.t("home.news.body"), 12, Theme.DIM);
|
||||
nt.add(nb);
|
||||
news.add(nt, BorderLayout.CENTER);
|
||||
body.add(news);
|
||||
}
|
||||
|
||||
private JPanel statCard(JLabel value, String label, String icon) {
|
||||
UI.Card c = new UI.Card(new BorderLayout());
|
||||
c.setBorder(new EmptyBorder(14, 18, 14, 18));
|
||||
JPanel l = new JPanel();
|
||||
l.setOpaque(false);
|
||||
l.setLayout(new BoxLayout(l, BoxLayout.Y_AXIS));
|
||||
l.add(value);
|
||||
l.add(Box.createVerticalStrut(2));
|
||||
l.add(Theme.label(label, 11.5f, Theme.DIM));
|
||||
c.add(l, BorderLayout.WEST);
|
||||
JLabel ic = Theme.label(icon, 20, Theme.ACCENT);
|
||||
c.add(ic, BorderLayout.EAST);
|
||||
return c;
|
||||
}
|
||||
|
||||
public void onShow() {
|
||||
List<ModelManifest.Package> ms = app.models();
|
||||
statModels.setText(String.valueOf(ms.size()));
|
||||
statMemory.setText(app.settings.effectiveMemoryMb() + " MB");
|
||||
modelGrid.removeAll();
|
||||
if (ms.isEmpty()) {
|
||||
UI.Card empty = new UI.Card(new BorderLayout(10, 6));
|
||||
empty.setBorder(new EmptyBorder(28, 24, 28, 24));
|
||||
JLabel t = Theme.boldLabel(I18n.t("models.empty"), 15, Theme.INK);
|
||||
empty.add(t, BorderLayout.NORTH);
|
||||
empty.add(Theme.label(I18n.t("models.emptyHint"), 12, Theme.DIM), BorderLayout.CENTER);
|
||||
UI.RoundButton go = UI.primary(I18n.t("home.emptyAction"));
|
||||
go.addActionListener(e -> app.navigate("download"));
|
||||
JPanel bp = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
|
||||
bp.setOpaque(false);
|
||||
bp.add(go);
|
||||
empty.add(bp, BorderLayout.SOUTH);
|
||||
modelGrid.setLayout(new GridLayout(1, 1));
|
||||
modelGrid.add(empty);
|
||||
} else {
|
||||
modelGrid.setLayout(new GridLayout(0, 3, 14, 14));
|
||||
for (ModelManifest.Package p : ms.subList(0, Math.min(ms.size(), 6))) modelGrid.add(card(p));
|
||||
}
|
||||
selector.removeAllItems();
|
||||
for (ModelManifest.Package p : ms) selector.addItem(p.manifest.localizedName());
|
||||
if (ms.isEmpty()) selector.addItem(I18n.t("models.empty"));
|
||||
String recent = app.settings.recentModels.isEmpty() ? "" : app.settings.recentModels.get(0);
|
||||
heroMeta.setText(ms.isEmpty() ? I18n.t("models.emptyHint")
|
||||
: I18n.f("home.count", ms.size()) + " · " + I18n.t("home.recent") + ":"
|
||||
+ (recent.isBlank() ? "—" : recentName(recent)));
|
||||
revalidate();
|
||||
repaint();
|
||||
}
|
||||
|
||||
private String recentName(String id) {
|
||||
for (ModelManifest.Package p : app.models()) if (p.id().equals(id)) return p.manifest.localizedName();
|
||||
return id;
|
||||
}
|
||||
|
||||
private JPanel card(ModelManifest.Package p) {
|
||||
UI.Card c = new UI.Card(new BorderLayout(10, 8));
|
||||
c.setBorder(new EmptyBorder(12, 12, 12, 12));
|
||||
c.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
|
||||
Image img = MainWindow.loadPreview(p, 92, 66);
|
||||
JLabel pic;
|
||||
if (img != null) pic = new JLabel(new ImageIcon(img));
|
||||
else pic = Theme.label("\u25CE", 30, Theme.ACCENT);
|
||||
pic.setPreferredSize(new Dimension(92, 66));
|
||||
c.add(pic, BorderLayout.WEST);
|
||||
JPanel info = new JPanel();
|
||||
info.setOpaque(false);
|
||||
info.setLayout(new BoxLayout(info, BoxLayout.Y_AXIS));
|
||||
info.add(Theme.boldLabel(p.manifest.localizedName(), 13.5f, Theme.INK));
|
||||
info.add(Box.createVerticalStrut(3));
|
||||
JLabel d = Theme.label(p.manifest.localizedDescription(), 10.5f, Theme.DIM);
|
||||
d.setToolTipText(p.manifest.localizedDescription());
|
||||
info.add(d);
|
||||
info.add(Box.createVerticalStrut(4));
|
||||
info.add(Theme.label("v" + p.manifest.version + " · " + com.gc.core.Hash.humanSize(p.sizeBytes), 10, Theme.FAINT));
|
||||
c.add(info, BorderLayout.CENTER);
|
||||
c.addMouseListener(new java.awt.event.MouseAdapter() {
|
||||
@Override public void mouseClicked(java.awt.event.MouseEvent e) { app.openModel(p); }
|
||||
@Override public void mouseEntered(java.awt.event.MouseEvent e) { c.setBorder(new EmptyBorder(12, 12, 12, 12)); }
|
||||
});
|
||||
return c;
|
||||
}
|
||||
|
||||
private static final class HeroPanel extends JPanel {
|
||||
HeroPanel() { setOpaque(false); }
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
int w = getWidth(), h = getHeight();
|
||||
GradientPaint gp = new GradientPaint(0, 0, Theme.HERO_TOP, w, h, Theme.HERO_BOTTOM);
|
||||
g2.setPaint(gp);
|
||||
g2.fillRoundRect(0, 0, w, h, 22, 22);
|
||||
// stars
|
||||
java.util.Random rnd = new java.util.Random(7);
|
||||
for (int i = 0; i < 70; i++) {
|
||||
int x = rnd.nextInt(Math.max(1, w)), y = rnd.nextInt(Math.max(1, h));
|
||||
g2.setColor(new Color(255, 255, 255, 30 + rnd.nextInt(90)));
|
||||
g2.fillOval(x, y, 1 + rnd.nextInt(2), 1 + rnd.nextInt(2));
|
||||
}
|
||||
// orbit arcs
|
||||
g2.setStroke(new BasicStroke(1.2f));
|
||||
g2.setColor(new Color(255, 255, 255, 38));
|
||||
int cx = w - 170, cy = h / 2 + 6;
|
||||
g2.drawOval(cx - 150, cy - 82, 300, 164);
|
||||
g2.drawOval(cx - 110, cy - 60, 220, 120);
|
||||
// sun glow
|
||||
g2.setPaint(new RadialGradientPaint(new Point2D.Float(w - 80, 50), 70,
|
||||
new float[]{0, 1}, new Color[]{new Color(255, 200, 90, 110), new Color(255, 200, 90, 0)}));
|
||||
g2.fillOval(w - 150, -20, 140, 140);
|
||||
// earth
|
||||
int er = 64;
|
||||
Shape earth = new Ellipse2D.Float(cx - er, cy - er, er * 2, er * 2);
|
||||
g2.setPaint(new GradientPaint(cx - er, cy - er, new Color(0x3D7BD9), cx + er, cy + er, new Color(0x152B5A)));
|
||||
g2.fill(earth);
|
||||
g2.setClip(earth);
|
||||
g2.setColor(new Color(0x4E8C4C));
|
||||
g2.fillOval(cx - 52, cy - 34, 48, 32);
|
||||
g2.fillOval(cx + 6, cy - 18, 34, 42);
|
||||
g2.fillOval(cx - 20, cy + 24, 60, 20);
|
||||
g2.setColor(new Color(0xE9EFF6));
|
||||
g2.fillOval(cx - 44, cy - 64, 88, 16);
|
||||
g2.fillOval(cx - 40, cy + 48, 80, 14);
|
||||
g2.setClip(null);
|
||||
g2.setColor(new Color(255, 255, 255, 80));
|
||||
g2.draw(earth);
|
||||
// tilt axis
|
||||
g2.setColor(new Color(255, 255, 255, 120));
|
||||
g2.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{4, 5}, 0));
|
||||
g2.drawLine(cx + 38, cy - 82, cx - 38, cy + 82);
|
||||
// terminator
|
||||
g2.setColor(new Color(255, 255, 255, 150));
|
||||
g2.drawArc(cx - er + 8, cy - er, er * 2 - 16, er * 2, 90, 180);
|
||||
g2.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.*;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.event.MouseAdapter;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** 主窗口:自绘无边框标题栏 + 左侧导航 + 内容页。 */
|
||||
public final class MainWindow {
|
||||
public static MainWindow I;
|
||||
public final AppPaths paths;
|
||||
public final Settings settings;
|
||||
public final JFrame frame;
|
||||
private final JPanel content;
|
||||
private final CardLayout cards = new CardLayout();
|
||||
private final Map<String, JComponent> pages = new LinkedHashMap<>();
|
||||
private final Map<String, UI.NavButton> navs = new LinkedHashMap<>();
|
||||
private final JLabel sidebarStatus = Theme.label("", 11, Theme.FAINT);
|
||||
private String current = "home";
|
||||
private List<ModelManifest.Package> models = new ArrayList<>();
|
||||
private final UserService users;
|
||||
private JLabel accountName;
|
||||
private JLabel accountSub;
|
||||
private JLabel accountAvatar;
|
||||
private JPanel rootPanel;
|
||||
private javax.swing.Timer themeTimer;
|
||||
|
||||
private MainWindow(AppPaths paths, Settings settings) { this(paths, settings, false); }
|
||||
|
||||
private MainWindow(AppPaths paths, Settings settings, boolean headless) {
|
||||
this.paths = paths;
|
||||
this.settings = settings;
|
||||
paths.waitForDevelopmentModels();
|
||||
users = new UserService(paths.homeRoot);
|
||||
users.applySavedTheme(settings);
|
||||
Theme.apply(settings);
|
||||
if (headless) {
|
||||
frame = null;
|
||||
} else {
|
||||
frame = new JFrame("GC · Astronomy Model Launcher");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setMinimumSize(new Dimension(1080, 700));
|
||||
frame.setSize(1260, 840);
|
||||
loadIcon();
|
||||
}
|
||||
|
||||
JPanel root = new JPanel(new BorderLayout());
|
||||
root.setBackground(Theme.BG);
|
||||
root.add(sidebar(), BorderLayout.WEST);
|
||||
content = new JPanel(cards);
|
||||
content.setOpaque(false);
|
||||
root.add(content, BorderLayout.CENTER);
|
||||
this.rootPanel = root;
|
||||
if (frame != null) {
|
||||
UI.installFrame(frame, root, "GC Launcher", "Astronomy Model Launcher · Java " + settings.launcherVersion);
|
||||
frame.setLocationRelativeTo(null);
|
||||
}
|
||||
|
||||
refreshModels();
|
||||
addPage("home", new HomePage(this));
|
||||
addPage("models", new ModelsPage(this));
|
||||
addPage("user", new UserPage(this));
|
||||
addPage("download", new DownloadPage(this));
|
||||
addPage("settings", new SettingsPage(this));
|
||||
addPage("about", new AboutPage(this));
|
||||
navigate("home");
|
||||
refreshAccountChip();
|
||||
|
||||
if (!headless) {
|
||||
themeTimer = new javax.swing.Timer(4000, e -> {
|
||||
if (Theme.refreshSystem(false)) {
|
||||
Theme.apply(settings);
|
||||
repaintAll();
|
||||
}
|
||||
});
|
||||
themeTimer.start();
|
||||
}
|
||||
if (!headless && settings.autoUpdateOnStartup) {
|
||||
new Thread(() -> {
|
||||
UpdateService.Result r = new UpdateService(paths, settings).run(false, p -> { });
|
||||
SwingUtilities.invokeLater(() -> {
|
||||
if (r.updatedModels() > 0) {
|
||||
refreshModels();
|
||||
toast(I18n.f("status.updated", r.updatedModels()));
|
||||
} else if (r.outcome() == UpdateService.Outcome.UNAVAILABLE) {
|
||||
updateStatus(I18n.t("status.offline"));
|
||||
}
|
||||
});
|
||||
}, "gc-startup-update").start();
|
||||
}
|
||||
}
|
||||
|
||||
/** 无头模式:不创建 JFrame,仅供构建自检离屏渲染页面。 */
|
||||
public static MainWindow smoke(AppPaths paths, Settings settings) {
|
||||
Theme.apply(settings);
|
||||
return new MainWindow(paths, settings, true);
|
||||
}
|
||||
|
||||
public JComponent rootPanel() { return rootPanel; }
|
||||
|
||||
public static void launch(AppPaths paths, Settings settings) {
|
||||
try {
|
||||
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
|
||||
UIManager.put("ToolTip.font", Theme.font(12));
|
||||
UIManager.put("Component.focusWidth", 0);
|
||||
} catch (Exception ignored) { }
|
||||
Theme.apply(settings);
|
||||
SwingUtilities.invokeLater(() -> {
|
||||
I = new MainWindow(paths, settings);
|
||||
I.frame.setVisible(true);
|
||||
I.frame.toFront();
|
||||
I.frame.requestFocus();
|
||||
I.frame.setAlwaysOnTop(true);
|
||||
new javax.swing.Timer(350, e -> {
|
||||
((javax.swing.Timer) e.getSource()).stop();
|
||||
I.frame.setAlwaysOnTop(false);
|
||||
I.frame.toFront();
|
||||
}).start();
|
||||
});
|
||||
}
|
||||
|
||||
private void loadIcon() {
|
||||
if (frame == null) return;
|
||||
try (InputStream in = MainWindow.class.getResourceAsStream("/assets/icon-256.png")) {
|
||||
if (in == null) return;
|
||||
Image img = ImageIO.read(in);
|
||||
if (img != null) frame.setIconImage(img);
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
private JComponent sidebar() {
|
||||
JPanel side = new JPanel(new BorderLayout());
|
||||
side.setBackground(Theme.SIDEBAR);
|
||||
side.setPreferredSize(new Dimension(218, 0));
|
||||
side.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Theme.LINE));
|
||||
|
||||
JPanel top = new JPanel();
|
||||
top.setOpaque(false);
|
||||
top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS));
|
||||
top.setBorder(new EmptyBorder(22, 16, 8, 16));
|
||||
|
||||
JPanel brand = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
|
||||
brand.setOpaque(false);
|
||||
brand.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JLabel logo = new JLabel("G") {
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
GradientPaint gp = new GradientPaint(0, 0, Theme.ACCENT, getWidth(), getHeight(), new Color(0x9B6CFF));
|
||||
g2.setPaint(gp);
|
||||
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 13, 13);
|
||||
g2.setColor(Color.WHITE);
|
||||
g2.setFont(Theme.bold(21));
|
||||
FontMetrics fm = g2.getFontMetrics();
|
||||
g2.drawString("G", (getWidth() - fm.stringWidth("G")) / 2, (getHeight() + fm.getAscent() - fm.getDescent()) / 2);
|
||||
g2.dispose();
|
||||
}
|
||||
};
|
||||
logo.setPreferredSize(new Dimension(42, 42));
|
||||
brand.add(logo);
|
||||
JPanel names = new JPanel();
|
||||
names.setOpaque(false);
|
||||
names.setLayout(new BoxLayout(names, BoxLayout.Y_AXIS));
|
||||
names.add(Theme.boldLabel("GC Launcher", 15, Theme.INK));
|
||||
names.add(Theme.label("Astronomy Classroom", 10, Theme.FAINT));
|
||||
brand.add(names);
|
||||
top.add(brand);
|
||||
top.add(Box.createVerticalStrut(24));
|
||||
|
||||
top.add(nav("home", "\u2302", I18n.t("nav.home")));
|
||||
top.add(Box.createVerticalStrut(3));
|
||||
top.add(nav("models", "\u25C8", I18n.t("nav.models")));
|
||||
top.add(Box.createVerticalStrut(3));
|
||||
top.add(nav("courseware", "\u25A4", "原始课件"));
|
||||
top.add(Box.createVerticalStrut(3));
|
||||
top.add(nav("download", "\u21E9", I18n.t("nav.download")));
|
||||
top.add(Box.createVerticalStrut(3));
|
||||
top.add(nav("toolbox", "\u2726", "百宝箱"));
|
||||
top.add(Box.createVerticalStrut(3));
|
||||
top.add(nav("user", "\u25C9", "用户中心"));
|
||||
top.add(Box.createVerticalStrut(3));
|
||||
top.add(nav("settings", "\u2699", I18n.t("nav.settings")));
|
||||
top.add(Box.createVerticalStrut(3));
|
||||
top.add(nav("about", "\u24D8", I18n.t("nav.about")));
|
||||
|
||||
side.add(top, BorderLayout.NORTH);
|
||||
|
||||
JPanel bottom = new JPanel();
|
||||
bottom.setOpaque(false);
|
||||
bottom.setLayout(new BoxLayout(bottom, BoxLayout.Y_AXIS));
|
||||
bottom.setBorder(new EmptyBorder(10, 14, 16, 14));
|
||||
|
||||
UI.Card account = new UI.Card(new BorderLayout(9, 0));
|
||||
account.setBorder(new EmptyBorder(9, 10, 9, 10));
|
||||
account.setMaximumSize(new Dimension(Integer.MAX_VALUE, 60));
|
||||
account.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
account.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
|
||||
accountAvatar = new JLabel("?") {
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
GradientPaint gp = new GradientPaint(0, 0, Theme.ACCENT, getWidth(), getHeight(), new Color(0x9B6CFF));
|
||||
g2.setPaint(gp);
|
||||
g2.fillOval(0, 0, getWidth(), getHeight());
|
||||
g2.setColor(Color.WHITE);
|
||||
g2.setFont(Theme.bold(14));
|
||||
FontMetrics fm = g2.getFontMetrics();
|
||||
String t = getText();
|
||||
g2.drawString(t, (getWidth() - fm.stringWidth(t)) / 2, (getHeight() + fm.getAscent() - fm.getDescent()) / 2);
|
||||
g2.dispose();
|
||||
}
|
||||
};
|
||||
accountAvatar.setPreferredSize(new Dimension(36, 36));
|
||||
account.add(accountAvatar, BorderLayout.WEST);
|
||||
JPanel ai = new JPanel();
|
||||
ai.setOpaque(false);
|
||||
ai.setLayout(new BoxLayout(ai, BoxLayout.Y_AXIS));
|
||||
accountName = Theme.boldLabel("登录 / 注册", 12, Theme.INK);
|
||||
accountSub = Theme.label("签到 · 积分", 9.5f, Theme.FAINT);
|
||||
ai.add(accountName); ai.add(accountSub);
|
||||
account.add(ai, BorderLayout.CENTER);
|
||||
JLabel chevron = Theme.label("›", 18, Theme.FAINT);
|
||||
account.add(chevron, BorderLayout.EAST);
|
||||
account.addMouseListener(new MouseAdapter() {
|
||||
@Override public void mouseClicked(MouseEvent e) { navigate("user"); }
|
||||
});
|
||||
bottom.add(account);
|
||||
bottom.add(Box.createVerticalStrut(8));
|
||||
|
||||
JPanel stat = new JPanel(new BorderLayout(8, 0));
|
||||
stat.setOpaque(false);
|
||||
stat.setBorder(new EmptyBorder(4, 8, 4, 8));
|
||||
JLabel dot = Theme.label("\u25CF", 8, Theme.SUCCESS);
|
||||
stat.add(dot, BorderLayout.WEST);
|
||||
sidebarStatus.setText(I18n.t("status.ready"));
|
||||
stat.add(sidebarStatus, BorderLayout.CENTER);
|
||||
bottom.add(stat);
|
||||
bottom.add(Box.createVerticalStrut(4));
|
||||
|
||||
JLabel edition = Theme.label("Java 2.0.0 · " + AppPaths.rid(), 10.5f, Theme.FAINT);
|
||||
edition.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
bottom.add(edition);
|
||||
bottom.add(Box.createVerticalStrut(4));
|
||||
JLabel line = Theme.label("OpenGL · JavaFX WebView", 9.5f, Theme.FAINT);
|
||||
line.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
bottom.add(line);
|
||||
side.add(bottom, BorderLayout.SOUTH);
|
||||
return side;
|
||||
}
|
||||
|
||||
private UI.NavButton nav(String key, String icon, String text) {
|
||||
UI.NavButton b = new UI.NavButton(icon, text);
|
||||
b.setMaximumSize(new Dimension(Integer.MAX_VALUE, 42));
|
||||
b.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
b.addActionListener(e -> navigate(key));
|
||||
navs.put(key, b);
|
||||
return b;
|
||||
}
|
||||
|
||||
private void addPage(String key, JComponent page) {
|
||||
pages.put(key, page);
|
||||
content.add(page, key);
|
||||
}
|
||||
|
||||
private JComponent createPage(String key) {
|
||||
return switch (key) {
|
||||
case "courseware" -> new CoursewarePage(this);
|
||||
case "toolbox" -> new ToolboxPage(this);
|
||||
case "user" -> new UserPage(this);
|
||||
case "home" -> new HomePage(this);
|
||||
case "models" -> new ModelsPage(this);
|
||||
case "download" -> new DownloadPage(this);
|
||||
case "settings" -> new SettingsPage(this);
|
||||
case "about" -> new AboutPage(this);
|
||||
default -> new JPanel();
|
||||
};
|
||||
}
|
||||
|
||||
public void navigate(String key) {
|
||||
if (key == null) return;
|
||||
if (!pages.containsKey(key)) addPage(key, createPage(key));
|
||||
current = key;
|
||||
cards.show(content, key);
|
||||
navs.forEach((k, b) -> b.setActive(k.equals(key)));
|
||||
JComponent page = pages.get(key);
|
||||
if (page instanceof HomePage h) h.onShow();
|
||||
else if (page instanceof ModelsPage m) m.onShow();
|
||||
else if (page instanceof DownloadPage d) d.onShow();
|
||||
else if (page instanceof SettingsPage sp) sp.onShow();
|
||||
else if (page instanceof AboutPage a) a.onShow();
|
||||
else if (page instanceof UserPage u) u.onShow();
|
||||
repaintAll();
|
||||
}
|
||||
|
||||
public String currentPage() { return current; }
|
||||
|
||||
public void refreshModels() {
|
||||
Path root = modelRoot();
|
||||
models = ModelManifest.scan(root).models;
|
||||
sidebarStatus.setText(models.isEmpty() ? I18n.t("models.empty") : I18n.f("home.count", models.size()));
|
||||
if (pages.get("home") instanceof HomePage h) h.onShow();
|
||||
if (pages.get("models") instanceof ModelsPage m) m.onShow();
|
||||
}
|
||||
|
||||
public Path modelRoot() {
|
||||
if (settings.modelRootOverride != null && !settings.modelRootOverride.isBlank())
|
||||
return Path.of(settings.modelRootOverride);
|
||||
return paths.modelRoot;
|
||||
}
|
||||
|
||||
public List<ModelManifest.Package> models() { return List.copyOf(models); }
|
||||
|
||||
public ModelManifest.Package findModel(String id) {
|
||||
for (ModelManifest.Package p : models) if (p.id().equals(id)) return p;
|
||||
return null;
|
||||
}
|
||||
|
||||
public void openModel(ModelManifest.Package pkg) {
|
||||
if (pkg == null) return;
|
||||
if (!pkg.hasBuiltinRenderer()) {
|
||||
UI.error(frame, I18n.f("player.errorTitle", pkg.manifest.localizedName()) + "\n"
|
||||
+ "Java 版仅内置 5 个官方模型(比例尺 / 等高线 / 自转 / 公转 / 地理)。");
|
||||
return;
|
||||
}
|
||||
if (!settings.recentModels.contains(pkg.id())) {
|
||||
settings.recentModels.add(0, pkg.id());
|
||||
if (settings.recentModels.size() > 8) settings.recentModels = new ArrayList<>(settings.recentModels.subList(0, 8));
|
||||
settings.save();
|
||||
}
|
||||
ModelWindow.open(this, pkg);
|
||||
}
|
||||
|
||||
public void toast(String s) {
|
||||
sidebarStatus.setText(s);
|
||||
if (frame != null) UI.toast(frame, s);
|
||||
SwingUtilities.invokeLater(() -> sidebarStatus.setText(models.isEmpty()
|
||||
? I18n.t("models.empty") : I18n.f("home.count", models.size())));
|
||||
}
|
||||
|
||||
public void rebuildForLanguage() {
|
||||
if (frame == null) return;
|
||||
I18n.load(settings.language);
|
||||
frame.dispose();
|
||||
MainWindow.launch(paths, settings);
|
||||
}
|
||||
|
||||
public void updateStatus(String s) { sidebarStatus.setText(s); }
|
||||
|
||||
public UserService users() { return users; }
|
||||
|
||||
public void refreshAccountChip() {
|
||||
if (accountName == null) return;
|
||||
if (users.loggedIn()) {
|
||||
UserService.Profile p = users.profile();
|
||||
String name = p == null ? users.currentUser() : p.username();
|
||||
accountName.setText(name);
|
||||
accountSub.setText(p == null ? "本地账号" : String.format(java.util.Locale.ROOT, "%.0f 积分 · 签到 %d 天", p.points(), p.consecutiveDays()));
|
||||
if (accountAvatar != null) accountAvatar.setText(name.substring(0, 1).toUpperCase(java.util.Locale.ROOT));
|
||||
} else {
|
||||
accountName.setText("登录 / 注册");
|
||||
accountSub.setText("签到 · 积分");
|
||||
if (accountAvatar != null) accountAvatar.setText("?");
|
||||
}
|
||||
if (accountName.getParent() != null) accountName.getParent().repaint();
|
||||
}
|
||||
|
||||
/** 主题切换后递归重绘,自绘组件会读取最新 Theme 颜色。 */
|
||||
public void repaintAll() {
|
||||
if (rootPanel != null) {
|
||||
rootPanel.repaint();
|
||||
repaintTree(rootPanel);
|
||||
}
|
||||
if (frame != null) frame.repaint();
|
||||
}
|
||||
|
||||
private static void repaintTree(Component c) {
|
||||
c.repaint();
|
||||
if (c instanceof Container container) for (Component child : container.getComponents()) repaintTree(child);
|
||||
}
|
||||
|
||||
public void updateAsync(Consumer<UpdateService.Result> callback) {
|
||||
new Thread(() -> {
|
||||
UpdateService.Result r = new UpdateService(paths, settings).run(true, p -> { });
|
||||
SwingUtilities.invokeLater(() -> {
|
||||
refreshModels();
|
||||
callback.accept(r);
|
||||
});
|
||||
}, "gc-update").start();
|
||||
}
|
||||
|
||||
public static Image loadPreview(ModelManifest.Package pkg, int w, int h) {
|
||||
Path p = pkg.previewPath();
|
||||
try {
|
||||
if (Files.isRegularFile(p)) {
|
||||
Image img = ImageIO.read(p.toFile());
|
||||
if (img != null) return img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
try (InputStream in = MainWindow.class.getResourceAsStream("/assets/icon-256.png")) {
|
||||
if (in != null) {
|
||||
Image img = ImageIO.read(in);
|
||||
if (img != null) return img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void openFolder(Component parent, Path path) {
|
||||
try { Desktop.getDesktop().open(path.toFile()); }
|
||||
catch (Exception e) { UI.error(parent, "无法打开目录: " + e.getMessage()); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.I18n;
|
||||
import com.gc.core.ModelManifest;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
|
||||
/** 独立模型窗口:标题栏 + 模型画布 + 关闭 / 全屏。 */
|
||||
public final class ModelWindow {
|
||||
private ModelWindow() {}
|
||||
|
||||
public static void open(MainWindow app, ModelManifest.Package pkg) {
|
||||
JFrame f = new JFrame(pkg.manifest.localizedName());
|
||||
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
|
||||
f.setSize(1240, 820);
|
||||
f.setMinimumSize(new Dimension(1000, 680));
|
||||
f.setLocationRelativeTo(app.frame);
|
||||
try { f.setIconImage(app.frame.getIconImage()); } catch (Exception ignored) { }
|
||||
|
||||
JPanel root = new JPanel(new BorderLayout());
|
||||
root.setBackground(Theme.BG);
|
||||
|
||||
JComponent view;
|
||||
String id = pkg.id();
|
||||
switch (id) {
|
||||
case "scale-calculator" -> view = new ScalePanel(pkg);
|
||||
case "contour-map" -> view = new ContourPanel(pkg);
|
||||
case "earth-rotation" -> view = new EarthPanel(pkg, false);
|
||||
case "earth-revolution" -> view = new EarthPanel(pkg, true);
|
||||
case "earth-geography" -> view = new GeographyPanel(pkg);
|
||||
default -> view = new JPanel();
|
||||
}
|
||||
root.add(view, BorderLayout.CENTER);
|
||||
UI.installFrame(f, root, pkg.manifest.localizedName(),
|
||||
pkg.id() + " · v" + pkg.manifest.version + " · OpenGL 3D", titleExtra(f, pkg));
|
||||
if (view instanceof EarthPanel ep) {
|
||||
f.addWindowListener(new java.awt.event.WindowAdapter() {
|
||||
@Override public void windowClosed(java.awt.event.WindowEvent e) { ep.disposePanel(); }
|
||||
});
|
||||
}
|
||||
f.setVisible(true);
|
||||
SwingUtilities.invokeLater(view::requestFocusInWindow);
|
||||
}
|
||||
|
||||
/** 标题栏右侧的自定义按钮:窗口本身无系统标题栏,最大化/关闭由自绘标题栏提供。 */
|
||||
private static JComponent titleExtra(JFrame f, ModelManifest.Package pkg) {
|
||||
UI.RoundButton help = UI.button("? 帮助").compact();
|
||||
help.addActionListener(e -> showHelp(f, pkg));
|
||||
return help;
|
||||
}
|
||||
|
||||
/** 读取模型自带 help.json,按当前语言显示教学帮助。 */
|
||||
private static void showHelp(JFrame owner, ModelManifest.Package pkg) {
|
||||
java.nio.file.Path file = pkg.dataDir().resolve("help.json");
|
||||
String text;
|
||||
try {
|
||||
java.util.Map<String, Object> root = com.gc.core.Json.obj(com.gc.core.Json.parse(file));
|
||||
Object node = root.get(I18n.language());
|
||||
if (node == null) node = root.get("zh-CN");
|
||||
if (node == null) node = root.values().stream().findFirst().orElse(null);
|
||||
java.util.Map<String, Object> doc = com.gc.core.Json.obj(node);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(com.gc.core.Json.str(doc, "title", pkg.manifest.localizedName())).append("\n\n");
|
||||
for (Object so : com.gc.core.Json.arr(doc.get("sections"))) {
|
||||
java.util.Map<String, Object> sec = com.gc.core.Json.obj(so);
|
||||
sb.append("【").append(com.gc.core.Json.str(sec, "h", "")).append("】\n");
|
||||
for (Object lo : com.gc.core.Json.arr(sec.get("lines"))) sb.append("· ").append(lo).append('\n');
|
||||
sb.append('\n');
|
||||
}
|
||||
text = sb.toString();
|
||||
} catch (Exception e) {
|
||||
text = "该模型没有可读取的 help.json。\n" + e.getMessage();
|
||||
}
|
||||
UI.textDialog(owner, pkg.manifest.localizedName() + " · 帮助", text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.AppPaths;
|
||||
import com.gc.core.Hash;
|
||||
import com.gc.core.I18n;
|
||||
import com.gc.core.ModelManifest;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.nio.file.Files;
|
||||
import java.util.List;
|
||||
|
||||
/** 模型库页:封面网格 + 启动 / 打开目录 / 删除。 */
|
||||
public final class ModelsPage extends JPanel {
|
||||
private final MainWindow app;
|
||||
private final JPanel body = new JPanel();
|
||||
private final JPanel grid = new JPanel(new GridLayout(0, 3, 16, 16));
|
||||
private final JLabel count = Theme.label("", 12, Theme.DIM);
|
||||
|
||||
public ModelsPage(MainWindow app) {
|
||||
this.app = app;
|
||||
setLayout(new BorderLayout());
|
||||
setOpaque(false);
|
||||
body.setOpaque(false);
|
||||
body.setLayout(new UI.VStackLayout());
|
||||
body.setBorder(new EmptyBorder(26, 30, 26, 30));
|
||||
JPanel top = new JPanel(new BorderLayout());
|
||||
top.setOpaque(false);
|
||||
top.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JPanel left = new JPanel();
|
||||
left.setOpaque(false);
|
||||
left.setLayout(new UI.VStackLayout());
|
||||
left.add(Theme.boldLabel(I18n.t("models.title"), 24, Theme.INK));
|
||||
left.add(Box.createVerticalStrut(5));
|
||||
left.add(Theme.label(I18n.t("models.subtitle"), 12.5f, Theme.DIM));
|
||||
top.add(left, BorderLayout.WEST);
|
||||
JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 0));
|
||||
right.setOpaque(false);
|
||||
UI.RoundButton folder = UI.button(I18n.t("models.folder"));
|
||||
folder.addActionListener(e -> MainWindow.openFolder(this, app.modelRoot()));
|
||||
UI.RoundButton refresh = UI.primary(I18n.t("common.refresh"));
|
||||
refresh.addActionListener(e -> app.refreshModels());
|
||||
right.add(folder);
|
||||
right.add(refresh);
|
||||
top.add(right, BorderLayout.EAST);
|
||||
top.setMaximumSize(new Dimension(Integer.MAX_VALUE, 64));
|
||||
top.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
body.add(top);
|
||||
body.add(Box.createVerticalStrut(14));
|
||||
count.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
count.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
|
||||
body.add(count);
|
||||
body.add(Box.createVerticalStrut(12));
|
||||
grid.setOpaque(false);
|
||||
grid.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
grid.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
|
||||
body.add(grid);
|
||||
body.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
add(UI.scroll(body), BorderLayout.CENTER);
|
||||
}
|
||||
|
||||
public void onShow() {
|
||||
List<ModelManifest.Package> ms = app.models();
|
||||
count.setText(I18n.f("home.count", ms.size()) + " · " + app.modelRoot());
|
||||
grid.removeAll();
|
||||
if (ms.isEmpty()) {
|
||||
grid.setLayout(new GridLayout(1, 1));
|
||||
UI.Card c = new UI.Card(new BorderLayout(8, 8));
|
||||
c.setBorder(new EmptyBorder(40, 30, 40, 30));
|
||||
c.add(Theme.boldLabel(I18n.t("models.empty"), 18, Theme.INK), BorderLayout.NORTH);
|
||||
c.add(Theme.label(I18n.t("models.emptyHint"), 12.5f, Theme.DIM), BorderLayout.CENTER);
|
||||
UI.RoundButton go = UI.primary(I18n.t("home.download"));
|
||||
go.addActionListener(e -> app.navigate("download"));
|
||||
JPanel bp = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
|
||||
bp.setOpaque(false);
|
||||
bp.add(go);
|
||||
c.add(bp, BorderLayout.SOUTH);
|
||||
grid.add(c);
|
||||
} else {
|
||||
grid.setLayout(new GridLayout(0, 3, 16, 16));
|
||||
for (ModelManifest.Package p : ms) grid.add(card(p));
|
||||
}
|
||||
body.revalidate();
|
||||
grid.revalidate();
|
||||
revalidate();
|
||||
repaint();
|
||||
}
|
||||
|
||||
private JComponent card(ModelManifest.Package p) {
|
||||
UI.Card c = new UI.Card(new BorderLayout(0, 0));
|
||||
c.setBorder(new EmptyBorder(0, 0, 0, 0));
|
||||
c.setPreferredSize(new Dimension(300, 286));
|
||||
|
||||
JPanel head = new JPanel(new BorderLayout());
|
||||
head.setOpaque(false);
|
||||
Image img = MainWindow.loadPreview(p, 320, 142);
|
||||
JLabel pic = img != null ? new JLabel(new ImageIcon(img)) : Theme.label("\u25CE", 52, Theme.ACCENT);
|
||||
pic.setHorizontalAlignment(SwingConstants.CENTER);
|
||||
pic.setPreferredSize(new Dimension(300, 142));
|
||||
pic.setBorder(new EmptyBorder(8, 8, 0, 8));
|
||||
head.add(pic, BorderLayout.CENTER);
|
||||
c.add(head, BorderLayout.NORTH);
|
||||
|
||||
JPanel info = new JPanel();
|
||||
info.setOpaque(false);
|
||||
info.setLayout(new UI.VStackLayout());
|
||||
info.setBorder(new EmptyBorder(10, 14, 8, 14));
|
||||
info.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JPanel nameRow = new JPanel(new BorderLayout());
|
||||
nameRow.setOpaque(false);
|
||||
nameRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 24));
|
||||
nameRow.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
nameRow.add(Theme.boldLabel(p.manifest.localizedName(), 14.5f, Theme.INK), BorderLayout.WEST);
|
||||
JLabel ver = Theme.label("v" + p.manifest.version, 10, Theme.ACCENT);
|
||||
ver.setOpaque(true);
|
||||
ver.setBackground(Theme.ACCENT_SOFT);
|
||||
ver.setBorder(new EmptyBorder(2, 6, 2, 6));
|
||||
nameRow.add(ver, BorderLayout.EAST);
|
||||
nameRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 24));
|
||||
info.add(nameRow);
|
||||
info.add(Box.createVerticalStrut(5));
|
||||
JLabel desc = Theme.label(p.manifest.localizedDescription(), 11, Theme.DIM);
|
||||
desc.setToolTipText(p.manifest.localizedDescription());
|
||||
desc.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
info.add(desc);
|
||||
info.add(Box.createVerticalStrut(6));
|
||||
JPanel meta = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
|
||||
meta.setOpaque(false);
|
||||
meta.add(Theme.label(p.id(), 10, Theme.FAINT));
|
||||
meta.add(Theme.label("· " + Hash.humanSize(p.sizeBytes), 10, Theme.FAINT));
|
||||
if (p.manifest.author != null && !p.manifest.author.isBlank())
|
||||
meta.add(Theme.label("· " + p.manifest.author, 10, Theme.FAINT));
|
||||
meta.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
|
||||
info.add(meta);
|
||||
c.add(info, BorderLayout.CENTER);
|
||||
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
|
||||
actions.setOpaque(false);
|
||||
actions.setBorder(new EmptyBorder(0, 10, 12, 10));
|
||||
UI.RoundButton launch = UI.primary(I18n.t("models.launch"));
|
||||
launch.setBorder(new EmptyBorder(7, 14, 7, 14));
|
||||
launch.addActionListener(e -> app.openModel(p));
|
||||
UI.RoundButton folder = UI.button(I18n.t("models.folder"));
|
||||
folder.setBorder(new EmptyBorder(7, 10, 7, 10));
|
||||
folder.addActionListener(e -> MainWindow.openFolder(this, p.directory));
|
||||
UI.RoundButton del = UI.button(I18n.t("models.delete")).danger();
|
||||
del.setBorder(new EmptyBorder(7, 10, 7, 10));
|
||||
del.addActionListener(e -> {
|
||||
if (!UI.confirm(this, I18n.f("home.deleteConfirm", p.manifest.localizedName()))) return;
|
||||
AppPaths.deleteTree(p.directory);
|
||||
app.settings.installedModelVersions.remove(p.id());
|
||||
app.settings.save();
|
||||
app.refreshModels();
|
||||
});
|
||||
actions.add(launch);
|
||||
actions.add(folder);
|
||||
actions.add(del);
|
||||
c.add(actions, BorderLayout.SOUTH);
|
||||
return c;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,640 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.I18n;
|
||||
import com.gc.core.ModelManifest;
|
||||
import com.gc.model.scale.ScaleData;
|
||||
import com.gc.model.scale.ScaleMath;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import javax.swing.event.ChangeListener;
|
||||
import java.awt.*;
|
||||
import java.awt.geom.RoundRectangle2D;
|
||||
import java.util.Locale;
|
||||
import java.util.Random;
|
||||
|
||||
/** 比例尺计算器:三栏输入 / 可视化标尺 / 三种写法与判读 + 实地尺与练习。 */
|
||||
public final class ScalePanel extends JPanel {
|
||||
private final ScaleMath.State s = new ScaleMath.State();
|
||||
private final ScaleData data;
|
||||
private final ModelManifest.Package pkg;
|
||||
private boolean updating;
|
||||
private final Random rnd = new Random();
|
||||
|
||||
private final UI.TextField mapField = new UI.TextField();
|
||||
private final UI.TextField realField = new UI.TextField();
|
||||
private final UI.TextField nField = new UI.TextField();
|
||||
private final UI.Select unitBox = new UI.Select(new String[]{"unit.km", "unit.m", "unit.cm"}).display(I18n::t);
|
||||
private final UI.Slider mapSlider = new UI.Slider(1, 200, 30, true);
|
||||
private final JLabel mapResult = Theme.boldLabel("", 13, Theme.INK);
|
||||
private final JLabel realResult = Theme.boldLabel("", 13, Theme.INK);
|
||||
private final JLabel nResult = Theme.boldLabel("", 13, Theme.INK);
|
||||
private final UI.Card mapCard = new UI.Card();
|
||||
private final UI.Card realCard = new UI.Card();
|
||||
private final UI.Card scaleCard = new UI.Card();
|
||||
private final UI.RoundButton btnReal = UI.button(I18n.t("mode.real"));
|
||||
private final UI.RoundButton btnMap = UI.button(I18n.t("mode.map"));
|
||||
private final UI.RoundButton btnScale = UI.button(I18n.t("mode.scale"));
|
||||
private final JLabel digital = Theme.boldLabel("", 17, Theme.INK);
|
||||
private final JLabel verbal = Theme.label("", 12.5f, Theme.INK);
|
||||
private final JLabel segmentLabel = Theme.label("", 12.5f, Theme.INK);
|
||||
private final JLabel gradeChip = new JLabel();
|
||||
private final JLabel gradeNote = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel gradeRule = Theme.label(I18n.t("grade.rule"), 10.5f, Theme.FAINT);
|
||||
private final JTextArea stepsArea = new JTextArea();
|
||||
private final JPanel stepsWrap = new JPanel(new BorderLayout());
|
||||
private final UI.Select landmarkBox = new UI.Select();
|
||||
private final JLabel landmarkResult = Theme.boldLabel("", 20, Theme.ACCENT);
|
||||
private final JLabel quizPrompt = Theme.label("", 12.5f, Theme.INK);
|
||||
private final UI.TextField quizInput = new UI.TextField();
|
||||
private final JLabel quizFeedback = Theme.boldLabel("", 12, Theme.SUCCESS);
|
||||
private final JLabel quizUnit = Theme.label("", 10.5f, Theme.FAINT);
|
||||
private final JLabel quizStreak = Theme.label("", 10.5f, Theme.FAINT);
|
||||
private final JPanel quizSteps = new JPanel();
|
||||
private final ScaleRuler ruler = new ScaleRuler();
|
||||
private ScaleMath.Quiz quiz;
|
||||
private int streak;
|
||||
|
||||
public ScalePanel(ModelManifest.Package pkg) {
|
||||
this.data = ScaleData.load(pkg.dataDir());
|
||||
this.pkg = pkg;
|
||||
setLayout(new BorderLayout());
|
||||
setBackground(new Color(0xF4F6FB));
|
||||
add(header(), BorderLayout.NORTH);
|
||||
JPanel center = new JPanel(new GridBagLayout());
|
||||
center.setOpaque(false);
|
||||
center.setBorder(new EmptyBorder(12, 16, 8, 16));
|
||||
GridBagConstraints gc = new GridBagConstraints();
|
||||
gc.fill = GridBagConstraints.BOTH; gc.weighty = 1;
|
||||
gc.gridx = 0; gc.gridy = 0; gc.weightx = 0; gc.insets = new Insets(0, 0, 0, 8);
|
||||
center.add(left(), gc);
|
||||
gc.gridx = 1; gc.weightx = 1; gc.insets = new Insets(0, 0, 0, 8);
|
||||
center.add(middle(), gc);
|
||||
gc.gridx = 2; gc.weightx = 0; gc.insets = new Insets(0, 0, 0, 0);
|
||||
center.add(right(), gc);
|
||||
add(center, BorderLayout.CENTER);
|
||||
add(bottom(), BorderLayout.SOUTH);
|
||||
wire();
|
||||
setMode(ScaleMath.SolveMode.REAL);
|
||||
newQuiz();
|
||||
refresh();
|
||||
}
|
||||
|
||||
private JComponent header() {
|
||||
JPanel h = new JPanel(new BorderLayout());
|
||||
h.setBackground(Color.WHITE);
|
||||
h.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0xE3E8F3)),
|
||||
new EmptyBorder(14, 20, 14, 20)));
|
||||
JPanel l = new JPanel();
|
||||
l.setOpaque(false);
|
||||
l.setLayout(new UI.VStackLayout());
|
||||
l.add(Theme.boldLabel(pkg.manifest.localizedName(), 22, new Color(0x111A2E)));
|
||||
l.add(Theme.label(pkg.manifest.localizedDescription(), 12, new Color(0x5B6A86)));
|
||||
h.add(l, BorderLayout.WEST);
|
||||
JPanel r = new JPanel();
|
||||
r.setOpaque(false);
|
||||
r.setLayout(new UI.VStackLayout());
|
||||
JLabel hint = Theme.label(I18n.t("mode.hint"), 10.5f, new Color(0x8A97B1));
|
||||
hint.setAlignmentX(Component.RIGHT_ALIGNMENT);
|
||||
r.add(hint);
|
||||
JPanel modes = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 6));
|
||||
modes.setOpaque(false);
|
||||
modes.add(btnReal); modes.add(btnMap); modes.add(btnScale);
|
||||
r.add(modes);
|
||||
h.add(r, BorderLayout.EAST);
|
||||
return h;
|
||||
}
|
||||
|
||||
private JComponent left() {
|
||||
UI.Card card = new UI.Card(new BorderLayout());
|
||||
card.setPreferredSize(new Dimension(315, 0));
|
||||
JPanel p = new JPanel();
|
||||
p.setOpaque(false);
|
||||
p.setLayout(new UI.VStackLayout());
|
||||
p.setBorder(new EmptyBorder(14, 14, 14, 14));
|
||||
JPanel head = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
|
||||
head.setOpaque(false);
|
||||
JLabel bar = new JLabel();
|
||||
bar.setPreferredSize(new Dimension(4, 16));
|
||||
bar.setOpaque(true); bar.setBackground(Theme.ACCENT);
|
||||
head.add(bar);
|
||||
head.add(Theme.boldLabel(I18n.t("input.title"), 13.5f, Theme.INK));
|
||||
p.add(head);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
|
||||
inputCard(mapCard, p, I18n.t("input.map"), mapResult, mapField, null, mapSlider);
|
||||
p.add(Box.createVerticalStrut(8));
|
||||
inputReal(p);
|
||||
p.add(Box.createVerticalStrut(8));
|
||||
inputScale(p);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
p.add(Theme.label(I18n.t("input.presets"), 11.5f, Theme.FAINT));
|
||||
JPanel presets = new JPanel(new GridLayout(0, 2, 6, 6));
|
||||
presets.setOpaque(false);
|
||||
for (ScaleData.Preset preset : data.presets) {
|
||||
UI.RoundButton b = UI.button(I18n.t(preset.nameKey()));
|
||||
b.setFont(Theme.font(10.5f));
|
||||
b.setBorder(new EmptyBorder(5, 7, 5, 7));
|
||||
b.addActionListener(e -> { s.n = preset.n(); ScaleMath.solve(s); refresh(); });
|
||||
presets.add(b);
|
||||
}
|
||||
p.add(presets);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
JSeparator sep = new JSeparator(); sep.setForeground(new Color(0xE3E8F3));
|
||||
p.add(sep);
|
||||
p.add(Box.createVerticalStrut(8));
|
||||
UI.RoundButton reset = UI.button(I18n.t("input.reset"));
|
||||
reset.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
reset.addActionListener(e -> {
|
||||
s.mapCm = 3; s.realCm = 300000; s.n = 100000; setMode(ScaleMath.SolveMode.REAL); ScaleMath.solve(s); refresh();
|
||||
});
|
||||
p.add(reset);
|
||||
p.add(Box.createVerticalStrut(4));
|
||||
p.add(Theme.label(I18n.t("input.dragHint"), 10.5f, Theme.FAINT));
|
||||
card.add(UI.scroll(p), BorderLayout.CENTER);
|
||||
return card;
|
||||
}
|
||||
|
||||
private void inputCard(UI.Card card, JPanel parent, String label, JLabel result,
|
||||
JTextField field, UI.Select unit, UI.Slider slider) {
|
||||
card.setLayout(new UI.VStackLayout());
|
||||
card.setBorder(new EmptyBorder(12, 12, 12, 12));
|
||||
card.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
card.setMaximumSize(new Dimension(Integer.MAX_VALUE, slider == null ? 100 : 150));
|
||||
JPanel top = new JPanel(new BorderLayout());
|
||||
top.setOpaque(false);
|
||||
top.add(Theme.label(label, 11.5f, Theme.DIM), BorderLayout.WEST);
|
||||
top.add(result, BorderLayout.EAST);
|
||||
card.add(top);
|
||||
card.add(Box.createVerticalStrut(6));
|
||||
JPanel row = new JPanel(new BorderLayout(6, 0));
|
||||
row.setOpaque(false);
|
||||
Theme.styleField(field);
|
||||
field.setPreferredSize(new Dimension(120, 34));
|
||||
row.add(field, BorderLayout.CENTER);
|
||||
if (unit != null) {
|
||||
unit.setPreferredSize(new Dimension(92, 34));
|
||||
row.add(unit, BorderLayout.EAST);
|
||||
}
|
||||
card.add(row);
|
||||
if (slider != null) {
|
||||
slider.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
slider.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30));
|
||||
card.add(Box.createVerticalStrut(4));
|
||||
card.add(slider);
|
||||
}
|
||||
parent.add(card);
|
||||
}
|
||||
|
||||
private void inputReal(JPanel p) {
|
||||
realCard.setLayout(new UI.VStackLayout());
|
||||
realCard.setBorder(new EmptyBorder(12, 12, 12, 12));
|
||||
realCard.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
realCard.setMaximumSize(new Dimension(Integer.MAX_VALUE, 100));
|
||||
JPanel top = new JPanel(new BorderLayout());
|
||||
top.setOpaque(false);
|
||||
top.add(Theme.label(I18n.t("input.real"), 11.5f, Theme.DIM), BorderLayout.WEST);
|
||||
top.add(realResult, BorderLayout.EAST);
|
||||
realCard.add(top);
|
||||
realCard.add(Box.createVerticalStrut(6));
|
||||
JPanel row = new JPanel(new BorderLayout(6, 0));
|
||||
row.setOpaque(false);
|
||||
Theme.styleField(realField);
|
||||
realField.setPreferredSize(new Dimension(120, 34));
|
||||
row.add(realField, BorderLayout.CENTER);
|
||||
unitBox.setPreferredSize(new Dimension(92, 34));
|
||||
row.add(unitBox, BorderLayout.EAST);
|
||||
realCard.add(row);
|
||||
p.add(realCard);
|
||||
}
|
||||
|
||||
private void inputScale(JPanel p) {
|
||||
scaleCard.setLayout(new UI.VStackLayout());
|
||||
scaleCard.setBorder(new EmptyBorder(12, 12, 12, 12));
|
||||
scaleCard.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
scaleCard.setMaximumSize(new Dimension(Integer.MAX_VALUE, 100));
|
||||
JPanel top = new JPanel(new BorderLayout());
|
||||
top.setOpaque(false);
|
||||
top.add(Theme.label(I18n.t("input.scale"), 11.5f, Theme.DIM), BorderLayout.WEST);
|
||||
top.add(nResult, BorderLayout.EAST);
|
||||
scaleCard.add(top);
|
||||
scaleCard.add(Box.createVerticalStrut(6));
|
||||
JPanel row = new JPanel(new BorderLayout(6, 0));
|
||||
row.setOpaque(false);
|
||||
JLabel prefix = Theme.boldLabel("1 :", 13, Theme.DIM);
|
||||
prefix.setBorder(new EmptyBorder(0, 8, 0, 4));
|
||||
row.add(prefix, BorderLayout.WEST);
|
||||
Theme.styleField(nField);
|
||||
nField.setPreferredSize(new Dimension(120, 34));
|
||||
row.add(nField, BorderLayout.CENTER);
|
||||
scaleCard.add(row);
|
||||
p.add(scaleCard);
|
||||
}
|
||||
|
||||
private JComponent middle() {
|
||||
UI.Card card = new UI.Card(new BorderLayout());
|
||||
JPanel p = new JPanel(new BorderLayout());
|
||||
p.setOpaque(false);
|
||||
p.setBorder(new EmptyBorder(16, 16, 12, 16));
|
||||
JPanel head = new JPanel(new BorderLayout());
|
||||
head.setOpaque(false);
|
||||
head.add(Theme.boldLabel(I18n.t("ruler.title"), 14, Theme.INK), BorderLayout.WEST);
|
||||
head.add(Theme.label(I18n.t("ruler.sameWidth"), 10.5f, Theme.FAINT), BorderLayout.EAST);
|
||||
p.add(head, BorderLayout.NORTH);
|
||||
p.add(ruler, BorderLayout.CENTER);
|
||||
JLabel hint = Theme.label(I18n.t("ruler.hint"), 10.5f, Theme.FAINT);
|
||||
hint.setBorder(new EmptyBorder(6, 2, 0, 2));
|
||||
p.add(hint, BorderLayout.SOUTH);
|
||||
card.add(p, BorderLayout.CENTER);
|
||||
return card;
|
||||
}
|
||||
|
||||
private JComponent right() {
|
||||
UI.Card card = new UI.Card(new BorderLayout());
|
||||
card.setPreferredSize(new Dimension(340, 0));
|
||||
JPanel p = new JPanel();
|
||||
p.setOpaque(false);
|
||||
p.setLayout(new UI.VStackLayout());
|
||||
p.setBorder(new EmptyBorder(14, 14, 14, 14));
|
||||
|
||||
p.add(Theme.boldLabel(I18n.t("forms.title"), 13.5f, Theme.INK));
|
||||
p.add(Box.createVerticalStrut(8));
|
||||
p.add(formRow(I18n.t("forms.digital"), digital));
|
||||
p.add(Box.createVerticalStrut(6));
|
||||
p.add(formRow(I18n.t("forms.verbal"), verbal));
|
||||
p.add(Box.createVerticalStrut(6));
|
||||
p.add(formRow(I18n.t("forms.segment"), segmentLabel));
|
||||
p.add(Box.createVerticalStrut(12));
|
||||
|
||||
UI.Card grade = new UI.Card();
|
||||
grade.setLayout(new UI.VStackLayout());
|
||||
grade.setBorder(new EmptyBorder(12, 12, 12, 12));
|
||||
grade.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
grade.setMaximumSize(new Dimension(Integer.MAX_VALUE, 120));
|
||||
JPanel gt = new JPanel(new BorderLayout(8, 0));
|
||||
gt.setOpaque(false);
|
||||
gt.add(Theme.label(I18n.t("grade.title"), 11.5f, Theme.DIM), BorderLayout.WEST);
|
||||
gradeChip.setFont(Theme.bold(11));
|
||||
gradeChip.setOpaque(true);
|
||||
gradeChip.setBorder(new EmptyBorder(3, 8, 3, 8));
|
||||
gt.add(gradeChip, BorderLayout.EAST);
|
||||
grade.add(gt);
|
||||
grade.add(Box.createVerticalStrut(6));
|
||||
grade.add(gradeNote);
|
||||
grade.add(Box.createVerticalStrut(4));
|
||||
grade.add(gradeRule);
|
||||
p.add(grade);
|
||||
p.add(Box.createVerticalStrut(12));
|
||||
|
||||
JPanel stepsHead = new JPanel(new BorderLayout());
|
||||
stepsHead.setOpaque(false);
|
||||
stepsHead.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30));
|
||||
stepsHead.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
stepsHead.add(Theme.boldLabel(I18n.t("steps.title"), 13.5f, Theme.INK), BorderLayout.WEST);
|
||||
UI.RoundButton toggle = UI.button(I18n.t("steps.show"));
|
||||
toggle.ghost();
|
||||
toggle.setFont(Theme.font(10.5f));
|
||||
toggle.addActionListener(e -> {
|
||||
boolean show = !stepsWrap.isVisible();
|
||||
stepsWrap.setVisible(show);
|
||||
toggle.setText(show ? I18n.t("steps.hide") : I18n.t("steps.show"));
|
||||
p.revalidate(); p.repaint();
|
||||
});
|
||||
stepsHead.add(toggle, BorderLayout.EAST);
|
||||
p.add(stepsHead);
|
||||
p.add(Box.createVerticalStrut(6));
|
||||
stepsArea.setEditable(false);
|
||||
stepsArea.setLineWrap(true);
|
||||
stepsArea.setWrapStyleWord(true);
|
||||
stepsArea.setFont(Theme.font(11));
|
||||
stepsArea.setForeground(Theme.DIM);
|
||||
stepsArea.setBackground(new Color(0xF7F9FE));
|
||||
stepsArea.setBorder(new EmptyBorder(8, 8, 8, 8));
|
||||
stepsWrap.setOpaque(false);
|
||||
stepsWrap.add(stepsArea, BorderLayout.CENTER);
|
||||
stepsWrap.setVisible(false);
|
||||
stepsWrap.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
stepsWrap.setMaximumSize(new Dimension(Integer.MAX_VALUE, 170));
|
||||
p.add(stepsWrap);
|
||||
p.add(Box.createVerticalStrut(10));
|
||||
|
||||
p.add(Theme.boldLabel(I18n.t("pit.title"), 13.5f, Theme.INK));
|
||||
p.add(Box.createVerticalStrut(5));
|
||||
for (String k : new String[]{"pit.1", "pit.2", "pit.3"})
|
||||
p.add(Theme.label(I18n.t(k), 10.5f, Theme.DIM));
|
||||
card.add(UI.scroll(p), BorderLayout.CENTER);
|
||||
return card;
|
||||
}
|
||||
|
||||
private JComponent formRow(String label, JLabel value) {
|
||||
JPanel p = new JPanel(new BorderLayout(10, 0));
|
||||
p.setOpaque(false);
|
||||
p.setMaximumSize(new Dimension(Integer.MAX_VALUE, 34));
|
||||
JLabel l = Theme.label(label, 11.5f, Theme.FAINT);
|
||||
l.setPreferredSize(new Dimension(52, 20));
|
||||
p.add(l, BorderLayout.WEST);
|
||||
p.add(value, BorderLayout.CENTER);
|
||||
return p;
|
||||
}
|
||||
|
||||
private JComponent bottom() {
|
||||
JPanel wrap = new JPanel(new GridLayout(1, 2, 16, 0));
|
||||
wrap.setOpaque(false);
|
||||
wrap.setBorder(new EmptyBorder(4, 16, 14, 16));
|
||||
wrap.setPreferredSize(new Dimension(0, 190));
|
||||
|
||||
UI.Card field = new UI.Card();
|
||||
field.setLayout(new UI.VStackLayout());
|
||||
field.setBorder(new EmptyBorder(12, 14, 12, 14));
|
||||
field.add(Theme.boldLabel(I18n.t("field.title"), 13, Theme.INK));
|
||||
field.add(Box.createVerticalStrut(4));
|
||||
field.add(Theme.label(I18n.t("field.hint"), 10.5f, Theme.FAINT));
|
||||
field.add(Box.createVerticalStrut(8));
|
||||
for (ScaleData.Landmark lm : data.landmarks) landmarkBox.addItem(I18n.t(lm.nameKey()));
|
||||
landmarkBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, 34));
|
||||
landmarkBox.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
field.add(landmarkBox);
|
||||
field.add(Box.createVerticalStrut(10));
|
||||
landmarkResult.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
field.add(landmarkResult);
|
||||
|
||||
UI.Card quizCard = new UI.Card();
|
||||
quizCard.setLayout(new UI.VStackLayout());
|
||||
quizCard.setBorder(new EmptyBorder(12, 14, 12, 14));
|
||||
JPanel qh = new JPanel(new BorderLayout());
|
||||
qh.setOpaque(false);
|
||||
qh.add(Theme.boldLabel(I18n.t("quiz.title"), 13, Theme.INK), BorderLayout.WEST);
|
||||
qh.add(quizStreak, BorderLayout.EAST);
|
||||
quizCard.add(qh);
|
||||
quizCard.add(Box.createVerticalStrut(5));
|
||||
quizPrompt.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
quizCard.add(quizPrompt);
|
||||
quizCard.add(Box.createVerticalStrut(6));
|
||||
JPanel ans = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
|
||||
ans.setOpaque(false);
|
||||
Theme.styleField(quizInput);
|
||||
quizInput.setPreferredSize(new Dimension(100, 32));
|
||||
ans.add(quizInput);
|
||||
UI.RoundButton check = UI.primary(I18n.t("quiz.check"));
|
||||
check.setBorder(new EmptyBorder(6, 12, 6, 12));
|
||||
check.addActionListener(e -> checkQuiz());
|
||||
UI.RoundButton next = UI.button(I18n.t("quiz.next"));
|
||||
next.setBorder(new EmptyBorder(6, 10, 6, 10));
|
||||
next.addActionListener(e -> newQuiz());
|
||||
ans.add(check);
|
||||
ans.add(next);
|
||||
ans.add(quizUnit);
|
||||
quizCard.add(ans);
|
||||
quizCard.add(Box.createVerticalStrut(5));
|
||||
quizFeedback.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
quizCard.add(quizFeedback);
|
||||
quizSteps.setOpaque(false);
|
||||
quizSteps.setLayout(new UI.VStackLayout());
|
||||
quizCard.add(quizSteps);
|
||||
|
||||
wrap.add(field);
|
||||
wrap.add(quizCard);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
private void wire() {
|
||||
ChangeListener slider = e -> {
|
||||
if (updating) return;
|
||||
s.mapCm = mapSlider.getValue() / 10.0;
|
||||
ScaleMath.solve(s);
|
||||
refresh();
|
||||
};
|
||||
mapSlider.addChangeListener(slider);
|
||||
mapField.addActionListener(e -> {
|
||||
try { s.mapCm = Double.parseDouble(mapField.getText().trim()); ScaleMath.solve(s); refresh(); }
|
||||
catch (Exception ex) { mapField.setText(ScaleMath.num(s.mapCm)); }
|
||||
});
|
||||
realField.addActionListener(e -> {
|
||||
Double cm = ScaleMath.tryParseReal(realField.getText(), String.valueOf(unitBox.getSelectedItem()));
|
||||
if (cm != null) { s.realCm = cm; ScaleMath.solve(s); refresh(); }
|
||||
else refresh();
|
||||
});
|
||||
unitBox.addActionListener(e -> refresh());
|
||||
nField.addActionListener(e -> {
|
||||
try { s.n = Double.parseDouble(nField.getText().trim().replace(",", "")); ScaleMath.solve(s); refresh(); }
|
||||
catch (Exception ex) { nField.setText(ScaleMath.formatN(s.n)); }
|
||||
});
|
||||
btnReal.addActionListener(e -> setMode(ScaleMath.SolveMode.REAL));
|
||||
btnMap.addActionListener(e -> setMode(ScaleMath.SolveMode.MAP));
|
||||
btnScale.addActionListener(e -> setMode(ScaleMath.SolveMode.SCALE));
|
||||
landmarkBox.addActionListener(e -> refresh());
|
||||
}
|
||||
|
||||
private void setMode(ScaleMath.SolveMode m) {
|
||||
s.mode = m;
|
||||
ScaleMath.solve(s);
|
||||
refresh();
|
||||
}
|
||||
|
||||
private void styleMode(UI.RoundButton b, boolean active) {
|
||||
b.primary = active;
|
||||
b.ghost = !active;
|
||||
b.repaint();
|
||||
}
|
||||
|
||||
private void refresh() {
|
||||
updating = true;
|
||||
styleMode(btnReal, s.mode == ScaleMath.SolveMode.REAL);
|
||||
styleMode(btnMap, s.mode == ScaleMath.SolveMode.MAP);
|
||||
styleMode(btnScale, s.mode == ScaleMath.SolveMode.SCALE);
|
||||
mapField.setText(ScaleMath.num(s.mapCm));
|
||||
String unit = String.valueOf(unitBox.getSelectedItem());
|
||||
realField.setText(ScaleMath.num(ScaleMath.toUnit(s.realCm, unit)));
|
||||
nField.setText(ScaleMath.formatN(s.n));
|
||||
mapSlider.setValue((int) Math.round(Math.max(0.1, Math.min(20, s.mapCm)) * 10));
|
||||
mapResult.setText(ScaleMath.num(s.mapCm) + " cm");
|
||||
realResult.setText(ScaleMath.formatRealCm(s.realCm).replace("unit.", ""));
|
||||
nResult.setText("N " + ScaleMath.formatN(s.n));
|
||||
highlight(mapCard, s.mode == ScaleMath.SolveMode.REAL);
|
||||
highlight(realCard, s.mode == ScaleMath.SolveMode.MAP);
|
||||
highlight(scaleCard, s.mode == ScaleMath.SolveMode.SCALE);
|
||||
|
||||
digital.setText(ScaleMath.digital(s.n));
|
||||
verbal.setText(I18n.f("forms.verbalTpl", ScaleMath.verbalDistance(s.n).replace("unit.", "")));
|
||||
ScaleMath.Segment seg = ScaleMath.pickSegment(s.n, 60, 120);
|
||||
segmentLabel.setText(I18n.f("forms.segmentDesc", ScaleMath.segmentLabel(seg.metersPerDiv()), seg.divCount()));
|
||||
ScaleMath.Grade g = ScaleMath.grade(s.n);
|
||||
String gk = ScaleMath.gradeKey(s.n);
|
||||
gradeChip.setText(I18n.t(gk));
|
||||
gradeChip.setForeground(g == ScaleMath.Grade.LARGE ? Theme.SUCCESS
|
||||
: g == ScaleMath.Grade.MEDIUM ? Theme.WARN : Theme.DANGER);
|
||||
gradeChip.setBackground(g == ScaleMath.Grade.LARGE ? new Color(0xE8F7F0)
|
||||
: g == ScaleMath.Grade.MEDIUM ? new Color(0xFFF6E6) : new Color(0xFDECEC));
|
||||
gradeNote.setText("<html><body style='width:200px'>" + I18n.t(gk + "Note") + "</body></html>");
|
||||
gradeNote.setForeground(Theme.DIM);
|
||||
stepsArea.setText(stepsText());
|
||||
ruler.set(s);
|
||||
refreshLandmark();
|
||||
updating = false;
|
||||
}
|
||||
|
||||
private void highlight(UI.Card c, boolean active) {
|
||||
c.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createLineBorder(active ? Theme.ACCENT : Theme.LINE, 1, true),
|
||||
new EmptyBorder(11, 11, 11, 11)));
|
||||
c.alt = active;
|
||||
c.repaint();
|
||||
}
|
||||
|
||||
private String stepsText() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(I18n.t("steps.1.unify")).append('\n');
|
||||
String formula = switch (s.mode) {
|
||||
case REAL -> I18n.t("steps.2.formulaReal");
|
||||
case MAP -> I18n.t("steps.2.formulaMap");
|
||||
case SCALE -> I18n.t("steps.2.formulaScale");
|
||||
};
|
||||
sb.append(formula).append('\n');
|
||||
String subst = switch (s.mode) {
|
||||
case REAL -> ScaleMath.num(s.mapCm) + " cm × " + ScaleMath.formatN(s.n);
|
||||
case MAP -> ScaleMath.formatRealCm(s.realCm).replace("unit.", "") + " ÷ " + ScaleMath.formatN(s.n);
|
||||
case SCALE -> ScaleMath.formatRealCm(s.realCm).replace("unit.", "") + " ÷ " + ScaleMath.num(s.mapCm) + " cm";
|
||||
};
|
||||
sb.append(I18n.f("steps.3.substitute", subst)).append('\n');
|
||||
String res = switch (s.mode) {
|
||||
case REAL -> ScaleMath.formatRealCm(s.realCm).replace("unit.", "");
|
||||
case MAP -> ScaleMath.num(s.mapCm) + " cm";
|
||||
case SCALE -> "1 : " + ScaleMath.formatN(s.n);
|
||||
};
|
||||
sb.append(I18n.f("steps.4.result", res)).append('\n');
|
||||
sb.append(I18n.t("steps.5.convert"));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void refreshLandmark() {
|
||||
if (landmarkBox.getSelectedIndex() < 0 || data.landmarks.isEmpty()) return;
|
||||
ScaleData.Landmark lm = data.landmarks.get(landmarkBox.getSelectedIndex());
|
||||
double mapCm = ScaleMath.realToMapCm(lm.meters() * 100, s.n);
|
||||
String text;
|
||||
if (mapCm > 100) text = I18n.t("field.tooLong");
|
||||
else if (mapCm < 0.001) text = I18n.t("field.tooShort");
|
||||
else text = I18n.f("field.mapLength", ScaleMath.num(mapCm) + " cm");
|
||||
landmarkResult.setText(text);
|
||||
}
|
||||
|
||||
private void newQuiz() {
|
||||
quiz = ScaleMath.generateQuiz(rnd);
|
||||
quizInput.setText("");
|
||||
quizFeedback.setText("");
|
||||
quizSteps.removeAll();
|
||||
quizUnit.setText(I18n.f("quiz.unit", I18n.t(quiz.answerUnitKey)));
|
||||
quizPrompText();
|
||||
quizStreak.setText(I18n.f("quiz.streak", streak));
|
||||
revalidate(); repaint();
|
||||
}
|
||||
|
||||
private void quizPrompText() {
|
||||
quizPrompt.setText("<html><body style='width:420px'>" + I18n.f(quiz.promptKey, quiz.promptArgs) + "</body></html>");
|
||||
}
|
||||
|
||||
private void checkQuiz() {
|
||||
try {
|
||||
double v = Double.parseDouble(quizInput.getText().trim().replace(",", ""));
|
||||
if (ScaleMath.checkAnswer(quiz, v)) {
|
||||
streak++;
|
||||
quizFeedback.setForeground(Theme.SUCCESS);
|
||||
quizFeedback.setText(I18n.t("quiz.correct"));
|
||||
quizSteps.removeAll();
|
||||
} else {
|
||||
streak = 0;
|
||||
quizFeedback.setForeground(Theme.DANGER);
|
||||
quizFeedback.setText(I18n.t("quiz.wrong"));
|
||||
quizSteps.removeAll();
|
||||
for (String k : quiz.stepKeys) {
|
||||
JLabel l = Theme.label(I18n.t(k), 10.5f, Theme.DIM);
|
||||
quizSteps.add(l);
|
||||
}
|
||||
}
|
||||
quizStreak.setText(I18n.f("quiz.streak", streak));
|
||||
revalidate(); repaint();
|
||||
} catch (Exception e) {
|
||||
quizFeedback.setForeground(Theme.DANGER);
|
||||
quizFeedback.setText(I18n.t("quiz.wrong"));
|
||||
}
|
||||
}
|
||||
|
||||
/** 中栏可视化标尺:图上 / 实地双条、线段式、比例尺光谱。 */
|
||||
private static final class ScaleRuler extends JComponent {
|
||||
private ScaleMath.State st = new ScaleMath.State();
|
||||
|
||||
void set(ScaleMath.State s) { st = s.copy(); repaint(); }
|
||||
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
int w = getWidth(), h = getHeight();
|
||||
g2.setColor(new Color(0xF7F9FE));
|
||||
g2.fillRoundRect(6, 4, w - 12, h - 8, 12, 12);
|
||||
int x = 26, y = 34;
|
||||
int maxW = w - 52;
|
||||
int blueW = (int) Math.max(30, Math.min(maxW, st.mapCm * 70));
|
||||
|
||||
g2.setFont(Theme.font(11));
|
||||
g2.setColor(new Color(0x5B6A86));
|
||||
g2.drawString(I18n.t("ruler.mapBar"), x, y - 12);
|
||||
g2.setColor(new Color(0x2F6BFF));
|
||||
g2.fillRoundRect(x, y, blueW, 16, 7, 7);
|
||||
g2.setColor(new Color(0x1F4FD0));
|
||||
g2.setFont(Theme.bold(10.5f));
|
||||
g2.drawString(ScaleMath.num(st.mapCm) + " cm", x + blueW + 8, y + 13);
|
||||
|
||||
int y2 = y + 52;
|
||||
g2.setFont(Theme.font(11));
|
||||
g2.setColor(new Color(0x5B6A86));
|
||||
g2.drawString(I18n.t("ruler.realBar"), x, y2 - 12);
|
||||
int greenW = blueW;
|
||||
g2.setColor(new Color(0x1F9D6B));
|
||||
g2.fillRoundRect(x, y2, greenW, 16, 7, 7);
|
||||
g2.setColor(new Color(0x137A51));
|
||||
g2.setFont(Theme.bold(10.5f));
|
||||
g2.drawString(ScaleMath.formatRealCm(st.realCm).replace("unit.", ""), x + greenW + 8, y2 + 13);
|
||||
|
||||
int y3 = y2 + 54;
|
||||
g2.setFont(Theme.bold(11.5f));
|
||||
g2.setColor(new Color(0x111A2E));
|
||||
g2.drawString(I18n.t("ruler.segment"), x, y3);
|
||||
g2.setFont(Theme.font(10));
|
||||
g2.setColor(new Color(0x8A97B1));
|
||||
g2.drawString(I18n.t("ruler.segmentHint"), x + 110, y3);
|
||||
ScaleMath.Segment seg = ScaleMath.pickSegment(st.n, 1, 90);
|
||||
int sy = y3 + 14;
|
||||
int segW = (int) Math.max(14, Math.min(60, seg.divPx()));
|
||||
int count = Math.min(seg.divCount(), Math.max(2, maxW / segW));
|
||||
for (int i = 0; i < count; i++) {
|
||||
g2.setColor(i % 2 == 0 ? new Color(0x111A2E) : Color.WHITE);
|
||||
g2.fillRect(x + i * segW, sy, segW, 12);
|
||||
g2.setColor(new Color(0x8A97B1));
|
||||
g2.drawRect(x + i * segW, sy, segW, 12);
|
||||
}
|
||||
g2.setColor(new Color(0x5B6A86));
|
||||
g2.setFont(Theme.font(9.5f));
|
||||
g2.drawString("0", x - 2, sy + 26);
|
||||
g2.drawString(ScaleMath.segmentLabel(seg.metersPerDiv() * count), x + count * segW - 18, sy + 26);
|
||||
g2.drawString(ScaleMath.segmentLabel(seg.metersPerDiv()), x + segW - 14, sy + 26);
|
||||
|
||||
int y4 = sy + 50;
|
||||
g2.setFont(Theme.bold(11.5f));
|
||||
g2.setColor(new Color(0x111A2E));
|
||||
g2.drawString(I18n.t("ruler.spectrum"), x, y4);
|
||||
int spY = y4 + 14, spH = 12;
|
||||
GradientPaint gp = new GradientPaint(x, 0, new Color(0x9CCBFF), x + maxW, 0, new Color(0xFF9D9D));
|
||||
g2.setPaint(gp);
|
||||
g2.fillRoundRect(x, spY, maxW, spH, 6, 6);
|
||||
int px = x + (int) (ScaleMath.spectrumPosition(st.n) * maxW);
|
||||
g2.setColor(new Color(0x111A2E));
|
||||
g2.fillPolygon(new int[]{px - 6, px + 6, px}, new int[]{spY - 7, spY - 7, spY}, 3);
|
||||
g2.setFont(Theme.font(9));
|
||||
g2.setColor(new Color(0x5B6A86));
|
||||
g2.drawString(I18n.t("ruler.scopeUp"), x, spY + spH + 14);
|
||||
String right = I18n.t("ruler.detailDown");
|
||||
g2.drawString(right, x + maxW - g2.getFontMetrics().stringWidth(right), spY + spH + 14);
|
||||
g2.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.*;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.event.MouseAdapter;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Locale;
|
||||
|
||||
/** 设置页:外观(深色/浅色/跟随系统)、语言、渲染、内存、更新与存储。 */
|
||||
public final class SettingsPage extends JPanel {
|
||||
private final MainWindow app;
|
||||
private final UI.Select language = new UI.Select(new String[]{"auto", "zh-CN", "en"})
|
||||
.display(v -> v.equals("auto") ? t("set.language.auto", "跟随系统") : v.equals("zh-CN") ? "简体中文" : "English");
|
||||
private final UI.Select fps = new UI.Select(new String[]{"24", "30", "60", "90", "120"});
|
||||
private final UI.Switch memoryAuto = new UI.Switch(t("set.memory.auto", "自动(根据设备内存分配)"), true);
|
||||
private final UI.Slider memory = new UI.Slider(512, 8192, 2048, true);
|
||||
private final JLabel memoryValue = Theme.boldLabel("", 13, Theme.ACCENT);
|
||||
private final UI.Switch autoUpdate = new UI.Switch(t("update.auto", "启动时自动检查更新"), true);
|
||||
private final UI.Switch signed = new UI.Switch(t("set.requireSigned", "要求清单签名"), true);
|
||||
private final UI.TextField repo = new UI.TextField();
|
||||
private final UI.TextField local = new UI.TextField();
|
||||
private final UI.TextField modelOverride = new UI.TextField();
|
||||
private final AppearanceOption[] appearanceOptions = new AppearanceOption[3];
|
||||
private String appearance = "auto";
|
||||
|
||||
public SettingsPage(MainWindow app) {
|
||||
this.app = app;
|
||||
setLayout(new BorderLayout());
|
||||
setOpaque(false);
|
||||
JPanel page = UI.page();
|
||||
page.add(UI.pageHeader(t("set.title", "设置"), t("set.subtitle", "外观、语言、渲染、内存、更新与本地存储。"),
|
||||
badge()), BorderLayout.NORTH);
|
||||
JPanel body = new JPanel();
|
||||
body.setOpaque(false);
|
||||
body.setLayout(new UI.VStackLayout());
|
||||
body.add(appearanceCard());
|
||||
body.add(Box.createVerticalStrut(16));
|
||||
body.add(general());
|
||||
body.add(Box.createVerticalStrut(16));
|
||||
body.add(updateCard());
|
||||
body.add(Box.createVerticalStrut(16));
|
||||
body.add(storage());
|
||||
body.add(Box.createVerticalStrut(20));
|
||||
page.add(UI.scroll(body), BorderLayout.CENTER);
|
||||
|
||||
JPanel footer = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 0));
|
||||
footer.setOpaque(false);
|
||||
footer.setBorder(new EmptyBorder(12, 0, 0, 0));
|
||||
UI.RoundButton reset = UI.button(t("common.reset", "重置"));
|
||||
reset.addActionListener(e -> { loadValues(); Theme.apply(app.settings); app.repaintAll(); });
|
||||
UI.RoundButton save = UI.primary(t("common.save", "保存"));
|
||||
save.addActionListener(e -> save());
|
||||
footer.add(reset);
|
||||
footer.add(save);
|
||||
page.add(footer, BorderLayout.SOUTH);
|
||||
add(page, BorderLayout.CENTER);
|
||||
memory.setStep(256);
|
||||
loadValues();
|
||||
}
|
||||
|
||||
private JComponent badge() {
|
||||
JLabel l = UI.pill("OpenGL 3D · JavaFX WebView", Theme.ACCENT, Theme.ACCENT_SOFT);
|
||||
return l;
|
||||
}
|
||||
|
||||
private UI.Card cardShell(String title, String desc) {
|
||||
UI.Card c = new UI.Card();
|
||||
c.setLayout(new UI.VStackLayout());
|
||||
c.setBorder(new EmptyBorder(18, 20, 18, 20));
|
||||
c.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.setMaximumSize(new Dimension(Integer.MAX_VALUE, 10000));
|
||||
JLabel heading = Theme.boldLabel(title, 15, Theme.INK);
|
||||
heading.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(heading);
|
||||
if (desc != null && !desc.isBlank()) {
|
||||
c.add(Box.createVerticalStrut(4));
|
||||
JLabel d = Theme.label(desc, 11.5f, Theme.DIM);
|
||||
d.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(d);
|
||||
}
|
||||
c.add(Box.createVerticalStrut(14));
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent appearanceCard() {
|
||||
UI.Card c = cardShell(t("set.appearance", "外观"),
|
||||
t("set.appearance.desc", "选择深色、浅色,或跟随操作系统自动切换。"));
|
||||
JPanel row = new JPanel(new GridLayout(1, 3, 12, 0));
|
||||
row.setOpaque(false);
|
||||
row.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 124));
|
||||
appearanceOptions[0] = new AppearanceOption("auto", t("set.appearance.auto", "跟随系统"), true, false, null);
|
||||
appearanceOptions[1] = new AppearanceOption("light", t("set.theme.light", "浅色"), false, false, null);
|
||||
appearanceOptions[2] = new AppearanceOption("dark", t("set.theme.dark", "深色"), false, true, null);
|
||||
for (AppearanceOption o : appearanceOptions) {
|
||||
o.addMouseListener(new MouseAdapter() {
|
||||
@Override public void mouseClicked(MouseEvent e) { chooseAppearance(o.mode); }
|
||||
});
|
||||
row.add(o);
|
||||
}
|
||||
c.add(row);
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
JLabel hint = Theme.label(t("set.appearance.hint", "跟随系统时会读取 macOS / Windows / Linux 的当前外观,系统切换后自动同步。"), 10.5f, Theme.FAINT);
|
||||
hint.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(hint);
|
||||
return c;
|
||||
}
|
||||
|
||||
private void chooseAppearance(String mode) {
|
||||
appearance = mode;
|
||||
for (AppearanceOption o : appearanceOptions) o.setSelected(o.mode.equals(mode));
|
||||
Settings preview = Settings.defaults();
|
||||
preview.theme = mode;
|
||||
preview.accentColor = app.settings.accentColor;
|
||||
Theme.apply(preview);
|
||||
app.repaintAll();
|
||||
}
|
||||
|
||||
private JComponent general() {
|
||||
UI.Card c = cardShell(t("set.general", "通用"), null);
|
||||
JPanel grid = new JPanel(new GridLayout(2, 2, 18, 14));
|
||||
grid.setOpaque(false);
|
||||
grid.setMaximumSize(new Dimension(Integer.MAX_VALUE, 124));
|
||||
grid.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
grid.add(UI.labeled(t("set.language", "界面语言"), language));
|
||||
grid.add(UI.labeled(t("set.fps", "渲染帧率"), fps));
|
||||
JPanel memHead = new JPanel(new BorderLayout());
|
||||
memHead.setOpaque(false);
|
||||
memHead.add(UI.labeled(t("set.memory", "运行内存"), memory), BorderLayout.CENTER);
|
||||
memHead.add(memoryValue, BorderLayout.EAST);
|
||||
grid.add(memHead);
|
||||
grid.add(UI.labeled(t("set.fps.desc", "越高越顺滑,CPU 占用也越高。"), Theme.label("OpenGL 垂直同步 · " + (Theme.dark ? "深色" : "浅色"), 11, Theme.FAINT)));
|
||||
c.add(grid);
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
c.add(memoryAuto);
|
||||
c.add(Box.createVerticalStrut(4));
|
||||
JLabel hint = Theme.label(t("set.memory.hint", "建议 2048 MB 以上,低配设备可选 1024 MB。"), 11, Theme.FAINT);
|
||||
hint.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(hint);
|
||||
memory.addChangeListener(e -> memoryValue.setText(memory.getValue() + " MB"));
|
||||
memoryAuto.addActionListener(e -> memory.setEnabled(!memoryAuto.isSelected()));
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent updateCard() {
|
||||
UI.Card c = cardShell(t("set.update", "更新"), t("update.desc", "模型与启动器更新使用签名清单校验。"));
|
||||
c.add(autoUpdate);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
c.add(signed);
|
||||
c.add(Box.createVerticalStrut(12));
|
||||
c.add(UI.labeled(t("set.updateRepo", "更新仓库"), repo));
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
c.add(UI.labeled(t("set.updateLocal", "离线模型源"), local));
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent storage() {
|
||||
UI.Card c = cardShell(t("set.storage", "存储"), null);
|
||||
JPanel paths = new JPanel(new GridLayout(2, 1, 0, 8));
|
||||
paths.setOpaque(false);
|
||||
paths.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
paths.setMaximumSize(new Dimension(Integer.MAX_VALUE, 82));
|
||||
paths.add(pathRow(t("set.dataDir", "数据目录"), app.paths.homeRoot));
|
||||
paths.add(pathRow(t("set.modelDir", "模型库目录"), app.modelRoot()));
|
||||
c.add(paths);
|
||||
c.add(Box.createVerticalStrut(12));
|
||||
c.add(UI.labeled(t("set.modelDir", "模型库目录") + " (override)", modelOverride));
|
||||
c.add(Box.createVerticalStrut(12));
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
actions.setOpaque(false);
|
||||
actions.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
UI.RoundButton openData = UI.button(t("set.openFolder", "打开文件夹"));
|
||||
openData.addActionListener(e -> MainWindow.openFolder(this, app.paths.homeRoot));
|
||||
UI.RoundButton openModel = UI.button(t("set.modelDir", "模型库目录"));
|
||||
openModel.addActionListener(e -> MainWindow.openFolder(this, app.modelRoot()));
|
||||
UI.RoundButton clear = UI.button(t("set.clearCache", "清理缓存")).danger();
|
||||
clear.addActionListener(e -> {
|
||||
if (UI.confirm(this, t("set.clearCache", "清理缓存") + "?")) {
|
||||
AppPaths.deleteTree(app.paths.cacheRoot());
|
||||
app.toast(t("set.cacheCleared", "缓存已清理"));
|
||||
}
|
||||
});
|
||||
actions.add(openData);
|
||||
actions.add(openModel);
|
||||
actions.add(clear);
|
||||
c.add(actions);
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent pathRow(String label, Path p) {
|
||||
JPanel row = new JPanel(new BorderLayout(8, 0));
|
||||
row.setOpaque(false);
|
||||
row.add(Theme.label(label, 11.5f, Theme.FAINT), BorderLayout.WEST);
|
||||
JTextField f = new JTextField(p.toString());
|
||||
f.setEditable(false);
|
||||
f.setFont(Theme.font(11.5f));
|
||||
f.setForeground(Theme.DIM);
|
||||
f.setBorder(new EmptyBorder(4, 8, 4, 8));
|
||||
f.setBackground(Theme.CARD_ALT);
|
||||
row.add(f, BorderLayout.CENTER);
|
||||
return row;
|
||||
}
|
||||
|
||||
public void loadValues() {
|
||||
Settings s = app.settings;
|
||||
language.setSelectedItem(s.language);
|
||||
fps.setSelectedItem(String.valueOf(s.renderFps));
|
||||
appearance = Theme.normalizeMode(s.theme);
|
||||
for (AppearanceOption o : appearanceOptions) if (o != null) o.setSelected(o.mode.equals(appearance));
|
||||
memoryAuto.setSelected(s.memoryAuto);
|
||||
memory.setValue(Math.max(512, Math.min(8192, s.memoryMb)));
|
||||
memory.setEnabled(!s.memoryAuto);
|
||||
memoryValue.setText(memory.getValue() + " MB");
|
||||
autoUpdate.setSelected(s.autoUpdateOnStartup);
|
||||
signed.setSelected(s.requireSignedManifest);
|
||||
repo.setText(s.updateRepository);
|
||||
local.setText(s.updateLocalRoot);
|
||||
modelOverride.setText(s.modelRootOverride);
|
||||
}
|
||||
|
||||
private void save() {
|
||||
Settings s = app.settings;
|
||||
String oldLang = s.language;
|
||||
String oldAppearance = Theme.normalizeMode(s.theme);
|
||||
s.language = String.valueOf(language.getSelectedItem());
|
||||
s.theme = appearance;
|
||||
s.renderFps = Integer.parseInt(String.valueOf(fps.getSelectedItem()));
|
||||
s.memoryAuto = memoryAuto.isSelected();
|
||||
s.memoryMb = memory.getValue();
|
||||
s.autoUpdateOnStartup = autoUpdate.isSelected();
|
||||
s.requireSignedManifest = signed.isSelected();
|
||||
s.updateRepository = repo.getText().trim();
|
||||
s.updateLocalRoot = local.getText().trim();
|
||||
s.modelRootOverride = modelOverride.getText().trim();
|
||||
s.save();
|
||||
I18n.load(s.language);
|
||||
Theme.apply(s);
|
||||
app.refreshModels();
|
||||
app.repaintAll();
|
||||
boolean langChanged = !oldLang.equals(s.language);
|
||||
if (langChanged) {
|
||||
if (UI.confirm(this, t("set.saved", "设置已保存") + "\n" + t("set.restartForLanguage", "切换语言需要重新加载界面,是否立即重启?")))
|
||||
app.rebuildForLanguage();
|
||||
} else {
|
||||
app.toast(t("set.saved", "设置已保存"));
|
||||
if (!oldAppearance.equals(s.theme)) app.repaintAll();
|
||||
}
|
||||
}
|
||||
|
||||
public void onShow() { loadValues(); }
|
||||
|
||||
private static String t(String key, String fallback) {
|
||||
String v = I18n.t(key);
|
||||
return v == null || v.equals(key) ? fallback : v;
|
||||
}
|
||||
|
||||
/** 自绘外观预览卡。 */
|
||||
private static final class AppearanceOption extends JComponent {
|
||||
final String mode;
|
||||
private final String label;
|
||||
private final boolean auto, darkPreview;
|
||||
private boolean selected, hover;
|
||||
|
||||
AppearanceOption(String mode, String label, boolean auto, boolean darkPreview, Void ignored) {
|
||||
this.mode = mode;
|
||||
this.label = label;
|
||||
this.auto = auto;
|
||||
this.darkPreview = darkPreview;
|
||||
setPreferredSize(new Dimension(180, 104));
|
||||
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
|
||||
addMouseListener(new MouseAdapter() {
|
||||
@Override public void mouseEntered(MouseEvent e) { hover = true; repaint(); }
|
||||
@Override public void mouseExited(MouseEvent e) { hover = false; repaint(); }
|
||||
});
|
||||
}
|
||||
|
||||
void setSelected(boolean b) { selected = b; repaint(); }
|
||||
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g2.setColor(selected ? Theme.ACCENT_SOFT : (hover ? Theme.CARD_HOVER : Theme.CARD));
|
||||
g2.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 12, 12);
|
||||
g2.setColor(selected ? Theme.ACCENT : Theme.LINE_STRONG);
|
||||
g2.setStroke(new BasicStroke(selected ? 2f : 1f));
|
||||
g2.drawRoundRect(0, 0, getWidth() - 2, getHeight() - 2, 12, 12);
|
||||
|
||||
int x = 12, y = 12, w = getWidth() - 24, h = 52;
|
||||
if (auto) {
|
||||
g2.setColor(new Color(0xF2F5FA));
|
||||
g2.fillRoundRect(x, y, w / 2, h, 7, 7);
|
||||
g2.setColor(new Color(0x172033));
|
||||
g2.fillRoundRect(x + w / 2, y, w - w / 2, h, 7, 7);
|
||||
g2.setColor(new Color(0x2F6BFF));
|
||||
g2.fillOval(x + w / 4 - 8, y + h / 2 - 8, 16, 16);
|
||||
g2.setColor(new Color(0x77A7FF));
|
||||
g2.fillOval(x + w * 3 / 4 - 8, y + h / 2 - 8, 16, 16);
|
||||
} else {
|
||||
g2.setColor(darkPreview ? new Color(0x121A29) : new Color(0xF3F6FC));
|
||||
g2.fillRoundRect(x, y, w, h, 7, 7);
|
||||
g2.setColor(darkPreview ? new Color(0x1E2B42) : Color.WHITE);
|
||||
g2.fillRoundRect(x + 6, y + 8, w / 4, h - 16, 5, 5);
|
||||
g2.setColor(darkPreview ? new Color(0x77A7FF) : new Color(0x2F6BFF));
|
||||
g2.fillRoundRect(x + w / 3, y + 10, w * 2 / 3 - 8, 7, 4, 4);
|
||||
g2.setColor(darkPreview ? new Color(0x2C3B56) : new Color(0xE3E8F3));
|
||||
g2.fillRoundRect(x + w / 3, y + 24, w * 2 / 3 - 8, 18, 5, 5);
|
||||
}
|
||||
g2.setFont(Theme.bold(12));
|
||||
g2.setColor(Theme.INK);
|
||||
FontMetrics fm = g2.getFontMetrics();
|
||||
g2.drawString(label, 12, getHeight() - 14);
|
||||
if (selected) {
|
||||
g2.setColor(Theme.ACCENT);
|
||||
g2.fillOval(getWidth() - 24, getHeight() - 22, 12, 12);
|
||||
g2.setColor(Color.WHITE);
|
||||
g2.setStroke(new BasicStroke(1.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
|
||||
g2.drawLine(getWidth() - 21, getHeight() - 16, getWidth() - 19, getHeight() - 14);
|
||||
g2.drawLine(getWidth() - 19, getHeight() - 14, getWidth() - 15, getHeight() - 19);
|
||||
}
|
||||
g2.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.Settings;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 应用主题令牌:深色 / 浅色 / 跟随系统三种外观。
|
||||
*
|
||||
* <p>所有颜色都由自绘组件在绘制时读取静态字段,因此切换外观后对整棵组件树
|
||||
* 调用 repaint() 即可立即生效,无需重建窗口。</p>
|
||||
*/
|
||||
public final class Theme {
|
||||
public static String mode = "auto";
|
||||
public static boolean dark;
|
||||
public static Color BG, SIDEBAR, CARD, CARD_ALT, CARD_HOVER, LINE, LINE_STRONG, INK, DIM, FAINT,
|
||||
ACCENT, ACCENT_DARK, ACCENT_SOFT, SUCCESS, DANGER, WARN, HERO_TOP, HERO_BOTTOM,
|
||||
NAV_HOVER, NAV_ACTIVE, TITLEBAR, SHADOW, GLASS, GLASS_LINE, SCROLL, SCROLL_HOVER;
|
||||
public static final String FONT = pickFont();
|
||||
public static int scale = 1;
|
||||
|
||||
private static boolean systemDark;
|
||||
private static long systemCheckedAt;
|
||||
private static final long SYSTEM_TTL_MS = 3_000;
|
||||
|
||||
private Theme() {}
|
||||
|
||||
static { apply(new Settings()); }
|
||||
|
||||
public static void apply(Settings s) {
|
||||
mode = normalizeMode(s.theme);
|
||||
dark = "dark".equals(mode) || ("auto".equals(mode) && systemDark());
|
||||
if (dark) {
|
||||
BG = new Color(0x0E1420); SIDEBAR = new Color(0x111827); CARD = new Color(0x172033);
|
||||
CARD_ALT = new Color(0x1E293D); CARD_HOVER = new Color(0x243149); LINE = new Color(0x2A3852);
|
||||
LINE_STRONG = new Color(0x3A4C6C); INK = new Color(0xF0F5FF); DIM = new Color(0xA8B8D2);
|
||||
FAINT = new Color(0x71839F); ACCENT = new Color(0x77A7FF); ACCENT_DARK = new Color(0x4F86F0);
|
||||
ACCENT_SOFT = new Color(0x1C2A46); SUCCESS = new Color(0x58D6A6); DANGER = new Color(0xF27A7A);
|
||||
WARN = new Color(0xF0B85C); HERO_TOP = new Color(0x101E3B); HERO_BOTTOM = new Color(0x274D86);
|
||||
NAV_HOVER = new Color(0x1C2740); NAV_ACTIVE = new Color(0x253753); TITLEBAR = new Color(0x0B101A);
|
||||
SHADOW = new Color(0, 0, 0, 90); GLASS = new Color(0x101A2B, true); GLASS_LINE = new Color(0x2D3D5B);
|
||||
SCROLL = new Color(0x2A3852); SCROLL_HOVER = new Color(0x3B4D6D);
|
||||
} else {
|
||||
BG = new Color(0xEDF1F8); SIDEBAR = new Color(0xFBFCFE); CARD = new Color(0xFFFFFF);
|
||||
CARD_ALT = new Color(0xF5F8FE); CARD_HOVER = new Color(0xF0F5FF); LINE = new Color(0xE1E8F4);
|
||||
LINE_STRONG = new Color(0xCBD7E9); INK = new Color(0x111B2E); DIM = new Color(0x586882);
|
||||
FAINT = new Color(0x8B99B1); ACCENT = new Color(0x2F6BFF); ACCENT_DARK = new Color(0x1F4FD0);
|
||||
ACCENT_SOFT = new Color(0xEAF1FF); SUCCESS = new Color(0x189E6C); DANGER = new Color(0xD64545);
|
||||
WARN = new Color(0xCB7A0E); HERO_TOP = new Color(0x12213F); HERO_BOTTOM = new Color(0x28508D);
|
||||
NAV_HOVER = new Color(0xF0F4FC); NAV_ACTIVE = new Color(0xE7F0FF); TITLEBAR = new Color(0xFAFBFE);
|
||||
SHADOW = new Color(27, 46, 80, 32); GLASS = new Color(0xFFFFFF, true); GLASS_LINE = new Color(0xD8E2F2);
|
||||
SCROLL = new Color(0xCBD6E6); SCROLL_HOVER = new Color(0xAEBED4);
|
||||
}
|
||||
try {
|
||||
String accent = s.accentColor;
|
||||
if (accent != null && accent.matches("#[0-9a-fA-F]{6}")) {
|
||||
ACCENT = Color.decode(accent);
|
||||
ACCENT_DARK = ACCENT.darker();
|
||||
if (!dark) ACCENT_SOFT = blend(ACCENT, Color.WHITE, 0.88);
|
||||
else ACCENT_SOFT = blend(ACCENT, new Color(0x111827), 0.76);
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
}
|
||||
|
||||
public static String normalizeMode(String value) {
|
||||
if (value == null) return "auto";
|
||||
String v = value.trim().toLowerCase(Locale.ROOT);
|
||||
if (v.equals("dark")) return "dark";
|
||||
if (v.equals("light")) return "light";
|
||||
return "auto";
|
||||
}
|
||||
|
||||
/** 重新检测系统外观;返回是否发生变化。 */
|
||||
public static boolean refreshSystem(boolean force) {
|
||||
if (!"auto".equals(mode)) return false;
|
||||
boolean before = systemDark;
|
||||
if (force) systemCheckedAt = 0;
|
||||
systemDark();
|
||||
return before != systemDark;
|
||||
}
|
||||
|
||||
public static boolean systemDark() {
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - systemCheckedAt > SYSTEM_TTL_MS) {
|
||||
systemCheckedAt = now;
|
||||
try {
|
||||
systemDark = detectSystemDark();
|
||||
} catch (Throwable ignored) {
|
||||
systemDark = inferFromUiManager();
|
||||
}
|
||||
}
|
||||
return systemDark;
|
||||
}
|
||||
|
||||
private static boolean detectSystemDark() {
|
||||
String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
|
||||
if (os.contains("mac")) {
|
||||
String out = run(600, "defaults", "read", "-g", "AppleInterfaceStyle");
|
||||
if (out != null && out.toLowerCase(Locale.ROOT).contains("dark")) return true;
|
||||
// 命令失败时不要立刻认为浅色,交给 UIManager 推断
|
||||
if (out == null) return inferFromUiManager();
|
||||
return false;
|
||||
}
|
||||
if (os.contains("win")) {
|
||||
String out = run(900, "reg", "query",
|
||||
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
|
||||
"/v", "AppsUseLightTheme");
|
||||
if (out != null) return out.replace(" ", "").contains("REG_DWORD,0x0");
|
||||
return inferFromUiManager();
|
||||
}
|
||||
String scheme = run(700, "gsettings", "get", "org.gnome.desktop.interface", "color-scheme");
|
||||
if (scheme != null) return scheme.toLowerCase(Locale.ROOT).contains("dark");
|
||||
String gtk = run(700, "gsettings", "get", "org.gnome.desktop.interface", "gtk-theme");
|
||||
if (gtk != null) return gtk.toLowerCase(Locale.ROOT).contains("dark");
|
||||
return inferFromUiManager();
|
||||
}
|
||||
|
||||
private static boolean inferFromUiManager() {
|
||||
Color c = UIManager.getColor("Panel.background");
|
||||
if (c == null) c = UIManager.getColor("control");
|
||||
if (c == null) return false;
|
||||
double lum = (0.2126 * c.getRed() + 0.7152 * c.getGreen() + 0.0722 * c.getBlue()) / 255.0;
|
||||
return lum < 0.5;
|
||||
}
|
||||
|
||||
private static String run(long timeoutMs, String... cmd) {
|
||||
try {
|
||||
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
|
||||
if (!p.waitFor(timeoutMs, TimeUnit.MILLISECONDS)) {
|
||||
p.destroyForcibly();
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) sb.append(line).append('\n');
|
||||
}
|
||||
return p.exitValue() == 0 ? sb.toString() : null;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Color blend(Color a, Color b, double ratioB) {
|
||||
double t = Math.max(0, Math.min(1, ratioB));
|
||||
return new Color(
|
||||
(int) Math.round(a.getRed() * (1 - t) + b.getRed() * t),
|
||||
(int) Math.round(a.getGreen() * (1 - t) + b.getGreen() * t),
|
||||
(int) Math.round(a.getBlue() * (1 - t) + b.getBlue() * t));
|
||||
}
|
||||
|
||||
public static Color alpha(Color c, int alpha) {
|
||||
return new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
|
||||
}
|
||||
|
||||
private static String pickFont() {
|
||||
String[] candidates = {"PingFang SC", "MiSans", "HarmonyOS Sans SC", "Microsoft YaHei UI",
|
||||
"Microsoft YaHei", "Noto Sans CJK SC", "Source Han Sans SC", "Segoe UI", "Dialog"};
|
||||
String[] available = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
|
||||
for (String c : candidates) for (String a : available) if (a.equalsIgnoreCase(c)) return c;
|
||||
return "Dialog";
|
||||
}
|
||||
|
||||
public static Font font(float size) { return new Font(FONT, Font.PLAIN, Math.round(size)); }
|
||||
public static Font bold(float size) { return new Font(FONT, Font.BOLD, Math.round(size)); }
|
||||
|
||||
public static JLabel label(String text, float size, Color color) {
|
||||
JLabel l = new JLabel(text);
|
||||
l.setFont(font(size));
|
||||
l.setForeground(color);
|
||||
l.setHorizontalAlignment(SwingConstants.LEFT);
|
||||
return l;
|
||||
}
|
||||
|
||||
public static JLabel boldLabel(String text, float size, Color color) {
|
||||
JLabel l = new JLabel(text);
|
||||
l.setFont(bold(size));
|
||||
l.setForeground(color);
|
||||
l.setHorizontalAlignment(SwingConstants.LEFT);
|
||||
return l;
|
||||
}
|
||||
|
||||
public static JPanel row(int gap, Component... comps) {
|
||||
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, gap, 0));
|
||||
p.setOpaque(false);
|
||||
for (Component c : comps) p.add(c);
|
||||
return p;
|
||||
}
|
||||
|
||||
public static JPanel column(int gap) {
|
||||
JPanel p = new JPanel();
|
||||
p.setOpaque(false);
|
||||
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
|
||||
p.setBorder(new EmptyBorder(gap, 0, 0, 0));
|
||||
return p;
|
||||
}
|
||||
|
||||
public static void fill(Graphics2D g, int x, int y, int w, int h, int r, Color c) {
|
||||
g.setColor(c);
|
||||
g.fillRoundRect(x, y, w, h, r, r);
|
||||
}
|
||||
|
||||
public static void drawString(Graphics2D g, String s, int x, int y) {
|
||||
g.drawString(s, x, y);
|
||||
}
|
||||
|
||||
public static String ellipsis(String s, FontMetrics fm, int width) {
|
||||
if (s == null) return "";
|
||||
if (fm.stringWidth(s) <= width) return s;
|
||||
String e = "…";
|
||||
while (s.length() > 1 && fm.stringWidth(s + e) > width) s = s.substring(0, s.length() - 1);
|
||||
return s + e;
|
||||
}
|
||||
|
||||
public static void styleField(JTextField f) {
|
||||
f.setFont(font(13));
|
||||
f.setForeground(INK);
|
||||
f.setBackground(CARD);
|
||||
f.setCaretColor(INK);
|
||||
f.setBorder(BorderFactory.createCompoundBorder(
|
||||
BorderFactory.createLineBorder(LINE, 1, true),
|
||||
new EmptyBorder(8, 11, 8, 11)));
|
||||
f.setOpaque(true);
|
||||
}
|
||||
|
||||
public static void styleArea(JTextArea a) {
|
||||
a.setFont(font(12.5f));
|
||||
a.setForeground(DIM);
|
||||
a.setBackground(CARD_ALT);
|
||||
a.setCaretColor(INK);
|
||||
a.setBorder(new EmptyBorder(8, 10, 8, 10));
|
||||
a.setLineWrap(true);
|
||||
a.setWrapStyleWord(true);
|
||||
}
|
||||
|
||||
/** 兼容旧调用:返回自绘下拉框。 */
|
||||
public static UI.Select combo(String[] items) {
|
||||
return new UI.Select(items);
|
||||
}
|
||||
|
||||
/** 兼容旧调用。 */
|
||||
public static void styleCombo(UI.Select c) {
|
||||
c.setFont(font(13));
|
||||
}
|
||||
|
||||
public static Color mutedOn(Color background) {
|
||||
double lum = (0.2126 * background.getRed() + 0.7152 * background.getGreen() + 0.0722 * background.getBlue()) / 255.0;
|
||||
return lum < 0.5 ? new Color(0xC3D1E7) : new Color(0x51617C);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.AppPaths;
|
||||
import com.gc.core.Hash;
|
||||
import com.gc.core.SystemInfo;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.datatransfer.StringSelection;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 百宝箱:IP / RAM / CPU / GPU 检测、内存优化、磁盘与系统信息。
|
||||
* 耗时的检测全部在后台线程执行,界面保持可交互。
|
||||
*/
|
||||
public final class ToolboxPage extends JPanel {
|
||||
private final MainWindow app;
|
||||
private final JPanel body = new JPanel();
|
||||
private final JLabel cpuName = Theme.boldLabel("检测中…", 14, Theme.INK);
|
||||
private final JLabel cpuMeta = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel cpuLoadText = Theme.boldLabel("—", 22, Theme.ACCENT);
|
||||
private final JLabel procLoadText = Theme.label("", 11, Theme.DIM);
|
||||
private final UI.Progress cpuBar = new UI.Progress();
|
||||
private final JLabel ramTotal = Theme.boldLabel("—", 18, Theme.INK);
|
||||
private final JLabel ramUsed = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel ramFree = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel heapText = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final UI.Progress ramBar = new UI.Progress();
|
||||
private final JLabel gpuName = Theme.boldLabel("检测中…", 14, Theme.INK);
|
||||
private final JLabel gpuMeta = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel opengl = Theme.label("", 11, Theme.FAINT);
|
||||
private final JLabel ipLocal = Theme.label("—", 11.5f, Theme.DIM);
|
||||
private final JLabel ipPublic = Theme.boldLabel("—", 18, Theme.INK);
|
||||
private final JLabel ipWhere = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel ipIsp = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel ipLatency = Theme.label("", 11.5f, Theme.FAINT);
|
||||
private final JLabel diskTotal = Theme.boldLabel("—", 18, Theme.INK);
|
||||
private final JLabel diskFree = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final UI.Progress diskBar = new UI.Progress();
|
||||
private final JLabel osLabel = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel javaLabel = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel screenLabel = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel uptimeLabel = Theme.label("", 11.5f, Theme.DIM);
|
||||
private final JLabel status = Theme.label("", 10.5f, Theme.FAINT);
|
||||
private SystemInfo.Snapshot snapshot;
|
||||
|
||||
public ToolboxPage(MainWindow app) {
|
||||
this.app = app;
|
||||
setLayout(new BorderLayout());
|
||||
setOpaque(false);
|
||||
JPanel page = UI.page();
|
||||
UI.RoundButton refresh = UI.primary("重新检测");
|
||||
refresh.addActionListener(e -> refreshAll());
|
||||
page.add(UI.pageHeader("百宝箱", "IP / CPU / RAM / GPU 检测、内存优化与系统实用工具", refresh), BorderLayout.NORTH);
|
||||
body.setOpaque(false);
|
||||
body.setLayout(new UI.VStackLayout());
|
||||
body.setBorder(new EmptyBorder(0, 0, 28, 0));
|
||||
body.add(row(cpuCard(), ramCard()));
|
||||
body.add(Box.createVerticalStrut(14));
|
||||
body.add(row(gpuCard(), networkCard()));
|
||||
body.add(Box.createVerticalStrut(14));
|
||||
body.add(row(diskCard(), systemCard()));
|
||||
body.add(Box.createVerticalStrut(12));
|
||||
status.setBorder(new EmptyBorder(0, 4, 0, 4));
|
||||
body.add(status);
|
||||
page.add(UI.scroll(body), BorderLayout.CENTER);
|
||||
add(page, BorderLayout.CENTER);
|
||||
refreshAll();
|
||||
}
|
||||
|
||||
private JComponent row(JComponent a, JComponent b) {
|
||||
JPanel p = new JPanel(new GridLayout(1, 2, 14, 0));
|
||||
p.setOpaque(false);
|
||||
p.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
p.setMaximumSize(new Dimension(Integer.MAX_VALUE, 250));
|
||||
p.setPreferredSize(new Dimension(900, 240));
|
||||
p.add(a);
|
||||
p.add(b);
|
||||
return p;
|
||||
}
|
||||
|
||||
private UI.Card card(String title, String icon) {
|
||||
UI.Card c = new UI.Card();
|
||||
c.setLayout(new UI.VStackLayout());
|
||||
c.setBorder(new EmptyBorder(17, 19, 17, 19));
|
||||
c.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.setMaximumSize(new Dimension(Integer.MAX_VALUE, 250));
|
||||
JPanel head = new JPanel(new BorderLayout());
|
||||
head.setOpaque(false);
|
||||
head.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
head.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26));
|
||||
head.add(Theme.boldLabel(title, 14, Theme.INK), BorderLayout.WEST);
|
||||
JLabel ic = Theme.label(icon, 16, Theme.ACCENT);
|
||||
head.add(ic, BorderLayout.EAST);
|
||||
c.add(head);
|
||||
c.add(Box.createVerticalStrut(12));
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent cpuCard() {
|
||||
UI.Card c = card("CPU 检测", "▥");
|
||||
cpuName.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(cpuName);
|
||||
cpuMeta.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(Box.createVerticalStrut(3));
|
||||
c.add(cpuMeta);
|
||||
c.add(Box.createVerticalStrut(12));
|
||||
JPanel row = new JPanel(new BorderLayout(12, 0));
|
||||
row.setOpaque(false);
|
||||
row.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 44));
|
||||
row.add(cpuLoadText, BorderLayout.WEST);
|
||||
procLoadText.setHorizontalAlignment(SwingConstants.RIGHT);
|
||||
row.add(procLoadText, BorderLayout.EAST);
|
||||
c.add(row);
|
||||
cpuBar.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
cpuBar.setMaximumSize(new Dimension(Integer.MAX_VALUE, 8));
|
||||
c.add(cpuBar);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
JLabel hint = Theme.label("系统负载来自 OperatingSystemMXBean;进程负载只统计本启动器 JVM。", 10, Theme.FAINT);
|
||||
hint.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(hint);
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent ramCard() {
|
||||
UI.Card c = card("RAM / 内存检测", "▤");
|
||||
JPanel row = new JPanel(new BorderLayout());
|
||||
row.setOpaque(false);
|
||||
row.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26));
|
||||
row.add(ramTotal, BorderLayout.WEST);
|
||||
JLabel tag = UI.pill("JVM " + app.settings.effectiveMemoryMb() + " MB", Theme.ACCENT, Theme.ACCENT_SOFT);
|
||||
row.add(tag, BorderLayout.EAST);
|
||||
c.add(row);
|
||||
c.add(Box.createVerticalStrut(7));
|
||||
ramBar.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
ramBar.setMaximumSize(new Dimension(Integer.MAX_VALUE, 8));
|
||||
c.add(ramBar);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
c.add(ramUsed);
|
||||
c.add(Box.createVerticalStrut(3));
|
||||
c.add(ramFree);
|
||||
c.add(Box.createVerticalStrut(3));
|
||||
c.add(heapText);
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
actions.setOpaque(false);
|
||||
actions.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
UI.RoundButton optimize = UI.primary("一键内存优化");
|
||||
optimize.addActionListener(e -> optimizeMemory());
|
||||
UI.RoundButton gc = UI.button("GC + 清理工作集");
|
||||
gc.addActionListener(e -> optimizeMemory());
|
||||
actions.add(optimize);
|
||||
actions.add(gc);
|
||||
c.add(actions);
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent gpuCard() {
|
||||
UI.Card c = card("GPU / 图形检测", "◈");
|
||||
gpuName.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(gpuName);
|
||||
c.add(Box.createVerticalStrut(3));
|
||||
gpuMeta.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(gpuMeta);
|
||||
c.add(Box.createVerticalStrut(9));
|
||||
opengl.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(opengl);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
JLabel hint = Theme.label("地球模型使用 JOGL OpenGL 着色器渲染;不可用时自动回退 Java2D。", 10, Theme.FAINT);
|
||||
hint.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(hint);
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent networkCard() {
|
||||
UI.Card c = card("IP / 网络检测", "⌁");
|
||||
c.add(ipLocal);
|
||||
c.add(Box.createVerticalStrut(7));
|
||||
c.add(ipPublic);
|
||||
c.add(Box.createVerticalStrut(3));
|
||||
c.add(ipWhere);
|
||||
c.add(Box.createVerticalStrut(3));
|
||||
c.add(ipIsp);
|
||||
c.add(Box.createVerticalStrut(3));
|
||||
c.add(ipLatency);
|
||||
c.add(Box.createVerticalStrut(9));
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
actions.setOpaque(false);
|
||||
UI.RoundButton refresh = UI.button("刷新 IP").compact();
|
||||
refresh.addActionListener(e -> refreshNetwork());
|
||||
actions.add(refresh);
|
||||
c.add(actions);
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent diskCard() {
|
||||
UI.Card c = card("磁盘 / 存储", "▣");
|
||||
c.add(diskTotal);
|
||||
c.add(Box.createVerticalStrut(6));
|
||||
diskBar.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
diskBar.setMaximumSize(new Dimension(Integer.MAX_VALUE, 8));
|
||||
c.add(diskBar);
|
||||
c.add(Box.createVerticalStrut(7));
|
||||
c.add(diskFree);
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
actions.setOpaque(false);
|
||||
UI.RoundButton open = UI.button("打开数据目录").compact();
|
||||
open.addActionListener(e -> MainWindow.openFolder(this, app.paths.homeRoot));
|
||||
UI.RoundButton cache = UI.button("清理缓存").danger().compact();
|
||||
cache.addActionListener(e -> {
|
||||
long before = dirSize(app.paths.cacheRoot());
|
||||
AppPaths.deleteTree(app.paths.cacheRoot());
|
||||
app.paths.ensureCreated();
|
||||
setStatus("缓存已清理,释放 " + Hash.humanSize(before));
|
||||
refreshDisk();
|
||||
});
|
||||
actions.add(open);
|
||||
actions.add(cache);
|
||||
c.add(actions);
|
||||
return c;
|
||||
}
|
||||
|
||||
private JComponent systemCard() {
|
||||
UI.Card c = card("系统信息", "⌘");
|
||||
c.add(osLabel);
|
||||
c.add(Box.createVerticalStrut(4));
|
||||
c.add(javaLabel);
|
||||
c.add(Box.createVerticalStrut(4));
|
||||
c.add(screenLabel);
|
||||
c.add(Box.createVerticalStrut(4));
|
||||
c.add(uptimeLabel);
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
actions.setOpaque(false);
|
||||
UI.RoundButton copy = UI.button("复制检测报告").compact();
|
||||
copy.addActionListener(e -> copyReport());
|
||||
UI.RoundButton logs = UI.button("打开日志").compact();
|
||||
logs.addActionListener(e -> MainWindow.openFolder(this, app.paths.logsRoot()));
|
||||
actions.add(copy);
|
||||
actions.add(logs);
|
||||
c.add(actions);
|
||||
return c;
|
||||
}
|
||||
|
||||
private void refreshAll() {
|
||||
setStatus("正在检测系统信息…");
|
||||
new Thread(() -> {
|
||||
SystemInfo.Snapshot s = SystemInfo.snapshot();
|
||||
SwingUtilities.invokeLater(() -> applySnapshot(s));
|
||||
}, "gc-toolbox-snapshot").start();
|
||||
refreshNetwork();
|
||||
}
|
||||
|
||||
private void applySnapshot(SystemInfo.Snapshot s) {
|
||||
snapshot = s;
|
||||
cpuName.setText(s.cpu().model());
|
||||
cpuMeta.setText(s.cpu().cores() + " 逻辑核心 · " + s.arch());
|
||||
double load = s.cpu().systemLoad();
|
||||
cpuLoadText.setText(load < 0 ? "—" : String.format(Locale.ROOT, "%.0f%%", load * 100));
|
||||
cpuBar.setValue(load < 0 ? 0 : load);
|
||||
procLoadText.setText(s.cpu().processLoad() < 0 ? "" : String.format(Locale.ROOT, "进程 %.1f%%", s.cpu().processLoad() * 100));
|
||||
ramTotal.setText(Hash.humanSize(s.memory().total()) + " 总内存");
|
||||
ramUsed.setText("已用 " + Hash.humanSize(s.memory().used()) + " · 可用 " + Hash.humanSize(s.memory().free()));
|
||||
ramFree.setText(String.format(Locale.ROOT, "使用率 %.0f%%", s.memory().used() * 100.0 / Math.max(1, s.memory().total())));
|
||||
heapText.setText("JVM 堆 " + Hash.humanSize(s.memory().heapUsed()) + " / " + Hash.humanSize(s.memory().heapMax()));
|
||||
ramBar.setValue(s.memory().used() / (double) Math.max(1, s.memory().total()));
|
||||
gpuName.setText(s.gpu().model());
|
||||
gpuMeta.setText("驱动 / 核心:" + s.gpu().driver() + " · " + s.gpu().vram());
|
||||
opengl.setText("OpenGL:" + s.gpu().opengl());
|
||||
osLabel.setText("系统:" + s.os());
|
||||
javaLabel.setText("Java:" + s.java());
|
||||
screenLabel.setText("显示:" + s.screen());
|
||||
long uptime = s.uptimeMs() / 1000;
|
||||
uptimeLabel.setText("运行:" + (uptime / 3600) + " 小时 " + (uptime % 3600 / 60) + " 分");
|
||||
refreshDisk();
|
||||
setStatus("检测完成 · " + java.time.LocalTime.now().withNano(0));
|
||||
}
|
||||
|
||||
private void refreshNetwork() {
|
||||
ipLocal.setText("局域网:检测中…");
|
||||
new Thread(() -> {
|
||||
SystemInfo.Network n = SystemInfo.network();
|
||||
SwingUtilities.invokeLater(() -> {
|
||||
ipLocal.setText("局域网:" + String.join(" · ", n.localIps()));
|
||||
ipPublic.setText(n.publicIp());
|
||||
ipWhere.setText("位置:" + n.location());
|
||||
ipIsp.setText("运营商:" + n.isp());
|
||||
ipLatency.setText(n.latencyMs() >= 0 ? "公网请求延迟:" + n.latencyMs() + " ms" : "公网请求失败");
|
||||
});
|
||||
}, "gc-toolbox-net").start();
|
||||
}
|
||||
|
||||
private void refreshDisk() {
|
||||
SystemInfo.Disk d = SystemInfo.disk();
|
||||
diskTotal.setText(Hash.humanSize(d.total()) + " 磁盘总量");
|
||||
diskFree.setText("可用 " + Hash.humanSize(d.free()) + " · 已用 " + Hash.humanSize(d.total() - d.free()));
|
||||
diskBar.setValue((d.total() - d.free()) / (double) Math.max(1, d.total()));
|
||||
}
|
||||
|
||||
private void optimizeMemory() {
|
||||
long freed = SystemInfo.optimizeMemory();
|
||||
setStatus("内存优化完成,回收约 " + Hash.humanSize(freed));
|
||||
new Thread(() -> {
|
||||
SystemInfo.Snapshot s = SystemInfo.snapshot();
|
||||
SwingUtilities.invokeLater(() -> applySnapshot(s));
|
||||
}, "gc-toolbox-mem").start();
|
||||
UI.toast(this, "已触发 GC、重置内存池峰值并释放空闲页");
|
||||
}
|
||||
|
||||
private void copyReport() {
|
||||
SystemInfo.Snapshot s = snapshot;
|
||||
if (s == null) { setStatus("尚未完成检测"); return; }
|
||||
String text = "GC 百宝箱检测报告\n"
|
||||
+ "系统: " + s.os() + "\n架构: " + s.arch() + "\nJava: " + s.java() + "\n"
|
||||
+ "CPU: " + s.cpu().model() + " / " + s.cpu().cores() + " 核 / 负载 " + Math.round(s.cpu().systemLoad() * 100) + "%\n"
|
||||
+ "内存: " + Hash.humanSize(s.memory().used()) + " / " + Hash.humanSize(s.memory().total()) + "\n"
|
||||
+ "GPU: " + s.gpu().model() + " / " + s.gpu().opengl() + "\n"
|
||||
+ "显示: " + s.screen() + "\n"
|
||||
+ "磁盘: 可用 " + Hash.humanSize(s.disk().free()) + " / " + Hash.humanSize(s.disk().total()) + "\n";
|
||||
try {
|
||||
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), null);
|
||||
UI.toast(this, "检测报告已复制到剪贴板");
|
||||
} catch (Exception e) { setStatus("复制失败:" + e.getMessage()); }
|
||||
}
|
||||
|
||||
private long dirSize(Path dir) {
|
||||
try (var walk = java.nio.file.Files.walk(dir)) {
|
||||
return walk.filter(java.nio.file.Files::isRegularFile).mapToLong(p -> {
|
||||
try { return java.nio.file.Files.size(p); } catch (Exception e) { return 0; }
|
||||
}).sum();
|
||||
} catch (Exception e) { return 0; }
|
||||
}
|
||||
|
||||
private void setStatus(String s) { status.setText(s); }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,84 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.AppPaths;
|
||||
import com.gc.core.ModelManifest;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** 无头 UI 冒烟:实例化 5 个模型面板并离屏渲染 PNG,用于构建自检。 */
|
||||
public final class UiSmoke {
|
||||
private UiSmoke() {}
|
||||
|
||||
public static int run(AppPaths paths, Path outDir) {
|
||||
try {
|
||||
Theme.apply(com.gc.core.Settings.defaults());
|
||||
Files.createDirectories(outDir);
|
||||
ModelManifest.Discovery d = ModelManifest.scan(paths.modelRoot);
|
||||
int n = 0;
|
||||
for (ModelManifest.Package pkg : d.models) {
|
||||
JComponent view;
|
||||
switch (pkg.id()) {
|
||||
case "scale-calculator" -> view = new ScalePanel(pkg);
|
||||
case "contour-map" -> view = new ContourPanel(pkg);
|
||||
case "earth-rotation" -> view = new EarthPanel(pkg, false);
|
||||
case "earth-revolution" -> view = new EarthPanel(pkg, true);
|
||||
case "earth-geography" -> view = new GeographyPanel(pkg);
|
||||
default -> { continue; }
|
||||
}
|
||||
if (pkg.id().equals("contour-map")) {
|
||||
try { Thread.sleep(1600); } catch (InterruptedException ignored) { }
|
||||
view.revalidate();
|
||||
}
|
||||
view.setSize(1240, 760);
|
||||
view.doLayout();
|
||||
layoutDeep(view);
|
||||
BufferedImage img = new BufferedImage(1240, 760, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
view.paint(g);
|
||||
g.dispose();
|
||||
Path out = outDir.resolve("model-" + pkg.id() + ".png");
|
||||
ImageIO.write(img, "png", out.toFile());
|
||||
System.out.println("PASS gui-smoke " + pkg.id() + " -> " + out);
|
||||
n++;
|
||||
}
|
||||
// 主窗口 5 个页面离屏渲染
|
||||
MainWindow mw = MainWindow.smoke(paths, com.gc.core.Settings.load(paths.settingsFile()));
|
||||
JComponent root = mw.rootPanel();
|
||||
root.setSize(1240, 820);
|
||||
for (String page : new String[]{"home", "models", "download", "settings", "about"}) {
|
||||
mw.navigate(page);
|
||||
layoutDeep(root);
|
||||
layoutDeep(root);
|
||||
BufferedImage img = new BufferedImage(1240, 820, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
root.paint(g);
|
||||
g.dispose();
|
||||
Path out = outDir.resolve("page-" + page + ".png");
|
||||
ImageIO.write(img, "png", out.toFile());
|
||||
System.out.println("PASS gui-page " + page + " -> " + out);
|
||||
}
|
||||
System.out.println("GUI SMOKE " + (n == 5 ? "PASS" : "FAIL") + " " + n + " model panels rendered");
|
||||
System.exit(n == 5 ? 0 : 1);
|
||||
return n == 5 ? 0 : 1;
|
||||
} catch (Throwable t) {
|
||||
t.printStackTrace();
|
||||
System.out.println("GUI SMOKE FAIL " + t);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private static void layoutDeep(Container c) {
|
||||
c.doLayout();
|
||||
for (Component child : c.getComponents()) {
|
||||
if (child instanceof Container cc) layoutDeep(cc);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
package com.gc.ui;
|
||||
|
||||
import com.gc.core.I18n;
|
||||
import com.gc.core.Settings;
|
||||
import com.gc.core.UserService;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import java.awt.*;
|
||||
import java.awt.event.MouseAdapter;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 用户页:完整实现原版本地账户功能。
|
||||
* 注册(本地算术人机验证)/ 登录 / 退出 / 30 天周期签到 / 积分 /
|
||||
* 人品值(当日首次免费,之后阶梯计费)/ 二选一(自定义选项)/ 主题色购买与退款。
|
||||
*/
|
||||
public final class UserPage extends JPanel {
|
||||
private final MainWindow app;
|
||||
private final UserService users;
|
||||
private final JPanel body = new JPanel();
|
||||
private String feedbackText = "";
|
||||
private boolean feedbackOk = true;
|
||||
private boolean registerMode;
|
||||
private String captchaQuestion;
|
||||
private int captchaAnswer;
|
||||
|
||||
private UI.TextField username;
|
||||
private UI.PasswordField password;
|
||||
private UI.PasswordField password2;
|
||||
private UI.TextField captcha;
|
||||
private UI.TextField optionA;
|
||||
private UI.TextField optionB;
|
||||
private JLabel fortuneValue;
|
||||
private JLabel fortuneComment;
|
||||
private JLabel pickResult;
|
||||
|
||||
public UserPage(MainWindow app) {
|
||||
this.app = app;
|
||||
this.users = app.users();
|
||||
setLayout(new BorderLayout());
|
||||
setOpaque(false);
|
||||
JPanel page = UI.page();
|
||||
page.add(UI.pageHeader(t("user.title", "用户中心"), t("user.subtitle", "本地账号 · 签到积分 · 每日人品值 · 主题色"), null), BorderLayout.NORTH);
|
||||
body.setOpaque(false);
|
||||
body.setLayout(new UI.VStackLayout());
|
||||
body.setBorder(new EmptyBorder(0, 0, 28, 0));
|
||||
page.add(UI.scroll(body), BorderLayout.CENTER);
|
||||
add(page, BorderLayout.CENTER);
|
||||
refresh();
|
||||
}
|
||||
|
||||
public void onShow() { refresh(); }
|
||||
|
||||
private void refresh() {
|
||||
body.removeAll();
|
||||
UserService.Profile p = users.profile();
|
||||
body.add(headerCard(p));
|
||||
body.add(Box.createVerticalStrut(14));
|
||||
if (p == null) body.add(authCard());
|
||||
else body.add(signInCard(p));
|
||||
body.add(Box.createVerticalStrut(14));
|
||||
body.add(fortuneCard(p));
|
||||
body.add(Box.createVerticalStrut(14));
|
||||
body.add(pickCard(p));
|
||||
body.add(Box.createVerticalStrut(14));
|
||||
body.add(themeCard(p));
|
||||
if (!feedbackText.isBlank()) {
|
||||
body.add(Box.createVerticalStrut(12));
|
||||
JLabel f = Theme.label(feedbackText, 12, feedbackOk ? Theme.SUCCESS : Theme.DANGER);
|
||||
f.setBorder(new EmptyBorder(2, 4, 0, 4));
|
||||
body.add(f);
|
||||
}
|
||||
body.revalidate();
|
||||
body.repaint();
|
||||
app.refreshAccountChip();
|
||||
}
|
||||
|
||||
private UI.Card shell() {
|
||||
UI.Card c = new UI.Card();
|
||||
c.setLayout(new UI.VStackLayout());
|
||||
c.setBorder(new EmptyBorder(18, 20, 18, 20));
|
||||
c.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.setMaximumSize(new Dimension(Integer.MAX_VALUE, 10000));
|
||||
return c;
|
||||
}
|
||||
|
||||
private void heading(UI.Card card, String title, String desc) {
|
||||
JLabel h = Theme.boldLabel(title, 15, Theme.INK);
|
||||
h.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
card.add(h);
|
||||
if (desc != null && !desc.isBlank()) {
|
||||
card.add(Box.createVerticalStrut(4));
|
||||
JLabel d = Theme.label(desc, 11.5f, Theme.DIM);
|
||||
d.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
card.add(d);
|
||||
}
|
||||
card.add(Box.createVerticalStrut(14));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 顶部账户卡
|
||||
|
||||
private JComponent headerCard(UserService.Profile p) {
|
||||
UI.Card c = shell();
|
||||
c.setMaximumSize(new Dimension(Integer.MAX_VALUE, 150));
|
||||
JPanel row = new JPanel(new BorderLayout(16, 0));
|
||||
row.setOpaque(false);
|
||||
row.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 88));
|
||||
JLabel avatar = new JLabel() {
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
GradientPaint gp = new GradientPaint(0, 0, Theme.ACCENT, getWidth(), getHeight(), new Color(0x9B6CFF));
|
||||
g2.setPaint(gp);
|
||||
g2.fillOval(0, 0, getWidth(), getHeight());
|
||||
g2.setColor(Color.WHITE);
|
||||
g2.setFont(Theme.bold(25));
|
||||
String s = p == null ? "?" : p.username().substring(0, 1).toUpperCase(Locale.ROOT);
|
||||
FontMetrics fm = g2.getFontMetrics();
|
||||
g2.drawString(s, (getWidth() - fm.stringWidth(s)) / 2, (getHeight() + fm.getAscent() - fm.getDescent()) / 2);
|
||||
g2.dispose();
|
||||
}
|
||||
};
|
||||
avatar.setPreferredSize(new Dimension(68, 68));
|
||||
row.add(avatar, BorderLayout.WEST);
|
||||
JPanel info = new JPanel();
|
||||
info.setOpaque(false);
|
||||
info.setLayout(new UI.VStackLayout());
|
||||
info.add(Theme.boldLabel(p == null ? t("user.notLoggedIn", "未登录") : p.username(), 19, Theme.INK));
|
||||
info.add(Box.createVerticalStrut(4));
|
||||
info.add(Theme.label(p == null ? t("user.loginHint", "登录后可签到攒积分、解锁主题色")
|
||||
: String.format(Locale.ROOT, "%s %s · %s %d", t("user.points", "积分"), UserService.formatPoints(p.points()),
|
||||
t("user.days", "连续签到"), p.consecutiveDays()), 12, Theme.DIM));
|
||||
info.add(Box.createVerticalStrut(5));
|
||||
if (p == null) info.add(Theme.label("数据只保存在本机 .GC/user/,不上传任何服务器", 10.5f, Theme.FAINT));
|
||||
else if (p.signedToday()) info.add(Theme.label(t("user.signedToday", "今天已签到,明天再来"), 10.5f, Theme.SUCCESS));
|
||||
else info.add(Theme.label(t("user.nextReward", "现在签到可得 {0} 积分").replace("{0}", String.valueOf(p.nextReward())), 10.5f, Theme.WARN));
|
||||
row.add(info, BorderLayout.CENTER);
|
||||
if (p != null) {
|
||||
UI.RoundButton logout = UI.button(t("user.logout", "退出登录")).danger();
|
||||
logout.addActionListener(e -> {
|
||||
users.logout();
|
||||
feedbackText = t("user.logoutDone", "已退出登录");
|
||||
feedbackOk = true;
|
||||
Theme.apply(app.settings);
|
||||
refresh();
|
||||
});
|
||||
JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 12));
|
||||
right.setOpaque(false);
|
||||
right.add(logout);
|
||||
row.add(right, BorderLayout.EAST);
|
||||
}
|
||||
c.add(row);
|
||||
c.add(Box.createVerticalStrut(12));
|
||||
JLabel foot = Theme.label("GC LOCAL ACCOUNT · SHA-512 加盐密码 · 无充值渠道", 9.5f, Theme.FAINT);
|
||||
foot.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(foot);
|
||||
return c;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 登录 / 注册
|
||||
|
||||
private JComponent authCard() {
|
||||
UI.Card c = shell();
|
||||
JPanel tabRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
|
||||
tabRow.setOpaque(false);
|
||||
tabRow.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
UI.RoundButton loginTab = UI.button(t("user.login", "登录"));
|
||||
UI.RoundButton regTab = UI.button(t("user.register", "注册"));
|
||||
if (!registerMode) loginTab.primary(); else regTab.primary();
|
||||
loginTab.addActionListener(e -> { registerMode = false; feedbackText = ""; refresh(); });
|
||||
regTab.addActionListener(e -> { registerMode = true; feedbackText = ""; newCaptcha(); refresh(); });
|
||||
tabRow.add(loginTab);
|
||||
tabRow.add(regTab);
|
||||
c.add(tabRow);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
|
||||
username = new UI.TextField();
|
||||
password = new UI.PasswordField();
|
||||
c.add(UI.labeled(t("user.username", "用户名"), username));
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
c.add(UI.labeled(t("user.password", "密码"), password));
|
||||
if (registerMode) {
|
||||
password2 = new UI.PasswordField();
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
c.add(UI.labeled(t("user.password2", "确认密码"), password2));
|
||||
if (captchaQuestion == null) newCaptcha();
|
||||
captcha = new UI.TextField();
|
||||
JPanel capRow = new JPanel(new BorderLayout(8, 0));
|
||||
capRow.setOpaque(false);
|
||||
JLabel q = Theme.boldLabel(t("user.captcha", "人机验证") + " " + captchaQuestion, 12.5f, Theme.INK);
|
||||
capRow.add(q, BorderLayout.CENTER);
|
||||
UI.RoundButton refresh = UI.button(t("user.refreshCaptcha", "换一题")).compact();
|
||||
refresh.addActionListener(e -> { newCaptcha(); refresh(); });
|
||||
capRow.add(refresh, BorderLayout.EAST);
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
c.add(capRow);
|
||||
c.add(Box.createVerticalStrut(6));
|
||||
c.add(UI.labeled(t("user.captchaAnswer", "验证码答案"), captcha));
|
||||
JLabel rule = Theme.label(t("user.usernameRule", "1–20 个字符,不能有空格,不能与他人重复"), 10.5f, Theme.FAINT);
|
||||
rule.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(Box.createVerticalStrut(6));
|
||||
c.add(rule);
|
||||
}
|
||||
c.add(Box.createVerticalStrut(6));
|
||||
JLabel hint = Theme.label(t("user.noRecharge", "积分只能通过每日签到获得,不提供任何充值渠道。"), 10.5f, Theme.FAINT);
|
||||
hint.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(hint);
|
||||
c.add(Box.createVerticalStrut(12));
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
|
||||
actions.setOpaque(false);
|
||||
actions.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
UI.RoundButton submit = UI.primary(registerMode ? t("user.register", "注册") : t("user.login", "登录"));
|
||||
submit.addActionListener(e -> submitAuth());
|
||||
actions.add(submit);
|
||||
if (registerMode) {
|
||||
UI.RoundButton switchTo = UI.button(t("user.switchToLogin", "已有账号?去登录")).ghost();
|
||||
switchTo.addActionListener(e -> { registerMode = false; feedbackText = ""; refresh(); });
|
||||
actions.add(switchTo);
|
||||
} else {
|
||||
UI.RoundButton switchTo = UI.button(t("user.switchToRegister", "没有账号?去注册")).ghost();
|
||||
switchTo.addActionListener(e -> { registerMode = true; newCaptcha(); feedbackText = ""; refresh(); });
|
||||
actions.add(switchTo);
|
||||
}
|
||||
c.add(actions);
|
||||
return c;
|
||||
}
|
||||
|
||||
private void submitAuth() {
|
||||
String name = username.getText().trim();
|
||||
String pw = new String(password.getPassword());
|
||||
if (name.isEmpty() || pw.isEmpty()) {
|
||||
setFeedback(false, t("user.fillAll", "请填写用户名和密码"));
|
||||
return;
|
||||
}
|
||||
if (registerMode) {
|
||||
if (password2 != null && !pw.equals(new String(password2.getPassword()))) {
|
||||
setFeedback(false, t("user.passwordMismatch", "两次密码不一致"));
|
||||
return;
|
||||
}
|
||||
if (captcha == null || captcha.getText().isBlank()) {
|
||||
setFeedback(false, t("user.fillCaptcha", "请填写验证码答案"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (Integer.parseInt(captcha.getText().trim()) != captchaAnswer) {
|
||||
setFeedback(false, t("user.captchaWrong", "验证码答案错误"));
|
||||
newCaptcha();
|
||||
refresh();
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
setFeedback(false, t("user.captchaWrong", "验证码答案错误"));
|
||||
return;
|
||||
}
|
||||
UserService.Result r = users.register(name, pw);
|
||||
setFeedback(r.ok(), r.message());
|
||||
if (r.ok()) {
|
||||
users.applySavedTheme(app.settings);
|
||||
Theme.apply(app.settings);
|
||||
refresh();
|
||||
} else {
|
||||
newCaptcha();
|
||||
refresh();
|
||||
}
|
||||
} else {
|
||||
UserService.Result r = users.login(name, pw);
|
||||
setFeedback(r.ok(), r.message());
|
||||
if (r.ok()) {
|
||||
users.applySavedTheme(app.settings);
|
||||
Theme.apply(app.settings);
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void newCaptcha() {
|
||||
int a = 2 + (int) (Math.random() * 8);
|
||||
int b = 2 + (int) (Math.random() * 8);
|
||||
if (Math.random() < 0.5) {
|
||||
captchaQuestion = a + " + " + b + " = ?";
|
||||
captchaAnswer = a + b;
|
||||
} else {
|
||||
int hi = Math.max(a, b), lo = Math.min(a, b);
|
||||
captchaQuestion = hi + " - " + lo + " = ?";
|
||||
captchaAnswer = hi - lo;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 签到
|
||||
|
||||
private JComponent signInCard(UserService.Profile p) {
|
||||
UI.Card c = shell();
|
||||
heading(c, t("user.checkin", "每日签到"),
|
||||
String.format(Locale.ROOT, t("user.cycleDay", "第 {0} / {1} 天").replace("{0}", String.valueOf(p.cycleDay()))
|
||||
.replace("{1}", String.valueOf(p.cycleDays())), p.cycleDay(), p.cycleDays()));
|
||||
UI.Progress progress = new UI.Progress();
|
||||
progress.setValue(p.cycleDay() / (double) p.cycleDays());
|
||||
progress.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
progress.setMaximumSize(new Dimension(Integer.MAX_VALUE, 10));
|
||||
progress.setPreferredSize(new Dimension(600, 10));
|
||||
c.add(progress);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
JPanel row = new JPanel(new BorderLayout(12, 0));
|
||||
row.setOpaque(false);
|
||||
row.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JLabel info = Theme.label(p.signedToday()
|
||||
? t("user.signedToday", "今天已签到,明天再来")
|
||||
: t("user.nextReward", "现在签到可得 {0} 积分").replace("{0}", String.valueOf(p.nextReward())),
|
||||
12, p.signedToday() ? Theme.SUCCESS : Theme.DIM);
|
||||
row.add(info, BorderLayout.CENTER);
|
||||
UI.RoundButton sign = UI.primary(p.signedToday() ? t("user.signedTodayShort", "已签到") : t("user.signin", "签到"));
|
||||
sign.setEnabled(!p.signedToday());
|
||||
sign.addActionListener(e -> {
|
||||
UserService.Result r = users.signIn();
|
||||
setFeedback(r.ok(), r.message());
|
||||
refresh();
|
||||
});
|
||||
row.add(sign, BorderLayout.EAST);
|
||||
c.add(row);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
JLabel rewards = Theme.label("第 7 / 14 / 21 / 28 天有周奖励,第 30 天满月奖励 100 积分", 10.5f, Theme.FAINT);
|
||||
rewards.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(rewards);
|
||||
return c;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 人品值
|
||||
|
||||
private JComponent fortuneCard(UserService.Profile p) {
|
||||
UI.Card c = shell();
|
||||
heading(c, t("user.fortune", "人品值"),
|
||||
t("user.fortuneDesc", "每天首次免费,之后按当日次数阶梯扣积分;数值纯属娱乐。"));
|
||||
JPanel row = new JPanel(new BorderLayout(18, 0));
|
||||
row.setOpaque(false);
|
||||
row.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
JLabel circle = new JLabel("?", SwingConstants.CENTER) {
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g2.setColor(Theme.ACCENT_SOFT);
|
||||
g2.fillOval(0, 0, getWidth() - 1, getHeight() - 1);
|
||||
g2.setColor(Theme.ACCENT);
|
||||
g2.setStroke(new BasicStroke(2f));
|
||||
g2.drawOval(1, 1, getWidth() - 3, getHeight() - 3);
|
||||
g2.dispose();
|
||||
super.paintComponent(g);
|
||||
}
|
||||
};
|
||||
circle.setFont(Theme.bold(34));
|
||||
circle.setForeground(Theme.ACCENT);
|
||||
circle.setPreferredSize(new Dimension(104, 104));
|
||||
row.add(circle, BorderLayout.WEST);
|
||||
JPanel info = new JPanel();
|
||||
info.setOpaque(false);
|
||||
info.setLayout(new UI.VStackLayout());
|
||||
if (fortuneComment != null) fortuneComment.setText(t("user.fortuneIdle", "点一下,看看今天手气"));
|
||||
fortuneComment = Theme.boldLabel(t("user.fortuneIdle", "点一下,看看今天手气"), 13, Theme.INK);
|
||||
fortuneComment.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
info.add(fortuneComment);
|
||||
info.add(Box.createVerticalStrut(6));
|
||||
String costText = p == null ? t("user.loginFirst", "请先登录")
|
||||
: p.fortuneCost() > 0 ? "本次需要 " + UserService.formatPoints(p.fortuneCost()) + " 积分"
|
||||
: "今日首次免费";
|
||||
JLabel cost = Theme.label(costText, 11, Theme.FAINT);
|
||||
cost.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
info.add(cost);
|
||||
info.add(Box.createVerticalStrut(10));
|
||||
UI.RoundButton roll = UI.primary(p != null && p.fortuneToday() ? t("user.fortuneAgain", "再算一次") : t("user.fortuneRoll", "开始计算"));
|
||||
roll.setEnabled(p != null);
|
||||
roll.addActionListener(e -> {
|
||||
UserService.FortuneResult r = users.fortune();
|
||||
setFeedback(r.ok(), r.message());
|
||||
UserService.Profile np = users.profile();
|
||||
if (r.ok() && np != null) {
|
||||
circle.setText(String.valueOf(r.value()));
|
||||
if (fortuneComment != null) fortuneComment.setText(r.comment());
|
||||
info.revalidate();
|
||||
info.repaint();
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
info.add(roll);
|
||||
row.add(info, BorderLayout.CENTER);
|
||||
c.add(row);
|
||||
fortuneValue = circle;
|
||||
return c;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 二选一
|
||||
|
||||
private JComponent pickCard(UserService.Profile p) {
|
||||
UI.Card c = shell();
|
||||
heading(c, t("user.pick", "二选一"), t("user.pickDesc", "填两个选项,服务端随机帮你选一个。"));
|
||||
JPanel fields = new JPanel(new GridLayout(1, 2, 12, 0));
|
||||
fields.setOpaque(false);
|
||||
fields.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
fields.setMaximumSize(new Dimension(Integer.MAX_VALUE, 62));
|
||||
optionA = new UI.TextField();
|
||||
optionB = new UI.TextField();
|
||||
fields.add(UI.labeled(t("user.option1", "选项一"), optionA));
|
||||
fields.add(UI.labeled(t("user.option2", "选项二"), optionB));
|
||||
c.add(fields);
|
||||
c.add(Box.createVerticalStrut(10));
|
||||
JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
|
||||
actions.setOpaque(false);
|
||||
actions.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
UI.RoundButton pick = UI.primary(t("user.pickRandom", "随机选择"));
|
||||
pick.setEnabled(p != null);
|
||||
pick.addActionListener(e -> {
|
||||
UserService.PickResult r = users.pick(optionA.getText(), optionB.getText());
|
||||
setFeedback(r.ok(), r.message());
|
||||
if (r.ok() && pickResult != null) {
|
||||
pickResult.setText(t("user.pickResult", "结果:") + " " + r.choice());
|
||||
pickResult.setForeground(Theme.ACCENT);
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
actions.add(pick);
|
||||
if (p != null) {
|
||||
actions.add(Theme.label(p.pickCost() > 0 ? "本次 " + UserService.formatPoints(p.pickCost()) + " 积分" : "今日首次免费",
|
||||
11, Theme.FAINT));
|
||||
}
|
||||
c.add(actions);
|
||||
if (pickResult != null) {
|
||||
pickResult.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
c.add(pickResult);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 主题色
|
||||
|
||||
private JComponent themeCard(UserService.Profile p) {
|
||||
UI.Card c = shell();
|
||||
heading(c, t("user.themeColor", "主题颜色"),
|
||||
t("user.themeDesc", "默认蓝色免费;预置色 50 积分一个,自定义色 150 积分一个;1 小时内换色退 80%。"));
|
||||
if (p != null && p.refundSeconds() > 0) {
|
||||
JLabel refund = Theme.label(t("user.refundHint", "1 小时内换色可退 80%,当前可退(剩余 {0})")
|
||||
.replace("{0}", formatRefund(p.refundSeconds())), 11, Theme.SUCCESS);
|
||||
refund.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
c.add(refund);
|
||||
c.add(Box.createVerticalStrut(8));
|
||||
}
|
||||
JPanel swatches = new JPanel(new FlowLayout(FlowLayout.LEFT, 12, 8));
|
||||
swatches.setOpaque(false);
|
||||
swatches.setAlignmentX(Component.LEFT_ALIGNMENT);
|
||||
String current = p == null ? "" : p.themeColor().toUpperCase(Locale.ROOT);
|
||||
for (int i = 0; i < UserService.PRESET_COLORS.length; i++) {
|
||||
String hex = UserService.PRESET_COLORS[i];
|
||||
int cost = UserService.themeCost(hex);
|
||||
swatches.add(new ColorSwatch(hex, UserService.PRESET_NAMES[i], cost,
|
||||
current.equals(hex), p == null || p.points() >= cost, p != null, () -> buyTheme(hex)));
|
||||
}
|
||||
swatches.add(new ColorSwatch(null, t("user.custom", "自定义"), UserService.CUSTOM_COLOR_COST,
|
||||
p != null && current.length() == 6 && !isPreset(current), p != null && p.points() >= UserService.CUSTOM_COLOR_COST,
|
||||
p != null, this::pickCustomColor));
|
||||
c.add(swatches);
|
||||
return c;
|
||||
}
|
||||
|
||||
private boolean isPreset(String hex) {
|
||||
for (String c : UserService.PRESET_COLORS) if (c.equalsIgnoreCase(hex)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void buyTheme(String hex) {
|
||||
UserService.Result r = users.buyTheme(hex);
|
||||
setFeedback(r.ok(), r.message());
|
||||
if (r.ok()) {
|
||||
users.applySavedTheme(app.settings);
|
||||
Theme.apply(app.settings);
|
||||
if (app.frame != null) app.frame.repaint();
|
||||
}
|
||||
refresh();
|
||||
}
|
||||
|
||||
private void pickCustomColor() {
|
||||
String hex = UI.input(this, t("user.customColor", "自定义颜色"),
|
||||
t("user.customColorCost", "自定义颜色需要 {0} 积分。").replace("{0}", String.valueOf(UserService.CUSTOM_COLOR_COST))
|
||||
+ "\n#RRGGBB", "#7C6CFF");
|
||||
if (hex == null) return;
|
||||
if (UserService.normalizeHex(hex).isEmpty()) {
|
||||
setFeedback(false, t("user.hexInvalid", "格式应为 #RRGGBB"));
|
||||
return;
|
||||
}
|
||||
buyTheme(UserService.normalizeHex(hex));
|
||||
}
|
||||
|
||||
private String formatRefund(int seconds) {
|
||||
if (seconds >= 60) return (seconds / 60) + " " + t("user.minutes", "分钟");
|
||||
return seconds + " " + t("user.seconds", "秒");
|
||||
}
|
||||
|
||||
private void setFeedback(boolean ok, String text) {
|
||||
feedbackOk = ok;
|
||||
feedbackText = text == null ? "" : text;
|
||||
if (ok) UI.toast(this, feedbackText);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 自绘色块
|
||||
|
||||
private static final class ColorSwatch extends JComponent {
|
||||
private final String hex;
|
||||
private final String name;
|
||||
private final int cost;
|
||||
private final boolean selected, affordable, enabled;
|
||||
private final Runnable action;
|
||||
private boolean hover;
|
||||
|
||||
ColorSwatch(String hex, String name, int cost, boolean selected, boolean affordable, boolean enabled, Runnable action) {
|
||||
this.hex = hex; this.name = name; this.cost = cost;
|
||||
this.selected = selected; this.affordable = affordable; this.enabled = enabled; this.action = action;
|
||||
setPreferredSize(new Dimension(74, 88));
|
||||
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
|
||||
addMouseListener(new MouseAdapter() {
|
||||
@Override public void mouseEntered(MouseEvent e) { hover = true; repaint(); }
|
||||
@Override public void mouseExited(MouseEvent e) { hover = false; repaint(); }
|
||||
@Override public void mouseClicked(MouseEvent e) { if (enabled && affordable) action.run(); }
|
||||
});
|
||||
}
|
||||
|
||||
@Override protected void paintComponent(Graphics g) {
|
||||
Graphics2D g2 = (Graphics2D) g.create();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
int x = 8, y = 4, s = 54;
|
||||
if (hex == null) {
|
||||
for (int i = 0; i < 12; i++) {
|
||||
g2.setColor(Color.getHSBColor(i / 12f, 0.55f, 1f));
|
||||
g2.fillArc(x, y, s, s, i * 30, 31);
|
||||
}
|
||||
} else {
|
||||
Color c = Color.decode("#" + hex);
|
||||
g2.setColor(c);
|
||||
g2.fillRoundRect(x, y, s, s, 14, 14);
|
||||
}
|
||||
g2.setColor(selected ? Theme.ACCENT : (hover ? Theme.LINE_STRONG : Theme.LINE));
|
||||
g2.setStroke(new BasicStroke(selected ? 2.5f : 1f));
|
||||
g2.drawRoundRect(x - 1, y - 1, s + 2, s + 2, 15, 15);
|
||||
if (!affordable) {
|
||||
g2.setColor(new Color(0, 0, 0, 120));
|
||||
g2.fillRoundRect(x, y, s, s, 14, 14);
|
||||
g2.setColor(Color.WHITE);
|
||||
g2.setFont(Theme.bold(15));
|
||||
g2.drawString("🔒", x + 18, y + 34);
|
||||
}
|
||||
if (selected) {
|
||||
g2.setColor(Color.WHITE);
|
||||
g2.setFont(Theme.bold(15));
|
||||
g2.drawString("✓", x + 38, y + 20);
|
||||
}
|
||||
g2.setFont(Theme.font(10.5f));
|
||||
g2.setColor(Theme.DIM);
|
||||
g2.drawString(name, x, y + s + 15);
|
||||
g2.setColor(affordable ? Theme.FAINT : Theme.DANGER);
|
||||
g2.drawString(cost == 0 ? t("user.free", "免费") : String.valueOf(cost), x, y + s + 29);
|
||||
g2.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static String t(String key, String fallback) {
|
||||
String v = I18n.t(key);
|
||||
return v == null || v.equals(key) ? fallback : v;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 405 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user