Compare commits

...
3 Commits
Author SHA1 Message Date
2509_92447106 e4ea4f054e 修复 2026-11-07 20:18:34 +08:00
2509_92447106 639ff1ba57 修复 2026-11-07 20:01:58 +08:00
2509_92447106 d81ab2acaa 修复 2026-11-07 19:31:02 +08:00
29 changed files with 492 additions and 141 deletions

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@
--> -->
<AvaloniaVersion>11.3.9</AvaloniaVersion> <AvaloniaVersion>11.3.9</AvaloniaVersion>
<MvvmVersion>8.2.2</MvvmVersion> <MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.0</Version> <Version>1.0.1</Version>
<Company>NeoRF</Company> <Company>NeoRF</Company>
<Product>Earth Model Studio</Product> <Product>Earth Model Studio</Product>
<NeutralLanguage>zh-Hans</NeutralLanguage> <NeutralLanguage>zh-Hans</NeutralLanguage>
+10 -2
View File
@@ -42,7 +42,7 @@ $TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.cspro
$PreviewProj = 'model/_engine/PreviewGen/PreviewGen.csproj' $PreviewProj = 'model/_engine/PreviewGen/PreviewGen.csproj'
$StampProj = 'model/_engine/VersionStamp/VersionStamp.csproj' $StampProj = 'model/_engine/VersionStamp/VersionStamp.csproj'
$Sln = 'EarthModelStudio.sln' $Sln = 'EarthModelStudio.sln'
$Version = '1.0.0' $Version = '1.0.1'
function Stamp-Versions { function Stamp-Versions {
Write-Host '==> 自动计算模型版本并生成 version.json' Write-Host '==> 自动计算模型版本并生成 version.json'
@@ -123,6 +123,8 @@ function Prepare-RuntimeLayout([string]$RelDir) {
function Publish-Rid([string]$Rid, [string]$OutDir) { function Publish-Rid([string]$Rid, [string]$OutDir) {
Write-Host "==> 编译 $Rid -> $OutDir" Write-Host "==> 编译 $Rid -> $OutDir"
# 先删旧产物目录,避免残留文件混进新包
if (Test-Path "$Root/$OutDir") { Remove-Item -Recurse -Force "$Root/$OutDir" }
dotnet publish $AppProj -c Release -r $Rid --self-contained true ` dotnet publish $AppProj -c Release -r $Rid --self-contained true `
-p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true ` -p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true `
-p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false -o "$Root/$OutDir" -p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false -o "$Root/$OutDir"
@@ -186,10 +188,16 @@ function Pack-Launcher {
} }
switch ($Task) { switch ($Task) {
'build' { dotnet build $Sln -c Debug } 'build' {
Get-ChildItem "$Root/dist/GC-*.zip","$Root/dist/models-*.zip" -ErrorAction SilentlyContinue |
Remove-Item -Force
dotnet build $Sln -c Debug
}
'run' { dotnet run --project $AppProj -c Debug } 'run' { dotnet run --project $AppProj -c Debug }
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" } 'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
'publish' { 'publish' {
# 先清理 dist 旧产物,再重新生成
if (Test-Path "$Root/dist") { Remove-Item -Recurse -Force "$Root/dist" }
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
Stamp-Versions Stamp-Versions
Publish-Rid 'osx-arm64' 'dist/mac-arm64' Publish-Rid 'osx-arm64' 'dist/mac-arm64'
+8 -1
View File
@@ -38,7 +38,7 @@ PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj" STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj" TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj"
SLN="EarthModelStudio.sln" SLN="EarthModelStudio.sln"
VERSION="1.0.0" VERSION="1.0.1"
TASK="${1:-build}" TASK="${1:-build}"
# 按模型包内容指纹自动写回 <id>.json 的 version,并生成 version.json # 按模型包内容指纹自动写回 <id>.json 的 version,并生成 version.json
@@ -117,6 +117,8 @@ publish_rid() {
RID="$1"; OUT="$2" RID="$1"; OUT="$2"
echo "" echo ""
echo "==> 编译 ${RID} -> ${OUT}" echo "==> 编译 ${RID} -> ${OUT}"
# 先删旧产物,避免上次 publish 的残留文件混进新包
rm -rf "$ROOT_DIR/$OUT"
dotnet publish "$APP_PROJ" \ dotnet publish "$APP_PROJ" \
-c Release \ -c Release \
-r "$RID" \ -r "$RID" \
@@ -192,6 +194,8 @@ PLIST
case "$TASK" in case "$TASK" in
build) build)
# 清理上次遗留的发布包 zip,避免误用旧产物
rm -f "$ROOT_DIR"/dist/GC-*.zip "$ROOT_DIR"/dist/models-*.zip 2>/dev/null || true
dotnet build "$SLN" -c Debug dotnet build "$SLN" -c Debug
;; ;;
run) run)
@@ -201,6 +205,9 @@ case "$TASK" in
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots" dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots"
;; ;;
publish) publish)
# 先清掉 dist 旧产物(含历史 zip / 目录),再重新生成
echo "==> 清理 dist 旧产物"
rm -rf "$ROOT_DIR/dist"
mkdir -p "$ROOT_DIR/dist" mkdir -p "$ROOT_DIR/dist"
stamp_versions stamp_versions
publish_rid "osx-arm64" "dist/mac-arm64" publish_rid "osx-arm64" "dist/mac-arm64"
+48 -27
View File
@@ -53,7 +53,7 @@ public class CelestialView : Control, IDisposable
AvaloniaProperty.Register<CelestialView, bool>(nameof(ExaggerateTilt)); AvaloniaProperty.Register<CelestialView, bool>(nameof(ExaggerateTilt));
public static readonly StyledProperty<int> FrameRateProperty = public static readonly StyledProperty<int> FrameRateProperty =
AvaloniaProperty.Register<CelestialView, int>(nameof(FrameRate), 30); AvaloniaProperty.Register<CelestialView, int>(nameof(FrameRate), 120);
public static readonly StyledProperty<bool> ShowHudProperty = public static readonly StyledProperty<bool> ShowHudProperty =
AvaloniaProperty.Register<CelestialView, bool>(nameof(ShowHud), true); AvaloniaProperty.Register<CelestialView, bool>(nameof(ShowHud), true);
@@ -379,7 +379,8 @@ public class CelestialView : Control, IDisposable
{ {
base.OnAttachedToVisualTree(e); base.OnAttachedToVisualTree(e);
_camElevTarget = DefaultElevation; _camElevTarget = DefaultElevation;
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(16), DispatcherPriority.Render, OnTick); // 8ms 轮询以支撑最高 120 FPS(模型内部仍按 FrameRate 限流);不依赖系统 VSync 节拍
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(8), DispatcherPriority.Render, OnTick);
_lastTick = Stopwatch.GetTimestamp(); _lastTick = Stopwatch.GetTimestamp();
_timer.Start(); _timer.Start();
} }
@@ -678,7 +679,11 @@ public class CelestialView : Control, IDisposable
private Vector3 RotationLight(Matrix4x4 cam, double tiltDeg) private Vector3 RotationLight(Matrix4x4 cam, double tiltDeg)
{ {
var axisCam = Vector3.TransformNormal(AxisWorld(tiltDeg), cam); var axisCam = Vector3.TransformNormal(AxisWorld(tiltDeg), cam);
var forwardRight = Vector3.Normalize(new Vector3(0.86f, 0f, 0.50f)); // 特写模式:光从正右方水平射来,晨昏线竖直居中、正对观察者,
// 便于课堂直观看昼夜半球;主画布仍用斜向光体现立体感。
var forwardRight = InsetMode
? new Vector3(1f, 0f, 0f)
: Vector3.Normalize(new Vector3(0.86f, 0f, 0.50f));
var u = forwardRight - axisCam * Vector3.Dot(forwardRight, axisCam); var u = forwardRight - axisCam * Vector3.Dot(forwardRight, axisCam);
if (u.Length() < 0.001f) u = new Vector3(1, 0, 0); if (u.Length() < 0.001f) u = new Vector3(1, 0, 0);
u = Vector3.Normalize(u); u = Vector3.Normalize(u);
@@ -704,40 +709,52 @@ public class CelestialView : Control, IDisposable
var tropic = TropicDegrees(runtime); var tropic = TropicDegrees(runtime);
var polar = 90.0 - tropic; var polar = 90.0 - tropic;
DrawParallel(ctx, cam, planet, center, radius, 0, EquatorPen, // 五条纬线一起画:先画线,再统一布置标签,避免自转时多个标签
labels ? Texts["lat.equator"] : null, LabelBrush); // 被投影到相近位置而互相覆盖 / 抖动(原来的逐条独立绘制会重叠)。
DrawParallel(ctx, cam, planet, center, radius, tropic, TropicPen, var lines = new (double Lat, IPen Pen, string? Label, IBrush Brush)[]
labels ? Texts["lat.tropicN"] : null, TropicBrush);
DrawParallel(ctx, cam, planet, center, radius, -tropic, TropicPen,
labels ? Texts["lat.tropicS"] : null, TropicBrush);
DrawParallel(ctx, cam, planet, center, radius, polar, PolarPen,
labels ? Texts["lat.polarN"] : null, PolarBrush);
DrawParallel(ctx, cam, planet, center, radius, -polar, PolarPen,
labels ? Texts["lat.polarS"] : null, PolarBrush);
}
private void DrawParallel(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet,
Point center, double radius, double lat, IPen pen, string? label, IBrush labelBrush)
{ {
DrawSpherePolyline(ctx, cam, planet, center, radius, pen, (0, EquatorPen, labels ? Texts["lat.equator"] : null, LabelBrush),
t => LatLonToUnit(lat, t * 360.0), 144); (tropic, TropicPen, labels ? Texts["lat.tropicN"] : null, TropicBrush),
if (label == null) return; (-tropic, TropicPen, labels ? Texts["lat.tropicS"] : null, TropicBrush),
(polar, PolarPen, labels ? Texts["lat.polarN"] : null, PolarBrush),
(-polar, PolarPen, labels ? Texts["lat.polarS"] : null, PolarBrush)
};
// 找该纬线上「最靠右且可见」的点作为标签锚点: foreach (var l in lines)
// 地球自转时标签始终留在可见半球右侧,不会忽隐忽现 DrawSpherePolyline(ctx, cam, planet, center, radius, l.Pen,
t => LatLonToUnit(l.Lat, t * 360.0), 144);
if (!labels) return;
// 收集每个标签的锚点,按屏幕 Y 排序后做垂直去重叠
var placed = new List<(double Y, double X, string Text, IBrush Brush)>();
foreach (var l in lines)
{
if (l.Label == null) continue;
Vector3 best = default; Vector3 best = default;
var bestScore = double.NegativeInfinity; var bestScore = double.NegativeInfinity;
for (var lon = -180; lon < 180; lon += 6) for (var lon = -180; lon < 180; lon += 6)
{ {
var world = Vector3.Transform(LatLonToUnit(lat, lon), planet); var world = Vector3.Transform(LatLonToUnit(l.Lat, lon), planet);
var c = Vector3.Transform(world, cam); var c = Vector3.Transform(world, cam);
if (c.Z < 0.10f) continue; if (c.Z < 0.10f) continue;
var score = c.X * 2.0 + c.Z; var score = c.X * 2.0 + c.Z;
if (score > bestScore) { bestScore = score; best = c; } if (score > bestScore) { bestScore = score; best = c; }
} }
if (double.IsNegativeInfinity(bestScore)) return; if (double.IsNegativeInfinity(bestScore)) continue;
var p = new Point(center.X + best.X * radius, center.Y - best.Y * radius); placed.Add((center.Y - best.Y * radius, center.X + best.X * radius, l.Label, l.Brush));
DrawLabelChip(ctx, label, p, InsetMode ? 9.0 : 10.5, labelBrush, toRight: false); }
placed.Sort((a, b) => a.Y.CompareTo(b.Y));
const double minGap = 16.0;
var lastY = double.NegativeInfinity;
foreach (var p in placed)
{
var y = p.Y;
if (y - lastY < minGap) y = lastY + minGap;
lastY = y;
DrawLabelChip(ctx, p.Text, new Point(p.X, y), InsetMode ? 9.0 : 10.5, p.Brush, toRight: false);
}
} }
/// <summary>带深色底衬的标签:压在明亮的地球上也读得清,且不会被画布边缘裁掉。</summary> /// <summary>带深色底衬的标签:压在明亮的地球上也读得清,且不会被画布边缘裁掉。</summary>
@@ -745,7 +762,11 @@ public class CelestialView : Control, IDisposable
double fontSize, IBrush brush, bool toRight) double fontSize, IBrush brush, bool toRight)
{ {
var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
new Typeface(FontFamily.Default, FontStyle.Normal, FontWeight.SemiBold), fontSize, brush); new Typeface(FontFamily.Default, FontStyle.Normal, FontWeight.SemiBold), fontSize, brush)
{
TextAlignment = TextAlignment.Left,
Trimming = TextTrimming.None
};
var x = toRight ? anchor.X + 9 : Math.Max(3, anchor.X - formatted.Width - 9); var x = toRight ? anchor.X + 9 : Math.Max(3, anchor.X - formatted.Width - 9);
var y = anchor.Y - formatted.Height - 4; var y = anchor.Y - formatted.Height - 4;
ctx.DrawRectangle(ChipBg, null, ctx.DrawRectangle(ChipBg, null,
+22 -11
View File
@@ -85,7 +85,7 @@ public sealed class EarthModelView : UserControl, IDisposable
ShowOrbit = true, ShowOrbit = true,
ShowGraticule = true, ShowGraticule = true,
ShowKeyLatitudes = true, ShowKeyLatitudes = true,
FrameRate = 60, FrameRate = 120,
View = IsRevolution ? SceneView.Revolution : SceneView.Rotation View = IsRevolution ? SceneView.Revolution : SceneView.Rotation
}; };
_canvas.JumpToOrbit(StartAngle); _canvas.JumpToOrbit(StartAngle);
@@ -216,8 +216,7 @@ public sealed class EarthModelView : UserControl, IDisposable
// ---------------------------------------------------------------- 顶部主工具栏 // ---------------------------------------------------------------- 顶部主工具栏
private Control BuildTopBar() private Control BuildTopBar()
{ {
var close = MakeButton(_texts["close"], () => _context.RequestClose()); // 关闭按钮统一放在窗口右上角的自建标题栏,这里不再重复放左上角
var title = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center }; var title = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center };
title.Children.Add(new TextBlock title.Children.Add(new TextBlock
{ {
@@ -268,14 +267,13 @@ public sealed class EarthModelView : UserControl, IDisposable
actions.Children.Add(MakeButton(_texts["classroom"], () => SetLessonsVisible(!_showLessons))); actions.Children.Add(MakeButton(_texts["classroom"], () => SetLessonsVisible(!_showLessons)));
actions.Children.Add(MakeButton("⛶", ToggleFullScreen, large: true)); actions.Children.Add(MakeButton("⛶", ToggleFullScreen, large: true));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") }; var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto") };
grid.Children.Add(close); Grid.SetColumn(title, 0);
Grid.SetColumn(title, 1);
title.Margin = new Thickness(14, 0, 0, 0); title.Margin = new Thickness(14, 0, 0, 0);
grid.Children.Add(title); grid.Children.Add(title);
Grid.SetColumn(_viewSwitch, 2); Grid.SetColumn(_viewSwitch, 1);
grid.Children.Add(_viewSwitch); grid.Children.Add(_viewSwitch);
Grid.SetColumn(actions, 4); Grid.SetColumn(actions, 3);
grid.Children.Add(actions); grid.Children.Add(actions);
return new Border { Background = PanelBg, Padding = new Thickness(16, 9), Child = grid }; return new Border { Background = PanelBg, Padding = new Thickness(16, 9), Child = grid };
@@ -716,10 +714,23 @@ public sealed class EarthModelView : UserControl, IDisposable
? _texts.Pick(season.TeachingI18n, _texts["orbitTeach"]) ? _texts.Pick(season.TeachingI18n, _texts["orbitTeach"])
: _texts["orbitTeach"]; : _texts["orbitTeach"];
if (_showCloseup && (double.IsNaN(_lastDeclination) || Math.Abs(_lastDeclination - decl) > 0.04)) // 特写的直射纬度用缓动逼近目标,而不是瞬间跳变:
// 公转时拖动/改变轨道角,晨昏线会平滑地移过去(每次 timer 步进一帧)。
if (_showCloseup)
{ {
_closeup.DeclinationDeg = decl; var target = decl;
_lastDeclination = decl; var current = _closeup.DeclinationDeg;
var diff = target - current;
if (Math.Abs(diff) < 0.02)
{
_closeup.DeclinationDeg = target;
}
else
{
// 每 140ms 走剩余距离的 ~18%,形成自然的 ease-out 动画
_closeup.DeclinationDeg = current + diff * 0.18;
}
_lastDeclination = target;
} }
} }
+2 -2
View File
@@ -23,6 +23,6 @@
"type": "NeoRF.EarthModels.RevolutionModelFactory", "type": "NeoRF.EarthModels.RevolutionModelFactory",
"preview": "preview.png", "preview": "preview.png",
"apiVersion": 1, "apiVersion": 1,
"version": "1.0-0a73a257ec", "version": "1.0-7380e0cff3",
"updatedAt": "2026-11-07T10:46:02Z" "updatedAt": "2026-11-07T12:01:08Z"
} }
+2 -2
View File
@@ -23,6 +23,6 @@
"type": "NeoRF.EarthModels.RotationModelFactory", "type": "NeoRF.EarthModels.RotationModelFactory",
"preview": "preview.png", "preview": "preview.png",
"apiVersion": 1, "apiVersion": 1,
"version": "1.0-6c97454f58", "version": "1.0-c74907bbce",
"updatedAt": "2026-11-07T10:46:02Z" "updatedAt": "2026-11-07T12:01:08Z"
} }
+11 -11
View File
@@ -1,30 +1,30 @@
{ {
"schema": 1, "schema": 1,
"generated": "2026-11-07T10:46:02Z", "generated": "2026-11-07T12:01:09Z",
"repository": "https://gitcode.com/2509_92447106/GC", "repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main", "branch": "main",
"modelDir": "model", "modelDir": "model",
"launcher": { "launcher": {
"version": "1.0.0", "version": "1.0.1",
"revision": "0d59eff631", "revision": "ba909d4dc3",
"packages": { "packages": {
"win-x64": { "win-x64": {
"path": "dist/GC-win-x64.zip", "path": "dist/GC-win-x64.zip",
"url": "", "url": "",
"sha256": "7bfb1cfab07934642eff4c52078a8f5f034f1d2432a7613f04674403c70f2b6d", "sha256": "2704fbc3e3acba5630a13a313af0eca45128827ed90e4718fd143a554ca70c3c",
"size": 78755039 "size": 39379924
}, },
"win-arm64": { "win-arm64": {
"path": "dist/GC-win-arm64.zip", "path": "dist/GC-win-arm64.zip",
"url": "", "url": "",
"sha256": "9fddf07fa18cbdb368e37204cfb96f5828207e5fe74ecb31fa66b61fa400fd1c", "sha256": "c8f69370b9e381418a6568aca11cac44cb034e0ab2a99f7e14fcbef1dc503a44",
"size": 75360988 "size": 37684316
}, },
"osx-arm64": { "osx-arm64": {
"path": "dist/GC-osx-arm64.zip", "path": "dist/GC-osx-arm64.zip",
"url": "", "url": "",
"sha256": "3517548b598eda62c92d873528f39e305c52c6fb246fa5ba5f3613f8b8cb315a", "sha256": "8588892dcfb982b7b52c3d74f3493fd8f27a327a0571095ab62dd4130857e082",
"size": 39847910 "size": 39852236
}, },
"osx-x64": { "osx-x64": {
"path": "dist/GC-osx-x64.zip", "path": "dist/GC-osx-x64.zip",
@@ -39,12 +39,12 @@
"models": [ "models": [
{ {
"id": "earth-revolution", "id": "earth-revolution",
"version": "1.0-0a73a257ec", "version": "1.0-7380e0cff3",
"dir": "model/earth-revolution" "dir": "model/earth-revolution"
}, },
{ {
"id": "earth-rotation", "id": "earth-rotation",
"version": "1.0-6c97454f58", "version": "1.0-c74907bbce",
"dir": "model/earth-rotation" "dir": "model/earth-rotation"
} }
] ]
@@ -1,5 +1,5 @@
{ {
"app.name": "Earth Model Studio", "app.name": "Morris GC",
"app.tagline": "Astronomy teaching models · visual launcher", "app.tagline": "Astronomy teaching models · visual launcher",
"app.version": "Version", "app.version": "Version",
"app.platform": "Platform", "app.platform": "Platform",
@@ -74,6 +74,7 @@
"set.memory.current": "In use", "set.memory.current": "In use",
"set.memory.unit": "MB", "set.memory.unit": "MB",
"set.memory.hint": "2048 MB or more is recommended; 1024 MB for low-end devices.", "set.memory.hint": "2048 MB or more is recommended; 1024 MB for low-end devices.",
"set.memory.auto": "Auto (allocate based on device memory)",
"set.preallocate": "Preload land data at startup", "set.preallocate": "Preload land data at startup",
"set.preallocate.desc": "Faster first frame, slightly slower startup.", "set.preallocate.desc": "Faster first frame, slightly slower startup.",
"set.sources": "Model sources", "set.sources": "Model sources",
@@ -1,5 +1,5 @@
{ {
"app.name": "地球模型工作室", "app.name": "Morris GC",
"app.tagline": "天文教学模型 · 可视化启动器", "app.tagline": "天文教学模型 · 可视化启动器",
"app.version": "版本", "app.version": "版本",
"app.platform": "平台", "app.platform": "平台",
@@ -74,6 +74,7 @@
"set.memory.current": "当前占用", "set.memory.current": "当前占用",
"set.memory.unit": "MB", "set.memory.unit": "MB",
"set.memory.hint": "建议 2048 MB 以上,低配设备可选 1024 MB。", "set.memory.hint": "建议 2048 MB 以上,低配设备可选 1024 MB。",
"set.memory.auto": "自动(根据设备内存分配)",
"set.preallocate": "启动时预加载模型地表数据", "set.preallocate": "启动时预加载模型地表数据",
"set.preallocate.desc": "打开后首帧更快,启动耗时略增。", "set.preallocate.desc": "打开后首帧更快,启动耗时略增。",
"set.sources": "模型源", "set.sources": "模型源",
@@ -13,12 +13,15 @@ public sealed class AppSettings
/// <summary>light | dark</summary> /// <summary>light | dark</summary>
public string Theme { get; set; } = "light"; public string Theme { get; set; } = "light";
/// <summary>渲染帧率:24 / 30 / 60</summary> /// <summary>渲染帧率:24 / 30 / 60 / 90 / 120(上限 120,关闭 VSync 同步)</summary>
public int RenderFps { get; set; } = 30; public int RenderFps { get; set; } = 120;
/// <summary>启动时运行内存分配(MB)——决定场景缓存/纹理预算。</summary> /// <summary>启动时运行内存分配(MB)——决定场景缓存/纹理预算。</summary>
public int MemoryMb { get; set; } = 2048; public int MemoryMb { get; set; } = 2048;
/// <summary>自动模式:根据设备可用内存自动计算预算(忽略 MemoryMb)。</summary>
public bool MemoryAuto { get; set; } = true;
/// <summary>启动时检查模型源更新。</summary> /// <summary>启动时检查模型源更新。</summary>
public bool CheckSourceOnStartup { get; set; } public bool CheckSourceOnStartup { get; set; }
@@ -38,7 +38,8 @@ public sealed class AppServices
var services = new AppServices(paths); var services = new AppServices(paths);
L.I.Initialize(services.Settings.Current.Language); L.I.Initialize(services.Settings.Current.Language);
services.Memory.Apply(services.Settings.Current.MemoryMb); services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto,
services.Settings.Current.MemoryMb);
Current = services; Current = services;
return services; return services;
@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
@@ -23,18 +22,26 @@ namespace EarthModelStudio.Services;
public sealed class GitCodeReleaseRemote : IModelRemote public sealed class GitCodeReleaseRemote : IModelRemote
{ {
private readonly GitCodeRemote _content; private readonly GitCodeRemote _content;
private readonly HttpClient _http;
private readonly string _releasesUrl; private readonly string _releasesUrl;
private readonly Dictionary<string, (string Url, string? Sha256, long Size)> _assets = new(); private readonly Dictionary<string, (string Url, string? Sha256, long Size, string Name)> _assets = new();
public GitCodeReleaseRemote(string? manifestUrl, string? repository, HttpClient? http = null) // 共享静态 HttpClient:避免每次检查更新都创建新实例导致端口耗尽;
// headers 只在一处设置,多个线程并发读取是线程安全的。
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return client;
}
public GitCodeReleaseRemote(string? manifestUrl, string? repository)
{ {
_content = new GitCodeRemote(manifestUrl, repository); _content = new GitCodeRemote(manifestUrl, repository);
var (owner, repo) = ParseOwnerRepo(repository); var (owner, repo) = ParseOwnerRepo(repository);
_releasesUrl = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases"; _releasesUrl = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases";
_http = http ?? new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
DisplayName = (string.IsNullOrWhiteSpace(repository) DisplayName = (string.IsNullOrWhiteSpace(repository)
? GitCodeRemote.DefaultRepository : repository!.TrimEnd('/')) + " (Release)"; ? GitCodeRemote.DefaultRepository : repository!.TrimEnd('/')) + " (Release)";
} }
@@ -77,7 +84,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(12)); timeout.CancelAfter(TimeSpan.FromSeconds(12));
var text = await _http.GetStringAsync(_releasesUrl, timeout.Token); var text = await Http.GetStringAsync(_releasesUrl, timeout.Token);
var trimmed = text.TrimStart(); var trimmed = text.TrimStart();
if (trimmed.Length == 0 || trimmed[0] != '[') return; // 可能是错误页/对象 if (trimmed.Length == 0 || trimmed[0] != '[') return; // 可能是错误页/对象
@@ -101,7 +108,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
if (rid == null || string.IsNullOrWhiteSpace(asset.Url)) continue; if (rid == null || string.IsNullOrWhiteSpace(asset.Url)) continue;
// 同名平台取第一个有效附件 // 同名平台取第一个有效附件
if (!_assets.ContainsKey(rid)) if (!_assets.ContainsKey(rid))
_assets[rid] = (asset.Url, asset.Sha256, asset.Size); _assets[rid] = (asset.Url, asset.Sha256, asset.Size, asset.Name);
} }
// 把附件地址写回 packages:有附件就用附件的直链与校验值, // 把附件地址写回 packages:有附件就用附件的直链与校验值,
@@ -114,6 +121,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
version.Launcher.Packages[rid] = pkg; version.Launcher.Packages[rid] = pkg;
} }
pkg.Url = info.Url; pkg.Url = info.Url;
pkg.AssetName = info.Name;
if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256; if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256;
if (info.Size > 0) pkg.Size = info.Size; if (info.Size > 0) pkg.Size = info.Size;
} }
@@ -141,13 +149,17 @@ public sealed class GitCodeReleaseRemote : IModelRemote
{ {
foreach (var a in assets.EnumerateArray()) foreach (var a in assets.EnumerateArray())
{ {
// 跳过 GitCode 自动生成的源码包(type=source),只取真正的发布附件
var type = Str(a, "type");
if (string.Equals(type, "source", StringComparison.OrdinalIgnoreCase)) continue;
info.Assets.Add(new ReleaseAsset info.Assets.Add(new ReleaseAsset
{ {
Name = Str(a, "name") ?? Str(a, "file_name") ?? "", Name = Str(a, "name") ?? Str(a, "file_name") ?? "",
BrowserDownloadUrl = Str(a, "browser_download_url"), BrowserDownloadUrl = Str(a, "browser_download_url"),
DownloadUrl = Str(a, "download_url") ?? Str(a, "url"), DownloadUrl = Str(a, "download_url") ?? Str(a, "url"),
Size = Num(a, "size"), Size = Num(a, "size"),
Sha256 = Str(a, "sha256") ?? Str(a, "digest") Sha256 = Str(a, "sha256") ?? Str(a, "digest"),
Type = type
}); });
} }
} }
@@ -21,6 +21,27 @@ public sealed class MemoryBudget
Changed?.Invoke(); Changed?.Invoke();
} }
/// <summary>
/// 自动预算:取设备可用物理内存的一部分(约 1/4),
/// 夹在 512–8192 MB 之间,低配设备也不会因为预算过大而卡顿。
/// </summary>
public static int AutoComputeMb()
{
try
{
var info = GC.GetGCMemoryInfo();
var totalMb = info.TotalAvailableMemoryBytes / (1024.0 * 1024.0);
if (totalMb > 0)
return (int)Math.Clamp(Math.Round(totalMb / 4.0 / 256.0) * 256, 512, 8192);
}
catch { /* 平台不支持时回退默认值 */ }
return 2048;
}
/// <summary>按设置应用:auto 时自动计算,否则用手动值。</summary>
public void ApplyAuto(bool auto, int manualMb)
=> Apply(auto ? AutoComputeMb() : manualMb);
/// <summary>内存情况变化(例如模型窗口开关)时刷新展示。</summary> /// <summary>内存情况变化(例如模型窗口开关)时刷新展示。</summary>
public void Refresh() => Changed?.Invoke(); public void Refresh() => Changed?.Invoke();
@@ -20,17 +20,29 @@ public sealed class ReleaseInfo
/// <summary>从 tag_name / name 里抽出的版本号(去掉前缀 v、GC- 等)。</summary> /// <summary>从 tag_name / name 里抽出的版本号(去掉前缀 v、GC- 等)。</summary>
public string Version => NormalizeVersion(TagName, Name); public string Version => NormalizeVersion(TagName, Name);
private static readonly string[] VersionPrefixes =
{ "v", "V", "GC-", "gc-", "release-", "Release-" };
private static readonly string[] PrereleaseTags =
{ "alpha", "beta", "rc", "pre", "dev", "snapshot" };
public static string NormalizeVersion(string tag, string name) public static string NormalizeVersion(string tag, string name)
{ {
var raw = !string.IsNullOrWhiteSpace(tag) ? tag : name; var raw = !string.IsNullOrWhiteSpace(tag) ? tag : name;
if (string.IsNullOrWhiteSpace(raw)) return ""; if (string.IsNullOrWhiteSpace(raw)) return "";
raw = raw!.Trim(); raw = raw!.Trim();
// "v1.0.1" / "GC-1.0.1" / "release-1.0.1" -> 取第一段像版本号的部分 // "v1.0.1" / "GC-1.0.1" / "release-1.0.1" -> 取第一段像版本号的部分
foreach (var prefix in new[] { "v", "V", "GC-", "gc-", "release-", "Release-" }) foreach (var prefix in VersionPrefixes)
if (raw.StartsWith(prefix, StringComparison.Ordinal)) { raw = raw[prefix.Length..]; break; } if (raw.StartsWith(prefix, StringComparison.Ordinal)) { raw = raw[prefix.Length..]; break; }
// 形如 GC-1.0.1-Win-amd64 时只取版本段 // 形如 GC-1.0.1-Win-amd64 时只取版本段;但 2.3.0-beta 这类预发布串要保留完整。
// 用「后缀是否常见预发布标签」区分,避免把 "-Win" 误当成预发布。
var dash = raw.IndexOf('-'); var dash = raw.IndexOf('-');
if (dash > 0 && System.Version.TryParse(raw[..dash], out _)) raw = raw[..dash]; if (dash > 0 && System.Version.TryParse(raw[..dash], out _))
{
var tail = raw[(dash + 1)..].ToLowerInvariant();
var isPrerelease = Array.Exists(PrereleaseTags, p => tail.StartsWith(p, StringComparison.Ordinal));
if (!isPrerelease) raw = raw[..dash];
}
return raw; return raw;
} }
} }
@@ -41,11 +53,43 @@ public sealed class ReleaseAsset
public string? BrowserDownloadUrl { get; set; } public string? BrowserDownloadUrl { get; set; }
public string? DownloadUrl { get; set; } public string? DownloadUrl { get; set; }
public long Size { get; set; } public long Size { get; set; }
public string? Sha256 { get; set; } /// <summary>附件类型:GitCode 用 "source" 表示自动生成的源码压缩包,需跳过。</summary>
public string? Type { get; set; }
private string? _sha256;
/// <summary>
/// 校验值。真实 Release 的 digest 形如 "sha256:899fc1...",
/// 这里统一剥掉算法前缀,只留 hex,便于与 SHA256.HashData 结果比较。
/// </summary>
public string? Sha256
{
get => _sha256;
set
{
if (string.IsNullOrWhiteSpace(value)) { _sha256 = null; return; }
var v = value!.Trim();
var colon = v.IndexOf(':');
if (colon > 0 && v[..colon].Equals("sha256", StringComparison.OrdinalIgnoreCase))
v = v[(colon + 1)..];
_sha256 = v.Trim();
}
}
[JsonIgnore] [JsonIgnore]
public string Url => BrowserDownloadUrl ?? DownloadUrl ?? ""; public string Url => BrowserDownloadUrl ?? DownloadUrl ?? "";
/// <summary>单文件发布包(.exe 等)不能走解压,需要直接作为 payload 内容。</summary>
public bool IsSingleFile
{
get
{
var n = Name.ToLowerInvariant();
return !n.EndsWith(".zip", StringComparison.Ordinal) &&
!n.EndsWith(".tar.gz", StringComparison.Ordinal) &&
!n.EndsWith(".tgz", StringComparison.Ordinal);
}
}
/// <summary>解析附件名里的系统/架构,映射到 .NET RID。</summary> /// <summary>解析附件名里的系统/架构,映射到 .NET RID。</summary>
/// <returns>如 win-x64 / win-arm64 / osx-arm64;无法识别返回 null。</returns> /// <returns>如 win-x64 / win-arm64 / osx-arm64;无法识别返回 null。</returns>
public string? RidFromName(string fullName) public string? RidFromName(string fullName)
@@ -60,8 +104,12 @@ public sealed class ReleaseAsset
if (!win && !mac && !linux) return null; if (!win && !mac && !linux) return null;
bool arm64 = lower.Contains("arm64") || lower.Contains("aarch64") || lower.Contains("win-arm"); bool arm64 = lower.Contains("arm64") || lower.Contains("aarch64") || lower.Contains("win-arm");
bool x86 = lower.Contains("x86") && !lower.Contains("x64") && !lower.Contains("amd64") && !arm64; // x86_64 / x86-64 / amd64 / x64 都是 64 位;只有裸 "x86"/"win-x86" 才是 32 位
// amd64 / x64 / x86_64 都视为 x64 bool is64 = lower.Contains("x64") || lower.Contains("amd64") ||
lower.Contains("x86-64") || lower.Contains("x86_64");
bool x86 = !is64 && !arm64 &&
(lower.Contains("x86") || lower.Contains("win32") || lower.Contains("i386"));
// 其余(未显式标注 32 位)一律按 64 位处理,覆盖 "GC-1.0.1-Windows.zip" 这类简写
var arch = arm64 ? "arm64" : x86 ? "x86" : "x64"; var arch = arm64 ? "arm64" : x86 ? "x86" : "x64";
if (win) return "win-" + arch; if (win) return "win-" + arch;
@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using EarthModelStudio.Models; using EarthModelStudio.Models;
namespace EarthModelStudio.Services; namespace EarthModelStudio.Services;
@@ -17,25 +18,41 @@ public sealed class SettingsService
public void Load() public void Load()
{ {
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings(); Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
if (Current.Sources.Count == 0) SeedSources(); SeedDefaultSource();
if (Current.MemoryMb < 256) Current.MemoryMb = 2048; if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
} }
/// <summary> /// <summary>
/// 自动更新由 UpdateService 负责(版本清单 version.json),这里不预置任何在线源; /// 默认下载源(gitcode 官方仓库)始终内置在列表里,且不允许删除:
/// 只给「下载」页留一条空的自定义源占位。 /// 它是启动器自动更新的同源仓库,用户清掉会导致模型无法回退。
/// 老配置里没有这条时自动补上;已有的用户自定义源保持不变。
/// </summary> /// </summary>
private void SeedSources() public const string DefaultSourceId = "gitcode-official";
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC";
private void SeedDefaultSource()
{ {
Current.Sources.Add(new ModelSource var existing = Current.Sources.FirstOrDefault(s =>
string.Equals(s.Id, DefaultSourceId, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{ {
Id = "custom", Current.Sources.Insert(0, new ModelSource
Name = "自定义源", {
Url = "", Id = DefaultSourceId,
Enabled = false Name = "Morris GC (GitCode)",
Url = DefaultSourceUrl,
Enabled = true,
BuiltIn = true
}); });
Save(); Save();
} }
else
{
// 强制保证内置标记与地址,避免旧配置被用户改坏后失去保护
existing.BuiltIn = true;
if (string.IsNullOrWhiteSpace(existing.Url)) existing.Url = DefaultSourceUrl;
}
}
public void Save() public void Save()
{ {
@@ -32,6 +32,8 @@ public sealed class RepoPackage
public string? Path { get; set; } public string? Path { get; set; }
public string? Sha256 { get; set; } public string? Sha256 { get; set; }
public long Size { get; set; } public long Size { get; set; }
/// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary>
public string? AssetName { get; set; }
} }
public sealed class RepoModel public sealed class RepoModel
@@ -314,24 +314,36 @@ public sealed class UpdateService
Directory.CreateDirectory(_paths.UpdateRoot); Directory.CreateDirectory(_paths.UpdateRoot);
var payload = Path.Combine(_paths.UpdateRoot, "payload"); var payload = Path.Combine(_paths.UpdateRoot, "payload");
if (Directory.Exists(payload)) Directory.Delete(payload, true); if (Directory.Exists(payload)) Directory.Delete(payload, true);
Directory.CreateDirectory(payload);
// 单文件发布包(.exe / .app.zip 里的可执行文件不在此列)就是程序本体,不能解压。
// 直接按附件原名放进 payload,脚本会把 payload/ 整体覆盖到安装目录。
var assetName = package!.AssetName;
bool singleFile = !string.IsNullOrWhiteSpace(assetName) &&
!assetName!.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) &&
!assetName.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase);
string executableName;
if (singleFile)
{
executableName = Path.GetFileName(assetName!);
await File.WriteAllBytesAsync(Path.Combine(payload, executableName), bytes, ct);
}
else
{
var zip = Path.Combine(_paths.CacheRoot, "launcher-" + Safe(launcher.Version) + ".zip"); var zip = Path.Combine(_paths.CacheRoot, "launcher-" + Safe(launcher.Version) + ".zip");
await File.WriteAllBytesAsync(zip, bytes, ct); await File.WriteAllBytesAsync(zip, bytes, ct);
try try { ZipSafety.ExtractToDirectory(zip, payload); }
{ finally { try { File.Delete(zip); } catch { } }
ZipSafety.ExtractToDirectory(zip, payload);
}
finally
{
try { File.Delete(zip); } catch { }
}
FlattenPayload(payload); FlattenPayload(payload);
executableName = Path.GetFileName(Environment.ProcessPath ?? "");
}
Json.Write(Path.Combine(_paths.UpdateRoot, "pending.json"), new PendingUpdate Json.Write(Path.Combine(_paths.UpdateRoot, "pending.json"), new PendingUpdate
{ {
Version = launcher.Version, Version = launcher.Version,
Rid = rid, Rid = rid,
InstallDirectory = _paths.InstallDirectory, InstallDirectory = _paths.InstallDirectory,
Executable = Path.GetFileName(Environment.ProcessPath ?? ""), Executable = executableName,
Payload = "payload", Payload = "payload",
DownloadedAt = DateTime.UtcNow.ToString("O") DownloadedAt = DateTime.UtcNow.ToString("O")
}); });
@@ -25,6 +25,16 @@
<GradientStop Color="#1A3057" Offset="0.55" /> <GradientStop Color="#1A3057" Offset="0.55" />
<GradientStop Color="#0E1A31" Offset="1" /> <GradientStop Color="#0E1A31" Offset="1" />
</LinearGradientBrush> </LinearGradientBrush>
<LinearGradientBrush x:Key="TitleBarBg" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Color="#101C33" Offset="0" />
<GradientStop Color="#0B1322" Offset="1" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="SideBgBrush" StartPoint="0%,0%" EndPoint="0%,100%">
<GradientStop Color="#0E1729" Offset="0" />
<GradientStop Color="#0A1120" Offset="1" />
</LinearGradientBrush>
</Styles.Resources> </Styles.Resources>
<Style Selector="Window"> <Style Selector="Window">
@@ -139,12 +149,6 @@
</Transitions> </Transitions>
</Setter> </Setter>
</Style> </Style>
<Style Selector="Button:pointerover">
<Setter Property="RenderTransform" Value="translateY(-1px)" />
</Style>
<Style Selector="Button:pressed">
<Setter Property="RenderTransform" Value="translateY(1px)" />
</Style>
<Style Selector="Button.primary"> <Style Selector="Button.primary">
<Setter Property="Foreground" Value="White" /> <Setter Property="Foreground" Value="White" />
</Style> </Style>
@@ -220,6 +224,8 @@
<Style Selector="Button.nav.active /template/ ContentPresenter#PART_ContentPresenter"> <Style Selector="Button.nav.active /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#1C2C4C" /> <Setter Property="Background" Value="#1C2C4C" />
<Setter Property="Foreground" Value="#FFFFFF" /> <Setter Property="Foreground" Value="#FFFFFF" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="BorderThickness" Value="3,0,0,0" />
</Style> </Style>
<!-- 输入 --> <!-- 输入 -->
@@ -246,4 +252,59 @@
<Setter Property="FontSize" Value="12.5" /> <Setter Property="FontSize" Value="12.5" />
</Style> </Style>
<!--
自建标题栏按钮只做背景/前景色渐变,不参与全局的 scale 动画:
titlebtn 用优先级更高的选择器把 RenderTransform 固定为恒等变换,
并清空 Transitions 里的 TransformOperationsTransition,彻底避开
hover 时 RenderTransform 类型/过渡器不匹配导致的渲染异常。
-->
<Style Selector="Button.titlebtn">
<Setter Property="Width" Value="38" />
<Setter Property="Height" Value="30" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="#A9B8D4" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="FontSize" Value="13" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="CornerRadius" Value="7" />
<Setter Property="Margin" Value="2,0" />
<Setter Property="RenderTransform" Value="scale(1)" />
<Setter Property="Transitions">
<Transitions>
<DoubleTransition Property="Opacity" Duration="0:0:0.12" />
<BrushTransition Property="Background" Duration="0:0:0.12" />
<BrushTransition Property="Foreground" Duration="0:0:0.12" />
</Transitions>
</Setter>
</Style>
<Style Selector="Button.titlebtn:pointerover">
<Setter Property="Background" Value="#223252" />
<Setter Property="Foreground" Value="#FFFFFF" />
<Setter Property="RenderTransform" Value="scale(1)" />
</Style>
<Style Selector="Button.titlebtn:pressed">
<Setter Property="RenderTransform" Value="scale(1)" />
</Style>
<Style Selector="Button.titlebtn.close:pointerover">
<Setter Property="Background" Value="#D64545" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<!--
按下反馈用 TransformOperations 语法,与上面 Button 的
TransformOperationsTransition 保持一致;若改成 ScaleTransform 对象,
状态切换时过渡器无法转换类型,会导致悬停/按下时渲染异常。
-->
<Style Selector="Button">
<Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
</Style>
<Style Selector="Button:pointerover">
<Setter Property="RenderTransform" Value="scale(0.98)" />
</Style>
<Style Selector="Button:pressed">
<Setter Property="RenderTransform" Value="scale(0.94)" />
</Style>
</Styles> </Styles>
@@ -93,6 +93,7 @@ public partial class DownloadViewModel : ObservableObject
internal void RemoveSource(SourceItemViewModel source) internal void RemoveSource(SourceItemViewModel source)
{ {
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model); _services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save(); _services.Settings.Save();
var wasSelected = SelectedSource == source; var wasSelected = SelectedSource == source;
@@ -325,6 +326,8 @@ public partial class SourceItemViewModel : ObservableObject
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name; public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost; public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost;
public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url); public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url);
/// <summary>内置默认源不可删除(下载页隐藏删除按钮)。</summary>
public bool CanRemove => !Model.BuiltIn;
public bool Enabled public bool Enabled
{ {
@@ -24,11 +24,12 @@ public partial class SettingsViewModel : ObservableObject
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new(); public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
public ObservableCollection<LanguageOption> Languages { get; } = new(); public ObservableCollection<LanguageOption> Languages { get; } = new();
public int[] FrameRates { get; } = { 24, 30, 60 }; public int[] FrameRates { get; } = { 24, 30, 60, 90, 120 };
[ObservableProperty] private LanguageOption? _selectedLanguage; [ObservableProperty] private LanguageOption? _selectedLanguage;
[ObservableProperty] private int _selectedFps = 30; [ObservableProperty] private int _selectedFps = 120;
[ObservableProperty] private double _memoryValue = 2048; [ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private bool _memoryAuto = true;
[ObservableProperty] private string _statusMessage = ""; [ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _autoUpdate = true; [ObservableProperty] private bool _autoUpdate = true;
@@ -46,7 +47,9 @@ public partial class SettingsViewModel : ObservableObject
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion) public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!; ? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
public string MemoryValueText => $"{(int)Math.Round(MemoryValue)} MB"; public string MemoryValueText => MemoryAuto
? $"{L.I["set.memory.auto"]} ({_services.Memory.BudgetMb} MB)"
: $"{(int)Math.Round(MemoryValue)} MB";
public string UsageText => _services.Memory.UsageText; public string UsageText => _services.Memory.UsageText;
public string ModelRoot => _services.Paths.ModelRoot; public string ModelRoot => _services.Paths.ModelRoot;
public string DataRoot => _services.Paths.DataRoot; public string DataRoot => _services.Paths.DataRoot;
@@ -69,6 +72,7 @@ public partial class SettingsViewModel : ObservableObject
var settings = _services.Settings.Current; var settings = _services.Settings.Current;
SelectedFps = settings.RenderFps; SelectedFps = settings.RenderFps;
MemoryValue = settings.MemoryMb; MemoryValue = settings.MemoryMb;
MemoryAuto = settings.MemoryAuto;
AutoUpdate = settings.AutoUpdateOnStartup; AutoUpdate = settings.AutoUpdateOnStartup;
Sources.Clear(); Sources.Clear();
@@ -133,6 +137,15 @@ public partial class SettingsViewModel : ObservableObject
OnPropertyChanged(nameof(UsageText)); OnPropertyChanged(nameof(UsageText));
} }
partial void OnMemoryAutoChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.MemoryAuto = value);
_services.Memory.ApplyAuto(value, (int)Math.Round(MemoryValue));
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand] [RelayCommand]
private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot); private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
@@ -160,6 +173,7 @@ public partial class SettingsViewModel : ObservableObject
internal void RemoveSource(SettingsSourceViewModel source) internal void RemoveSource(SettingsSourceViewModel source)
{ {
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model); _services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save(); _services.Settings.Save();
Sources.Remove(source); Sources.Remove(source);
@@ -184,6 +198,8 @@ public partial class SettingsSourceViewModel : ObservableObject
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name; public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url; public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url;
/// <summary>内置默认源不可删除。</summary>
public bool CanRemove => !Model.BuiltIn;
public bool Enabled public bool Enabled
{ {
@@ -32,7 +32,7 @@
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" /> <TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel> </StackPanel>
<Button Grid.Column="1" Classes="ghost small" Content="✕" <Button Grid.Column="1" Classes="ghost small" Content="✕"
Command="{Binding RemoveCommand}" VerticalAlignment="Center" /> IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
</Grid> </Grid>
</DataTemplate> </DataTemplate>
</ListBox.ItemTemplate> </ListBox.ItemTemplate>
@@ -5,27 +5,52 @@
Title="{loc:Loc app.name}" Title="{loc:Loc app.name}"
Width="1220" Height="800" Width="1220" Height="800"
MinWidth="1040" MinHeight="700" MinWidth="1040" MinHeight="700"
Background="{DynamicResource AppBg}" Background="Transparent"
TransparencyLevelHint="Transparent"
SystemDecorations="None"
WindowStartupLocation="CenterScreen"> WindowStartupLocation="CenterScreen">
<Grid ColumnDefinitions="236,*" RowDefinitions="*,Auto"> <!-- 禁用系统标题栏,改用自建标题栏。
窗口本身透明(四角露出桌面 => 圆角可见),内容 Border 自己不透明并
<!-- 侧栏 --> 用 CornerRadius + ClipToBounds 裁出圆角;AcrylicBlur 会引入系统白色,
<Border Grid.Column="0" Grid.RowSpan="2" Background="{DynamicResource SideBg}"> 所以这里用纯 Transparent 避免白边。 -->
<Grid RowDefinitions="Auto,*,Auto" Margin="16,22,16,18"> <Border CornerRadius="16" ClipToBounds="True"
Background="{DynamicResource AppBg}"
<StackPanel Orientation="Horizontal" Spacing="11"> BorderBrush="#1B2740" BorderThickness="1"
<Border Width="38" Height="38" CornerRadius="12" Background="#1C2C4C"> BoxShadow="0 18 50 0 #400A1226">
<TextBlock Text="◎" FontSize="20" Foreground="#8FB6FF" <Grid RowDefinitions="44,*">
<!-- 自建标题栏 -->
<Border x:Name="TitleBar" Grid.Row="0" Background="{DynamicResource TitleBarBg}"
PointerPressed="OnTitleBarPointerPressed">
<Grid ColumnDefinitions="*,Auto,Auto" Margin="16,0,8,0">
<StackPanel Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
<Border Width="22" Height="22" CornerRadius="7" Background="#1C2C4C">
<TextBlock Text="◎" FontSize="13" Foreground="#8FB6FF"
HorizontalAlignment="Center" VerticalAlignment="Center" /> HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border> </Border>
<StackPanel VerticalAlignment="Center" Spacing="1"> <TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="12.5"
<TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="13.5" FontWeight="SemiBold" /> FontWeight="SemiBold" VerticalAlignment="Center" />
<TextBlock Text="{loc:Loc app.tagline}" Foreground="#7C90B4" FontSize="10" />
</StackPanel> </StackPanel>
<Button x:Name="MinimizeButton" Grid.Column="1" Classes="titlebtn"
Content="—" Click="OnMinimizeClick" />
<Button x:Name="CloseButton" Grid.Column="2" Classes="titlebtn close"
Content="✕" Click="OnCloseClick" />
</Grid>
</Border>
<!-- 原内容整体下移一行 -->
<Grid Grid.Row="1" ColumnDefinitions="236,*" RowDefinitions="*,Auto">
<!-- 侧栏:品牌已在标题栏展示,这里只留一句副标题,避免重复 -->
<Border Grid.Column="0" Grid.RowSpan="2" Background="{DynamicResource SideBgBrush}">
<Grid RowDefinitions="Auto,*,Auto" Margin="16,20,16,18">
<StackPanel Spacing="3" Margin="2,0,0,0">
<TextBlock Text="{loc:Loc app.tagline}" Foreground="#7C90B4" FontSize="10.5"
TextWrapping="Wrap" />
</StackPanel> </StackPanel>
<StackPanel Grid.Row="1" Margin="0,30,0,0" Spacing="6"> <StackPanel Grid.Row="1" Margin="0,26,0,0" Spacing="6">
<TextBlock Text="MENU" Foreground="#4C5F80" FontSize="9.5" FontWeight="SemiBold" Margin="14,0,0,4" /> <TextBlock Text="MENU" Foreground="#4C5F80" FontSize="9.5" FontWeight="SemiBold" Margin="14,0,0,4" />
<Button Classes="nav" Classes.active="{Binding IsHomeActive}" <Button Classes="nav" Classes.active="{Binding IsHomeActive}"
Command="{Binding GoHomeCommand}" Content="{loc:Loc nav.home}" /> Command="{Binding GoHomeCommand}" Content="{loc:Loc nav.home}" />
@@ -71,4 +96,6 @@
</Grid> </Grid>
</Border> </Border>
</Grid> </Grid>
</Grid>
</Border>
</Window> </Window>
@@ -8,6 +8,7 @@ using Avalonia.Animation.Easings;
using Avalonia.Threading; using Avalonia.Threading;
using System.Linq; using System.Linq;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using EarthModelStudio.Models; using EarthModelStudio.Models;
using EarthModelStudio.Services; using EarthModelStudio.Services;
@@ -144,6 +145,35 @@ public partial class MainWindow : Window
window.Activate(); window.Activate();
} }
// ---- 自建标题栏 ------------------------------------------------------
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
{
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
BeginMoveDrag(e);
}
private void OnMinimizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
=> WindowState = WindowState.Minimized;
// 关闭动画:先淡出再真正 Close(第 4 项)
private async void OnCloseClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
{
if (_isClosing) return;
Opacity = 1;
Transitions = new Transitions
{
new DoubleTransition
{
Property = OpacityProperty,
Duration = TimeSpan.FromMilliseconds(180),
Easing = new CubicEaseIn()
}
};
Opacity = 0;
await Task.Delay(190);
Close();
}
private void OnClosed(object? sender, EventArgs e) private void OnClosed(object? sender, EventArgs e)
{ {
_isClosing = true; _isClosing = true;
@@ -2,6 +2,7 @@ using System;
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Input; using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media; using Avalonia.Media;
using System.Collections.Generic; using System.Collections.Generic;
using EarthModelStudio.Models; using EarthModelStudio.Models;
@@ -28,12 +29,65 @@ public sealed class PlayerWindow : Window
MinHeight = 680; MinHeight = 680;
Background = new SolidColorBrush(Color.Parse("#05070F")); Background = new SolidColorBrush(Color.Parse("#05070F"));
WindowStartupLocation = WindowStartupLocation.CenterOwner; WindowStartupLocation = WindowStartupLocation.CenterOwner;
Content = model.View; // 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
var titleBar = new Border
{
Height = 34,
Background = new SolidColorBrush(Color.Parse("#0A1120")),
Child = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
Children =
{
new TextBlock
{
Text = package.LocalizedName,
Foreground = new SolidColorBrush(Color.Parse("#A9B8D4")),
FontSize = 11.5,
Margin = new Thickness(14, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
[Grid.ColumnProperty] = 0
},
new Button
{
Content = "✕",
Width = 40,
Height = 28,
Background = Brushes.Transparent,
Foreground = new SolidColorBrush(Color.Parse("#A9B8D4")),
BorderThickness = new Thickness(0),
FontSize = 13,
CornerRadius = new CornerRadius(7),
Margin = new Thickness(0, 0, 8, 0),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
[Grid.ColumnProperty] = 1
}
}
}
};
titleBar.PointerPressed += OnTitleBarPointerPressed;
if (titleBar.Child is Grid g)
foreach (var child in g.Children)
if (child is Button b) b.Click += (_, _) => Close();
Content = new DockPanel { LastChildFill = true };
DockPanel.SetDock(titleBar, Dock.Top);
((DockPanel)Content).Children.Add(titleBar);
((DockPanel)Content).Children.Add(model.View);
KeyDown += OnKeyDown; KeyDown += OnKeyDown;
Closed += OnClosed; Closed += OnClosed;
} }
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
{
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
BeginMoveDrag(e);
}
private void OnKeyDown(object? sender, KeyEventArgs e) private void OnKeyDown(object? sender, KeyEventArgs e)
{ {
switch (e.Key) switch (e.Key)
@@ -50,7 +50,10 @@
Foreground="{DynamicResource Accent}" VerticalAlignment="Center" /> Foreground="{DynamicResource Accent}" VerticalAlignment="Center" />
</Grid> </Grid>
<TextBlock Classes="muted" Text="{loc:Loc set.memory.desc}" TextWrapping="Wrap" /> <TextBlock Classes="muted" Text="{loc:Loc set.memory.desc}" TextWrapping="Wrap" />
<CheckBox Content="{loc:Loc set.memory.auto}" IsChecked="{Binding MemoryAuto}"
Margin="0,2,0,0" />
<Slider Minimum="512" Maximum="8192" TickFrequency="256" IsSnapToTickEnabled="False" <Slider Minimum="512" Maximum="8192" TickFrequency="256" IsSnapToTickEnabled="False"
IsEnabled="{Binding !MemoryAuto}"
Value="{Binding MemoryValue}" Margin="0,4,0,0" /> Value="{Binding MemoryValue}" Margin="0,4,0,0" />
<Grid ColumnDefinitions="*,Auto"> <Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="faint" Text="{loc:Loc set.memory.hint}" TextWrapping="Wrap" /> <TextBlock Classes="faint" Text="{loc:Loc set.memory.hint}" TextWrapping="Wrap" />
@@ -75,7 +78,7 @@
<TextBlock Text="{Binding UrlText}" Classes="faint" TextTrimming="CharacterEllipsis" MaxWidth="520" /> <TextBlock Text="{Binding UrlText}" Classes="faint" TextTrimming="CharacterEllipsis" MaxWidth="520" />
</StackPanel> </StackPanel>
<Button Grid.Column="2" Classes="ghost small" Content="✕" <Button Grid.Column="2" Classes="ghost small" Content="✕"
Command="{Binding RemoveCommand}" VerticalAlignment="Center" /> IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
</Grid> </Grid>
</Border> </Border>
</DataTemplate> </DataTemplate>
@@ -143,14 +146,6 @@
<TextBlock Classes="h3" Text="{loc:Loc set.version}" /> <TextBlock Classes="h3" Text="{loc:Loc set.version}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}" /> <TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}" />
</Grid> </Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.platform}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding PlatformText}" TextWrapping="Wrap" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.modelFormat}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.modelFormat.desc}" TextWrapping="Wrap" />
</Grid>
<Grid ColumnDefinitions="200,*"> <Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.license}" /> <TextBlock Classes="h3" Text="{loc:Loc set.license}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.licenseValue}" /> <TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.licenseValue}" />
+11 -11
View File
@@ -1,30 +1,30 @@
{ {
"schema": 1, "schema": 1,
"generated": "2026-11-07T10:46:02Z", "generated": "2026-11-07T12:01:09Z",
"repository": "https://gitcode.com/2509_92447106/GC", "repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main", "branch": "main",
"modelDir": "model", "modelDir": "model",
"launcher": { "launcher": {
"version": "1.0.0", "version": "1.0.1",
"revision": "0d59eff631", "revision": "ba909d4dc3",
"packages": { "packages": {
"win-x64": { "win-x64": {
"path": "dist/GC-win-x64.zip", "path": "dist/GC-win-x64.zip",
"url": "", "url": "",
"sha256": "7bfb1cfab07934642eff4c52078a8f5f034f1d2432a7613f04674403c70f2b6d", "sha256": "2704fbc3e3acba5630a13a313af0eca45128827ed90e4718fd143a554ca70c3c",
"size": 78755039 "size": 39379924
}, },
"win-arm64": { "win-arm64": {
"path": "dist/GC-win-arm64.zip", "path": "dist/GC-win-arm64.zip",
"url": "", "url": "",
"sha256": "9fddf07fa18cbdb368e37204cfb96f5828207e5fe74ecb31fa66b61fa400fd1c", "sha256": "c8f69370b9e381418a6568aca11cac44cb034e0ab2a99f7e14fcbef1dc503a44",
"size": 75360988 "size": 37684316
}, },
"osx-arm64": { "osx-arm64": {
"path": "dist/GC-osx-arm64.zip", "path": "dist/GC-osx-arm64.zip",
"url": "", "url": "",
"sha256": "3517548b598eda62c92d873528f39e305c52c6fb246fa5ba5f3613f8b8cb315a", "sha256": "8588892dcfb982b7b52c3d74f3493fd8f27a327a0571095ab62dd4130857e082",
"size": 39847910 "size": 39852236
}, },
"osx-x64": { "osx-x64": {
"path": "dist/GC-osx-x64.zip", "path": "dist/GC-osx-x64.zip",
@@ -39,12 +39,12 @@
"models": [ "models": [
{ {
"id": "earth-revolution", "id": "earth-revolution",
"version": "1.0-0a73a257ec", "version": "1.0-7380e0cff3",
"dir": "model/earth-revolution" "dir": "model/earth-revolution"
}, },
{ {
"id": "earth-rotation", "id": "earth-rotation",
"version": "1.0-6c97454f58", "version": "1.0-c74907bbce",
"dir": "model/earth-rotation" "dir": "model/earth-rotation"
} }
] ]