Performance Optimization

Asteroid belts are now processed without GC allocations
Fog Raymarching shader now discards samples far from fog surface
Gravity depth calculation avoids some expensive operations
This commit is contained in:
Reinier Vens 2020-12-03 17:32:34 +00:00
commit 76eca26972
13 changed files with 2842 additions and 2879 deletions

View file

@ -57,6 +57,7 @@ Material:
- _NoiseFrequency: 0.01
- _NoiseSpeed: 0.02
- _NoiseStrength: 75
- _SafetyDistance: 50
- _StepExponent: 2
- _TintExponent: 4
m_Colors:

View file

@ -13,7 +13,7 @@ GameObject:
- component: {fileID: 2844878085845264008}
- component: {fileID: 917803079556930035}
- component: {fileID: 4397878771830533054}
m_Layer: 0
m_Layer: 14
m_Name: Asteroid Belt
m_TagString: Untagged
m_Icon: {fileID: 0}
@ -56,6 +56,8 @@ MeshRenderer:
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
@ -67,6 +69,7 @@ MeshRenderer:
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
@ -79,6 +82,7 @@ MeshRenderer:
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!64 &917803079556930035
MeshCollider:
m_ObjectHideFlags: 0
@ -89,9 +93,9 @@ MeshCollider:
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 3
serializedVersion: 4
m_Convex: 0
m_CookingOptions: 14
m_CookingOptions: 30
m_Mesh: {fileID: 0}
--- !u!114 &4397878771830533054
MonoBehaviour:

View file

@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 6f2f6975fe3175545ae0dcbb8e4f136d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load diff

View file

@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: f032e3ceed591844e80327e865f2c582
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

BIN
Assets/Resources/Settings.asset (Stored with Git LFS)

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -14,6 +14,7 @@ public class GameSettings : ScriptableObject
public int DefaultMinimapZoom;
public float IconSize;
public int AsteroidMeshCount = 5;
public float MinimapAsteroidSize = 3;
public PlanetSettings PlanetSettings;
public ZoneGenerationSettings ZoneSettings;
}

View file

@ -7,13 +7,14 @@ using UniRx;
using UnityEngine;
using static Unity.Mathematics.math;
using Unity.Mathematics;
using UnityEngine.Serialization;
using Random = UnityEngine.Random;
public class SectorRenderer : MonoBehaviour
{
public Transform FogCameraParent;
public GameSettings Settings;
public Transform SectorRoot;
public Transform ZoneRoot;
public Transform SectorBrushes;
public MeshRenderer SectorBoundaryBrush;
public MeshRenderer MinimapGravityQuad;
@ -24,11 +25,14 @@ public class SectorRenderer : MonoBehaviour
public float FogFarFadeFraction = .125f;
public float FarPlaneDistanceMultiplier = 2;
public InstancedMesh[] AsteroidMeshes;
public int AsteroidSpritesheetWidth = 4;
public int AsteroidSpritesheetHeight = 4;
// public Mesh[] AsteroidMeshes;
// public Material AsteroidMaterial;
[Header("Prefabs")]
// public MeshFilter AsteroidBeltUI;
public PlanetObject Planet;
public GasGiantObject GasGiant;
public SunObject Sun;
@ -37,8 +41,11 @@ public class SectorRenderer : MonoBehaviour
public Texture2D PlanetoidIcon;
public Texture2D PlanetIcon;
// private Dictionary<Guid, AsteroidBeltUI> _beltObjects = new Dictionary<Guid, AsteroidBeltUI>();
private Dictionary<Guid, PlanetObject> _planets = new Dictionary<Guid, PlanetObject>();
private Dictionary<Guid, InstancedMesh[]> _beltMeshes = new Dictionary<Guid, InstancedMesh[]>();
private Dictionary<Guid, Matrix4x4[][]> _beltMatrices = new Dictionary<Guid, Matrix4x4[][]>();
private Dictionary<Guid, float3[]> _beltAsteroidPositions = new Dictionary<Guid, float3[]>();
private Zone _zone;
private float _viewDistance;
private float _maxDepth;
@ -97,6 +104,7 @@ public class SectorRenderer : MonoBehaviour
}
_planets.Clear();
_beltMeshes.Clear();
_beltMatrices.Clear();
}
}
@ -108,6 +116,19 @@ public class SectorRenderer : MonoBehaviour
while(meshes.Count > Settings.AsteroidMeshCount)
meshes.RemoveAt(Random.Range(0,meshes.Count));
_beltMeshes[planetData.ID] = meshes.ToArray();
_beltMatrices[planetData.ID] = new Matrix4x4[meshes.Count][];
_beltAsteroidPositions[planetData.ID] = new float3[beltData.Asteroids.Length];
var count = beltData.Asteroids.Length / meshes.Count;
var remainder = beltData.Asteroids.Length - count * meshes.Count;
for (int i = 0; i < meshes.Count; i++)
{
_beltMatrices[planetData.ID][i] = new Matrix4x4[i<meshes.Count-1 ? count : count+remainder];
}
// var beltObject = Instantiate(AsteroidBeltUI, ZoneRoot);
// var collider = beltObject.GetComponent<MeshCollider>();
// var belt = new AsteroidBeltUI(_zone, _zone.AsteroidBelts[beltData.ID], beltObject, collider, AsteroidSpritesheetWidth, AsteroidSpritesheetHeight, Settings.MinimapAsteroidSize);
// _beltObjects[beltData.ID] = belt;
}
else
{
@ -116,14 +137,14 @@ public class SectorRenderer : MonoBehaviour
{
if (planetData is SunData sunData)
{
planet = Instantiate(Sun, SectorRoot);
planet = Instantiate(Sun, ZoneRoot);
var sun = (SunObject) planet;
sunData.LightColor.Subscribe(c => sun.Light.color = c);
sunData.Mass.Subscribe(m => sun.Light.range = Settings.PlanetSettings.LightRadius.Evaluate(m));
sunData.FogTintColor.Subscribe(c => sun.FogTint.material.SetColor("_Color", c));
sunData.Mass.Subscribe(m => sun.FogTint.transform.localScale = Settings.PlanetSettings.FogTintRadius.Evaluate(m) * Vector3.one);
}
else planet = Instantiate(GasGiant, SectorRoot);
else planet = Instantiate(GasGiant, ZoneRoot);
var gas = (GasGiantObject) planet;
var gasGiant = _zone.PlanetInstances[planetData.ID] as GasGiant;
@ -140,7 +161,7 @@ public class SectorRenderer : MonoBehaviour
}
else
{
planet = Instantiate(Planet, SectorRoot);
planet = Instantiate(Planet, ZoneRoot);
//planet.Icon.material.mainTexture = planetData.Mass > Context.GlobalData.PlanetMass ? PlanetIcon : PlanetoidIcon;
}
@ -153,7 +174,7 @@ public class SectorRenderer : MonoBehaviour
planet.GravityWell.material.SetFloat("_Depth", f);
});
_planets.Add(planetData.ID, planet);
_planets[planetData.ID] = planet;
}
}
@ -161,18 +182,25 @@ public class SectorRenderer : MonoBehaviour
{
foreach(var belt in _zone.AsteroidBelts)
{
// _beltObjects[belt.Key].Update();
var meshes = _beltMeshes[belt.Key];
for (int i = 0; i < _beltAsteroidPositions[belt.Key].Length; i++)
_beltAsteroidPositions[belt.Key][i] = float3(belt.Value.Transforms[i].x, _zone.GetHeight(belt.Value.Transforms[i].xy), belt.Value.Transforms[i].y);
var count = belt.Value.Transforms.Length / meshes.Length;
for (int i = 0; i < meshes.Length; i++)
{
var matrices = belt.Value.Transforms
.Skip((int) (((float)i / meshes.Length) * belt.Value.Transforms.Length))
.Take((int) (1f / meshes.Length * belt.Value.Transforms.Length))
.Select((v, x) => Matrix4x4.TRS(
new Vector3(v.x, _zone.GetHeight(v.xy), v.y),
Quaternion.Euler(cos(v.z + (float) i / meshes.Length) * 100, sin(v.z + (float) i / meshes.Length) * 100, (float)x/belt.Value.Transforms.Length * 360),
Vector3.one * v.w))
.ToArray();
Graphics.DrawMeshInstanced(meshes[i].Mesh, 0, meshes[i].Material, matrices);
for (int t = 0; t < _beltMatrices[belt.Key][i].Length; t++)
{
var tx = t + i * count;
_beltMatrices[belt.Key][i][t] = Matrix4x4.TRS(_beltAsteroidPositions[belt.Key][tx],
Quaternion.Euler(
cos(belt.Value.Transforms[tx].z + (float) i / meshes.Length) * 100,
sin(belt.Value.Transforms[tx].z + (float) i / meshes.Length) * 100,
(float) tx / belt.Value.Transforms.Length * 360),
Vector3.one * belt.Value.Transforms[tx].w);
}
Graphics.DrawMeshInstanced(meshes[i].Mesh, 0, meshes[i].Material, _beltMatrices[belt.Key][i]);
}
}
@ -213,3 +241,91 @@ public class InstancedMesh
public Mesh Mesh;
public Material Material;
}
public class AsteroidBeltUI
{
private MeshFilter _filter;
private MeshCollider _collider;
private Vector3[] _vertices;
private Vector3[] _normals;
private Vector2[] _uvs;
private int[] _indices;
private Guid _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];
_orbitParent = orbit.Data.Parent;
_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()
{
var parentPosition = _zone.GetOrbitPosition(_orbitParent);
for (var i = 0; i < _belt.Data.Asteroids.Length; i++)
{
var rotation = Quaternion.Euler(90, _belt.Transforms[i].z, 0);
var position = new Vector3(_belt.Transforms[i].x, _zone.GetHeight(parentPosition), _belt.Transforms[i].y);
_vertices[i * 4] = rotation * new Vector3(-_belt.Transforms[i].w * _scale,-_belt.Transforms[i].w * _scale,0) + position;
_vertices[i * 4 + 1] = rotation * new Vector3(-_belt.Transforms[i].w * _scale,_belt.Transforms[i].w * _scale,0) + position;
_vertices[i * 4 + 2] = rotation * new Vector3(_belt.Transforms[i].w * _scale,_belt.Transforms[i].w * _scale,0) + position;
_vertices[i * 4 + 3] = rotation * new Vector3(_belt.Transforms[i].w * _scale,-_belt.Transforms[i].w * _scale,0) + position;
}
_mesh.bounds = new Bounds((Vector2) parentPosition, Vector3.one * (_size * 2));
_mesh.vertices = _vertices;
_collider.sharedMesh = _mesh;
}
}

View file

@ -19,7 +19,7 @@ public class Zone
public Dictionary<Guid, Orbit> Orbits = new Dictionary<Guid, Orbit>();
public Dictionary<Guid, AsteroidBelt> AsteroidBelts = new Dictionary<Guid, AsteroidBelt>();
private HashSet<Guid> _updatedOrbits;
private HashSet<Guid> _updatedOrbits = new HashSet<Guid>();
private PlanetSettings _settings;
private float _time;
@ -44,13 +44,13 @@ public class Zone
switch (planet)
{
case AsteroidBeltData belt:
AsteroidBelts[belt.ID] = new AsteroidBelt(belt.Asteroids.Length);
AsteroidBelts[belt.ID] = new AsteroidBelt(belt);
break;
case GasGiantData gas:
PlanetInstances.Add(gas.ID, new GasGiant(settings, gas));
PlanetInstances.Add(gas.ID, new GasGiant(settings, gas, Orbits[planet.Orbit]));
break;
default:
PlanetInstances.Add(planet.ID, new Planet(settings, planet));
PlanetInstances.Add(planet.ID, new Planet(settings, planet, Orbits[planet.Orbit]));
break;
}
}
@ -79,7 +79,7 @@ public class Zone
public void Update(float time, float deltaTime)
{
_time = time;
_updatedOrbits = new HashSet<Guid>();
_updatedOrbits.Clear();
foreach (var orbit in Orbits)
{
orbit.Value.PreviousPosition = orbit.Value.Position;
@ -266,24 +266,24 @@ public class Zone
float result = -PowerPulse(length(position)/(Data.Radius*2), _settings.ZoneDepthExponent) * _settings.ZoneDepth;
foreach (var body in PlanetInstances.Values)
{
var p = (position - GetOrbitPosition(body.BodyData.Orbit));
var dist = length(p);
var p = (position - body.Orbit.Position); //GetOrbitPosition(body.BodyData.Orbit)
var dist = lengthsq(p);
var gravityRadius = body.GravityWellRadius.Value;
if (dist < gravityRadius)
if (dist < gravityRadius*gravityRadius)
{
var depth = body.GravityWellDepth.Value;
result -= PowerPulse(dist / gravityRadius, body.BodyData.GravityDepthExponent.Value) * depth;
result -= PowerPulse(sqrt(dist) / gravityRadius, body.BodyData.GravityDepthExponent.Value) * depth;
}
if (body is GasGiant gas)
{
var waveRadius = gas.GravityWavesRadius.Value;
if(dist < waveRadius)
if(dist < waveRadius*waveRadius)
{
var depth = gas.GravityWavesDepth.Value;
var frequency = _settings.WaveFrequency.Evaluate(body.BodyData.Mass.Value);
var speed = _settings.WaveSpeed.Evaluate(body.BodyData.Mass.Value);
result -= RadialWaves(dist / waveRadius, 8, 1.5f, frequency, _time * speed) * depth;
result -= RadialWaves(sqrt(dist) / waveRadius, 8, 1.5f, frequency, _time * speed) * depth;
}
}
}
@ -337,13 +337,15 @@ public class Zone
public class Planet
{
public Orbit Orbit;
public BodyData BodyData;
public ReadOnlyReactiveProperty<float> GravityWellDepth;
public ReadOnlyReactiveProperty<float> GravityWellRadius;
public ReadOnlyReactiveProperty<float> BodyRadius;
public Planet(PlanetSettings settings, BodyData data)
public Planet(PlanetSettings settings, BodyData data, Orbit orbit)
{
Orbit = orbit;
BodyData = data;
BodyRadius = new ReadOnlyReactiveProperty<float>(
data.Mass.CombineLatest(data.BodyRadiusMultiplier,
@ -364,7 +366,7 @@ public class GasGiant : Planet
public ReadOnlyReactiveProperty<float> GravityWavesRadius;
public ReadOnlyReactiveProperty<float> GravityWavesSpeed;
public GasGiant(PlanetSettings settings, GasGiantData data) : base(settings, data)
public GasGiant(PlanetSettings settings, GasGiantData data, Orbit orbit) : base(settings, data, orbit)
{
GasGiantData = data;
GravityWavesDepth = new ReadOnlyReactiveProperty<float>(
@ -386,16 +388,18 @@ public class GasGiant : Planet
public class AsteroidBelt
{
public AsteroidBeltData Data;
public float4[] Transforms; // x, y, rotation, scale
public float4[] PreviousTransforms; // x, y, rotation, scale
public Dictionary<int, float> RespawnTimers = new Dictionary<int, float>();
public Dictionary<int, float> Damage = new Dictionary<int, float>();
public Dictionary<(Guid, int), float> MiningAccumulator = new Dictionary<(Guid, int), float>();
public AsteroidBelt(int count)
public AsteroidBelt(AsteroidBeltData data)
{
Transforms = new float4[count];
PreviousTransforms = new float4[count];
Data = data;
Transforms = new float4[data.Asteroids.Length];
PreviousTransforms = new float4[data.Asteroids.Length];
}
}

View file

@ -22,6 +22,7 @@
_NoiseStrength("Noise Strength", float) = 1
_NoiseFrequency("Noise Frequency", float) = 1
_NoiseSpeed("Noise Speed", float) = 1
_SafetyDistance("Safety Distance", float) = 20
}
CGINCLUDE;
@ -70,7 +71,8 @@
_DepthBlend,
_NoiseFrequency,
_NoiseStrength,
_NoiseSpeed;
_NoiseSpeed,
_SafetyDistance;
// Dithering
sampler2D _DitheringTex;
@ -109,27 +111,27 @@
float2 uv = -(pos.xz-_GridTransform.xy)/_GridTransform.z + float2(.5,.5);
float surface = tex2Dlod(_Surface, half4(uv, 0, 0)).r;
float patch = tex2Dlod(_Patch, half4(uv, 0, 0)).r;
float displacement = tex2Dlod(_Displacement, half4(uv, 0, 0)).r;
float4 lightTint = tex2Dlod(_TintTexture, half4(uv, 0, 0));
float4 lightTint = tex2Dlod(_TintTexture, half4(uv, 0, 0));
float fillDensity = saturate(-pos.y * _GridFillDensity);
if(pos.y + surface - _GridFloorOffset < _SafetyDistance)
{
float patch = tex2Dlod(_Patch, half4(uv, 0, 0)).r;
float displacement = tex2Dlod(_Displacement, half4(uv, 0, 0)).r;
float noise = pow(triNoise3d(pos*_NoiseFrequency, _NoiseSpeed),2);// + triNoise3d(pos*_NoiseFrequency*2, _NoiseSpeed * 2) * .5;
pos.y += noise * _NoiseStrength;
float patchDensity = saturate((-abs(pos.y+displacement)+patch)/_GridPatchBlend)*_GridPatchDensity;
float floorDist = -pos.y-(surface)+_GridFloorOffset;
float floorDensity = floorDist/_GridFloorBlend*_GridFloorDensity;
float fillDensity = saturate(-pos.y * _GridFillDensity);
//
float fogDensity = patchDensity + max(0,floorDensity);
//half blend = pow(max(-fogTex,1),2);
//float alpha = min(max(fogDensity * (1 - noise * _NoiseStrength) + fillDensity, _AlphaFloor), .99);
float alpha = min(max(max(fogDensity, 0) + fillDensity, _AlphaFloor), .99);
float albedo = (pow(1-alpha, _TintExponent));
return float4((albedo*_Tint*lightTint).rgb, alpha);
//return float4(tint.xxx,saturate(fogTex)) * _Tint;
// return max(clamp((-abs(pos.y+displacement)+patch)/_GridPatchDensity,0,1),
// max(clamp((pos.y+(surface+_GridCeilingOffset)*_GridCeilingFollow)/_GridCeilingDensity,0,1),
// clamp((-pos.y-(surface+_GridFloorOffset))/_GridFloorDensity,0,1)));
float noise = pow(triNoise3d(pos*_NoiseFrequency, _NoiseSpeed),2);// + triNoise3d(pos*_NoiseFrequency*2, _NoiseSpeed * 2) * .5;
pos.y += noise * _NoiseStrength;
float patchDensity = saturate((-abs(pos.y+displacement)+patch)/_GridPatchBlend)*_GridPatchDensity;
float floorDist = -pos.y-(surface)+_GridFloorOffset;
float floorDensity = floorDist/_GridFloorBlend*_GridFloorDensity;
float fogDensity = patchDensity + max(0,floorDensity);
float alpha = min(max(max(fogDensity, 0) + fillDensity, _AlphaFloor), .99);
float albedo = (pow(1-alpha, _TintExponent));
return float4((albedo*_Tint*lightTint).rgb, alpha);
}
float albedo = pow(1-fillDensity, _TintExponent);
return float4((albedo*_Tint*lightTint).rgb, fillDensity);
}
void RaymarchStep( in float3 pos, in float stepSize, in float weight, inout float4 sum )

BIN
GameData/lotsabelts.zone Normal file

Binary file not shown.

BIN
ProjectSettings/TagManager.asset (Stored with Git LFS)

Binary file not shown.