Merge gravity-grid-lowering

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-15 19:52:48 +02:00
commit 55cc7eda41
57 changed files with 1346 additions and 1575 deletions

View file

@ -0,0 +1,334 @@
using System;
using System.IO;
using System.Linq;
using GameCult.Caching;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;
using CultMath;
namespace Aetheria.EditorTools
{
/// <summary>
/// Batchmode check for campaign aetheria-gravity, cut grid-lowering: what the Gravity Field pass draws is the sim's
/// height. It builds a zone from Settings.asset's PlanetSettings with three bodies, runs the real lowering
/// (GravityLowering.Lower and CreateField), renders the field through an orthographic camera that culls layer 9 into
/// a float target, and compares every texel with -Zone.GetHeight at the texel centre's world position. It then checks
/// that the texture's gradient points where Zone.GetForce does, and that ARPG.unity and the body prefabs are wired
/// the way the cut leaves them (the gravity cameras cull layer 9 alone, nothing but the run-time field sits on it).
///
/// Renders, so it needs a graphics device: run WITHOUT -nographics (as FlowFieldParityVerify).
/// Unity -batchmode -projectPath &lt;repo&gt; -executeMethod Aetheria.EditorTools.GravityFieldParityVerify.Run -logFile &lt;path&gt;
/// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure.
/// </summary>
public static class GravityFieldParityVerify
{
const string Tag = "[GravityFieldParityVerify]";
const int Size = 256;
// Measured on this tree (the "max error" line this run prints): the largest |texel + GetHeight| over the windows of the three
// frames and windows is 0.0065 u, in the last frame's planetoid window (float32 on both sides, the GPU's log against the CPU's, the
// quad's interpolated world position). The tolerance is 4.6x that. A 0.1% error in the tail constant (.5 -> .501)
// moves the drawn height by 0.053 u where all three tails reach (the planetoid and zone windows), 1.8x the
// tolerance; a reference of zero moves it by about 150 u.
const float Tolerance = 0.03f;
// The worst angle between the texture's central difference and GetForce (B28: 1.0 degrees median zone, 2.9 worst).
const float GradientDegrees = 3f;
static float _maxError, _maxAngle;
static bool _ok = true;
static void OnLog(string message, string stack, LogType type)
{
if ((type == LogType.Error || type == LogType.Exception || type == LogType.Assert) && !message.StartsWith(Tag))
Fail("logged-error", message.Split('\n')[0]);
}
static void Fail(string check, string detail)
{
Debug.LogError($"{Tag} FAIL {check}: {detail}");
_ok = false;
}
public static void Run()
{
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
{
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
EditorApplication.Exit(1);
return;
}
Application.logMessageReceived += OnLog;
var work = Path.Combine(Path.GetTempPath(), "gravity-parity-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(work);
ComputeBuffer wells = null;
GameObject field = null;
try
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")
?? throw new InvalidOperationException("No Settings.asset.");
var material = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Brushes/Gravity Field.mat")
?? throw new InvalidOperationException("No Gravity Field.mat.");
var zone = BuildZone(settings, work, out var orbits);
GravityLowering.Lower(zone, ref wells);
field = GravityLowering.CreateField(material);
// Three frames through the one buffer, as ZoneRenderer.Update runs it: the bodies as built, then two moves
// (an orbit's Position is what Zone.GetHeight reads). A lowering that mirrors an axis or stops refreshing
// the upload agrees with the sim in the first frame only where it is symmetric, and not after a move.
CheckFrame("built", zone, orbits);
orbits[1].Position = new float2(-420f, 560f);
orbits[2].Position = new float2(900f, -700f);
GravityLowering.Lower(zone, ref wells);
CheckFrame("moved", zone, orbits);
orbits[0].Position = new float2(210f, -95f);
orbits[2].Position = new float2(-1800f, 1300f);
GravityLowering.Lower(zone, ref wells);
CheckFrame("moved-again", zone, orbits);
Debug.Log($"{Tag} max error {_maxError:G4} u (tolerance {Tolerance:G4}); max gradient angle {_maxAngle:F2} degrees (limit {GradientDegrees:F0})");
CheckWiring(settings);
Debug.Log(_ok ? $"{Tag} PASS" : $"{Tag} FAIL: see errors above");
}
catch (Exception e)
{
Debug.LogError($"{Tag} FAIL exception: {e}");
_ok = false;
}
finally
{
Application.logMessageReceived -= OnLog;
if (field != null) UnityEngine.Object.DestroyImmediate(field);
wells?.Release();
try { Directory.Delete(work, true); } catch { }
}
EditorApplication.Exit(_ok ? 0 : 1);
}
static float Core(Zone zone, float mass) => zone.Settings.RocheLimit.Evaluate(mass);
static Vector2 At(Orbit orbit) => new Vector2(orbit.Position.x, orbit.Position.y);
// Orbits 0-2 are the sun, the planet and the planetoid, each window centred where the body is now; orbit 3 is the
// body of no strength. The zone window holds all four.
static void CheckFrame(string frame, Zone zone, Orbit[] orbits)
{
CheckTexels(frame + "-planetoid", zone, At(orbits[2]), 4f * Core(zone, 29.2f));
CheckTexels(frame + "-sun", zone, At(orbits[0]), 4f * Core(zone, 14152f));
CheckTexels(frame + "-zone", zone, Vector2.zero, 1.05f * zone.Pack.Radius);
CheckGradient(zone, orbits.Select(At).ToArray());
}
// A sun (14152 at (-130, 85)), a planet (273.9 at (610, -240)), a planetoid (29.2 at (670, -270)) and a body of
// mass 0, whose well has no strength (a legal body; its curves give c = 0 and R = 0), at (1700, 300): parentless,
// fixed, off both axes and asymmetric, so the zone's wells sit where the verify says before any Update and a
// mirrored or swapped axis cannot agree with the sim.
static Zone BuildZone(GameSettings settings, string work, out Orbit[] orbits)
{
var cache = AetheriaStores.Open(Path.Combine(work, "catalog.cc"), Path.Combine(work, "run.cc"), catalogWritable: true);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), settings.GameplaySettings, _ => { });
var positions = new[] { new Vector2(-130f, 85f), new Vector2(610f, -240f), new Vector2(670f, -270f), new Vector2(1700f, 300f) };
var masses = new[] { 14152f, 273.9f, 29.2f, 0f };
var keys = new CultRecordKey[positions.Length];
var pack = new ZonePack { Radius = 4182f };
for (var i = 0; i < positions.Length; i++)
{
var orbit = keys[i] = cache.Upsert(new OrbitData { FixedPosition = new float2(positions[i].x, positions[i].y) }).Key;
var body = cache.Upsert(new PlanetData
{ Name = "Body " + i, Orbit = new CultRecordRef<OrbitData>(orbit), Mass = masses[i] }).Key;
pack.Orbits.Add(new CultRecordRef<OrbitData>(orbit));
pack.Planets.Add(new CultRecordRef<BodyData>(body));
}
var zone = new Zone(items, settings.PlanetSettings, pack, new GalaxyZone { Name = "Gravity Parity", Owner = null }, null);
orbits = keys.Select(k => zone.Orbits[k]).ToArray();
return zone;
}
// Renders the field through a downward orthographic camera that culls layer 9 only, centred on `centre` with
// half-size `half`, and returns the depth of every texel with the world xz of the texel's centre, which is asked
// of the camera rather than assumed.
static void Render(Vector2 centre, float half, out float[] depth, out Vector2[] world)
{
var rt = new RenderTexture(Size, Size, 0, RenderTextureFormat.RFloat) { filterMode = FilterMode.Point };
var cameraObject = new GameObject("Gravity Parity Camera");
var read = new Texture2D(Size, Size, TextureFormat.RFloat, false);
var previous = RenderTexture.active;
try
{
var camera = cameraObject.AddComponent<Camera>();
camera.orthographic = true;
camera.orthographicSize = half;
camera.aspect = 1f;
camera.nearClipPlane = .3f;
camera.farClipPlane = 1000f;
camera.cullingMask = 1 << GravityLowering.FieldLayer;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = Color.black;
camera.allowHDR = false;
camera.allowMSAA = false;
camera.targetTexture = rt;
cameraObject.transform.SetPositionAndRotation(new Vector3(centre.x, 100f, centre.y), Quaternion.Euler(90f, 0f, 0f));
camera.Render();
RenderTexture.active = rt;
read.ReadPixels(new Rect(0, 0, Size, Size), 0, 0);
read.Apply();
depth = read.GetPixelData<float>(0).ToArray();
world = new Vector2[Size * Size];
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var p = camera.ViewportToWorldPoint(new Vector3((x + .5f) / Size, (y + .5f) / Size, 100f));
world[y * Size + x] = new Vector2(p.x, p.z);
}
}
finally
{
RenderTexture.active = previous;
UnityEngine.Object.DestroyImmediate(cameraObject);
UnityEngine.Object.DestroyImmediate(read);
rt.Release();
UnityEngine.Object.DestroyImmediate(rt);
}
}
static void CheckTexels(string window, Zone zone, Vector2 centre, float half)
{
Render(centre, half, out var depth, out var world);
var worst = 0f;
var live = 0;
for (var i = 0; i < depth.Length; i++)
{
var expected = -zone.GetHeight(new float2(world[i].x, world[i].y));
if (float.IsNaN(depth[i])) { Fail($"{window}-texels", $"texel {i}: NaN"); return; }
var error = Math.Abs(depth[i] - expected);
worst = Math.Max(worst, error);
if (Math.Abs(expected) > 1f) live++;
if (error > Tolerance)
{
Fail($"{window}-texels", $"texel {i} at ({world[i].x:F2}, {world[i].y:F2}): expected {expected:G6}, drawn {depth[i]:G6}, error {error:G4} > {Tolerance:G4}");
return;
}
}
_maxError = Math.Max(_maxError, worst);
// A window that draws nothing agrees with a zone that is flat: the check must be live.
if (live < depth.Length / 2) Fail($"{window}-texels", $"only {live} of {depth.Length} texels are deeper than 1 u; the check is vacuous");
Debug.Log($"{Tag} {window}: {depth.Length} texels, max error {worst:G4} u");
}
// The texture's central difference (over two 4 u texels, mid-zone) points where GetForce does: depth = -h, so its
// gradient is the force over the exaggeration. This is what the slope readers (the shader's slopeFlow, the nebula
// surface normal, the drawn grid) take from the texture.
static void CheckGradient(Zone zone, Vector2[] bodies)
{
Render(new Vector2(1500f, 0f), 512f, out var depth, out var world);
var compared = 0;
for (var y = 1; y < Size - 1; y++)
for (var x = 1; x < Size - 1; x++)
{
var here = world[y * Size + x];
if (bodies.Any(b => (b - here).magnitude < 16f)) continue;
// The world step of each texel axis is read from the camera, so a flipped or rotated target is still measured.
var au = world[y * Size + x + 1] - world[y * Size + x - 1];
var av = world[(y + 1) * Size + x] - world[(y - 1) * Size + x];
var du = depth[y * Size + x + 1] - depth[y * Size + x - 1];
var dv = depth[(y + 1) * Size + x] - depth[(y - 1) * Size + x];
var det = au.x * av.y - au.y * av.x;
var g = new Vector2((du * av.y - dv * au.y) / det, (dv * au.x - du * av.x) / det);
var f = zone.GetForce(new float2(here.x, here.y));
var angle = Vector2.Angle(g, new Vector2(f.x, f.y));
if (float.IsNaN(angle) || angle > GradientDegrees)
{
Fail("gradient", $"at ({here.x:F1}, {here.y:F1}) the drawn slope points {angle:F2} degrees from the force (limit {GradientDegrees:F0})");
return;
}
_maxAngle = Math.Max(_maxAngle, angle);
compared++;
}
if (compared < Size * Size / 2) Fail("gradient", $"only {compared} texels were compared");
}
// Main Menu.unity has no ZoneRenderer, so no Gravity Field and no lowered potential: its gravity cameras draw the
// menu's own brush objects (Boundary on layer 9, the Waves on layer 10) and are presentation by spec (follow-up
// menu-grid-brushes), not a reader of the potential. This pins that: a ZoneRenderer in the menu would make its
// cameras readers of the field, and they would have to cull layer 9 alone like ARPG's.
static void CheckMenuWiring()
{
var scene = EditorSceneManager.OpenScene("Assets/Scenes/Main Menu.unity", OpenSceneMode.Single);
try
{
if (UnityEngine.Object.FindFirstObjectByType<ZoneRenderer>(FindObjectsInactive.Include) != null)
Fail("wiring", "Main Menu.unity has a ZoneRenderer: its gravity cameras now read the Gravity Field and must cull layer 9 alone");
var seen = 0;
foreach (var camera in UnityEngine.Object.FindObjectsByType<Camera>(FindObjectsInactive.Include, FindObjectsSortMode.None))
{
if (camera.targetTexture == null || camera.targetTexture.name != "Fog Surface Displacement") continue;
seen++;
const int menuBrushLayers = (1 << 9) | (1 << 10);
if (camera.cullingMask != menuBrushLayers)
Fail("wiring", $"Main Menu camera {camera.name} culls mask {camera.cullingMask}, not the menu brush layers 9 and 10");
}
if (seen != 1) Fail("wiring", $"{seen} Fog Surface Displacement cameras in Main Menu.unity, expected 1");
}
finally
{
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
}
}
static void CheckWiring(GameSettings settings)
{
var scene = EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Single);
try
{
var gravityTargets = new[] { "Fog Surface Displacement", "Slime Gravity", "MinimapGravity" };
var seen = 0;
foreach (var camera in UnityEngine.Object.FindObjectsByType<Camera>(FindObjectsInactive.Include, FindObjectsSortMode.None))
{
if (camera.targetTexture == null || !gravityTargets.Contains(camera.targetTexture.name)) continue;
seen++;
if (camera.cullingMask != 1 << GravityLowering.FieldLayer)
Fail("wiring", $"camera {camera.name} (target {camera.targetTexture.name}) culls mask {camera.cullingMask}, not layer {GravityLowering.FieldLayer} alone");
}
if (seen < gravityTargets.Length) Fail("wiring", $"only {seen} gravity cameras found in ARPG.unity");
// The map screen's gravity camera has no target until MapRenderer gives it one at run time.
var map = UnityEngine.Object.FindFirstObjectByType<MapRenderer>(FindObjectsInactive.Include);
if (map == null || map.GravityCamera == null) Fail("wiring", "no MapRenderer.GravityCamera in ARPG.unity");
else if (map.GravityCamera.cullingMask != 1 << GravityLowering.FieldLayer)
Fail("wiring", $"MapRenderer.GravityCamera culls mask {map.GravityCamera.cullingMask}, not layer {GravityLowering.FieldLayer} alone");
var renderer = UnityEngine.Object.FindFirstObjectByType<ZoneRenderer>(FindObjectsInactive.Include);
if (renderer == null) Fail("wiring", "no ZoneRenderer in ARPG.unity");
else if (renderer.GravityField == null || renderer.GravityField.shader.name != "Brushes/Gravity Field")
Fail("wiring", "ZoneRenderer.GravityField is not a Brushes/Gravity Field material");
foreach (var r in UnityEngine.Object.FindObjectsByType<Renderer>(FindObjectsInactive.Include, FindObjectsSortMode.None))
if (r.gameObject.layer == GravityLowering.FieldLayer)
Fail("wiring", $"renderer {r.name} in ARPG.unity sits on layer {GravityLowering.FieldLayer}");
}
finally
{
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
}
CheckMenuWiring();
foreach (var path in new[]
{
"Assets/Prefabs/RPG/Planets/Planet.prefab", "Assets/Prefabs/RPG/Planets/Gas Giant.prefab",
"Assets/Prefabs/RPG/Planets/Sun.prefab", "Assets/Prefabs/RPG/Wormhole 1.prefab"
})
{
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
if (prefab == null) { Fail("wiring", $"no prefab at {path}"); continue; }
foreach (var r in prefab.GetComponentsInChildren<Renderer>(true))
if (r.gameObject.layer == GravityLowering.FieldLayer)
Fail("wiring", $"renderer {r.name} in {path} sits on layer {GravityLowering.FieldLayer}");
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1ceb2bdab0804463b1998471d47e82fa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,32 @@
using CultMath;
using static CultMath.math;
using float2 = CultMath.float2;
/// <summary>
/// The law of one gravity well: a 2D point mass with a softened core. Outside the core radius the potential is
/// logarithmic and the pull is c / r; inside it the pull falls linearly to zero at the centre and meets the tail in
/// value and slope at the core radius. c is the well's strength (u^2/s^2), R its core radius (u). No threshold
/// anywhere: a well pulls at every distance. Zone.GetForce and Zone.GetHeight sum this over a zone's bodies.
/// </summary>
public static class GravityField
{
// The tail's additive constant: it makes the tail meet the core in value at the core radius. Gravity.cginc is generated from it.
public const float TailOffset = .5f;
// The potential at distance r from the body, defined up to a constant (callers subtract their reference).
// A well of no strength (a body whose curves are unauthored, so c = 0 and R = 0) digs nothing.
public static float Potential(float c, float coreRadius, float r) =>
c == 0f ? 0f :
r < coreRadius
? c * r * r / (2 * coreRadius * coreRadius)
: c * (log(r / coreRadius) + TailOffset);
// The acceleration at `offsetFromBody`, toward the body: zero at the body itself.
public static float2 Acceleration(float c, float coreRadius, float2 offsetFromBody)
{
var r = length(offsetFromBody);
if (r == 0f) return float2.zero;
var pull = r < coreRadius ? c * r / (coreRadius * coreRadius) : c / r;
return -offsetFromBody / r * pull;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5b0c7d3e9a1f4e2c8d6a7f1b3c9e0a42
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,63 @@
using System.Globalization;
/// <summary>
/// The single author of Assets/Shaders/Gravity.cginc, the GPU lowering of the zone's potential. The law is
/// GravityField's (its constants are read here, not respelled) and the height is Zone.GetHeight: each well's
/// potential minus its reference, summed, divided by the exaggeration. Unity does not run C# when it imports a
/// shader, so the committed cginc is this output; GravityShaderTests fails unless it equals Source() exactly.
/// To change the shader, change this file and regenerate: AETHERIA_REGENERATE_GRAVITY_CGINC=1 dotnet test --filter GravityShaderTests.
/// </summary>
public static class GravityShader
{
public const string Path = "Assets/Shaders/Gravity.cginc";
/// <summary>The whole file, with LF line ends.</summary>
public static string Source() => (Template
.Replace("@TAIL@", GravityField.TailOffset.ToString("R", CultureInfo.InvariantCulture)))
.Replace("\r\n", "\n");
private const string Template = @"#ifndef AETHERIA_GRAVITY_INCLUDED
#define AETHERIA_GRAVITY_INCLUDED
// GENERATED by ServerShared/GravityShader.cs from GravityField; do not edit (GravityShaderTests fails on any difference).
// The lowering of the zone's potential (aetheria-gravity, cut grid-lowering). The law is ServerShared's GravityField
// and the height is Zone.GetHeight; this file decides nothing. GravityLowering.Lower fills the buffer and the globals
// from the zone (positions from Orbit.Position, reference from Zone.WellReference) each frame.
// GravityFieldParityVerify renders it and compares every texel with -Zone.GetHeight.
struct GravityWell
{
float2 position;
float strength;
float coreRadius;
float reference;
};
StructuredBuffer<GravityWell> _GravityWells;
int _GravityWellCount;
float _HeightExaggeration;
// GravityField.Potential: c is the well's strength, R its core radius, r the distance.
float gravityPotential(float c, float R, float r)
{
return c == 0 ? 0 :
r < R
? c * r * r / (2 * R * R)
: c * (log(r / R) + @TAIL@);
}
// Zone.GetHeight at world xz: each well's potential minus its own reference, summed, divided by the exaggeration.
float gravityHeight(float2 p)
{
float result = 0;
for (int i = 0; i < _GravityWellCount; i++)
{
GravityWell well = _GravityWells[i];
result += gravityPotential(well.strength, well.coreRadius, length(p - well.position)) - well.reference;
}
return result / _HeightExaggeration;
}
#endif
";
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9a3fa1e9df764459b709270e58e79974
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -4,20 +4,26 @@ using static ItemRotation;
public sealed class Crossing : Scenario
{
public override string Name => "Crossing";
public override string Brief => "A Lightning Projector at the starboard gun and a Cell Blaster at the port gun, a fast Djinni crossing close ahead and an " +
"unpiloted one waiting at range. The Djinni starts to port moving across the bow; the arena's gravity bends its run. Make the pass coasting: give no throttle until the Djinni has crossed the bow, then fly freely (thrusting from the start carries you past it). Verify: as the Djinni crosses close, FastBlast lands some and projector " +
public override string Brief => "A Lightning Projector at the starboard gun and a Cell Blaster at the port gun, an unpiloted Djinni coasting across the bow " +
"close ahead and an unpiloted one waiting at range. The crosser is launched to port at 50 m/s and only coasts: nothing steers it, " +
"its hull drag slows it to about 25 m/s at the bow line, and it does not shoot back. Make the pass coasting: give no throttle until the Djinni has crossed the bow, then fly freely " +
"(thrusting from the start carries you past it). Verify: as the Djinni crosses close, FastBlast lands some and projector " +
"almost none; against the Djinni at range both land. Fly it again without the Fire Control Array: " +
"with it the small gun lands more.";
public override uint Seed => 112;
public override bool Ambient => false;
// Where the Djinni sit: the player is at the origin facing +z. The crosser starts ahead and to port, facing across
// the bow and already moving at the Djinni's 50 m/s cap, so its run sweeps across the bow within seconds (the arena
// pulls the player to port, which brings the two together). The waiting Djinni sits inside the Lightning Projector's arc at 80% of
// its Range.
public static readonly CultMath.float2 CrosserAt = float2(-150, 200), CrosserFacing = float2(1, 0), CrosserVelocity = float2(50, 0);
// Where the Djinni sit: the player is at Origin facing +z. Origin is 250 m or more from every body, where the zone's
// pull is weakest (about 1.4 u/s^2; the sum of the wells never drops to nothing, and at the old origin the player sat on the star).
// The crosser is unpiloted and placed moving at the Djinni's 50 m/s cap, so its pass is ballistic: bent by the field and slowed
// by hull drag (it reaches the bow line at about 25 m/s relative to the player, 3.6 s in), and nothing steers it.
// CrosserAt is the centre of the start window in which the pass holds: shifting it by 10 m along either axis keeps the pass
// inside the test's time and distance windows (CrossingHoldsAcrossTheStartWindow).
// The waiting Djinni sits inside the Lightning Projector's arc at 80% of its Range.
public static readonly CultMath.float2 Origin = float2(724, 124);
public static readonly CultMath.float2 CrosserAt = Origin + float2(-128, 45), CrosserFacing = float2(1, 0), CrosserVelocity = float2(50, 0);
public const float ProjectorRange = 1216f; // the Lightning Projector's Range in metres, 1216.4 as the fit stands settled at rest
public static readonly CultMath.float2 Waiting = float2(0, ProjectorRange * .8f);
public static readonly CultMath.float2 Waiting = Origin + float2(0, ProjectorRange * .8f);
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
@ -39,8 +45,8 @@ public sealed class Crossing : Scenario
("Compact Sensor", int2(3, 10), None),
("Fire Control Array", int2(1, 6), Clockwise));
stage.Player(fighter, float2(0, 0), facing: float2(0, 1));
stage.Place(stage.Generated("Djinni"), CrosserAt, facing: CrosserFacing, stance: ScenarioStance.Hostile, piloted: true, velocity: CrosserVelocity);
stage.Player(fighter, Origin, facing: float2(0, 1));
stage.Place(stage.Generated("Djinni"), CrosserAt, facing: CrosserFacing, stance: ScenarioStance.Hostile, velocity: CrosserVelocity);
stage.Place(stage.Bare("Djinni"), Waiting);
}
}

View file

@ -10,11 +10,13 @@ public sealed class LockOn : Scenario
public override uint Seed => 113;
public override bool Ambient => false;
// The hostile starts about 4000 m off, to the side of the player's axis, facing the player. At that range its passive
// sensors hold no track of the player (the test asks the sim's own PassiveInfo against the detection threshold); the
// player sees the hostile a little sooner, at about tick 20. The hostile closes, sees the player some eight seconds in,
// and locks two ticks later. At Duel's 900 m (and at 600 m) it sees and locks within a second.
public static readonly CultMath.float2 HostileAt = float2(1500, 3700);
// The hostile starts about 4000 m off, ahead and to port of the player, facing the player. At that range its passive
// sensors hold no track of the player (the test asks the sim's own PassiveInfo against the detection threshold). The
// hostile closes, sees the player some fourteen seconds in and locks. The zone's pull bends the hostile's run and moves the
// player, and the warning must still point at where the hostile was staged to within 5 degrees at the lock: this side keeps
// the bend under one degree (on the far side it is more than seven). At Duel's 900 m (and at 600 m) it sees and locks
// within a second.
public static readonly CultMath.float2 HostileAt = float2(-2000, 3450);
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);

View file

@ -13,15 +13,22 @@ using static CultMath.math;
[Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject]
public class PlanetSettings
{
public ExponentialCurve GravityDepth;
public ExponentialCurve GravityRadius;
public ExponentialCurve LightRadius;
public ExponentialCurve BodyRadius;
// The closest a child may orbit its parent, in u, by the parent's mass, and the softened core radius of the parent's
// well (the steepest drawn slope sits at the Roche limit). Authored like BodyRadius, never per body.
public ExponentialCurve RocheLimit = new ExponentialCurve();
// A body's well strength by its mass (GravityField): c in u^2/s^2 (the pull is c / r beyond the core, which is the Roche limit).
public ExponentialCurve WellStrength = new ExponentialCurve();
// The one global exaggeration of gravity height: height = potential / K, in u/s^2 per unit of height.
public float HeightExaggeration = 1f;
public float AsteroidVerticalOffset = -5f;
public ExponentialLerp AsteroidSize;
public ExponentialLerp AsteroidHitpoints;
public ExponentialLerp AsteroidRespawnTime;
public float GravityStrength;
public float SecureAreaRadiusMultiplier = .45f;
public ExponentialCurve OrbitPeriod;

View file

@ -130,9 +130,8 @@ public class Ship : Entity
Position.xz += Velocity * delta;
Velocity += Zone.GetForce(Position.xz) * delta;
var normal = Zone.GetNormal(Position.xz);
var force = new float2(normal.x, normal.z);
Velocity += Zone.GravityAcceleration(force, Zone.Settings.GravityStrength) * delta;
var shipRight = Direction.Rotate(ItemRotation.Clockwise);
var forward = cross(float3(shipRight.x, 0, shipRight.y), normal);
Rotation = quaternion.LookRotation(forward, normal);

View file

@ -612,22 +612,20 @@ public class Zone
return security;
}
// The potential of a body's well at the zone's edge, subtracted so every well is zero there: the one owner of the
// reference. GetHeight sums with it and the renderer's lowering (GravityLowering) hands it to the shader unchanged.
public float WellReference(Planet body) => GravityField.Potential(body.WellStrength, body.RocheLimit, Pack.Radius);
public float GetHeight(float2 position)
{
var result = 0f;
foreach (var body in PlanetInstances.Values)
{
var p = position - body.Orbit.Position; //GetOrbitPosition(body.BodyData.Orbit)
var distSqr = lengthsq(p);
var gravityRadius = body.GravityWellRadius;
if (distSqr < gravityRadius*gravityRadius)
{
var depth = body.GravityWellDepth;
result -= PowerPulse(sqrt(distSqr) / gravityRadius, body.BodyData.GravityDepthExponent) * depth;
}
var offset = position - body.Orbit.Position;
result += GravityField.Potential(body.WellStrength, body.RocheLimit, length(offset)) - WellReference(body);
}
return result;
return result / Settings.HeightExaggeration;
}
public float GetLight(float2 position)
@ -647,33 +645,21 @@ public class Zone
internal float SchematicCellSize => _itemManager.GameplaySettings.SchematicCellSize;
internal float FieldCrossSection(AsteroidBeltData belt) => _itemManager.ItemData.Get(belt.Kind)?.CrossSection ?? 0f;
// The one law of how a gravity well pushes anything: ships, floating items and mines all read it. The shape is
// the one ships have always felt, normalize(f) * strength * (1 / (1 - |f|^2) - 1), gated off below |f|^2 = .001.
// It is an acceleration, per second: the legacy law added that amount once per 60 fps frame with no dt, so
// GravityReferenceRate (60) restates it and `acceleration * dt` gives the legacy push at 60 fps.
public const float GravityReferenceRate = 60f;
public static float2 GravityAcceleration(float2 normalXz, float strength)
{
var magnitude = lengthsq(normalXz);
if (magnitude <= .001f) return float2.zero;
return normalize(normalXz) * strength * (1 / (1 - magnitude) - 1) * GravityReferenceRate;
}
// The acceleration the well exerts at `position`.
// The one source of gravitational acceleration (u/s^2): the sum of every body's well (GravityField). Ships,
// floating items, clouds and mines all read it, and so does Flow. It is the gradient of the potential GetHeight
// draws, so the two cannot disagree.
public float2 GetForce(float2 position)
{
var normal = GetNormal(position);
return GravityAcceleration(new float2(normal.x, normal.z), Settings.GravityStrength);
var force = float2.zero;
foreach (var body in PlanetInstances.Values)
force += GravityField.Acceleration(body.WellStrength, body.RocheLimit, position - body.Orbit.Position);
return force;
}
// The global flow velocity at `position` in zone time, in u/s (FlowField is the law). The slope term reads the
// downhill gradient, which GetNormal's xz is proportional to.
public float3 Flow(float3 position)
{
var normal = GetNormal(position.xz);
return FlowField.At(Settings.Flow, position, FlowScroll, new float2(normal.x, normal.z));
}
// downhill direction, which is the force.
public float3 Flow(float3 position) =>
FlowField.At(Settings.Flow, position, FlowScroll, GetForce(position.xz));
// The flow's noise scroll at zone time (Zone.Flow evaluates at exactly this); lowered to the shaders' _FlowScroll.
public float2 FlowScroll => FlowField.Scroll(Settings.Flow, _time);
@ -688,16 +674,12 @@ public class Zone
return pow((x + 1) * (1 - x), exponent);
}
public float3 GetNormal(float2 pos, float step = .1f, float mul = 1)
// The surface normal of the drawn height (potential / K), derived from the force. Display only (ship tilt): the
// sim never reads it as a force.
public float3 GetNormal(float2 pos)
{
float hL = GetHeight(new float2(pos.x - step, pos.y)) * mul;
float hR = GetHeight(new float2(pos.x + step, pos.y)) * mul;
float hD = GetHeight(new float2(pos.x, pos.y - step)) * mul;
float hU = GetHeight(new float2(pos.x, pos.y + step)) * mul;
// Deduce terrain normal
float3 normal = new float3((hL - hR), (hD - hU), step*2);
return normalize(normal).xzy;
var slope = GetForce(pos) / Settings.HeightExaggeration;
return normalize(new float3(slope.x, 1f, slope.y));
}
}
@ -706,10 +688,13 @@ public class Planet
public Orbit Orbit;
protected readonly PlanetSettings Settings;
public BodyData BodyData;
public float GravityWellDepth;
public float GravityWellRadius;
public float BodyRadius;
// The well (GravityField): strength c by mass, and the Roche limit, which is both the closest a child may orbit and
// the well's softened core radius R (one curve of mass, never per body). Both are authored PlanetSettings curves.
public float WellStrength;
public float RocheLimit;
public Planet(PlanetSettings settings, BodyData data, Orbit orbit)
{
Settings = settings;
@ -721,8 +706,12 @@ public class Planet
public void CalculateProperties()
{
BodyRadius = Settings.BodyRadius.Evaluate(BodyData.Mass) * BodyData.BodyRadiusMultiplier;
GravityWellRadius = Settings.GravityRadius.Evaluate(BodyData.Mass) * BodyData.GravityRadiusMultiplier;
GravityWellDepth = Settings.GravityDepth.Evaluate(BodyData.Mass) * BodyData.GravityDepthMultiplier;
WellStrength = Settings.WellStrength.Evaluate(BodyData.Mass);
RocheLimit = Settings.RocheLimit.Evaluate(BodyData.Mass);
if (!(WellStrength >= 0f) || float.IsInfinity(WellStrength))
throw new InvalidOperationException("A body's well strength must be finite and not negative (PlanetSettings.WellStrength).");
if (WellStrength > 0 && !(RocheLimit > 0f && !float.IsInfinity(RocheLimit)))
throw new InvalidOperationException("A body's Roche limit, which is its core radius, must be positive and finite (PlanetSettings.RocheLimit).");
}
}

View file

@ -86,15 +86,6 @@ public abstract class BodyData
[JsonProperty("bodyRadiusMul")] [Key(5)]
public float BodyRadiusMultiplier = 1;
[JsonProperty("gravRadiusMul")] [Key(6)]
public float GravityRadiusMultiplier = 1;
[JsonProperty("depthMul")] [Key(7)]
public float GravityDepthMultiplier = 1;
[JsonProperty("depthExp")] [Key(8)]
public float GravityDepthExponent = 16;
}
[CultDocument("aetheria.planetdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]

View file

@ -0,0 +1,78 @@
using System.Runtime.InteropServices;
using UnityEngine;
/// <summary>
/// The renderer's lowering of the zone's potential (aetheria-gravity, cut grid-lowering). Zone.GetHeight owns the drawn
/// height: this hands its inputs (each well's position, strength, core radius and reference, and the exaggeration) to
/// Assets/Shaders/Gravity.cginc, which sums them per texel, and makes the one quad that carries the sum into every
/// camera that culls layer 9. Nothing here decides a height.
/// </summary>
public static class GravityLowering
{
/// <summary>The layer the gravity cameras cull; nothing but the run-time field sits on it.</summary>
public const int FieldLayer = 9;
/// <summary>The quad's side in u: larger than any zone (10000) plus any view (4096); texels outside a camera cost nothing.</summary>
public const float FieldExtent = 100000f;
// Mirrors the well record of Gravity.cginc: float2 position, strength, coreRadius, reference.
[StructLayout(LayoutKind.Sequential)]
struct WellRecord
{
public Vector2 Position;
public float Strength;
public float CoreRadius;
public float Reference;
}
static readonly int Stride = Marshal.SizeOf<WellRecord>();
static readonly int WellsId = Shader.PropertyToID("_GravityWells");
static readonly int CountId = Shader.PropertyToID("_GravityWellCount");
static readonly int ExaggerationId = Shader.PropertyToID("_HeightExaggeration");
static WellRecord[] _records = new WellRecord[0];
/// <summary>
/// Fills one record per body of the zone (a null zone has none) and sets the shader globals. The buffer is the
/// caller's, (re)allocated to the body count (at least one, so the global is always bound).
/// </summary>
public static void Lower(Zone zone, ref ComputeBuffer wells)
{
var count = zone?.PlanetInstances.Count ?? 0;
var capacity = Mathf.Max(count, 1);
if (wells == null || wells.count != capacity)
{
wells?.Release();
wells = new ComputeBuffer(capacity, Stride);
}
if (_records.Length != capacity) _records = new WellRecord[capacity];
var i = 0;
if (zone != null)
foreach (var body in zone.PlanetInstances.Values)
_records[i++] = new WellRecord
{
Position = new Vector2(body.Orbit.Position.x, body.Orbit.Position.y),
Strength = body.WellStrength,
CoreRadius = body.RocheLimit,
Reference = zone.WellReference(body)
};
wells.SetData(_records);
Shader.SetGlobalBuffer(WellsId, wells);
Shader.SetGlobalInt(CountId, count);
Shader.SetGlobalFloat(ExaggerationId, zone?.Settings.HeightExaggeration ?? 1f);
}
/// <summary>The one quad of the field: flat in xz at y 0 on layer 9, drawn with the Gravity Field material.</summary>
public static GameObject CreateField(Material material)
{
var field = new GameObject("Gravity Field") { layer = FieldLayer };
field.transform.rotation = Quaternion.Euler(90f, 0f, 0f);
field.transform.localScale = FieldExtent * Vector3.one;
field.AddComponent<MeshFilter>().sharedMesh = Resources.GetBuiltinResource<Mesh>("Quad.fbx");
var renderer = field.AddComponent<MeshRenderer>();
renderer.sharedMaterial = material;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
return field;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1a5e08474b514e509ed1477b3ac06e94
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -9,7 +9,6 @@ using UnityEngine;
public class PlanetObject : MonoBehaviour
{
public MeshRenderer Body;
public MeshRenderer GravityWell;
public MeshRenderer Icon;
public CelestialBodyGenerator Generator;
}

View file

@ -46,6 +46,8 @@ public class ZoneRenderer : MonoBehaviour
public MineInstance MinePrefab;
public VapourCloudInstance CloudPrefab;
public Material[] MapGravityMaterials;
// The gravity field's material (Brushes/Gravity Field): GravityLowering makes the one quad that draws it.
public Material GravityField;
[Header("Tour")] public bool Tour;
public float TourSwitchTime = 5f;
@ -77,7 +79,8 @@ public class ZoneRenderer : MonoBehaviour
// is stored on AsteroidBelt any more.
private Dictionary<CultRecordKey, float4[]> _beltTransforms = new Dictionary<CultRecordKey, float4[]>();
private float _viewDistance;
//private float _maxDepth;
private GameObject _gravityField;
private ComputeBuffer _gravityWells;
private float _minimapDistance;
private int _tourIndex = -1;
@ -195,6 +198,7 @@ public class ZoneRenderer : MonoBehaviour
SectorBrushes.localScale = zone.Pack.Radius * 2 * Vector3.one;
SlimeGravityCamera.orthographicSize = zone.Pack.Radius;
SlimeRenderer.ZoneRadius = zone.Pack.Radius;
if (_gravityField == null) _gravityField = GravityLowering.CreateField(GravityField);
foreach (var p in zone.Planets)
LoadPlanet(p.Key, p.Value);
@ -321,9 +325,17 @@ public class ZoneRenderer : MonoBehaviour
WormholeInstances.Add(wormhole, (instance.gameObject, icon));
}
void OnDestroy()
{
_gravityWells?.Release();
_gravityWells = null;
}
public void ClearZone()
{
if (Zone == null) return;
_gravityWells?.Release();
_gravityWells = null;
foreach (var wormhole in WormholeInstances.Values)
{
Destroy(wormhole.gravity);
@ -491,11 +503,6 @@ public class ZoneRenderer : MonoBehaviour
var planetInstance = Zone.PlanetInstances[key];
planet.Body.transform.localScale = planetInstance.BodyRadius * Vector3.one;
planet.GravityWell.transform.localScale = planetInstance.GravityWellRadius * Vector3.one;
// var depth = planetInstance.GravityWellDepth;
// if (depth > _maxDepth) _maxDepth = depth;
planet.GravityWell.material.SetFloat("_Depth", planetInstance.GravityWellDepth);
planet.Icon.transform.position = new Vector3(0, -planetInstance.GravityWellDepth, 0);
planet.Icon.transform.localScale = Settings.IconSize.Evaluate(planetInstance.BodyData.Mass) * Vector3.one;
@ -513,6 +520,7 @@ public class ZoneRenderer : MonoBehaviour
void Update()
{
var maxDepth = 0f;
GravityLowering.Lower(Zone, ref _gravityWells);
foreach (var loot in _floatingItems.Values)
{
loot.ViewOrigin = PerspectiveEntity.Position;
@ -576,6 +584,7 @@ public class ZoneRenderer : MonoBehaviour
if (-height > maxDepth) maxDepth = -height;
planet.Value.transform.position = new Vector3(p.x, 0, p.y);
planet.Value.Body.transform.localPosition = new Vector3(0, height + planetInstance.BodyRadius * 2, 0);
planet.Value.Icon.transform.localPosition = new Vector3(0, height, 0);
if (planet.Value is GasGiantObject gasGiantObject)
{
if (!(planet.Value is SunObject))