This commit is contained in:
2509_92447106 committed 2026-11-07 16:05:56 +08:00
commit 60113ab76e
81 files changed
+8520

No files matched your search

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>NeoRF.EarthModels</RootNamespace>
<AssemblyName>EarthModelPreview</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<!-- 直接编译共享引擎源码:封面必须由模型自己的渲染器画 -->
<Compile Include="../src/**/*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" />
</ItemGroup>
</Project>
+113
View File
@@ -0,0 +1,113 @@
using System;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Media.Imaging;
using NeoRF.EarthModels;
namespace NeoRF.EarthModels.Preview;
/// <summary>
/// 封面生成工具:用模型自己的渲染器给每个模型画一张封面 preview.png。
/// 封面在模型包里,启动器只负责显示 —— 所以公转模型的封面一定就是公转场景。
/// 用法:dotnet run --project model-src/tools/PreviewGen -- &lt;仓库根&gt;
/// </summary>
internal static class Program
{
private const int Width = 768;
private const int Height = 316;
[STAThread]
public static int Main(string[] args)
{
var root = args.Length > 0 ? args[0] : Directory.GetCurrentDirectory();
var modelRoot = Path.Combine(root, "model");
if (!Directory.Exists(modelRoot))
{
Console.Error.WriteLine($"找不到模型库: {modelRoot}");
return 1;
}
var bench = args.Contains("--bench");
AppBuilder.Configure<Application>()
.UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting();
foreach (var modelDir in Directory.GetDirectories(modelRoot))
{
var id = Path.GetFileName(modelDir);
if (id.StartsWith(".")) continue;
var dataDir = Path.Combine(modelDir, id + ".model");
var sceneFile = Path.Combine(dataDir, "scene.json");
if (!File.Exists(sceneFile)) continue;
var runtime = SceneRuntime.Load(dataDir, 2048);
var texts = ModelStrings.Load(dataDir, "zh-CN");
var revolution = string.Equals(runtime.Scene.DefaultView, "revolution", StringComparison.OrdinalIgnoreCase);
var view = new CelestialView
{
Scene = runtime,
Texts = texts,
View = revolution ? SceneView.Revolution : SceneView.Rotation,
IsPlaying = false,
ShowHud = false,
ShowLabels = false,
ShowOrbit = true,
ShowGraticule = true,
Width = Width,
Height = Height
};
view.Measure(new Size(Width, Height));
view.Arrange(new Rect(0, 0, Width, Height));
view.JumpToOrbit(revolution ? 45 : 0);
view.JumpToSpin(20);
if (bench)
{
// 真实窗口尺寸下的帧耗时
view.Width = 1240;
view.Height = 820;
view.Measure(new Size(1240, 820));
view.Arrange(new Rect(0, 0, 1240, 820));
// 模拟播放态(运动时降分辨率),分别测静止高清帧与运动帧
var animField = typeof(NeoRF.EarthModels.CelestialView)
.GetField("_animating", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var sw = System.Diagnostics.Stopwatch.StartNew();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
var still = sw.Elapsed.TotalMilliseconds / 20;
animField?.SetValue(view, true);
sw.Restart();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
Console.WriteLine($"{id}: 静止 {still:0.0} ms/frame · 播放 {sw.Elapsed.TotalMilliseconds / 20:0.0} ms/frame");
continue;
}
var outFile = Path.Combine(dataDir, "preview.png");
using (var bitmap = new RenderTargetBitmap(new PixelSize(Width, Height), new Vector(96, 96)))
{
bitmap.Render(view);
bitmap.Save(outFile);
}
Console.WriteLine($"preview -> {outFile}");
}
return 0;
}
}
File diff suppressed because it is too large. Load diff
+560
View File
@@ -0,0 +1,560 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels;
/// <summary>
/// 模型自己的界面:画布 + 工具栏 + 速度条 + 教学要点。
/// 带过渡动画、缩放控件与「暂停后可拖动」提示;启动器只负责开窗口。
/// </summary>
public sealed class EarthModelView : UserControl
{
private static readonly IBrush PanelBg = new SolidColorBrush(Color.Parse("#C40A1020"));
private static readonly IBrush ControlBg = new SolidColorBrush(Color.Parse("#16233C"));
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#2E6BE6"));
private static readonly IBrush TitleBrush = new SolidColorBrush(Color.Parse("#F2F6FF"));
private static readonly IBrush TextBrush = new SolidColorBrush(Color.Parse("#DCE7FA"));
private static readonly IBrush MutedBrush = new SolidColorBrush(Color.Parse("#7E93B8"));
private static readonly IBrush FaintBrush = new SolidColorBrush(Color.Parse("#61779C"));
private static readonly IBrush BodyBrush = new SolidColorBrush(Color.Parse("#8CA0C4"));
private static readonly TimeSpan HoverDuration = TimeSpan.FromMilliseconds(120);
private static readonly TimeSpan PanelDuration = TimeSpan.FromMilliseconds(190);
private readonly IModelContext _context;
private readonly ModelStrings _texts;
private readonly SceneRuntime _runtime;
private readonly List<string> _views;
private readonly List<ModelButton> _viewButtons = new();
private readonly CelestialView _canvas;
private Border? _viewSwitch;
private StackPanel? _seasonPanel;
private Border? _lessons;
private ModelButton? _playButton;
private TextBlock? _zoomText;
private bool _playing = true;
private bool _labels = true;
private bool _orbit = true;
private bool _grid = true;
private bool _tilt;
private bool _showLessons = true;
public EarthModelView(IModelContext context, SceneRuntime runtime)
{
_context = context;
_runtime = runtime;
_texts = ModelStrings.Load(context.DataDirectory, context.Language);
_views = ResolveViews(runtime.Scene);
Background = new SolidColorBrush(Color.Parse("#05070F"));
_canvas = new CelestialView
{
Scene = runtime,
Texts = _texts,
ShowLabels = true,
ShowOrbit = true,
ShowGraticule = true,
FrameRate = 60,
View = IsRevolution ? SceneView.Revolution : SceneView.Rotation
};
_canvas.JumpToOrbit(StartAngle);
_canvas.JumpToSpin(20);
_canvas.ZoomChanged += zoom =>
{
if (_zoomText != null) _zoomText.Text = $"{zoom * 100:0}%";
};
var root = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto") };
var top = BuildTopBar();
root.Children.Add(top);
var stage = new Grid();
stage.Children.Add(_canvas);
_lessons = BuildLessonsPanel();
stage.Children.Add(_lessons);
Grid.SetRow(stage, 1);
root.Children.Add(stage);
var bottom = BuildBottomBar();
Grid.SetRow(bottom, 2);
root.Children.Add(bottom);
Content = root;
ApplyVisibility();
// 打开时整窗淡入,避免“啪”地出现
Opacity = 0;
Transitions = new Transitions
{
new DoubleTransition
{
Property = OpacityProperty,
Duration = TimeSpan.FromMilliseconds(260),
Easing = new CubicEaseOut()
}
};
AttachedToVisualTree += (_, _) => Opacity = 1;
}
private string CurrentView { get; set; } = "rotation";
private double StartAngle => IsRevolution ? 60 : 0;
private bool IsRevolution => string.Equals(CurrentView, "revolution", StringComparison.OrdinalIgnoreCase);
private bool HasViewSwitch => _views.Count > 1;
private static string NormalizeView(string? view)
=> string.Equals(view, "revolution", StringComparison.OrdinalIgnoreCase) ? "revolution" : "rotation";
private List<string> ResolveViews(SceneDefinition scene)
{
var list = new List<string>();
foreach (var v in scene.Views)
{
var normalized = NormalizeView(v);
if (!list.Contains(normalized)) list.Add(normalized);
}
if (list.Count == 0) list.Add(NormalizeView(scene.DefaultView));
CurrentView = list[0];
return list;
}
// ---------------------------------------------------------------- 顶部
private Control BuildTopBar()
{
var close = MakeButton(_texts["close"], () => _context.RequestClose());
var title = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center };
title.Children.Add(new TextBlock
{
Text = _texts.Pick(_runtime.Scene.NameI18n, _texts["title"]),
Foreground = TitleBrush,
FontSize = 13,
FontWeight = FontWeight.SemiBold
});
title.Children.Add(new TextBlock
{
Text = _texts.Pick(_runtime.Scene.DescriptionI18n, ""),
Foreground = MutedBrush,
FontSize = 10.5,
MaxWidth = 330,
TextTrimming = TextTrimming.CharacterEllipsis
});
var switchPanel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };
switchPanel.Children.Add(MakeViewButton("rotation", _texts["view.rotation"]));
switchPanel.Children.Add(MakeViewButton("revolution", _texts["view.revolution"]));
_viewSwitch = new Border
{
Background = ControlBg,
CornerRadius = new CornerRadius(10),
Padding = new Thickness(3),
Margin = new Thickness(16, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
Child = switchPanel
};
var actions = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 7,
VerticalAlignment = VerticalAlignment.Center
};
// 缩放:− / 百分比 / + / 复位
actions.Children.Add(MakeButton("−", () => _canvas.ZoomBy(1 / 1.25), compact: true));
_zoomText = new TextBlock
{
Text = "100%",
Foreground = TextBrush,
FontSize = 11,
Width = 38,
VerticalAlignment = VerticalAlignment.Center,
TextAlignment = TextAlignment.Center
};
actions.Children.Add(_zoomText);
actions.Children.Add(MakeButton("+", () => _canvas.ZoomBy(1.25), compact: true));
actions.Children.Add(MakeButton("⟲", () =>
{
_canvas.ResetView();
_canvas.JumpToOrbit(StartAngle);
_canvas.JumpToSpin(20);
}, compact: true));
_playButton = MakeButton(_texts["pause"], TogglePlay);
actions.Children.Add(_playButton);
actions.Children.Add(MakeButton(_texts["reset"], () =>
{
_canvas.ResetAnimation();
_canvas.JumpToOrbit(StartAngle);
}));
actions.Children.Add(MakeToggle(_texts["labels"], _labels, on => { _labels = on; _canvas.ShowLabels = on; }));
actions.Children.Add(MakeToggle(_texts["orbit"], _orbit, on => { _orbit = on; _canvas.ShowOrbit = on; }));
actions.Children.Add(MakeToggle(_texts["grid"], _grid, on => { _grid = on; _canvas.ShowGraticule = on; }));
actions.Children.Add(MakeToggle(_texts["tilt"], _tilt, on => { _tilt = on; _canvas.ExaggerateTilt = on; }));
actions.Children.Add(MakeButton(_texts["lessons"], () => SetLessonsVisible(!_showLessons)));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") };
grid.Children.Add(close);
Grid.SetColumn(title, 1);
title.Margin = new Thickness(14, 0, 0, 0);
grid.Children.Add(title);
Grid.SetColumn(_viewSwitch, 2);
grid.Children.Add(_viewSwitch);
Grid.SetColumn(actions, 4);
grid.Children.Add(actions);
return new Border { Background = PanelBg, Padding = new Thickness(16, 11), Child = grid };
}
private ModelButton MakeViewButton(string view, string label)
{
var button = MakeButton(label, () => SwitchView(view));
button.SetBase(string.Equals(CurrentView, view, StringComparison.OrdinalIgnoreCase) ? Accent : ControlBg);
button.Tag = view;
button.IsVisible = _views.Contains(view);
_viewButtons.Add(button);
return button;
}
private ModelButton MakeToggle(string label, bool initial, Action<bool> changed)
{
var state = initial;
ModelButton? button = null;
button = MakeButton(label, () =>
{
state = !state;
changed(state);
button?.SetBase(state ? Accent : ControlBg);
});
button.SetBase(initial ? Accent : ControlBg);
return button;
}
private void SwitchView(string view)
{
CurrentView = NormalizeView(view);
_canvas.View = IsRevolution ? SceneView.Revolution : SceneView.Rotation;
_canvas.JumpToOrbit(StartAngle);
foreach (var button in _viewButtons)
button.SetBase(string.Equals(button.Tag as string, CurrentView, StringComparison.OrdinalIgnoreCase)
? Accent
: ControlBg);
ApplyVisibility();
}
// ---------------------------------------------------------------- 底部
private Control BuildBottomBar()
{
var speedLabel = new TextBlock
{
Text = _texts["speed"],
Foreground = new SolidColorBrush(Color.Parse("#9DB0D0")),
VerticalAlignment = VerticalAlignment.Center
};
var slider = new Slider
{
Minimum = 0.25,
Maximum = 4,
Value = 1,
Margin = new Thickness(12, 0, 0, 0),
Width = 180
};
var speedText = new TextBlock
{
Text = "1×",
Foreground = TextBrush,
VerticalAlignment = VerticalAlignment.Center,
Width = 46,
Margin = new Thickness(6, 0, 0, 0)
};
slider.ValueChanged += (_, e) =>
{
_canvas.Speed = e.NewValue;
speedText.Text = $"{e.NewValue:0.##}×";
};
var hint = new TextBlock
{
Text = _texts["hint"],
Foreground = FaintBrush,
FontSize = 10.5,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(22, 0, 0, 0),
TextTrimming = TextTrimming.CharacterEllipsis
};
_seasonPanel = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 6,
VerticalAlignment = VerticalAlignment.Center
};
_seasonPanel.Children.Add(new TextBlock
{
Text = _texts["seasons"],
Foreground = MutedBrush,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0)
});
_seasonPanel.Children.Add(MakeSeasonButton(0));
_seasonPanel.Children.Add(MakeSeasonButton(90));
_seasonPanel.Children.Add(MakeSeasonButton(180));
_seasonPanel.Children.Add(MakeSeasonButton(270));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") };
grid.Children.Add(speedLabel);
Grid.SetColumn(slider, 1);
grid.Children.Add(slider);
Grid.SetColumn(speedText, 2);
grid.Children.Add(speedText);
Grid.SetColumn(hint, 3);
grid.Children.Add(hint);
Grid.SetColumn(_seasonPanel, 4);
grid.Children.Add(_seasonPanel);
return new Border { Background = PanelBg, Padding = new Thickness(16, 10), Child = grid };
}
private ModelButton MakeSeasonButton(double angle)
{
var key = angle switch
{
0 => "season.springEquinox",
90 => "season.summerSolstice",
180 => "season.autumnEquinox",
_ => "season.winterSolstice"
};
return MakeButton(_texts[key], () =>
{
if (!IsRevolution) SwitchView("revolution");
_canvas.JumpToOrbit(angle);
});
}
// ---------------------------------------------------------------- 教学要点
private Border BuildLessonsPanel()
{
var header = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
header.Children.Add(new TextBlock
{
Text = _texts["lessons"],
Foreground = TitleBrush,
FontWeight = FontWeight.SemiBold,
FontSize = 12.5,
VerticalAlignment = VerticalAlignment.Center
});
var close = MakeButton("✕", () => SetLessonsVisible(false));
close.SetBase(Brushes.Transparent);
Grid.SetColumn(close, 1);
header.Children.Add(close);
var list = new StackPanel { Spacing = 2 };
foreach (var lesson in _runtime.Scene.Lessons)
{
var title = new TextBlock
{
Text = _texts.Pick(lesson.TitleI18n, ""),
Foreground = new SolidColorBrush(Color.Parse("#CFE0FF")),
FontSize = 12,
FontWeight = FontWeight.SemiBold,
TextWrapping = TextWrapping.Wrap
};
var body = new TextBlock
{
Text = _texts.Pick(lesson.BodyI18n, ""),
Foreground = BodyBrush,
FontSize = 11,
TextWrapping = TextWrapping.Wrap
};
var stack = new StackPanel { Spacing = 3 };
stack.Children.Add(title);
stack.Children.Add(body);
var button = new Button
{
Content = stack,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left,
Padding = new Thickness(8, 7),
Margin = new Thickness(0, 1),
Cursor = new Cursor(StandardCursorType.Hand),
Transitions = new Transitions
{
new BrushTransition { Property = BackgroundProperty, Duration = HoverDuration }
}
};
var captured = lesson;
button.Click += (_, _) => ApplyLesson(captured);
button.PointerEntered += (_, _) => button.Background = new SolidColorBrush(Color.Parse("#1B2A47"));
button.PointerExited += (_, _) => button.Background = Brushes.Transparent;
list.Children.Add(button);
}
var content = new StackPanel { Spacing = 8 };
content.Children.Add(header);
content.Children.Add(new ScrollViewer
{
Content = list,
MaxHeight = 380,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto
});
var panel = new Border
{
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Center,
Width = 272,
Margin = new Thickness(0, 58, 16, 80),
Background = new SolidColorBrush(Color.Parse("#D00B1226")),
CornerRadius = new CornerRadius(14),
Padding = new Thickness(13),
BorderBrush = new SolidColorBrush(Color.Parse("#26374F")),
BorderThickness = new Thickness(1),
Child = content,
RenderTransform = new TranslateTransform(0, 0)
};
panel.Transitions = new Transitions
{
new DoubleTransition { Property = OpacityProperty, Duration = PanelDuration, Easing = new CubicEaseOut() },
new DoubleTransition
{
Property = TranslateTransform.XProperty,
Duration = PanelDuration,
Easing = new CubicEaseOut()
}
};
return panel;
}
private void SetLessonsVisible(bool visible)
{
_showLessons = visible;
if (_lessons == null) return;
if (visible)
{
_lessons.IsVisible = true;
_lessons.Opacity = 1;
if (_lessons.RenderTransform is TranslateTransform transform) transform.X = 0;
return;
}
_lessons.Opacity = 0;
if (_lessons.RenderTransform is TranslateTransform hidden) hidden.X = 26;
var timer = new DispatcherTimer { Interval = PanelDuration };
timer.Tick += (_, _) =>
{
timer.Stop();
if (!_showLessons && _lessons != null) _lessons.IsVisible = false;
};
timer.Start();
}
private void ApplyLesson(Lesson lesson)
{
if (!string.IsNullOrWhiteSpace(lesson.View))
{
var view = NormalizeView(lesson.View);
if (!string.Equals(view, CurrentView, StringComparison.OrdinalIgnoreCase)) SwitchView(view);
}
if (lesson.AngleDeg.HasValue) _canvas.JumpToOrbit(lesson.AngleDeg.Value);
}
// ---------------------------------------------------------------- 工具
private ModelButton MakeButton(string text, Action onClick, bool compact = false)
{
var button = new ModelButton
{
Content = new TextBlock { Text = text, FontSize = 11.5 },
Foreground = TextBrush,
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(8),
Padding = compact ? new Thickness(8, 4) : new Thickness(9, 5),
MinWidth = compact ? 26 : 0,
VerticalAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand)
};
button.SetBase(ControlBg);
button.Click += (_, _) => onClick();
return button;
}
private void TogglePlay()
{
_playing = !_playing;
_canvas.IsPlaying = _playing;
if (_playButton?.Content is TextBlock block)
block.Text = _playing ? _texts["pause"] : _texts["play"];
}
private void ApplyVisibility()
{
if (_viewSwitch != null) _viewSwitch.IsVisible = HasViewSwitch;
if (_lessons != null) _lessons.IsVisible = _showLessons;
if (_seasonPanel != null) _seasonPanel.IsVisible = IsRevolution;
}
/// <summary>带悬停过渡的按钮:本地基础色 + 悬停提亮。</summary>
private sealed class ModelButton : Button
{
private IBrush _base = ControlBg;
private IBrush _hover = ControlBg;
public ModelButton()
{
Transitions = new Transitions
{
new BrushTransition { Property = BackgroundProperty, Duration = HoverDuration }
};
}
public void SetBase(IBrush brush)
{
_base = brush;
_hover = Lighten(brush);
Background = brush;
}
protected override void OnPointerEntered(PointerEventArgs e)
{
base.OnPointerEntered(e);
Background = _hover;
}
protected override void OnPointerExited(PointerEventArgs e)
{
base.OnPointerExited(e);
Background = _base;
}
private static IBrush Lighten(IBrush brush)
{
if (brush is not SolidColorBrush solid) return brush;
var c = solid.Color;
return new SolidColorBrush(Color.FromArgb(c.A,
(byte)Math.Min(255, c.R + 26),
(byte)Math.Min(255, c.G + 26),
(byte)Math.Min(255, c.B + 30)));
}
}
}
+37
View File
@@ -0,0 +1,37 @@
using System;
using Avalonia.Controls;
using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels;
/// <summary>
/// 地球模型共享运行时:读自己目录下的 scene.json / land.json / i18n,
/// 然后把自带界面交给启动器。启动器完全不知道“地球”“节气”这些东西。
/// </summary>
public sealed class EarthModelRuntime : IModelRuntime
{
public const int SupportedApiVersion = 1;
private SceneRuntime? _scene;
/// <summary>后台准备:读场景、生成地表纹理(耗时都花在这里,进度条能实时走)。</summary>
public void Prepare(IModelContext context)
{
context.ReportProgress(0.03, "读取场景数据");
_scene = SceneRuntime.Load(context.DataDirectory, context.MemoryBudgetMb, context.ReportProgress);
context.Log($"[{context.ModelId}] 场景已加载:{_scene.Scene.DefaultView}," +
$"地表纹理 {(_scene.Texture == null ? "无" : _scene.Texture.Width + "×" + _scene.Texture.Height)}");
}
/// <summary>UI 线程构建界面(很快)。</summary>
public Control CreateView(IModelContext context)
{
context.ReportProgress(0.78, "构建界面");
_scene ??= SceneRuntime.Load(context.DataDirectory, context.MemoryBudgetMb, context.ReportProgress);
var view = new EarthModelView(context, _scene);
context.ReportProgress(1.0, "准备就绪");
return view;
}
public void Dispose() => GC.SuppressFinalize(this);
}
+159
View File
@@ -0,0 +1,159 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NeoRF.EarthModels;
/// <summary>&lt;id&gt;.model/land.json —— 简化的大陆轮廓(经纬度多边形)。</summary>
public sealed class LandData
{
[JsonPropertyName("polygons")] public List<LandPolygon> Polygons { get; set; } = new();
public static LandData? Load(string path)
{
if (!File.Exists(path)) return null;
try
{
return JsonSerializer.Deserialize<LandData>(File.ReadAllText(path), ModelJson.Options);
}
catch (Exception ex)
{
Console.Error.WriteLine($"解析地表数据失败 {path}: {ex.Message}");
return null;
}
}
}
public sealed class LandPolygon
{
[JsonPropertyName("name")] public string? Name { get; set; }
/// <summary>[[lon, lat], ...]</summary>
[JsonPropertyName("points")] public List<double[]> Points { get; set; } = new();
}
/// <summary>
/// 等经纬度栅格地表掩膜(0=海洋 255=陆地),双线性采样。
/// 每个模型只生成一次,受内存预算约束。
/// </summary>
public sealed class LandMask
{
public int Width { get; init; }
public int Height { get; init; }
public byte[] Bits { get; init; } = Array.Empty<byte>();
public long ByteSize => Bits.LongLength;
public static LandMask Build(LandData data, int width = 1440, int height = 720)
{
var bits = new byte[width * height];
foreach (var poly in data.Polygons)
{
if (poly.Points.Count < 3) continue;
var pts = Unwrap(poly.Points);
if (pts.Count < 3) continue;
for (var shift = -1; shift <= 1; shift++)
Rasterize(bits, width, height, pts, shift * 360.0);
}
return new LandMask { Width = width, Height = height, Bits = bits };
}
private static List<(double Lon, double Lat)> Unwrap(List<double[]> points)
{
var result = new List<(double, double)>(points.Count);
if (points.Count == 0 || points[0].Length < 2) return result;
var prev = points[0][0];
result.Add((prev, points[0][1]));
for (var i = 1; i < points.Count; i++)
{
if (points[i].Length < 2) continue;
var lon = points[i][0];
while (lon - prev > 180) lon -= 360;
while (prev - lon > 180) lon += 360;
result.Add((lon, points[i][1]));
prev = lon;
}
return result;
}
private static void Rasterize(byte[] bits, int w, int h, List<(double Lon, double Lat)> pts, double lonShift)
{
var n = pts.Count;
var xs = new double[n];
var ys = new double[n];
double minY = double.MaxValue, maxY = double.MinValue;
for (var i = 0; i < n; i++)
{
xs[i] = (pts[i].Lon + lonShift + 180.0) / 360.0 * w;
ys[i] = (90.0 - pts[i].Lat) / 180.0 * h;
if (ys[i] < minY) minY = ys[i];
if (ys[i] > maxY) maxY = ys[i];
}
var y0 = Math.Max(0, (int)Math.Floor(minY));
var y1 = Math.Min(h - 1, (int)Math.Ceiling(maxY));
var crossings = new List<double>(16);
for (var y = y0; y <= y1; y++)
{
var sy = y + 0.5;
crossings.Clear();
for (var i = 0; i < n; i++)
{
var j = (i + 1) % n;
double ya = ys[i], yb = ys[j];
if (!((ya <= sy && yb > sy) || (yb <= sy && ya > sy))) continue;
var t = (sy - ya) / (yb - ya);
crossings.Add(xs[i] + t * (xs[j] - xs[i]));
}
if (crossings.Count < 2) continue;
crossings.Sort();
for (var k = 0; k + 1 < crossings.Count; k += 2)
{
var xa = (int)Math.Ceiling(crossings[k] - 0.5);
var xb = (int)Math.Floor(crossings[k + 1] - 0.5);
if (xb < xa) continue;
if (xb - xa >= w - 1)
{
for (var x = 0; x < w; x++) bits[y * w + x] = 255;
continue;
}
for (var x = xa; x <= xb; x++)
{
var mx = x % w;
if (mx < 0) mx += w;
bits[y * w + mx] = 255;
}
}
}
}
/// <summary>返回 0..1 的陆地覆盖度。</summary>
public double Sample(double lonDeg, double latDeg)
{
var u = (lonDeg + 180.0) / 360.0 * Width - 0.5;
var v = (90.0 - latDeg) / 180.0 * Height - 0.5;
var x0 = (int)Math.Floor(u);
var y0 = (int)Math.Floor(v);
var fx = u - x0;
var fy = v - y0;
double sum = 0;
for (var dy = 0; dy < 2; dy++)
{
var y = y0 + dy;
if (y < 0) y = 0;
if (y >= Height) y = Height - 1;
var wy = dy == 0 ? 1 - fy : fy;
for (var dx = 0; dx < 2; dx++)
{
var x = x0 + dx;
var mx = x % Width;
if (mx < 0) mx += Width;
var wx = dx == 0 ? 1 - fx : fx;
sum += Bits[y * Width + mx] * wx * wy;
}
}
return sum / 255.0;
}
}
+27
View File
@@ -0,0 +1,27 @@
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NeoRF.EarthModels;
/// <summary>模型自己的 JSON 读写(不依赖启动器)。</summary>
public static class ModelJson
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
public static T? Read<T>(string path)
{
if (!File.Exists(path)) return default;
return JsonSerializer.Deserialize<T>(File.ReadAllText(path), Options);
}
}
+182
View File
@@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.Json;
namespace NeoRF.EarthModels;
/// <summary>
/// 模型自己的一份文案。优先读模型数据目录里的 <c>i18n/&lt;language&gt;.json</c>,
/// 缺失时回退到代码内的默认文案,保证模型在没有语言包时也能完整显示。
/// 启动器不再持有任何模型相关文案。
/// </summary>
public sealed class ModelStrings
{
private readonly Dictionary<string, string> _texts;
public string Language { get; }
private ModelStrings(string language, Dictionary<string, string> texts)
{
Language = language;
_texts = texts;
}
public static ModelStrings Default { get; } = new("zh-CN", DefaultTexts.Zh);
public string this[string key]
=> _texts.TryGetValue(key, out var value) ? value
: DefaultTexts.Zh.TryGetValue(key, out var fallback) ? fallback
: key;
public string F(string key, params object[] args)
=> string.Format(CultureInfo.InvariantCulture, this[key], args);
public string Pick(Dictionary<string, string>? i18n, string fallback)
{
if (i18n == null) return fallback;
if (i18n.TryGetValue(Language, out var exact) && !string.IsNullOrWhiteSpace(exact)) return exact;
foreach (var pair in i18n)
{
if (Language.StartsWith(pair.Key, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(pair.Value))
return pair.Value;
}
if (i18n.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh;
return fallback;
}
public static ModelStrings Load(string dataDirectory, string language)
{
var zh = new Dictionary<string, string>(DefaultTexts.Zh);
var isEnglish = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
var chosen = isEnglish ? new Dictionary<string, string>(DefaultTexts.En) : new Dictionary<string, string>(zh);
// 语言包可以覆盖任意键:i18n/<language>.json
var dir = Path.Combine(dataDirectory, "i18n");
Overlay(Path.Combine(dir, language + ".json"), chosen);
if (!isEnglish) Overlay(Path.Combine(dir, "zh-CN.json"), chosen);
return new ModelStrings(isEnglish ? "en" : "zh-CN", chosen);
}
private static void Overlay(string path, Dictionary<string, string> target)
{
if (!File.Exists(path)) return;
try
{
var map = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(path), ModelJson.Options);
if (map == null) return;
foreach (var pair in map) target[pair.Key] = pair.Value;
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取模型语言包失败 {path}: {ex.Message}");
}
}
}
internal static class DefaultTexts
{
public static readonly Dictionary<string, string> Zh = new()
{
["title"] = "地球模型",
["view.rotation"] = "自转",
["view.revolution"] = "公转",
["play"] = "播放",
["pause"] = "暂停",
["speed"] = "速度",
["reset"] = "重置",
["labels"] = "标注",
["orbit"] = "轨道",
["grid"] = "经纬网",
["tilt"] = "夸张倾角",
["lessons"] = "教学要点",
["seasons"] = "节气定位",
["close"] = "关闭窗口",
["hint"] = "双指捏合或滚轮缩放 · 拖动可转动地球",
["shortcutHint"] = "空格 播放/暂停 · ←→ 步进 · 1–4 二分二至 · F 全屏",
["classroom"] = "课堂演示",
["directPoint"] = "太阳直射",
["frozen"] = "已定格",
["running"] = "播放中",
["step"] = "步进",
["closeup"] = "地球特写",
["overhead"] = "俯视",
["sideview"] = "侧视",
["zoom"] = "缩放",
["orbitTeach"] = "太阳直射点在南北回归线之间往返,形成四季更替。",
["lat.equator"] = "赤道",
["lat.tropicN"] = "北回归线 23.5°N",
["lat.tropicS"] = "南回归线 23.5°S",
["lat.polarN"] = "北极圈 66.5°N",
["lat.polarS"] = "南极圈 66.5°S",
["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"] = "冬至"
};
public static readonly Dictionary<string, string> En = new()
{
["title"] = "Earth model",
["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",
["hint"] = "Pinch or scroll to zoom · drag to turn the Earth",
["shortcutHint"] = "Space play/pause · ←→ step · 1–4 solstices & equinoxes · F fullscreen",
["classroom"] = "Classroom",
["directPoint"] = "Subsolar",
["frozen"] = "Frozen",
["running"] = "Playing",
["step"] = "Step",
["closeup"] = "Earth close-up",
["overhead"] = "Top view",
["sideview"] = "Side view",
["zoom"] = "Zoom",
["orbitTeach"] = "The subsolar point travels between the tropics, producing the seasons.",
["lat.equator"] = "Equator",
["lat.tropicN"] = "Tropic of Cancer 23.5°N",
["lat.tropicS"] = "Tropic of Capricorn 23.5°S",
["lat.polarN"] = "Arctic Circle 66.5°N",
["lat.polarS"] = "Antarctic Circle 66.5°S",
["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"
};
}
+74
View File
@@ -0,0 +1,74 @@
using System.Collections.Generic;
namespace NeoRF.EarthModels;
/// <summary>&lt;id&gt;.model/scene.json —— 模型数据(可视化场景描述)。</summary>
public sealed class SceneDefinition
{
public int SchemaVersion { get; set; } = 1;
public string Type { get; set; } = "planet";
/// <summary>rotation | revolution</summary>
public string DefaultView { get; set; } = "rotation";
/// <summary>模型支持的视图;为空表示只有 defaultView。</summary>
public List<string> Views { get; set; } = new();
public Dictionary<string, string>? NameI18n { get; set; }
public Dictionary<string, string>? DescriptionI18n { get; set; }
public StarDefinition Star { get; set; } = new();
public PlanetDefinition Planet { get; set; } = new();
public OrbitDefinition Orbit { get; set; } = new();
public List<Lesson> Lessons { get; set; } = new();
}
public sealed class StarDefinition
{
public string Name { get; set; } = "Sun";
public Dictionary<string, string>? NameI18n { get; set; }
public string Color { get; set; } = "#FFC24B";
/// <summary>相对行星半径的视觉倍率</summary>
public double RadiusScale { get; set; } = 0.5;
}
public sealed class PlanetDefinition
{
public string Name { get; set; } = "Earth";
public Dictionary<string, string>? NameI18n { get; set; }
/// <summary>黄赤交角:教材值 23.5°(23°26′),决定南北回归线纬度。</summary>
public double AxialTiltDeg { get; set; } = 23.5;
/// <summary>回归线纬度,默认与黄赤交角一致;极圈 = 90 − 回归线。</summary>
public double TropicDeg { get; set; } = 23.5;
public double RotationHours { get; set; } = 23.93;
public double OrbitDays { get; set; } = 365.26;
public string OceanColor { get; set; } = "#1B5FA8";
public string LandColor { get; set; } = "#4F8C4C";
public string? IceColor { get; set; } = "#E8EEF4";
public string? LandFile { get; set; } = "land.json";
public bool ShowGraticule { get; set; } = true;
}
public sealed class OrbitDefinition
{
public double SemiMajorAxis { get; set; } = 4.0;
public double Eccentricity { get; set; } = 0.0167;
public bool Show { get; set; } = true;
public List<SeasonPoint> Seasons { get; set; } = new();
}
public sealed class SeasonPoint
{
/// <summary>0=春分 90=夏至 180=秋分 270=冬至</summary>
public double AngleDeg { get; set; }
public string Key { get; set; } = "";
public string? Date { get; set; }
/// <summary>该节气的太阳直射纬度:春分/秋分 0,夏至 +23.5,冬至 −23.5。</summary>
public double? DeclinationDeg { get; set; }
/// <summary>课堂现象说明(写在模型数据里,启动器不参与)。</summary>
public Dictionary<string, string>? TeachingI18n { get; set; }
}
public sealed class Lesson
{
public Dictionary<string, string>? TitleI18n { get; set; }
public Dictionary<string, string>? BodyI18n { get; set; }
public string? View { get; set; }
public double? AngleDeg { get; set; }
}
+65
View File
@@ -0,0 +1,65 @@
using System;
using System.IO;
using Avalonia.Media;
namespace NeoRF.EarthModels;
/// <summary>
/// 模型自己的场景运行时:场景描述 + 预烘焙地表纹理 + 调色板。
/// 数据来自模型数据目录,不依赖启动器。
/// </summary>
public sealed class SceneRuntime
{
public SceneDefinition Scene { get; init; } = new();
public PlanetTexture? Texture { get; init; }
public Color Ocean { get; init; } = Color.Parse("#1B5FA8");
public Color Land { get; init; } = Color.Parse("#4F8C4C");
public Color Ice { get; init; } = Color.Parse("#E6EDF4");
public Color Star { get; init; } = Color.Parse("#FFC24B");
public long MemoryBytes => Texture?.ByteSize ?? 0;
public static SceneRuntime Load(string dataDirectory, int memoryBudgetMb,
Action<double, string?>? progress = null)
{
progress?.Invoke(0.06, "读取场景数据");
var scenePath = Path.Combine(dataDirectory, "scene.json");
var scene = ModelJson.Read<SceneDefinition>(scenePath) ?? new SceneDefinition();
var ocean = Parse(scene.Planet.OceanColor, "#1B5FA8");
var land = Parse(scene.Planet.LandColor, "#4F8C4C");
var ice = Parse(scene.Planet.IceColor, "#E6EDF4");
LandData? landData = null;
var landFile = scene.Planet.LandFile;
if (!string.IsNullOrWhiteSpace(landFile))
{
var path = Path.IsPathRooted(landFile!) ? landFile! : Path.Combine(dataDirectory, landFile!);
progress?.Invoke(0.12, "读取地表轮廓");
landData = LandData.Load(path);
}
// 内存预算决定纹理分辨率(1024 宽约 3 MB)
var width = memoryBudgetMb >= 1024 ? PlanetTexture.DefaultWidth
: memoryBudgetMb >= 512 ? 768
: 512;
progress?.Invoke(0.16, "生成地表纹理");
var texture = PlanetTexture.Build(landData, width, ocean, land, ice,
t => progress?.Invoke(0.16 + t * 0.48, "生成地表纹理"));
progress?.Invoke(0.68, "场景就绪");
return new SceneRuntime
{
Scene = scene,
Texture = texture,
Ocean = ocean,
Land = land,
Ice = ice,
Star = Parse(scene.Star.Color, "#FFC24B")
};
}
private static Color Parse(string? value, string fallback)
=> Color.TryParse(string.IsNullOrWhiteSpace(value) ? fallback : value, out var c) ? c : Color.Parse(fallback);
}
+476
View File
@@ -0,0 +1,476 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia.Media;
namespace NeoRF.EarthModels;
/// <summary>
/// 预烘焙的等经纬度地表贴图:反照率 + 高度 + 冰盖 + 云层 + 夜间灯光。
/// 只在模型加载时算一次,之后每帧只做采样 —— 比逐像素跑噪声快一个数量级,
/// 而且能画出「真实一点」的地表:海洋深度、沙漠/雨林/针叶林带、山脉阴影、极地冰盖。
/// </summary>
public sealed class PlanetTexture
{
public const int DefaultWidth = 1024;
public int Width { get; }
public int Height { get; }
/// <summary>打包的反照率(0xRRGGBB),每像素一次双线性即可拿三通道。</summary>
public uint[] Albedo { get; }
/// <summary>地形高度(0=海平面,255=高山)</summary>
public byte[] Elevation { get; }
/// <summary>云量</summary>
public byte[] Cloud { get; }
/// <summary>夜间灯光</summary>
public byte[] Lights { get; }
/// <summary>预烘焙的地形坡度:东向 / 北向高度梯度(加载时算一次,每帧直接采样)。</summary>
public float[] SlopeEast { get; }
public float[] SlopeNorth { get; }
public long ByteSize => (long)(Albedo.Length * 4 + Elevation.Length + Cloud.Length + Lights.Length
+ SlopeEast.Length * 4 + SlopeNorth.Length * 4);
private PlanetTexture(int width, int height)
{
Width = width;
Height = height;
var count = width * height;
Albedo = new uint[count];
Elevation = new byte[count];
Cloud = new byte[count];
Lights = new byte[count];
SlopeEast = new float[count];
SlopeNorth = new float[count];
}
public static PlanetTexture Build(LandData? landData, int width, Color ocean, Color land, Color ice,
Action<double>? progress = null)
{
width = Math.Clamp(width, 256, 2048);
var height = width / 2;
var texture = new PlanetTexture(width, height);
progress?.Invoke(0.08);
var mask = landData == null ? null : LandMask.Build(landData, width, height);
progress?.Invoke(0.28);
// 到海岸的距离:海里用来做深度,陆地上用来做大陆性(内陆更干)
var landDistance = new float[width * height];
var oceanDistance = new float[width * height];
ComputeDistances(mask, width, height, landDistance, oceanDistance);
progress?.Invoke(0.42);
Parallel.For(0, height, y =>
{
var lat = 90.0 - (y + 0.5) * 180.0 / height;
var latAbs = MathF.Abs((float)lat);
var rowBase = y * width;
for (var x = 0; x < width; x++)
{
var lon = (x + 0.5) * 360.0 / width - 180.0;
var index = rowBase + x;
var isLand = mask == null || mask.Bits[index] > 127;
var elevation = Fbm(lon * 2.1, lat * 2.1, 4, 0x51A3);
var moisture = Fbm(lon * 1.35 + 40, lat * 1.35 - 20, 3, 0x9E2B);
var detail = Fbm(lon * 0.85, lat * 0.85, 3, 0x2C77);
if (isLand)
{
// 内陆更干,靠海更湿
var inland = Math.Clamp(landDistance[index] / (width * 0.06f), 0f, 1f);
var wet = Math.Clamp(moisture * 0.78f + (1f - inland) * 0.16f
- MathF.Max(0f, latAbs - 45f) / 90f, 0f, 1f);
var (r, g, b) = LandPalette(latAbs, wet, inland, elevation, detail, land, ice);
texture.Albedo[index] = Pack(r, g, b);
texture.Elevation[index] = (byte)Math.Clamp(elevation * 235f + detail * 20f, 0, 255);
// 夜间灯光:沿海平原、中低纬,稀疏分布
// 夜间灯光:低频的城市群辉光(高频点会在小尺寸球面上变成噪点)
var cityGlow = Smooth(0.55f, 0.92f, Fbm(lon * 1.7, lat * 1.7, 3, 0x7A31));
if (latAbs < 60 && inland < 0.55f && elevation < 0.75f)
texture.Lights[index] = ToByte(cityGlow * 0.55f);
}
else
{
// 海洋:按离岸距离做深浅
var depth = Math.Clamp(oceanDistance[index] / (width * 0.09f), 0f, 1f);
depth = (float)Math.Pow(depth, 0.65);
var shallowR = Math.Min(1f, ocean.R / 255f + 0.16f);
var shallowG = Math.Min(1f, ocean.G / 255f + 0.22f);
var shallowB = Math.Min(1f, ocean.B / 255f + 0.16f);
var deepR = ocean.R / 255f * 0.32f;
var deepG = ocean.G / 255f * 0.40f;
var deepB = ocean.B / 255f * 0.52f;
var wave = (detail - 0.5f) * 0.035f;
texture.Albedo[index] = Pack(
ToByte(shallowR + (deepR - shallowR) * depth + wave),
ToByte(shallowG + (deepG - shallowG) * depth + wave),
ToByte(shallowB + (deepB - shallowB) * depth + wave));
texture.Elevation[index] = 0;
}
// 极地冰盖:纬度 + 噪声边界,海洋也能结冰
var iceEdge = 62f + (detail - 0.5f) * 9f;
var iceAmt = Smooth(iceEdge - 7f, iceEdge + 6f, latAbs);
if (iceAmt > 0.001f)
{
var iceR = ice.R / 255f;
var iceG = ice.G / 255f;
var iceB = ice.B / 255f;
var packed = texture.Albedo[index];
texture.Albedo[index] = Pack(
ToByte(Lerp(((packed >> 16) & 0xFF) / 255f, iceR, iceAmt)),
ToByte(Lerp(((packed >> 8) & 0xFF) / 255f, iceG, iceAmt)),
ToByte(Lerp((packed & 0xFF) / 255f, iceB, iceAmt)));
}
// 云:多个尺度的 fbm,赤道与中纬多云
var cloudBase = Fbm(lon * 0.55, lat * 0.7, 3, 0x1144);
var band = 0.5f + 0.5f * MathF.Cos(latAbs / 90f * MathF.PI * 3.1f);
var cloud = Smooth(0.48f, 0.84f, cloudBase * 0.86f + band * 0.14f);
texture.Cloud[index] = ToByte(cloud * 0.72f);
}
});
// 云层做一次模糊,避免小尺寸球面上采样出噪点
Blur(texture.Cloud, width, height, 2);
// 预烘焙地形坡度:渲染时不必每像素再取 4 次高度
BakeSlopes(texture, width, height);
progress?.Invoke(0.62);
return texture;
}
private static (byte R, byte G, byte B) LandPalette(float latAbs, float wet, float inland, float elevation,
float detail, Color landBase, Color ice)
{
// 基色随纬度:赤道雨林 -> 温带 -> 针叶林 -> 苔原
float r, g, b;
var tropical = (1f - Smooth(8f, 24f, latAbs));
var temperate = Smooth(20f, 34f, latAbs) * (1f - Smooth(46f, 60f, latAbs));
var boreal = Smooth(46f, 60f, latAbs) * (1f - Smooth(62f, 70f, latAbs));
var tundra = Smooth(60f, 72f, latAbs);
r = 0.13f; g = 0.36f; b = 0.17f; // 温带草原绿
r = Lerp(r, 0.10f, tropical); g = Lerp(g, 0.42f, tropical); b = Lerp(b, 0.19f, tropical);
r = Lerp(r, 0.17f, boreal); g = Lerp(g, 0.28f, boreal); b = Lerp(b, 0.17f, boreal);
r = Lerp(r, 0.34f, tundra); g = Lerp(g, 0.36f, tundra); b = Lerp(b, 0.31f, tundra);
// 湿润度:干 -> 沙漠/草原
var dry = Math.Clamp(1f - wet * 0.95f, 0f, 1f);
var desertBand = Math.Clamp(1f - MathF.Abs(latAbs - 24f) / 13f, 0f, 1f);
var desert = Math.Clamp(dry * 0.72f + desertBand * 0.62f, 0f, 1f);
r = Lerp(r, 0.72f, desert * 0.85f);
g = Lerp(g, 0.60f, desert * 0.85f);
b = Lerp(b, 0.38f, desert * 0.85f);
// 高原/山地:岩石和雪
var rock = Smooth(0.62f, 0.86f, elevation);
r = Lerp(r, 0.44f, rock * 0.7f);
g = Lerp(g, 0.40f, rock * 0.7f);
b = Lerp(b, 0.34f, rock * 0.7f);
var snow = Smooth(0.86f, 0.97f, elevation + (latAbs - 40f) / 220f);
r = Lerp(r, ice.R / 255f, snow);
g = Lerp(g, ice.G / 255f, snow);
b = Lerp(b, ice.B / 255f, snow);
// 细节扰动,避免大面积纯色
var grain = (detail - 0.5f) * 0.07f;
var baseMix = 0.25f;
return (
ToByte(Math.Clamp(r + grain + (landBase.R / 255f - 0.3f) * baseMix * 0.2f, 0f, 1f)),
ToByte(Math.Clamp(g + grain + (landBase.G / 255f - 0.45f) * baseMix * 0.2f, 0f, 1f)),
ToByte(Math.Clamp(b + grain + (landBase.B / 255f - 0.3f) * baseMix * 0.2f, 0f, 1f)));
}
/// <summary>可分离盒式模糊(原地),用于软化云层。</summary>
private static void Blur(byte[] data, int width, int height, int radius)
{
var temp = new byte[data.Length];
for (var y = 0; y < height; y++)
{
var row = y * width;
for (var x = 0; x < width; x++)
{
var sum = 0;
var count = 0;
for (var k = -radius; k <= radius; k++)
{
var sx = (x + k + width) % width;
sum += data[row + sx];
count++;
}
temp[row + x] = (byte)(sum / count);
}
}
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
var sum = 0;
var count = 0;
for (var k = -radius; k <= radius; k++)
{
var sy = Math.Clamp(y + k, 0, height - 1);
sum += temp[sy * width + x];
count++;
}
data[y * width + x] = (byte)(sum / count);
}
}
}
/// <summary>由高度图算东西/南北梯度,供球面光照直接使用。</summary>
private static void BakeSlopes(PlanetTexture t, int width, int height)
{
const float relief = 0.055f * 90f;
for (var y = 0; y < height; y++)
{
var row = y * width;
var up = Math.Max(0, y - 1) * width;
var down = Math.Min(height - 1, y + 1) * width;
for (var x = 0; x < width; x++)
{
var left = (x - 1 + width) % width;
var right = (x + 1) % width;
t.SlopeEast[row + x] = (t.Elevation[row + right] - t.Elevation[row + left]) / 255f * relief;
t.SlopeNorth[row + x] = (t.Elevation[up + x] - t.Elevation[down + x]) / 255f * relief;
}
}
}
// ---------------------------------------------------------------- 距离场
private static void ComputeDistances(LandMask? mask, int width, int height, float[] landDistance, float[] oceanDistance)
{
var count = width * height;
const float big = 1e6f;
for (var i = 0; i < count; i++)
{
var isLand = mask != null && mask.Bits[i] > 127;
landDistance[i] = isLand ? big : -big;
oceanDistance[i] = isLand ? -big : big;
}
// 两遍 chamfer:陆地到海洋的距离 / 海洋到陆地的距离
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var i = y * width + x;
if (mask != null && mask.Bits[i] > 127)
{
var best = big;
if (x > 0 && mask.Bits[i - 1] <= 127) best = 0.5f;
if (x < width - 1 && mask.Bits[i + 1] <= 127) best = Math.Min(best, 0.5f);
if (y > 0 && mask.Bits[i - width] <= 127) best = Math.Min(best, 0.5f);
if (y < height - 1 && mask.Bits[i + width] <= 127) best = Math.Min(best, 0.5f);
if (best < big) landDistance[i] = best;
}
if (mask != null && mask.Bits[i] <= 127)
{
var best = big;
if (x > 0 && mask.Bits[i - 1] > 127) best = 0.5f;
if (x < width - 1 && mask.Bits[i + 1] > 127) best = Math.Min(best, 0.5f);
if (y > 0 && mask.Bits[i - width] > 127) best = Math.Min(best, 0.5f);
if (y < height - 1 && mask.Bits[i + width] > 127) best = Math.Min(best, 0.5f);
if (best < big) oceanDistance[i] = best;
}
}
}
// 正向传递
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var i = y * width + x;
Propagate(landDistance, i, width, height, x, y, -1, 0, 1.4142f);
Propagate(oceanDistance, i, width, height, x, y, -1, 0, 1.4142f);
if (x > 0)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i - 1] + 1f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - 1] + 1f);
}
if (y > 0)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width] + 1f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width] + 1f);
if (x > 0)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width - 1] + 1.4142f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width - 1] + 1.4142f);
}
if (x < width - 1)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width + 1] + 1.4142f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width + 1] + 1.4142f);
}
}
}
}
// 反向传递
for (var y = height - 1; y >= 0; y--)
{
for (var x = width - 1; x >= 0; x--)
{
var i = y * width + x;
if (x < width - 1)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i + 1] + 1f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + 1] + 1f);
}
if (y < height - 1)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width] + 1f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width] + 1f);
if (x < width - 1)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width + 1] + 1.4142f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width + 1] + 1.4142f);
}
if (x > 0)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width - 1] + 1.4142f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width - 1] + 1.4142f);
}
}
}
}
for (var i = 0; i < count; i++)
{
landDistance[i] = MathF.Max(0f, landDistance[i]);
oceanDistance[i] = MathF.Max(0f, oceanDistance[i]);
}
}
private static void Propagate(float[] map, int index, int width, int height, int x, int y, int dx, int dy, float w)
{
var nx = x + dx;
var ny = y + dy;
if (nx < 0 || nx >= width || ny < 0 || ny >= height) return;
var other = ny * width + nx;
map[index] = Math.Min(map[index], map[other] + w);
}
// ---------------------------------------------------------------- 噪声
/// <summary>值噪声 + 分形叠加(确定性,跨平台一致)。</summary>
public static float Fbm(double x, double y, int octaves, int seed)
{
var amplitude = 1.0;
var frequency = 1.0;
var sum = 0.0;
var norm = 0.0;
for (var i = 0; i < octaves; i++)
{
sum += amplitude * ValueNoise(x * frequency, y * frequency, seed + i * 101);
norm += amplitude;
amplitude *= 0.5;
frequency *= 2.07;
}
return (float)(sum / norm);
}
private static double ValueNoise(double x, double y, int seed)
{
var xi = (int)Math.Floor(x);
var yi = (int)Math.Floor(y);
var xf = x - xi;
var yf = y - yi;
var u = xf * xf * (3 - 2 * xf);
var v = yf * yf * (3 - 2 * yf);
var a = Hash(xi, yi, seed);
var b = Hash(xi + 1, yi, seed);
var c = Hash(xi, yi + 1, seed);
var d = Hash(xi + 1, yi + 1, seed);
return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v;
}
private static double Hash(int x, int y, int seed)
{
var h = (uint)(x * 374761393 + y * 668265263 + seed * 1442695041);
h = (h ^ (h >> 13)) * 1274126177u;
h ^= h >> 16;
return (h & 0xFFFFFF) / (double)0xFFFFFF;
}
// ---------------------------------------------------------------- 采样
public void Sample(double lon, double lat, out float r, out float g, out float b,
out float elevation, out float cloud, out float lights,
out float slopeEast, out float slopeNorth)
{
var u = (lon + 180.0) / 360.0 * Width - 0.5;
var v = (90.0 - lat) / 180.0 * Height - 0.5;
var x0 = (int)Math.Floor(u);
var y0 = (int)Math.Floor(v);
var fx = (float)(u - x0);
var fy = (float)(v - y0);
var x1 = x0 + 1;
var y1 = y0 + 1;
if (x0 < 0) x0 += Width; if (x1 < 0) x1 += Width;
if (x0 >= Width) x0 -= Width; if (x1 >= Width) x1 -= Width;
y0 = Math.Clamp(y0, 0, Height - 1);
y1 = Math.Clamp(y1, 0, Height - 1);
var i00 = y0 * Width + x0;
var i10 = y0 * Width + x1;
var i01 = y1 * Width + x0;
var i11 = y1 * Width + x1;
float w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy), w01 = (1 - fx) * fy, w11 = fx * fy;
var p00 = Albedo[i00];
var p10 = Albedo[i10];
var p01 = Albedo[i01];
var p11 = Albedo[i11];
var rr = ((p00 >> 16) & 0xFF) * w00 + ((p10 >> 16) & 0xFF) * w10 + ((p01 >> 16) & 0xFF) * w01 + ((p11 >> 16) & 0xFF) * w11;
var gg = ((p00 >> 8) & 0xFF) * w00 + ((p10 >> 8) & 0xFF) * w10 + ((p01 >> 8) & 0xFF) * w01 + ((p11 >> 8) & 0xFF) * w11;
var bb = (p00 & 0xFF) * w00 + (p10 & 0xFF) * w10 + (p01 & 0xFF) * w01 + (p11 & 0xFF) * w11;
r = rr / 255f;
g = gg / 255f;
b = bb / 255f;
elevation = (Elevation[i00] * w00 + Elevation[i10] * w10 + Elevation[i01] * w01 + Elevation[i11] * w11) / 255f;
cloud = (Cloud[i00] * w00 + Cloud[i10] * w10 + Cloud[i01] * w01 + Cloud[i11] * w11) / 255f;
lights = Lights[i00] / 255f;
slopeEast = SlopeEast[i00] * w00 + SlopeEast[i10] * w10 + SlopeEast[i01] * w01 + SlopeEast[i11] * w11;
slopeNorth = SlopeNorth[i00] * w00 + SlopeNorth[i10] * w10 + SlopeNorth[i01] * w01 + SlopeNorth[i11] * w11;
}
/// <summary>只采样高度(法线扰动用)。</summary>
public float SampleHeight(double lon, double lat)
{
var u = (lon + 180.0) / 360.0 * Width - 0.5;
var v = (90.0 - lat) / 180.0 * Height - 0.5;
var x = Math.Clamp((int)Math.Round(u), 0, Width - 1);
var y = Math.Clamp((int)Math.Round(v), 0, Height - 1);
return Elevation[y * Width + x] / 255f;
}
public float SampleCloud(double lon, double lat)
{
var u = (lon + 180.0) / 360.0 * Width - 0.5;
var v = (90.0 - lat) / 180.0 * Height - 0.5;
var x = Math.Clamp((int)Math.Round(u), 0, Width - 1);
var y = Math.Clamp((int)Math.Round(v), 0, Height - 1);
return Cloud[y * Width + x] / 255f;
}
public static byte ToByte(float v) => (byte)Math.Clamp((int)(v * 255f + 0.5f), 0, 255);
private static uint Pack(byte r, byte g, byte b) => ((uint)r << 16) | ((uint)g << 8) | b;
private static float Lerp(float a, float b, float t) => a + (b - a) * Math.Clamp(t, 0f, 1f);
private static float Smooth(float edge0, float edge1, float x)
{
if (edge1 <= edge0) return x >= edge1 ? 1f : 0f;
var t = Math.Clamp((x - edge0) / (edge1 - edge0), 0f, 1f);
return t * t * (3f - 2f * t);
}
}
+172
View File
@@ -0,0 +1,172 @@
using System;
using System.Numerics;
using System.Threading.Tasks;
using Avalonia.Media.Imaging;
namespace NeoRF.EarthModels;
/// <summary>
/// 球体像素级渲染:正交投影 + 预烘焙地表纹理 + 地形光照 + 云层 + 夜灯 + 大气边缘光。
/// 纯 CPU 光栅、按行并行,不依赖 GPU,三平台效果一致。
/// </summary>
public static unsafe class SphereRaster
{
/// <summary>把球体画进 WriteableBitmap(整张位图会被覆盖)。</summary>
public static void Draw(WriteableBitmap bitmap, int size, Matrix4x4 cam, Matrix4x4 planet,
Vector3 light, PlanetTexture texture, double cloudShift, bool showClouds)
{
using var framebuffer = bitmap.Lock();
var stride = framebuffer.RowBytes / 4;
Render((uint*)framebuffer.Address, stride, size, cam, planet, light, texture, cloudShift, showClouds);
}
public static void Render(uint* dst, int stride, int size, Matrix4x4 cam, Matrix4x4 planet,
Vector3 light, PlanetTexture texture, double cloudShift, bool showClouds)
{
var radius = size * 0.5f - 1.0f;
var center = size * 0.5f;
var inv = 1f / radius;
// 相机空间法线 -> 行星本地法线
var combined = Matrix4x4.Multiply(planet, cam);
var mt = Matrix4x4.Transpose(combined);
float m11 = mt.M11, m12 = mt.M12, m13 = mt.M13;
float m21 = mt.M21, m22 = mt.M22, m23 = mt.M23;
float m31 = mt.M31, m32 = mt.M32, m33 = mt.M33;
var lx = light.X; var ly = light.Y; var lz = light.Z;
Parallel.For(0, size, y =>
{
var ny = (center - y - 0.5f) * inv;
var row = dst + (long)y * stride;
for (var x = 0; x < size; x++)
{
var nx = (x + 0.5f - center) * inv;
var r2 = nx * nx + ny * ny;
if (r2 >= 1f)
{
row[x] = 0;
continue;
}
var nz = MathF.Sqrt(1f - r2);
// 本地法线(用于取经纬度)
var ux = nx * m11 + ny * m21 + nz * m31;
var uy = nx * m12 + ny * m22 + nz * m32;
var uz = nx * m13 + ny * m23 + nz * m33;
var lat = MathF.Asin(Math.Clamp(uy, -1f, 1f)) * 57.2957795f;
var lon = MathF.Atan2(ux, uz) * 57.2957795f;
var cloudLon = lon + cloudShift;
if (cloudLon > 180) cloudLon -= 360;
if (cloudLon < -180) cloudLon += 360;
texture.Sample(lon, lat, out var ar, out var ag, out var ab,
out var elevation, out var cloud, out var lights,
out var dEast, out var dNorth);
// ---- 地形法线:局部基向量可由球面法线直接推出,不必再算 6 次三角函数
// 点 P=(cosLat·sinLon, sinLat, cosLat·cosLon) = (ux,uy,uz)
// 东向 = (cosLon,0,-sinLon),北向 = (-sinLat·sinLon, cosLat, -sinLat·cosLon)
var cosLat = MathF.Sqrt(MathF.Max(ux * ux + uz * uz, 1e-6f));
var invCos = 1f / cosLat;
var eastX = uz * invCos;
var eastZ = -ux * invCos;
var northX = -uy * ux * invCos;
var northY = cosLat;
var northZ = -uy * uz * invCos;
var nLocalX = ux + eastX * dEast + northX * dNorth;
var nLocalY = uy + northY * dNorth;
var nLocalZ = uz + eastZ * dEast + northZ * dNorth;
var nLen = MathF.Sqrt(nLocalX * nLocalX + nLocalY * nLocalY + nLocalZ * nLocalZ);
if (nLen > 0.0001f) { nLocalX /= nLen; nLocalY /= nLen; nLocalZ /= nLen; }
var nCamX = nLocalX * combined.M11 + nLocalY * combined.M21 + nLocalZ * combined.M31;
var nCamY = nLocalX * combined.M12 + nLocalY * combined.M22 + nLocalZ * combined.M32;
var nCamZ = nLocalX * combined.M13 + nLocalY * combined.M23 + nLocalZ * combined.M33;
var lam = nx * lx + ny * ly + nz * lz; // 几何光照(晨昏线)
var bump = nCamX * lx + nCamY * ly + nCamZ * lz; // 地形光照
var day = Smooth(-0.18f, 0.22f, lam);
var terrainLight = 0.82f + 0.42f * MathF.Max(0f, bump - lam);
var shade = (0.055f + 0.945f * day) * terrainLight;
var br = ar * shade;
var bg = ag * shade;
var bb = ab * shade;
// 海面高光(高度为 0 视为水面)
if (elevation < 0.02f)
{
var t2 = MathF.Max(0f, lam);
var t4 = t2 * t2 * t2 * t2;
var t8 = t4 * t4;
var t16 = t8 * t8;
var spec = t16 * t8 * t4 * t2 * t2 * 0.62f;
br += spec * 0.95f;
bg += spec * 0.98f;
bb += spec;
}
// 云层(随经度缓慢漂移)
if (showClouds && cloud > 0.02f)
{
var cloudLight = 0.10f + 0.90f * day;
var c = Math.Clamp(cloud * 0.92f, 0f, 1f);
var cloudR = 0.98f * cloudLight;
var cloudG = 0.985f * cloudLight;
var cloudB = 1.0f * cloudLight;
br += (cloudR - br) * c;
bg += (cloudG - bg) * c;
bb += (cloudB - bb) * c;
}
// 夜间灯光
if (lights > 0.01f)
{
var night = 1f - day;
var glow = lights * night * 0.35f;
br += glow * 0.95f;
bg += glow * 0.72f;
bb += glow * 0.38f;
}
// 大气边缘散射
var rim = 1f - nz;
rim *= rim;
var litRim = rim * MathF.Max(0f, lam) * 0.98f;
br += 0.30f * litRim;
bg += 0.55f * litRim;
bb += 1.00f * litRim;
// 夜面极淡反照
var nightSide = 1f - day;
br += 0.008f * nightSide;
bg += 0.013f * nightSide;
bb += 0.028f * nightSide;
var coverage = 1f;
var edge = (1f - MathF.Sqrt(r2)) * radius;
if (edge < 1f) coverage = MathF.Max(0f, edge);
var a = (uint)(coverage * 255f);
var r8 = (uint)(Math.Clamp(br, 0f, 1f) * 255f * coverage);
var g8 = (uint)(Math.Clamp(bg, 0f, 1f) * 255f * coverage);
var b8 = (uint)(Math.Clamp(bb, 0f, 1f) * 255f * coverage);
row[x] = (a << 24) | (r8 << 16) | (g8 << 8) | b8;
}
});
}
private static float Smooth(float edge0, float edge1, float x)
{
if (edge1 <= edge0) return x >= edge1 ? 1f : 0f;
var t = Math.Clamp((x - edge0) / (edge1 - edge0), 0f, 1f);
return t * t * (3f - 2f * t);
}
}