diff --git a/Assets/Materials/UI/MapAsteroid.mat b/Assets/Materials/UI/MapAsteroid.mat new file mode 100644 index 000000000..a0dbbdb1f --- /dev/null +++ b/Assets/Materials/UI/MapAsteroid.mat @@ -0,0 +1,31 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 8 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: MapAsteroid + m_Shader: {fileID: 4800000, guid: 22e2fc798f044a3aa2f6cd71f1df09a7, type: 3} + m_ValidKeywords: [] + m_InvalidKeywords: [] + m_LightmapFlags: 0 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: 3000 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _MainTex: + m_Texture: {fileID: 2800000, guid: 060aefd5a3d5ced4dabd9190a140e76e, type: 3} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Ints: [] + m_Floats: [] + m_Colors: + - _Color: {r: 1, g: 1, b: 1, a: 1} + m_BuildTextureStacks: [] diff --git a/Assets/Prefabs/RTS/Asteroid Belt.prefab.meta b/Assets/Materials/UI/MapAsteroid.mat.meta similarity index 52% rename from Assets/Prefabs/RTS/Asteroid Belt.prefab.meta rename to Assets/Materials/UI/MapAsteroid.mat.meta index f1298ae38..2c044e9e9 100644 --- a/Assets/Prefabs/RTS/Asteroid Belt.prefab.meta +++ b/Assets/Materials/UI/MapAsteroid.mat.meta @@ -1,7 +1,8 @@ fileFormatVersion: 2 -guid: 1f1bfa2175a13b647888e2949e0cb138 -PrefabImporter: +guid: c1012d5466454651b7279be93ef9af88 +NativeFormatImporter: externalObjects: {} + mainObjectFileID: 2100000 userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Prefabs/RTS/Asteroid Belt.prefab b/Assets/Prefabs/RTS/Asteroid Belt.prefab deleted file mode 100644 index 38df4e9e3..000000000 --- a/Assets/Prefabs/RTS/Asteroid Belt.prefab +++ /dev/null @@ -1,111 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!1 &992254348637625916 -GameObject: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - serializedVersion: 6 - m_Component: - - component: {fileID: 1779911639310264026} - - component: {fileID: 349597964696402918} - - component: {fileID: 2844878085845264008} - - component: {fileID: 917803079556930035} - - component: {fileID: 4397878771830533054} - m_Layer: 14 - m_Name: Asteroid Belt - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!4 &1779911639310264026 -Transform: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 992254348637625916} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: 0, y: 0, z: 0} - m_LocalScale: {x: 1, y: 1, z: 1} - m_Children: [] - m_Father: {fileID: 0} - m_RootOrder: 0 - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!33 &349597964696402918 -MeshFilter: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 992254348637625916} - m_Mesh: {fileID: 0} ---- !u!23 &2844878085845264008 -MeshRenderer: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 992254348637625916} - m_Enabled: 1 - m_CastShadows: 1 - m_ReceiveShadows: 1 - m_DynamicOccludee: 1 - m_MotionVectors: 1 - m_LightProbeUsage: 1 - m_ReflectionProbeUsage: 1 - m_RayTracingMode: 2 - m_RayTraceProcedural: 0 - m_RenderingLayerMask: 1 - m_RendererPriority: 0 - m_Materials: - - {fileID: 2100000, guid: c018d99199afeca448c64b9022ac7270, type: 2} - m_StaticBatchInfo: - firstSubMesh: 0 - subMeshCount: 0 - m_StaticBatchRoot: {fileID: 0} - m_ProbeAnchor: {fileID: 0} - m_LightProbeVolumeOverride: {fileID: 0} - m_ScaleInLightmap: 1 - m_ReceiveGI: 1 - m_PreserveUVs: 0 - m_IgnoreNormalsForChartDetection: 0 - m_ImportantGI: 0 - m_StitchLightmapSeams: 0 - m_SelectedEditorRenderState: 3 - m_MinimumChartSize: 4 - m_AutoUVMaxDistance: 0.5 - m_AutoUVMaxAngle: 89 - m_LightmapParameters: {fileID: 0} - m_SortingLayerID: 0 - m_SortingLayer: 0 - m_SortingOrder: 0 - m_AdditionalVertexStreams: {fileID: 0} ---- !u!64 &917803079556930035 -MeshCollider: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 992254348637625916} - m_Material: {fileID: 0} - m_IsTrigger: 0 - m_Enabled: 1 - serializedVersion: 4 - m_Convex: 0 - m_CookingOptions: 30 - m_Mesh: {fileID: 0} ---- !u!114 &4397878771830533054 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 992254348637625916} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 52538a3309c36fc4583c964a1c0b705f, type: 3} - m_Name: - m_EditorClassIdentifier: diff --git a/Assets/Scenes/ARPG.unity b/Assets/Scenes/ARPG.unity index a7940de8e..0bee4642b 100644 --- a/Assets/Scenes/ARPG.unity +++ b/Assets/Scenes/ARPG.unity @@ -16421,8 +16421,7 @@ MonoBehaviour: TourFollowDistance: 100 TourHeightOffset: 50 TourFollowOffsetDegrees: 55 - AsteroidBeltUI: {fileID: 349597964696402918, guid: 1f1bfa2175a13b647888e2949e0cb138, - type: 3} + MapAsteroidMaterial: {fileID: 2100000, guid: c1012d5466454651b7279be93ef9af88, type: 2} Planet: {fileID: 8287217960984982033, guid: 88ace6073e3db1a46bd3aaf4f971acb9, type: 3} GasGiant: {fileID: 3250623180916197132, guid: 85753b4a7c762274385af384abed7a04, type: 3} diff --git a/Assets/Scripts/Editor/CapabilityPresentationSmoke.cs b/Assets/Scripts/Editor/CapabilityPresentationSmoke.cs index 75d97c63f..fd8f1cffd 100644 --- a/Assets/Scripts/Editor/CapabilityPresentationSmoke.cs +++ b/Assets/Scripts/Editor/CapabilityPresentationSmoke.cs @@ -85,6 +85,11 @@ public static class CapabilityPresentationSmoke ?? throw new InvalidOperationException("No Tractor Beam prefab."); // An entity's instance as the game builds it: the beam is a child before SetEntity on both ship paths, so the // binder finds it as the game does. + // The scene's map: an entity registers its icon with the ZoneRenderer's presenter, so each instance carries a quad. + var mapRenderer = new GameObject("Smoke Zone Renderer").AddComponent(); + mapRenderer.Settings = AssetDatabase.LoadAssetAtPath("Assets/Resources/Settings.asset"); + mapRenderer.MapGravityMaterials = new Material[0]; + Awaken(mapRenderer); (GameObject Object, EntityInstance Instance, TractorBeam Beam) Bound(string name, Entity entity) { var go = new GameObject(name); @@ -98,7 +103,11 @@ public static class CapabilityPresentationSmoke var tractor = ((GameObject)PrefabUtility.InstantiatePrefab(beamPrefab, go.transform)).GetComponent(); tractor.Power = .8f; tractor.Direction = Vector3.forward; - bound.SetEntity(null, entity); + var icon = GameObject.CreatePrimitive(PrimitiveType.Quad); + icon.transform.SetParent(go.transform); + bound.MapIcon = icon.GetComponent(); + bound.MapIcon.sharedMaterial = new Material(Shader.Find("Unlit/Color")); + bound.SetEntity(mapRenderer, entity); return (go, bound, tractor); } var (instanceObject, instance, beam) = Bound("Smoke Entity Instance", ship); diff --git a/Assets/Scripts/Editor/MapBeltPerf.cs b/Assets/Scripts/Editor/MapBeltPerf.cs new file mode 100644 index 000000000..7e4e5a594 --- /dev/null +++ b/Assets/Scripts/Editor/MapBeltPerf.cs @@ -0,0 +1,117 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using GameCult.Caching; +using UnityEditor; +using CultMath; +using UnityEngine; +using float4 = CultMath.float4; +using Debug = UnityEngine.Debug; + +// The map's belt cost per frame, CPU milliseconds and managed allocation, for belts of 1000, 2250 (the generated +// maximum, Settings.asset) and 4000 asteroids: the base revision's AsteroidBeltUI.Update (MapBeltPerfBase, a verbatim copy) +// and MapPresenter's belt upload and draw, each as the median and interquartile range of 21 runs of 300 frames after +// a warm-up, in this one Unity job. CPU time only: GPU cost is not covered. Needs a GPU device. +// +// Unity -batchmode -projectPath -executeMethod MapBeltPerf.Run -logFile +public static class MapBeltPerf +{ + private const int Warmup = 60, Frames = 300, RunCount = 21; + + public static void Run() + { + var work = Path.Combine(Path.GetTempPath(), $"map-belt-perf-{Guid.NewGuid():N}"); + try + { + Directory.CreateDirectory(work); + foreach (var count in new[] { 1000, 2250, 4000 }) Measure(work, count); + EditorApplication.Exit(0); + } + catch (Exception exception) + { + Debug.LogException(exception); + EditorApplication.Exit(1); + } + } + + private static void Measure(string work, int count) + { + var settings = AssetDatabase.LoadAssetAtPath("Assets/Resources/Settings.asset"); + var cache = AetheriaStores.Open(Path.Combine(work, $"c{count}.cc"), Path.Combine(work, $"r{count}.cc"), catalogWritable: true); + cache.Upsert(new VerseGrammar { Revision = 1 }); + var sunOrbit = cache.Upsert(new OrbitData()).Key; + var sunKey = cache.Upsert(new PlanetData { Name = "Sun", Orbit = new CultRecordRef(sunOrbit), Mass = 400f }).Key; + var beltOrbit = cache.Upsert(new OrbitData { Parent = new CultRecordRef(sunOrbit), Distance = 900f, Phase = .42f }).Key; + var asteroids = Enumerable.Range(0, count).Select(i => new Asteroid + { Distance = 120f + i * .01f, Phase = CultMath.math.frac(i * .618f), Size = CultMath.math.frac(i * .37f + .1f), RotationSpeed = .15f + i * 1e-4f }).ToArray(); + var beltKey = cache.Upsert(new AsteroidBeltData { Orbit = new CultRecordRef(beltOrbit), Asteroids = asteroids }).Key; + var pack = new ZonePack + { + Orbits = { new CultRecordRef(sunOrbit), new CultRecordRef(beltOrbit) }, + Planets = { new CultRecordRef(sunKey), new CultRecordRef(beltKey) }, + Radius = 5000f, Mass = 10000f, Time = 0 + }; + var items = new ItemManager(cache, new ProvenanceLedger(), settings.GameplaySettings, _ => { }); + var zone = new Zone(items, new PlanetSettings + { + BodyRadius = new ExponentialCurve(), WellStrength = new ExponentialCurve { Multiplier = 1f, Exponent = 1f }, + RocheLimit = new ExponentialCurve { Constant = 2f }, + AsteroidSize = new ExponentialLerp { Minimum = 2f, Maximum = 9f, Exponent = 1.7f }, + AsteroidHitpoints = new ExponentialLerp { Minimum = 10f, Maximum = 300f, Exponent = 2f }, + AsteroidRespawnTime = new ExponentialLerp { Minimum = 5f, Maximum = 60f, Exponent = 1f } + }, pack, new GalaxyZone { Name = "Perf", Owner = null }, null); + + var transforms = new float4[count]; + var presenter = new MapPresenter(new Material[0], AssetDatabase.LoadAssetAtPath("Assets/Materials/UI/MapAsteroid.mat"), 4, 4, 3f); + presenter.BeltsOnMinimap = true; + presenter.RegisterBelt(beltKey, transforms); + var baseBelt = new MapBeltPerfBase(zone, zone.AsteroidBelts[beltKey], 4, 4, 3f); + + Report("base", count, Runs(zone, beltKey, transforms, () => baseBelt.Update(transforms, 0f))); + Report("head", count, Runs(zone, beltKey, transforms, () => presenter.Draw(zone, 0))); + presenter.Clear(); + } + + // Each run is Frames frames after Warmup frames; the figure is one run's CPU ms per frame and managed bytes per frame. + private static (double ms, long bytes)[] Runs(Zone zone, CultRecordKey beltKey, float4[] transforms, Action frame) + { + var results = new (double, long)[RunCount]; + var stopwatch = new Stopwatch(); + var time = 0.0; + for (var run = -1; run < RunCount; run++) + { + stopwatch.Reset(); + long allocated = 0; + for (var i = 0; i < Warmup + Frames; i++) + { + zone.EvaluateBelt(beltKey, transforms, time += 0.016); + var bytes = GC.GetAllocatedBytesForCurrentThread(); + if (i >= Warmup) stopwatch.Start(); + frame(); + if (i >= Warmup) stopwatch.Stop(); + if (i >= Warmup) allocated += GC.GetAllocatedBytesForCurrentThread() - bytes; + } + if (run >= 0) results[run] = (stopwatch.Elapsed.TotalMilliseconds / Frames, allocated / Frames); + } + return results; + } + + private static double Quantile(double[] sorted, double q) + { + var at = q * (sorted.Length - 1); + var low = (int)Math.Floor(at); + var high = Math.Min(low + 1, sorted.Length - 1); + return sorted[low] + (sorted[high] - sorted[low]) * (at - low); + } + + private static void Report(string revision, int count, (double ms, long bytes)[] runs) + { + var ms = runs.Select(r => r.ms).OrderBy(v => v).ToArray(); + var bytes = runs.Select(r => (double)r.bytes).OrderBy(v => v).ToArray(); + var units = Process.GetProcessesByName("Unity").Length; + Debug.Log($"[MapBeltPerf] revision={revision} asteroids={count} runs={runs.Length} frames_per_run={Frames} " + + $"cpu_ms_median={Quantile(ms, .5):F4} iqr={Quantile(ms, .25):F4}-{Quantile(ms, .75):F4} " + + $"gc_bytes_median={Quantile(bytes, .5):F0} unity_processes={units} cpus={Environment.ProcessorCount}"); + } +} diff --git a/Assets/Scripts/Editor/MapBeltPerf.cs.meta b/Assets/Scripts/Editor/MapBeltPerf.cs.meta new file mode 100644 index 000000000..5a06251b4 --- /dev/null +++ b/Assets/Scripts/Editor/MapBeltPerf.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2bf3d3dcd7e3dd940add2640db93e3fe \ No newline at end of file diff --git a/Assets/Scripts/Editor/MapBeltPerfBase.cs b/Assets/Scripts/Editor/MapBeltPerfBase.cs new file mode 100644 index 000000000..6470b9c9a --- /dev/null +++ b/Assets/Scripts/Editor/MapBeltPerfBase.cs @@ -0,0 +1,88 @@ +using GameCult.Caching; +using CultMath; +using UnityEngine; +using static CultMath.math; +using float2 = CultMath.float2; +using float4 = CultMath.float4; +using Random = UnityEngine.Random; + +// The base revision's per-frame belt map path, copied from ZoneRenderer.cs at da6fe033 (class AsteroidBeltUI) so that +// MapBeltPerf can measure it beside MapPresenter in one job. Only the lead it read from ActionGameManager.Clock is +// fixed at zero. Not used by the game. +public class MapBeltPerfBase +{ + private Vector3[] _vertices; + private Vector3[] _normals; + private Vector2[] _uvs; + private int[] _indices; + private CultRecordKey _orbitParent; + private Mesh _mesh; + private float _size; + private Zone _zone; + private AsteroidBelt _belt; + private float _scale; + + public MapBeltPerfBase(Zone zone, AsteroidBelt belt, int spritesheetWidth, int spritesheetHeight, float scale) + { + _belt = belt; + _zone = zone; + var orbit = zone.Orbits[belt.Data.Orbit.Key]; + _orbitParent = orbit.Data.Parent.Key; + _vertices = new Vector3[_belt.Data.Asteroids.Length * 4]; + _normals = new Vector3[_belt.Data.Asteroids.Length * 4]; + _uvs = new Vector2[_belt.Data.Asteroids.Length * 4]; + _indices = new int[_belt.Data.Asteroids.Length * 6]; + _scale = scale; + + var maxDist = 0f; + var spriteSize = float2(1f / spritesheetWidth, 1f / spritesheetHeight); + // vertex order: bottom left, top left, top right, bottom right + for (var i = 0; i < belt.Data.Asteroids.Length; i++) + { + if (belt.Data.Asteroids[i].Distance > maxDist) + maxDist = belt.Data.Asteroids[i].Distance; + var spriteX = Random.Range(0, spritesheetWidth); + var spriteY = Random.Range(0, spritesheetHeight); + + _uvs[i * 4] = new Vector2(spriteX * spriteSize.x, spriteY * spriteSize.y); + _uvs[i * 4 + 1] = new Vector2(spriteX * spriteSize.x, spriteY * spriteSize.y + spriteSize.y); + _uvs[i * 4 + 2] = new Vector2(spriteX * spriteSize.x + spriteSize.x, spriteY * spriteSize.y + spriteSize.y); + _uvs[i * 4 + 3] = new Vector2(spriteX * spriteSize.x + spriteSize.x, spriteY * spriteSize.y); + + _indices[i * 6] = i * 4; + _indices[i * 6 + 1] = i * 4 + 1; + _indices[i * 6 + 2] = i * 4 + 3; + _indices[i * 6 + 3] = i * 4 + 3; + _indices[i * 6 + 4] = i * 4 + 1; + _indices[i * 6 + 5] = i * 4 + 2; + } + + for (var i = 0; i < _normals.Length; i++) _normals[i] = -Vector3.forward; + + _mesh = new Mesh(); + _mesh.vertices = _vertices; + _mesh.uv = _uvs; + _mesh.triangles = _indices; + _mesh.normals = _normals; + _mesh.bounds = new Bounds(Vector3.zero, Vector3.one * maxDist); + _size = maxDist; + } + + public void Update(float4[] transforms, float height) + { + var parentPosition = DrawAhead.Orbit(_zone, _orbitParent, 0f); + for (var i = 0; i < transforms.Length; i++) + { + var transform = transforms[i]; + var rotation = Quaternion.Euler(90, transform.z, 0); + var position = new Vector3(transform.x, height, transform.y); + _vertices[i * 4] = rotation * new Vector3(-transform.w * _scale, -transform.w * _scale, 0) + position; + _vertices[i * 4 + 1] = rotation * new Vector3(-transform.w * _scale, transform.w * _scale, 0) + position; + _vertices[i * 4 + 2] = rotation * new Vector3(transform.w * _scale, transform.w * _scale, 0) + position; + _vertices[i * 4 + 3] = rotation * new Vector3(transform.w * _scale, -transform.w * _scale, 0) + position; + } + + _mesh.bounds = new Bounds(new Vector3(parentPosition.x, 0, parentPosition.y), Vector3.one * (_size * 2)); + _mesh.vertices = _vertices; + } +} diff --git a/Assets/Scripts/Editor/MapBeltPerfBase.cs.meta b/Assets/Scripts/Editor/MapBeltPerfBase.cs.meta new file mode 100644 index 000000000..662341fb1 --- /dev/null +++ b/Assets/Scripts/Editor/MapBeltPerfBase.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c3e6b631c94f2384c87cf1906907af9f \ No newline at end of file diff --git a/Assets/Scripts/Editor/MapPresenterCapture.cs b/Assets/Scripts/Editor/MapPresenterCapture.cs new file mode 100644 index 000000000..1e0a727f0 --- /dev/null +++ b/Assets/Scripts/Editor/MapPresenterCapture.cs @@ -0,0 +1,119 @@ +using System; +using System.IO; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; + +// Proof that a planet icon and a ping tint reach the pixels of the real map cameras when the planet's well is deeper +// than 1000 below the camera. The ARPG scene's own "Map Overlays" and "Map Tint" cameras (position, orthographic size, +// clip planes and culling mask as authored) render into a render texture on a solid black background. For each, in +// order: a control render with nothing drawn; a render with the thing placed 1100 below the camera (a plain quad, and the +// PingEffect prefab), which must equal the control because the far plane clips it; then MapPresenter's draw of the sun +// (well deeper than 2000) or the PingEffect prefab placed where EntityInstance places it, which must differ from the +// control at its pixel. A capture that draws nothing fails the last check, and one that cannot tell drawn from clipped +// fails the middle one. +// +// Unity -batchmode -projectPath -executeMethod MapPresenterCapture.Run -logFile +// +// Needs a GPU device; do not pass -nographics or -quit: Run exits the Editor itself, 0 on success and 1 on any failure. +public static class MapPresenterCapture +{ + private const int Size = 64; + + public static void Run() + { + var work = Path.Combine(Path.GetTempPath(), $"map-presenter-capture-{Guid.NewGuid():N}"); + try + { + Directory.CreateDirectory(work); + Check(work); + Debug.Log("[MapPresenterCapture] ok"); + EditorApplication.Exit(0); + } + catch (Exception exception) + { + Debug.LogException(exception); + EditorApplication.Exit(1); + } + } + + private static void Require(bool condition, string what) + { + if (!condition) throw new InvalidOperationException(what); + } + + private static Camera SceneCamera(string name) + { + foreach (var camera in UnityEngine.Object.FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None)) + if (camera.name == name) return camera; + throw new InvalidOperationException($"No camera named {name} in the scene."); + } + + private static Color Render(Camera camera, RenderTexture target, Vector3 at) + { + camera.targetTexture = target; + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.black; + camera.Render(); + var viewport = camera.WorldToViewportPoint(new Vector3(at.x, 0, at.z)); + var previous = RenderTexture.active; + RenderTexture.active = target; + var read = new Texture2D(Size, Size, TextureFormat.RGBA32, false); + read.ReadPixels(new Rect(0, 0, Size, Size), 0, 0); + RenderTexture.active = previous; + var pixel = read.GetPixel(Mathf.Clamp((int)(viewport.x * Size), 0, Size - 1), Mathf.Clamp((int)(viewport.y * Size), 0, Size - 1)); + UnityEngine.Object.DestroyImmediate(read); + return pixel; + } + + private static float Distance(Color a, Color b) => Mathf.Abs(a.r - b.r) + Mathf.Abs(a.g - b.g) + Mathf.Abs(a.b - b.b); + + private static void Check(string work) + { + EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Single); + var f = MapPresenterSmoke.Build(work, flatIcons: true); + f.Map.SetMinimapScale(300f); + var target = new RenderTexture(Size, Size, 24, RenderTextureFormat.ARGB32); + var layer = LayerMask.NameToLayer("Minimap"); + + // Planet: the sun's icon through the map overlays camera. + var overlays = SceneCamera("Map Overlays"); + Require((overlays.cullingMask & (1 << layer)) != 0, "The Map Overlays camera does not see the Minimap layer."); + var well = f.Zone.GetHeight(DrawAhead.Orbit(f.Zone, f.Zone.PlanetInstances[f.SunKey].BodyData.Orbit.Key, 0), 0); + Require(well < -1000f, $"The fixture sun's well is {well}, not deeper than 1000."); + Require(f.Map.TryDrawn(f.SunKey, out var sun), "The sun registered no icon."); + var sunAt = sun.GetPosition(); + // Control: the pixel with nothing queued. Then a quad 1100 below the camera, deeper than the far plane, which must + // leave the pixel as it was. Then the presenter's draw, which must change it. Draws queue for the cameras that + // render after them, so the order is empty, deep, drawn. + var empty = Render(overlays, target, sunAt); + var quad = GameObject.CreatePrimitive(PrimitiveType.Quad); + var deepMesh = quad.GetComponent().sharedMesh; + var deepMaterial = new Material(Shader.Find("Unlit/Color")) { color = Color.white }; + UnityEngine.Object.DestroyImmediate(quad); + Graphics.RenderMesh(new RenderParams(deepMaterial) { layer = layer }, deepMesh, 0, + Matrix4x4.TRS(new Vector3(sunAt.x, -1100f, sunAt.z), Quaternion.Euler(90, 0, 0), Vector3.one * 300f)); + var deep = Render(overlays, target, sunAt); + Require(Distance(deep, empty) < .01f, $"A mesh 1100 below the camera drew: {deep} against {empty}."); + f.Map.Draw(f.Zone, 0); + var drawn = Render(overlays, target, sunAt); + Require(Distance(drawn, empty) > .3f, $"The sun's icon is not in the pixels: drawn {drawn}, empty {empty}."); + + // Ping tint: the PingEffect prefab where EntityInstance places it, through the map tint camera. + var tint = SceneCamera("Map Tint"); + var ping = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath("Assets/Content/Prefabs/PingEffect.prefab")); + ping.transform.localScale = Vector3.one * 300f; + var pingAt = new Vector3(sunAt.x, MapPresenter.PlaneY, sunAt.z); + ping.transform.position = pingAt; + ping.SetActive(false); + var untinted = Render(tint, target, pingAt); + ping.SetActive(true); + ping.transform.position = new Vector3(sunAt.x, -1100f, sunAt.z); + var deepPing = Render(tint, target, pingAt); + Require(Distance(deepPing, untinted) < .01f, $"A ping 1100 below the camera drew: {deepPing} against {untinted}."); + ping.transform.position = pingAt; + var tinted = Render(tint, target, pingAt); + Require(Distance(tinted, untinted) > .02f, $"The ping tint is not in the pixels: with {tinted}, without {untinted}."); + Debug.Log($"[MapPresenterCapture] well={well} sun drawn={drawn} empty={empty} deep={deep}; ping tinted={tinted} untinted={untinted} deep={deepPing}"); + } +} diff --git a/Assets/Scripts/Editor/MapPresenterCapture.cs.meta b/Assets/Scripts/Editor/MapPresenterCapture.cs.meta new file mode 100644 index 000000000..53caa5ee1 --- /dev/null +++ b/Assets/Scripts/Editor/MapPresenterCapture.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cfa012aaae63b5044bdfd1b6b44ca9da \ No newline at end of file diff --git a/Assets/Scripts/Editor/MapPresenterSmoke.cs b/Assets/Scripts/Editor/MapPresenterSmoke.cs new file mode 100644 index 000000000..8881880ed --- /dev/null +++ b/Assets/Scripts/Editor/MapPresenterSmoke.cs @@ -0,0 +1,239 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using GameCult.Caching; +using UnityEditor; +using UnityEngine; +using CultMath; +using CultMath.UnityBridge; +using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; +using float4 = CultMath.float4; + +// Batch proof of MapPresenter's contract on a real Zone, without a scene: a sun with a very deep well, a belt, and ships +// registered through EntityInstance.SetEntity as the game does. Planet icons draw at the map plane inside both map +// cameras' clip range however deep the well, a rolled and pitched hull's icon turns by yaw alone, every kind registers one +// draw and leaves no icon child behind, a belt is one instanced draw of every asteroid, and an entity's fade reaches its +// icon the frame it is set. Not reached: prefab, mod ship, station and turret instances (they register through the same +// call), and the rendered pixels (a GPU capture). +// +// Unity -batchmode -projectPath -executeMethod MapPresenterSmoke.Run -logFile +// +// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure. +public static class MapPresenterSmoke +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + private const int Asteroids = 24; + + public static void Run() + { + var work = Path.Combine(Path.GetTempPath(), $"map-presenter-smoke-{Guid.NewGuid():N}"); + try + { + Directory.CreateDirectory(work); + Check(work); + Debug.Log("[MapPresenterSmoke] ok"); + EditorApplication.Exit(0); + } + catch (Exception exception) + { + Debug.LogException(exception); + EditorApplication.Exit(1); + } + } + + private static void Require(bool condition, string what) + { + if (!condition) throw new InvalidOperationException(what); + } + + private static void Awaken(Component component) => component.GetType().GetMethod("Awake", Any)?.Invoke(component, null); + + // flat: authored lying on the map plane (facing up), as a real icon is; the smoke's own icons are authored upright + // so that their rotation is exactly the yaw. + private static MeshRenderer NewIcon(Transform parent, bool flat) + { + var icon = GameObject.CreatePrimitive(PrimitiveType.Quad); + icon.layer = LayerMask.NameToLayer("Minimap"); + icon.transform.SetParent(parent, false); + if (flat) icon.transform.localRotation = Quaternion.Euler(90, 0, 0); + var renderer = icon.GetComponent(); + renderer.sharedMaterial = new Material(Shader.Find("Unlit/Color")) { color = new Color(1, 1, 1, .8f) }; + return renderer; + } + + // What Build leaves registered with a presenter, for the checks here and for MapPresenterCapture. + internal sealed class Fixture + { + public Zone Zone; + public MapPresenter Map; + public Ship Ship, Other; + public EntityInstance ShipInstance, OtherInstance; + public CultRecordKey SunKey, BeltKey; + public float4[] Belt; + public Transform Roots; + } + + private static void Check(string work) + { + var f = Build(work, flatIcons: false); + Checks(f); + } + + internal static Fixture Build(string work, bool flatIcons) + { + var settings = AssetDatabase.LoadAssetAtPath("Assets/Resources/Settings.asset") + ?? throw new InvalidOperationException("No Settings.asset."); + var planetSettings = new PlanetSettings + { + BodyRadius = new ExponentialCurve(), + WellStrength = new ExponentialCurve { Multiplier = 1f, Exponent = 1f }, + RocheLimit = new ExponentialCurve { Constant = 2f }, + AsteroidSize = new ExponentialLerp { Minimum = 2f, Maximum = 9f, Exponent = 1.7f }, + AsteroidHitpoints = new ExponentialLerp { Minimum = 10f, Maximum = 300f, Exponent = 2f }, + AsteroidRespawnTime = new ExponentialLerp { Minimum = 5f, Maximum = 60f, Exponent = 1f } + }; + var cache = AetheriaStores.Open(Path.Combine(work, "c.cc"), Path.Combine(work, "r.cc"), catalogWritable: true); + cache.Upsert(new VerseGrammar { Revision = 1 }); + var shape = new Shape(5, 4); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + cache.Upsert(new HullData { Name = "Smoke Hull", HullType = HullType.Ship, Shape = shape, Durability = 1000, Mass = 1000, Armor = 0 }); + var sunOrbit = cache.Upsert(new OrbitData()).Key; + var sunKey = cache.Upsert(new PlanetData { Name = "Sun", Orbit = new CultRecordRef(sunOrbit), Mass = 1e6f }).Key; + var rootOrbit = cache.Upsert(new OrbitData { Parent = new CultRecordRef(sunOrbit), Distance = 4000f, Phase = .17f }).Key; + var beltOrbit = cache.Upsert(new OrbitData { Parent = new CultRecordRef(rootOrbit), Distance = 900f, Phase = .42f }).Key; + var asteroids = Enumerable.Range(0, Asteroids).Select(i => new Asteroid + { Distance = 120f + i * 11.3f, Phase = frac(i * .618f), Size = frac(i * .37f + .1f), RotationSpeed = .15f + i * .037f }).ToArray(); + var beltKey = cache.Upsert(new AsteroidBeltData { Orbit = new CultRecordRef(beltOrbit), Asteroids = asteroids }).Key; + var pack = new ZonePack + { + Orbits = { new CultRecordRef(sunOrbit), new CultRecordRef(rootOrbit), new CultRecordRef(beltOrbit) }, + Planets = { new CultRecordRef(sunKey), new CultRecordRef(beltKey) }, + Radius = 5000f, Mass = 10000f, Time = 0 + }; + var ledger = new ProvenanceLedger(); + for (var i = 1; i <= 8; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 }; + var items = new ItemManager(cache, ledger, settings.GameplaySettings, _ => { }); + var zone = new Zone(items, planetSettings, pack, new GalaxyZone { Name = "Smoke", Owner = null }, null); + var hullRef = items.ItemData.RefOf(items.ItemData.GetByName("Smoke Hull")); + var ship = new Ship(items, zone, new EquippableItem { Data = hullRef, Durability = 1000, Lot = 1 }, new EntitySettings()); + var other = new Ship(items, zone, new EquippableItem { Data = hullRef, Durability = 1000, Lot = 2 }, new EntitySettings()); + ship.Position = float3(300, 50, 200); + other.Position = float3(-300, -90, 100); + zone.Admit(ship, piloted: false); + zone.Admit(other, piloted: false); + + // A hull heading 40 degrees from +z, pitched up 89.9 and rolled 30: its forward is almost vertical, where the pose's + // eulerAngles.y is the gimbal decomposition (yaw and roll folded together), not the heading. The heading is the + // forward projected onto the map plane, 40. The fixture asserts the two differ, so a yaw read from eulerAngles + // cannot pass. + var pose = Quaternion.Euler(0, 40, 0) * Quaternion.Euler(-89.9f, 0, 30); + var flatForward = pose * Vector3.forward; + Require(Mathf.Abs(Mathf.DeltaAngle(Mathf.Atan2(flatForward.x, flatForward.z) * Mathf.Rad2Deg, 40f)) < .5f, "The fixture's forward does not head 40."); + Require(Mathf.Abs(Mathf.DeltaAngle(pose.eulerAngles.y, 40f)) > 10f, $"The fixture's eulerAngles.y {pose.eulerAngles.y} is aligned with its heading."); + ship.Direction = float2(Mathf.Sin(40 * Mathf.Deg2Rad), Mathf.Cos(40 * Mathf.Deg2Rad)); + typeof(Ship).GetProperty("Rotation", Any).GetSetMethod(true).Invoke(ship, new object[] { new CultMath.quaternion(pose.x, pose.y, pose.z, pose.w) }); + + var map = new MapPresenter(new Material[0], AssetDatabase.LoadAssetAtPath("Assets/Materials/UI/MapAsteroid.mat"), 4, 4, 3f); + var roots = new GameObject("Smoke Roots").transform; + EntityInstance Bound(Entity entity) + { + var body = new GameObject(entity.Name); + body.transform.SetParent(roots); + var instance = body.AddComponent(); + Awaken(instance); + instance.HullColliders = new HullCollider[0]; + instance.RadiatorHardpoints = new RadiatorHardpoint[0]; + instance.ThrusterHardpoints = new ThrusterHardpoint[0]; + instance.WeaponHardpoints = new WeaponHardpoint[0]; + instance.ArticulationPoints = new ArticulationPoint[0]; + instance.MapIcon = NewIcon(body.transform, flatIcons); + var zoneRenderer = new GameObject("Smoke Zone Renderer").AddComponent(); + zoneRenderer.Settings = settings; + zoneRenderer.MapGravityMaterials = new Material[0]; + Awaken(zoneRenderer); + typeof(ZoneRenderer).GetProperty("Map").GetSetMethod(true).Invoke(zoneRenderer, new object[] { map }); + instance.SetEntity(zoneRenderer, entity); + return instance; + } + var shipInstance = Bound(ship); + var otherInstance = Bound(other); + var sunRoot = new GameObject("Smoke Sun").transform; + sunRoot.SetParent(roots); + map.RegisterPlanet(sunKey, NewIcon(sunRoot, flatIcons), sunRoot); + var belt = new float4[Asteroids]; + map.RegisterBelt(beltKey, belt); + zone.EvaluateBelt(beltKey, belt, DrawAhead.Time(zone, 0)); + map.BeltsOnMinimap = true; + map.SetFade(ship, 1f); + map.SetFade(other, 1f); + map.SetMinimapScale(2f); + map.Draw(zone, 0); + return new Fixture { Zone = zone, Map = map, Ship = ship, Other = other, ShipInstance = shipInstance, + OtherInstance = otherInstance, SunKey = sunKey, BeltKey = beltKey, Belt = belt, Roots = roots }; + } + + private static void Checks(Fixture f) + { + var (zone, map, ship, other, sunKey, beltKey, belt, roots) = (f.Zone, f.Map, f.Ship, f.Other, f.SunKey, f.BeltKey, f.Belt, f.Roots); + // Deep planet: the sun's field is deeper than 2000 below the plane, and its icon sits on the map plane inside both + // map cameras' clip range (minimap at y 10, map screen at y 1; near 0.3, far 1000, looking down). + var well = zone.GetHeight(DrawAhead.Orbit(zone, zone.PlanetInstances[sunKey].BodyData.Orbit.Key, 0), 0); + Require(well < -2000f, $"The fixture sun's well is {well}, not below -2000."); + Require(map.TryDrawn(sunKey, out var sunIcon), "The sun registered no icon."); + var y = sunIcon.GetPosition().y; + Require(y < 1f - .3f && y > 10f - 1000f && Mathf.Abs(y - MapPresenter.PlaneY) < .5f, $"The sun's icon is drawn at y {y}, not on the map plane."); + + // Axes: each icon sits at its sim position's planar x and z (a ship at (300, 200), the other at (-300, 100), the sun at + // its orbit), never swapped, and never at the 3D height (the ships ride at y 50 and -90, the sun's well is below -2000). + var shipAt = DrawAhead.Position(ship, 0); + Require(Mathf.Abs(shipAt.x - 300f) < 1e-3f && Mathf.Abs(shipAt.z - 200f) < 1e-3f, $"The ship's sim position is ({shipAt.x}, {shipAt.z}), not (300, 200)."); + var sunAt = DrawAhead.Orbit(zone, zone.PlanetInstances[sunKey].BodyData.Orbit.Key, 0); + Require(map.TryDrawn(ship, out var shipIcon, out _), "The ship registered no icon."); + Require(Mathf.Abs(shipIcon.GetPosition().x - 300f) < 1e-3f && Mathf.Abs(shipIcon.GetPosition().z - 200f) < 1e-3f, + $"The ship's icon is at ({shipIcon.GetPosition().x}, {shipIcon.GetPosition().z}), not its sim position (300, 200)."); + Require(map.TryDrawn(other, out var otherIcon, out _), "The second ship registered no icon."); + Require(Mathf.Abs(otherIcon.GetPosition().x + 300f) < 1e-3f && Mathf.Abs(otherIcon.GetPosition().z - 100f) < 1e-3f, + $"The second ship's icon is at ({otherIcon.GetPosition().x}, {otherIcon.GetPosition().z}), not (-300, 100)."); + Require(Mathf.Abs(sunIcon.GetPosition().x - sunAt.x) < 1e-3f && Mathf.Abs(sunIcon.GetPosition().z - sunAt.y) < 1e-3f, + $"The sun's icon is at ({sunIcon.GetPosition().x}, {sunIcon.GetPosition().z}), not its orbit ({sunAt.x}, {sunAt.y})."); + Require(Mathf.Abs(otherIcon.GetPosition().y - (MapPresenter.PlaneY + MapPresenter.ShipOffset)) < 1e-4f, "The second ship's icon took the 3D height."); + + // Tilted hull: the icon turns by the heading projected onto the map plane (40) times its authored rotation (identity here), with no roll or pitch. + var want = Quaternion.Euler(0, 40, 0); + Require(Quaternion.Angle(shipIcon.rotation, want) < .1f, $"The icon is rotated {shipIcon.rotation.eulerAngles}, not yaw 40 alone."); + Require(Vector3.Angle(shipIcon.rotation * Vector3.up, Vector3.up) < .1f, "The icon's up axis tilted with the hull."); + Require(Mathf.Abs(shipIcon.GetPosition().y - (MapPresenter.PlaneY + MapPresenter.ShipOffset)) < 1e-4f, "The ship's icon left the map plane."); + + // Every kind registers once: three icons drew, and no icon child remains under any registered transform. + Require(map.IconCount == 3 && map.IconDraws == 3, $"{map.IconCount} icons, {map.IconDraws} drawn; expected 3 and 3."); + Require(roots.GetComponentsInChildren(true).Length == 0, "An icon child remains under an entity or planet transform."); + + // A belt is one instanced draw of every asteroid, and its buffer holds this frame's floats. + Require(map.BeltDraws == 1 && map.LastBeltInstances == belt.Length, $"{map.BeltDraws} belt draws of {map.LastBeltInstances} instances; expected 1 of {belt.Length}."); + var read = new float4[belt.Length]; + map.ReadBelt(beltKey, read); + for (var i = 0; i < belt.Length; i++) + Require(read[i].x == belt[i].x && read[i].y == belt[i].y && read[i].z == belt[i].z && read[i].w == belt[i].w, $"Belt buffer differs from the frame's floats at {i}."); + + // The setting still gates belts on the minimap, and the map screen always shows them. + map.BeltsOnMinimap = false; + map.Draw(zone, 0); + Require(map.BeltDraws == 0, "A belt drew on the minimap with the setting off."); + map.OpenMapScreen(true); + map.Draw(zone, 0); + Require(map.BeltDraws == 1, "The map screen did not draw the belt with the setting off."); + map.OpenMapScreen(false); + map.BeltsOnMinimap = true; + + // Fade: half faded reaches the icon's colour alpha on the next draw; faded out draws nothing. + map.SetFade(ship, .5f); + map.Draw(zone, 0); + Require(map.TryDrawn(ship, out _, out var alpha) && Mathf.Abs(alpha - .4f) < 1e-3f, $"Icon alpha {alpha}, expected 0.8 * 0.5."); + map.SetFade(ship, 0f); + map.Draw(zone, 0); + Require(map.IconDraws == 2, $"{map.IconDraws} icons drew with one fully faded out; expected 2."); + } +} diff --git a/Assets/Scripts/Editor/MapPresenterSmoke.cs.meta b/Assets/Scripts/Editor/MapPresenterSmoke.cs.meta new file mode 100644 index 000000000..2fff0ea86 --- /dev/null +++ b/Assets/Scripts/Editor/MapPresenterSmoke.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 58982a1c397cc2f4d9706fd103af6654 \ No newline at end of file diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index 657293181..ecb4af6d2 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -297,10 +297,7 @@ public class ActionGameManager : MonoBehaviour ItemManager = new ItemManager(CultCache, PendingScenario != null ? new ProvenanceLedger() : RunSave.Lots(CultCache), Settings.GameplaySettings, Debug.Log); ZoneRenderer.ItemManager = ItemManager; - - // If hiding minimap asteroids, turn them off to start with - if (!PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap) - ZoneRenderer.ShowAsteroidUI = false; + ZoneRenderer.Map.BeltsOnMinimap = PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap; // TODO: Process Stories diff --git a/Assets/Scripts/Gameplay/EntityInstance.cs b/Assets/Scripts/Gameplay/EntityInstance.cs index e263bac27..945661078 100644 --- a/Assets/Scripts/Gameplay/EntityInstance.cs +++ b/Assets/Scripts/Gameplay/EntityInstance.cs @@ -80,6 +80,8 @@ public class EntityInstance : MonoBehaviour var materials = new List<(Material material, List<(MeshRenderer renderer, int index)> submeshes)>(); foreach (var mesh in meshes) { + // The map icon is drawn by MapPresenter, not as part of the hull (SetEntity hands it over). + if (mesh == MapIcon) continue; _meshes.Add(mesh, mesh.sharedMaterials); for (var i = 0; i < mesh.sharedMaterials.Length; i++) { @@ -165,6 +167,9 @@ public class EntityInstance : MonoBehaviour ZoneRenderer = zoneRenderer; var hullData = entity.ItemManager.GetData(entity.Hull) as HullData; + zoneRenderer.Map.RegisterEntity(entity, MapIcon, transform); + MapIcon = null; + if(Shield) Shield.Entity = entity; @@ -187,7 +192,8 @@ public class EntityInstance : MonoBehaviour { var pingInstance = Instantiate(PingPrefab); var pingMesh = pingInstance.GetComponent(); - pingInstance.position = DrawAhead.Position(entity, ActionGameManager.Clock.Lead).ToUnity(); + var drawn = DrawAhead.Position(entity, ActionGameManager.Clock.Lead); + pingInstance.position = new Vector3(drawn.x, MapPresenter.PlaneY, drawn.z); _pingBrightness = pingMesh.material.GetFloat("_Depth"); _currentPing = (pingInstance, pingMesh); }; @@ -366,7 +372,10 @@ public class EntityInstance : MonoBehaviour OnFadedIn = null; ShowUnfadedElements(); } - foreach(var material in _fadeMaterials) material.SetFloat("_Fade", _fade); + { + foreach(var material in _fadeMaterials) material.SetFloat("_Fade", _fade); + ZoneRenderer.Map.SetFade(Entity, _fade); + } } else { @@ -381,7 +390,10 @@ public class EntityInstance : MonoBehaviour OnFadedOut?.Invoke(); OnFadedOut = null; } - foreach(var material in _fadeMaterials) material.SetFloat("_Fade", _fade); + { + foreach(var material in _fadeMaterials) material.SetFloat("_Fade", _fade); + ZoneRenderer.Map.SetFade(Entity, _fade); + } } } diff --git a/Assets/Scripts/UI/Menu/MapRenderer.cs b/Assets/Scripts/UI/Menu/MapRenderer.cs index e8b1d49bb..d6e585872 100644 --- a/Assets/Scripts/UI/Menu/MapRenderer.cs +++ b/Assets/Scripts/UI/Menu/MapRenderer.cs @@ -51,10 +51,7 @@ public class MapRenderer : MonoBehaviour TintCamera.gameObject.SetActive(true); InfluenceCamera.gameObject.SetActive(true); Title.text = $"Zone: {GameManager.Zone.GalaxyZone.Name}"; - - // If hiding minimap asteroids, turn them back on for the map screen - if (!ActionGameManager.PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap) - ZoneRenderer.ShowAsteroidUI = true; + GameManager.ZoneRenderer.Map.OpenMapScreen(true); } private void OnDisable() @@ -67,10 +64,7 @@ public class MapRenderer : MonoBehaviour GravityCamera.gameObject.SetActive(false); TintCamera.gameObject.SetActive(false); InfluenceCamera.gameObject.SetActive(false); - - // If hiding minimap asteroids, turn them back off when leaving the map screen - if (!ActionGameManager.PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap) - ZoneRenderer.ShowAsteroidUI = false; + GameManager.ZoneRenderer.Map.OpenMapScreen(false); } void ReleaseTextures() @@ -129,6 +123,6 @@ public class MapRenderer : MonoBehaviour InfluenceCamera.transform.position = pos; InfluenceCamera.orthographicSize = _size.y * Scale * .5f; - GameManager.ZoneRenderer.SetIconSize(IconSize * Scale); + GameManager.ZoneRenderer.Map.SetMapScreenScale(IconSize * Scale); } } diff --git a/Assets/Scripts/Zone Display/MapPresenter.cs b/Assets/Scripts/Zone Display/MapPresenter.cs new file mode 100644 index 000000000..b2970737c --- /dev/null +++ b/Assets/Scripts/Zone Display/MapPresenter.cs @@ -0,0 +1,246 @@ +using System.Collections.Generic; +using CultMath; +using CultMath.UnityBridge; +using GameCult.Caching; +using UnityEngine; +using UnityEngine.Rendering; +using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; +using float4 = CultMath.float4; +using quaternion = CultMath.quaternion; + +// The one owner of map-space projection (ruling map-icons-placed-in-2d): where every map icon and belt asteroid is +// drawn, its yaw, its size, its fade, and the contour's depth range. Icons are not world objects: each is a mesh, +// a material instance and an authored rotation read once from the icon child at registration (the child is then +// destroyed), drawn every frame on the Minimap layer at the map plane from sim state through DrawAhead. Roll and +// pitch never reach an icon, and field depth never decides whether one is seen. Both map cameras (the minimap's +// and the map screen's) see these same draws; only the size input differs. +public class MapPresenter +{ + // The map plane. Every map camera is orthographic and looks down from above it, so this height is inside every + // clip range; the offsets only order overlapping icons (planets under stations under ships, belts under all). + public const float PlaneY = 0f; + public const float BeltOffset = -.1f, PlanetOffset = 0f, OrbitalOffset = .1f, ShipOffset = .2f; + + // The one place the heading of an icon is decided (question contact-icon-heading, yaw-for-all): every icon turns + // with its entity's yaw. Another answer changes only this function. + public static float IconYaw(Entity entity, quaternion drawnRotation) + { + var forward = drawnRotation.ToUnity() * Vector3.forward; + return Mathf.Atan2(forward.x, forward.z) * Mathf.Rad2Deg; + } + + private sealed class Icon + { + public Mesh Mesh; + public Material Material; + public Color Base; + public Quaternion Authored; + public float Offset; + public Entity Entity; + public CultRecordKey Planet; + public float Fade; + public Matrix4x4 Drawn; + } + + private readonly List _icons = new List(); + private readonly Dictionary _entityIcons = new Dictionary(); + private readonly Material[] _gravityMaterials; + private readonly int _layer = LayerMask.NameToLayer("Minimap"); + private float _minimapScale = 1, _mapScreenScale; + private bool _mapScreenOpen; + private readonly Material _asteroidMaterial; + private readonly Vector4 _spriteSheet; + private readonly float _asteroidSize; + + public MapPresenter(Material[] gravityMaterials, Material asteroidMaterial, int spriteColumns, int spriteRows, + float asteroidSize) + { + _gravityMaterials = gravityMaterials; + _asteroidMaterial = asteroidMaterial; + _spriteSheet = new Vector4(spriteColumns, spriteRows, 0, 0); + _asteroidSize = asteroidSize; + } + + // The icon size: the map screen's scale while it is open, else the minimap's zoom. + public float IconSize => _mapScreenOpen ? _mapScreenScale : _minimapScale; + public void SetMinimapScale(float scale) => _minimapScale = scale; + public void OpenMapScreen(bool open) => _mapScreenOpen = open; + + // PlayerGraphicsSettings.ShowAsteroidsInMinimap: belt sprites on the minimap; the map screen always shows them. + public bool BeltsOnMinimap { get; set; } + public void SetMapScreenScale(float scale) => _mapScreenScale = scale; + + // Destroy in play mode, DestroyImmediate where the editor smokes run without one. + private static void Discard(Object doomed) + { + if (Application.isPlaying) Object.Destroy(doomed); + else Object.DestroyImmediate(doomed); + } + + public int IconCount => _icons.Count; + // What the last Draw issued, for the smoke. + public int IconDraws { get; private set; } + public int BeltDraws { get; private set; } + public int LastBeltInstances { get; private set; } + public bool TryDrawn(CultRecordKey planet, out Matrix4x4 drawn) + { + drawn = default; + var icon = _icons.Find(candidate => candidate.Entity == null && candidate.Planet.Equals(planet)); + if (icon == null) return false; + drawn = icon.Drawn; + return true; + } + + // What a belt's buffer holds on the GPU side, read back. + public void ReadBelt(CultRecordKey key, float4[] into) => _belts[key].Buffer.GetData(into); + + public bool TryDrawn(Entity entity, out Matrix4x4 drawn, out float alpha) + { + drawn = default; + alpha = 0; + if (!_entityIcons.TryGetValue(entity, out var icon)) return false; + drawn = icon.Drawn; + alpha = icon.Material.GetColor("_Color").a; + return true; + } + + // Reads the icon child once (mesh, material, rotation relative to its root) and destroys it: from here on no + // world transform carries the icon. + private Icon Take(MeshRenderer renderer, Transform root, float offset) + { + var icon = new Icon + { + Mesh = renderer.GetComponent().sharedMesh, + Material = Object.Instantiate(renderer.sharedMaterial), + Authored = Quaternion.Inverse(root.rotation) * renderer.transform.rotation, + Offset = offset, + Fade = 1, + }; + icon.Base = icon.Material.HasProperty("_Color") ? icon.Material.GetColor("_Color") : Color.white; + Discard(renderer.gameObject); + _icons.Add(icon); + return icon; + } + + public void RegisterEntity(Entity entity, MeshRenderer renderer, Transform root) + { + var icon = Take(renderer, root, entity is Ship ? ShipOffset : OrbitalOffset); + icon.Entity = entity; + icon.Fade = 0; + _entityIcons[entity] = icon; + } + + public void RegisterPlanet(CultRecordKey key, MeshRenderer renderer, Transform root) => + Take(renderer, root, PlanetOffset).Planet = key; + + // The entity's fade, applied to its icon the same frame the hull's materials take it. + public void SetFade(Entity entity, float fade) + { + if (_entityIcons.TryGetValue(entity, out var icon)) icon.Fade = fade; + } + + public void Unregister(Entity entity) + { + if (!_entityIcons.Remove(entity, out var icon)) return; + _icons.Remove(icon); + Discard(icon.Material); + } + + private sealed class Belt + { + public float4[] Source; + public ComputeBuffer Buffer; + public MaterialPropertyBlock Block = new MaterialPropertyBlock(); + } + + private readonly Dictionary _belts = new Dictionary(); + private static readonly int BeltProperty = Shader.PropertyToID("_Belt"); + private static readonly int SheetProperty = Shader.PropertyToID("_Sheet"); + private static readonly int PlaneProperty = Shader.PropertyToID("_PlaneY"); + private static readonly int SizeProperty = Shader.PropertyToID("_AsteroidSize"); + + // A belt's map sprites: the 3D belt's per-frame float4s (x, y planar, z spin, w size), uploaded as they are. + public void RegisterBelt(CultRecordKey key, float4[] source) => + _belts[key] = new Belt + { + Source = source, + Buffer = new ComputeBuffer(source.Length, 16, ComputeBufferType.Structured, ComputeBufferMode.SubUpdates) + }; + + // One instanced draw per belt: six vertices per asteroid, expanded to a quad on the map plane by the shader. + private void DrawBelt(Belt belt) + { + var upload = belt.Buffer.BeginWrite(0, belt.Source.Length); + upload.CopyFrom(belt.Source); + belt.Buffer.EndWrite(belt.Source.Length); + belt.Block.SetBuffer(BeltProperty, belt.Buffer); + belt.Block.SetVector(SheetProperty, _spriteSheet); + belt.Block.SetFloat(PlaneProperty, PlaneY + BeltOffset); + belt.Block.SetFloat(SizeProperty, _asteroidSize); + var parameters = new RenderParams(_asteroidMaterial) + { + layer = _layer, matProps = belt.Block, shadowCastingMode = ShadowCastingMode.Off, + worldBounds = new Bounds(Vector3.zero, Vector3.one * 1e6f), + }; + Graphics.RenderPrimitives(parameters, MeshTopology.Triangles, 6, belt.Source.Length); + BeltDraws++; + LastBeltInstances = belt.Source.Length; + } + + // Every registered icon and belt for this frame, from sim state at the drawn time; and the contour's depth range, + // the deepest drawn planet's field depth (the map gravity materials' normalisation, not a camera bound). + public void Draw(Zone zone, float lead) + { + var size = IconSize; + IconDraws = BeltDraws = 0; + var maxDepth = 0f; + foreach (var icon in _icons) + { + float2 planar; + Quaternion yaw = Quaternion.identity; + if (icon.Entity != null) + { + var drawn = DrawAhead.Position(icon.Entity, lead); + planar = drawn.xz; + var rotation = icon.Entity is Ship ship ? DrawAhead.Rotation(ship, lead) : quaternion.identity; + yaw = Quaternion.Euler(0, IconYaw(icon.Entity, rotation), 0); + } + else + { + var body = zone.PlanetInstances[icon.Planet]; + planar = DrawAhead.Orbit(zone, body.BodyData.Orbit.Key, lead); + maxDepth = Mathf.Max(maxDepth, -DrawAhead.Height(zone, planar, lead)); + } + + if (icon.Fade <= .01f) continue; + if (icon.Material.HasProperty("_Color")) + icon.Material.SetColor("_Color", new Color(icon.Base.r, icon.Base.g, icon.Base.b, icon.Base.a * icon.Fade)); + var parameters = new RenderParams(icon.Material) { layer = _layer, shadowCastingMode = ShadowCastingMode.Off }; + icon.Drawn = Matrix4x4.TRS(new Vector3(planar.x, PlaneY + icon.Offset, planar.y), yaw * icon.Authored, + Vector3.one * size); + Graphics.RenderMesh(parameters, icon.Mesh, 0, icon.Drawn); + IconDraws++; + } + + var depthRange = Mathf.Max(maxDepth, 1f); + foreach (var material in _gravityMaterials) + { + material.SetFloat("_StartDepth", 0f); + material.SetFloat("_DepthRange", depthRange); + } + + if (BeltsOnMinimap || _mapScreenOpen) + foreach (var belt in _belts.Values) DrawBelt(belt); + } + + public void Clear() + { + foreach (var icon in _icons) Discard(icon.Material); + _icons.Clear(); + _entityIcons.Clear(); + foreach (var belt in _belts.Values) belt.Buffer.Release(); + _belts.Clear(); + } +} diff --git a/Assets/Scripts/Zone Display/MapPresenter.cs.meta b/Assets/Scripts/Zone Display/MapPresenter.cs.meta new file mode 100644 index 000000000..e1aa78267 --- /dev/null +++ b/Assets/Scripts/Zone Display/MapPresenter.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4e57670bc5f68f6408969ff913cfa8c2 \ No newline at end of file diff --git a/Assets/Scripts/Zone Display/MapView.cs b/Assets/Scripts/Zone Display/MapView.cs deleted file mode 100644 index a2e51c246..000000000 --- a/Assets/Scripts/Zone Display/MapView.cs +++ /dev/null @@ -1,111 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -using System; -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.InputSystem; -using UnityEngine.Serialization; - -public class MapView : MonoBehaviour -{ - public Camera Main; - public Camera MinimapGravity; - public Camera Minimap; - public MeshRenderer GravityRenderer; - public float ZoomSpeed; - [FormerlySerializedAs("SectorRenderer")] public ZoneRenderer ZoneRenderer; - - private Transform _minimapTransform; - private CopyTransform _minimapCopyTransform; - private RenderTexture _minimapTexture; - private Transform _minimapGravityTransform; - private CopyTransform _minimapGravityCopyTransform; - private RenderTexture _minimapGravityTexture; - private Transform _gravityRendererTransform; - private CopyTransform _gravityRendererCopyTransform; - private RenderTexture _fullscreenGravityTexture; - private AetheriaInput.UIActions _input; - private float _viewDistance = 1024; - private float _aspectRatio; - private Vector3 _previousGravityRendererScale; - - void OnEnable() - { - _aspectRatio = (float) Screen.width / Screen.height; - Main.gameObject.SetActive(false); - _minimapTexture = Minimap.targetTexture; - _minimapTransform = Minimap.transform; - _minimapCopyTransform = Minimap.GetComponent(); - _minimapCopyTransform.enabled = false; - _minimapGravityTexture = MinimapGravity.targetTexture; - _minimapGravityTransform = MinimapGravity.transform; - _minimapGravityCopyTransform = MinimapGravity.GetComponent(); - _minimapGravityCopyTransform.enabled = false; - _gravityRendererTransform = GravityRenderer.transform; - _gravityRendererCopyTransform = GravityRenderer.GetComponent(); - _gravityRendererCopyTransform.enabled = false; - _previousGravityRendererScale = _gravityRendererTransform.localScale; - - _fullscreenGravityTexture = new RenderTexture(Screen.width / 2, Screen.height / 2, 1, RenderTextureFormat.RFloat); - GravityRenderer.material.mainTexture = _fullscreenGravityTexture; - MinimapGravity.targetTexture = _fullscreenGravityTexture; - Minimap.targetTexture = null; - SetZoom(); - } - - void SetZoom() - { - //ZoneRenderer.ViewDistance = _viewDistance * _aspectRatio; - Minimap.orthographicSize = MinimapGravity.orthographicSize = _viewDistance; - _gravityRendererTransform.localScale = new Vector3(_viewDistance*_aspectRatio*2, _viewDistance*2, 1); - } - - // public void BindInput(AetheriaInput.UIActions input) - // { - // _input = input; - // _input.ScrollWheel.performed += OnScroll; - // } - - // private void OnScroll(InputAction.CallbackContext context) - // { - // _viewDistance *= (1 - context.ReadValue().y * ZoomSpeed); - // SetZoom(); - // } - - void Update() - { - if (_input.Click.ReadValue() > .5f) - { - var delta = _input.Drag.ReadValue(); - - var pos = _minimapTransform.position; - pos.x -= delta.x * _viewDistance / Screen.height; - pos.z -= delta.y * _viewDistance / Screen.height; - - var gravPos = _gravityRendererTransform.position; - gravPos.x = pos.x; - gravPos.z = pos.z; - - _gravityRendererTransform.position = gravPos; - Main.transform.position = _minimapTransform.position = _minimapGravityTransform.position = pos; - } - } - - private void OnDisable() - { - // _input.ScrollWheel.performed -= OnScroll; - - Main.gameObject.SetActive(true); - _minimapGravityCopyTransform.enabled = true; - _minimapCopyTransform.enabled = true; - _gravityRendererCopyTransform.enabled = true; - - Minimap.targetTexture = _minimapTexture; - MinimapGravity.targetTexture = _minimapGravityTexture; - GravityRenderer.material.mainTexture = _minimapGravityTexture; - _fullscreenGravityTexture.Release(); - } -} diff --git a/Assets/Scripts/Zone Display/MapView.cs.meta b/Assets/Scripts/Zone Display/MapView.cs.meta deleted file mode 100644 index b97643a75..000000000 --- a/Assets/Scripts/Zone Display/MapView.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 76d9e45f376fcfe409f3a4f26ccb4f3e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/Zone Display/ZoneRenderer.cs b/Assets/Scripts/Zone Display/ZoneRenderer.cs index 8126eb096..3c584c956 100644 --- a/Assets/Scripts/Zone Display/ZoneRenderer.cs +++ b/Assets/Scripts/Zone Display/ZoneRenderer.cs @@ -59,7 +59,8 @@ public class ZoneRenderer : MonoBehaviour // public Material AsteroidMaterial; [Header("Prefabs")] - public MeshFilter AsteroidBeltUI; + // The map's belt sprites (Aetheria/MapBelt): MapPresenter draws every belt with it. + public Material MapAsteroidMaterial; public PlanetObject Planet; public GasGiantObject GasGiant; public SunObject Sun; @@ -72,7 +73,6 @@ public class ZoneRenderer : MonoBehaviour [HideInInspector] public Dictionary EntityInstances = new Dictionary(); [HideInInspector] public Dictionary Planets = new Dictionary(); - private Dictionary _beltObjects = new Dictionary(); private Dictionary _beltMeshes = new Dictionary(); private Dictionary _beltMatrices = new Dictionary(); // Cut 1 (docs/mining-cut.md): the renderer's own buffer, filled from Zone.EvaluateBelt each frame. No pose @@ -93,13 +93,14 @@ public class ZoneRenderer : MonoBehaviour private IDisposable[] _perspectiveSubscriptions = new IDisposable[2]; private List _zoneSubscriptions = new List(); private PlanetObject[] _suns; - private bool _showAsteroidUI; public Dictionary WormholeInstances = new Dictionary(); private Dictionary _floatingItems = new Dictionary(); private Dictionary _mines = new Dictionary(); private Dictionary _clouds = new Dictionary(); + // The one owner of map-space projection: every map icon and belt sprite is drawn by it. + public MapPresenter Map { get; private set; } public Zone Zone { get; private set; } public ItemManager ItemManager { get; set; } @@ -151,31 +152,15 @@ public class ZoneRenderer : MonoBehaviour _minimapDistance = value; foreach (var camera in MinimapCameras) camera.orthographicSize = value; - SetIconSize(value * Settings.MinimapIconSize); + Map.SetMinimapScale(value * Settings.MinimapIconSize); // MinimapGravityQuad.transform.localScale = value * 2 * Vector3.one; } } - public bool ShowAsteroidUI + void Awake() { - get { return _showAsteroidUI; } - set - { - if (value != _showAsteroidUI) - { - _showAsteroidUI = value; - foreach (var beltUI in _beltObjects.Values) - { - beltUI.Filter.gameObject.SetActive(_showAsteroidUI); - } - } - } - } - - public void SetIconSize(float size) - { - foreach(var entityInstance in EntityInstances.Values) entityInstance.MapIcon.transform.localScale = Vector3.one * size; - foreach(var planet in Planets.Values) planet.Icon.transform.localScale = Vector3.one * size; + Map = new MapPresenter(MapGravityMaterials, MapAsteroidMaterial, AsteroidSpritesheetWidth, + AsteroidSpritesheetHeight, Settings.MinimapAsteroidSize); } void Start() @@ -395,12 +380,7 @@ public class ZoneRenderer : MonoBehaviour } Planets.Clear(); - foreach (var beltObject in _beltObjects.Values) - { - Destroy(beltObject.Filter); - } - - _beltObjects.Clear(); + Map.Clear(); _beltMeshes.Clear(); _beltMatrices.Clear(); _beltTransforms.Clear(); @@ -455,6 +435,7 @@ public class ZoneRenderer : MonoBehaviour } } + Map.Unregister(entity); Destroy(EntityInstances[entity].gameObject); EntityInstances.Remove(entity); } @@ -476,16 +457,7 @@ public class ZoneRenderer : MonoBehaviour _beltMatrices[key][i] = new Matrix4x4[i < meshes.Count - 1 ? count : count + remainder]; } - var beltObject = Instantiate(AsteroidBeltUI, ZoneRoot); - var collider = beltObject.GetComponent(); - var belt = new AsteroidBeltUI(Zone, - Zone.AsteroidBelts[key], - beltObject, - collider, - AsteroidSpritesheetWidth, - AsteroidSpritesheetHeight, - Settings.MinimapAsteroidSize); - _beltObjects[key] = belt; + Map.RegisterBelt(key, _beltTransforms[key]); } else { @@ -525,7 +497,7 @@ public class ZoneRenderer : MonoBehaviour var planetInstance = Zone.PlanetInstances[key]; planet.Body.transform.localScale = planetInstance.BodyRadius * Vector3.one; - planet.Icon.transform.localScale = Settings.IconSize.Evaluate(planetInstance.BodyData.Mass) * Vector3.one; + Map.RegisterPlanet(key, planet.Icon, planet.transform); Planets[key] = planet; @@ -539,9 +511,13 @@ public class ZoneRenderer : MonoBehaviour LODHandler.FindPlanets(); } + void LateUpdate() + { + Map.Draw(Zone, ActionGameManager.Clock.Lead); + } + void Update() { - var maxDepth = 0f; var lead = ActionGameManager.Clock.Lead; GravityLowering.Lower(Zone, lead, ref _gravityWells); foreach (var loot in _floatingItems.Values) @@ -594,9 +570,6 @@ public class ZoneRenderer : MonoBehaviour Graphics.DrawMeshInstanced(meshes[i].Mesh, 0, meshes[i].Material, matrices[i]); } } - - if(_showAsteroidUI) - _beltObjects[key].Update(transforms, height); } foreach (var planet in Planets) @@ -604,10 +577,8 @@ public class ZoneRenderer : MonoBehaviour var planetInstance = Zone.PlanetInstances[planet.Key]; var p = DrawAhead.Orbit(Zone, planetInstance.BodyData.Orbit.Key, lead); var height = DrawAhead.Height(Zone, p, lead); - 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)) @@ -641,13 +612,6 @@ public class ZoneRenderer : MonoBehaviour wormhole.icon.transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg - 90); } - //var fogPos = FogCameraParent.position; - var depthRange = Mathf.Max(maxDepth, 1f); - foreach (var mat in MapGravityMaterials) - { - mat.SetFloat("_StartDepth", 0f); - mat.SetFloat("_DepthRange", depthRange); - } // var gravPos = MinimapGravityQuad.transform.position; // MinimapGravityQuad.transform.position = gravPos; // MinimapTintQuad.transform.position = gravPos - Vector3.up*10; @@ -661,98 +625,3 @@ public class InstancedMesh public Mesh Mesh; public Material Material; } - -public class AsteroidBeltUI -{ - public MeshFilter Filter; - private MeshCollider _collider; - private Vector3[] _vertices; - private Vector3[] _normals; - private Vector2[] _uvs; - private int[] _indices; - private CultRecordKey _orbitParent; - private Mesh _mesh; - private float _size; - private Zone _zone; - private AsteroidBelt _belt; - private float _scale; - - public AsteroidBeltUI(Zone zone, - AsteroidBelt belt, - MeshFilter meshFilter, - MeshCollider collider, - int spritesheetWidth, - int spritesheetHeight, - float scale) - { - _belt = belt; - _zone = zone; - Filter = meshFilter; - _collider = collider; - var orbit = zone.Orbits[belt.Data.Orbit.Key]; - _orbitParent = orbit.Data.Parent.Key; - _vertices = new Vector3[_belt.Data.Asteroids.Length * 4]; - _normals = new Vector3[_belt.Data.Asteroids.Length * 4]; - _uvs = new Vector2[_belt.Data.Asteroids.Length * 4]; - _indices = new int[_belt.Data.Asteroids.Length * 6]; - _scale = scale; - - var maxDist = 0f; - var spriteSize = float2(1f / spritesheetWidth, 1f / spritesheetHeight); - // vertex order: bottom left, top left, top right, bottom right - for (var i = 0; i < belt.Data.Asteroids.Length; i++) - { - if (belt.Data.Asteroids[i].Distance > maxDist) - maxDist = belt.Data.Asteroids[i].Distance; - var spriteX = Random.Range(0, spritesheetWidth); - var spriteY = Random.Range(0, spritesheetHeight); - - _uvs[i * 4] = new Vector2(spriteX * spriteSize.x, spriteY * spriteSize.y); - _uvs[i * 4 + 1] = new Vector2(spriteX * spriteSize.x, spriteY * spriteSize.y + spriteSize.y); - _uvs[i * 4 + 2] = new Vector2(spriteX * spriteSize.x + spriteSize.x, spriteY * spriteSize.y + spriteSize.y); - _uvs[i * 4 + 3] = new Vector2(spriteX * spriteSize.x + spriteSize.x, spriteY * spriteSize.y); - - _indices[i * 6] = i * 4; - _indices[i * 6 + 1] = i * 4 + 1; - _indices[i * 6 + 2] = i * 4 + 3; - _indices[i * 6 + 3] = i * 4 + 3; - _indices[i * 6 + 4] = i * 4 + 1; - _indices[i * 6 + 5] = i * 4 + 2; - } - - for (var i = 0; i < _normals.Length; i++) - { - _normals[i] = -Vector3.forward; - } - - _mesh = new Mesh(); - _mesh.vertices = _vertices; - _mesh.uv = _uvs; - _mesh.triangles = _indices; - _mesh.normals = _normals; - _mesh.bounds = new Bounds(Vector3.zero, Vector3.one * maxDist); - _size = maxDist; - - Filter.mesh = _mesh; - //_collider.sharedMesh = _mesh; - } - - public void Update(float4[] transforms, float height) - { - var parentPosition = DrawAhead.Orbit(_zone, _orbitParent, ActionGameManager.Clock.Lead); - for (var i = 0; i < transforms.Length; i++) - { - var transform = transforms[i]; - var rotation = Quaternion.Euler(90, transform.z, 0); - var position = new Vector3(transform.x, height, transform.y); - _vertices[i * 4] = rotation * new Vector3(-transform.w * _scale, -transform.w * _scale, 0) + position; - _vertices[i * 4 + 1] = rotation * new Vector3(-transform.w * _scale, transform.w * _scale, 0) + position; - _vertices[i * 4 + 2] = rotation * new Vector3(transform.w * _scale, transform.w * _scale, 0) + position; - _vertices[i * 4 + 3] = rotation * new Vector3(transform.w * _scale, -transform.w * _scale, 0) + position; - } - - _mesh.bounds = new Bounds(new Vector3(parentPosition.x, 0, parentPosition.y), Vector3.one * (_size * 2)); - _mesh.vertices = _vertices; - //_collider.sharedMesh = _mesh; - } -} diff --git a/Assets/Shaders/MapBelt.shader b/Assets/Shaders/MapBelt.shader new file mode 100644 index 000000000..9c4d0dfcf --- /dev/null +++ b/Assets/Shaders/MapBelt.shader @@ -0,0 +1,59 @@ +// The minimap and map screen's belt asteroids: one instanced draw per belt, six vertices per asteroid expanded to a +// quad on the map plane. _Belt holds the belt's per-frame float4s (x, y planar, z spin in degrees, w size); the sprite +// cell is a hash of the instance id, so a belt keeps its sprites without any per-asteroid CPU state. +Shader "Aetheria/MapBelt" +{ + Properties { _MainTex ("Sprite Sheet", 2D) = "white" {} _Color ("Color", Color) = (1,1,1,1) } + SubShader + { + Tags { "Queue"="Transparent" "RenderType"="Transparent" "IgnoreProjector"="True" } + Cull Off ZWrite Off Blend SrcAlpha OneMinusSrcAlpha + Pass + { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma target 4.5 + #include "UnityCG.cginc" + + sampler2D _MainTex; + fixed4 _Color; + StructuredBuffer _Belt; + float4 _Sheet; + float _PlaneY; + float _AsteroidSize; + + struct v2f { float4 pos : SV_POSITION; float2 uv : TEXCOORD0; }; + + uint Hash(uint x) + { + x = x * 747796405u + 2891336453u; + x = ((x >> ((x >> 28u) + 4u)) ^ x) * 277803737u; + return (x >> 22u) ^ x; + } + + v2f vert(uint vid : SV_VertexID, uint iid : SV_InstanceID) + { + // Triangles (0,1,3) and (3,1,2) over the corners bottom left, top left, top right, bottom right. + static const uint corner[6] = { 0, 1, 3, 3, 1, 2 }; + static const float2 offsets[4] = { float2(-1, -1), float2(-1, 1), float2(1, 1), float2(1, -1) }; + float4 a = _Belt[iid]; + float2 o = offsets[corner[vid]]; + float theta = radians(a.z); + float s = sin(theta), c = cos(theta); + float2 q = o * a.w * _AsteroidSize; + float3 world = float3(a.x + q.x * c + q.y * s, _PlaneY, a.y - q.x * s + q.y * c); + uint cell = Hash(iid) % (uint)(_Sheet.x * _Sheet.y); + float2 size = float2(1.0 / _Sheet.x, 1.0 / _Sheet.y); + float2 origin = float2(cell % (uint)_Sheet.x, cell / (uint)_Sheet.x) * size; + v2f v; + v.pos = mul(UNITY_MATRIX_VP, float4(world, 1)); + v.uv = origin + (o * .5 + .5) * size; + return v; + } + + fixed4 frag(v2f v) : SV_Target { return tex2D(_MainTex, v.uv) * _Color; } + ENDCG + } + } +} diff --git a/Assets/Shaders/MapBelt.shader.meta b/Assets/Shaders/MapBelt.shader.meta new file mode 100644 index 000000000..350a8b48a --- /dev/null +++ b/Assets/Shaders/MapBelt.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 22e2fc798f044a3aa2f6cd71f1df09a7 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: