Initial ARPG Port
ARPG scene assets from old project are now correctly visualizing sectors generated by ZoneGenerator and updated by GameContext
This commit is contained in:
parent
1e2b474fc1
commit
d12d7c5c45
379 changed files with 42700 additions and 7253 deletions
63
Assets/Scripts/ActionGameManager.cs
Normal file
63
Assets/Scripts/ActionGameManager.cs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using MessagePack;
|
||||
using UnityEngine;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
using float2 = Unity.Mathematics.float2;
|
||||
|
||||
public class ActionGameManager : MonoBehaviour
|
||||
{
|
||||
public DatabaseCache Cache { get; private set; }
|
||||
public GameContext Context { get; private set; }
|
||||
public Zone CurrentZone { get; private set; }
|
||||
|
||||
public event EventHandler<ZoneChangeEventArgs> ZoneChanged;
|
||||
|
||||
void Start()
|
||||
{
|
||||
var filePath = new DirectoryInfo(Application.dataPath).Parent;
|
||||
Cache = new DatabaseCache();
|
||||
Cache.Load(filePath.FullName);
|
||||
Context = new GameContext(Cache, Debug.Log);
|
||||
|
||||
var zoneFile = Path.Combine(filePath.FullName, "Home.msgpack");
|
||||
|
||||
// If the game has already been run, there will be a Home file containing a ZonePack; if not, generate one
|
||||
var zonePack = File.Exists(zoneFile) ?
|
||||
MessagePackSerializer.Deserialize<ZonePack>(File.ReadAllBytes(zoneFile)) :
|
||||
ZoneGenerator.GenerateZone(
|
||||
context: Context,
|
||||
name: "Home",
|
||||
position: float2.zero,
|
||||
mapLayers: Context.MapLayers.Values,
|
||||
resources: Context.Resources,
|
||||
mass: 100000,
|
||||
radius: 1500
|
||||
);
|
||||
|
||||
//var oldZone = CurrentZone;
|
||||
CurrentZone = Context.GetZone(zonePack);
|
||||
//ZoneChanged?.Invoke(this, new ZoneChangeEventArgs(oldZone, CurrentZone));
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
Context.Time = Time.time;
|
||||
Context.Update();
|
||||
}
|
||||
}
|
||||
|
||||
public class ZoneChangeEventArgs : EventArgs
|
||||
{
|
||||
public Zone OldZone { get; set; }
|
||||
public Zone NewZone { get; set; }
|
||||
|
||||
public ZoneChangeEventArgs(Zone oldZone, Zone newZone)
|
||||
{
|
||||
OldZone = oldZone;
|
||||
NewZone = newZone;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ActionGameManager.cs.meta
Normal file
11
Assets/Scripts/ActionGameManager.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 39f95af24dd29a645895a57a75460b0c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
30
Assets/Scripts/BlueNoiseProvider.cs
Normal file
30
Assets/Scripts/BlueNoiseProvider.cs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using Random = UnityEngine.Random;
|
||||
|
||||
[ExecuteInEditMode]
|
||||
public class BlueNoiseProvider : MonoBehaviour
|
||||
{
|
||||
public Texture2D NoiseTexture;
|
||||
|
||||
private Camera _camera;
|
||||
|
||||
void Start()
|
||||
{
|
||||
_camera = Camera.main;
|
||||
|
||||
Shader.SetGlobalTexture("_DitheringTex", NoiseTexture);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
Shader.SetGlobalVector("_DitheringCoords", new Vector4(
|
||||
(float)_camera.scaledPixelWidth / (float)NoiseTexture.width,
|
||||
(float)_camera.scaledPixelWidth / (float)NoiseTexture.height,
|
||||
Random.value,
|
||||
Random.value
|
||||
));
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/BlueNoiseProvider.cs.meta
Normal file
11
Assets/Scripts/BlueNoiseProvider.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 13f1fa636e0245e42be783568a76e3d6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
31
Assets/Scripts/CameraPerlinOrbit.cs
Normal file
31
Assets/Scripts/CameraPerlinOrbit.cs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.noise;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class CameraPerlinOrbit : MonoBehaviour
|
||||
{
|
||||
public Transform Target;
|
||||
public float Distance;
|
||||
public float MinElevation = .25f;
|
||||
public float MaxElevation = .5f;
|
||||
public float Frequency = .1f;
|
||||
public float VerticalLookOffset;
|
||||
|
||||
void Start()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
// Update is called once per frame
|
||||
void Update()
|
||||
{
|
||||
transform.position = normalize(float3(
|
||||
snoise(float2(0, Time.time * Frequency)),
|
||||
smoothstep(snoise(float2(10, Time.time * Frequency)), -1, 1) * (MaxElevation - MinElevation) + MinElevation,
|
||||
snoise(float2(20, Time.time * Frequency)))) * Distance + (float3) Target.position;
|
||||
transform.LookAt(Target.position + Vector3.up * VerticalLookOffset);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/CameraPerlinOrbit.cs.meta
Normal file
11
Assets/Scripts/CameraPerlinOrbit.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 83d58735b61546b45930f055a9e2e30a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
47
Assets/Scripts/CopyTransform.cs
Normal file
47
Assets/Scripts/CopyTransform.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class CopyTransform : MonoBehaviour
|
||||
{
|
||||
public Transform Target;
|
||||
public bool CopyXPosition = false;
|
||||
public bool CopyYPosition = false;
|
||||
public bool CopyZPosition = false;
|
||||
public bool CopyRotation = false;
|
||||
//public Vector3 RotationOffsetEulerAngles = Vector3.zero;
|
||||
public Camera PixelSnapCamera;
|
||||
public float PixelSnapIncrement = 1;
|
||||
|
||||
private float _snapLength;
|
||||
|
||||
void Update ()
|
||||
{
|
||||
var snap = PixelSnapCamera != null;
|
||||
if(snap)
|
||||
_snapLength = PixelSnapCamera.orthographicSize * PixelSnapIncrement / PixelSnapCamera.targetTexture.width;
|
||||
|
||||
var x = CopyXPosition ? Target.position.x : transform.position.x;
|
||||
if (snap)
|
||||
{
|
||||
var x1 = (int) (x / _snapLength);
|
||||
x = x1 * _snapLength;
|
||||
}
|
||||
|
||||
var z = CopyZPosition ? Target.position.z : transform.position.z;
|
||||
if (snap)
|
||||
{
|
||||
var z1 = (int) (z / _snapLength);
|
||||
z = z1 * _snapLength;
|
||||
}
|
||||
|
||||
transform.position = new Vector3(x, CopyYPosition ? Target.position.y : transform.position.y, z);
|
||||
|
||||
if (CopyRotation)
|
||||
{
|
||||
var flatForward = Target.forward;
|
||||
flatForward.y = 0;
|
||||
transform.rotation = Quaternion.LookRotation(Vector3.down, flatForward.normalized);
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/CopyTransform.cs.meta
Normal file
11
Assets/Scripts/CopyTransform.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 7ec4eea2d4fa2f64f80e17d11987e6f6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -192,6 +192,11 @@ public class DatabaseListView : EditorWindow
|
|||
{
|
||||
_databaseCache.Save(new DirectoryInfo(Application.dataPath).Parent.FullName);
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Load"))
|
||||
{
|
||||
_databaseCache.Load(new DirectoryInfo(Application.dataPath).Parent.FullName);
|
||||
}
|
||||
}
|
||||
|
||||
using (new HorizontalScope())
|
||||
|
|
|
|||
119
Assets/Scripts/GradientMapper.cs
Normal file
119
Assets/Scripts/GradientMapper.cs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
[ExecuteInEditMode]
|
||||
public class GradientMapper : MonoBehaviour
|
||||
{
|
||||
[Header("Gradient map parameters")] public Vector2Int GradientMapDimensions = new Vector2Int(32, 1);
|
||||
public Gradient Gradient;
|
||||
|
||||
[Header("Enable testing")] public bool Testing = false;
|
||||
|
||||
private MeshRenderer _meshRenderer;
|
||||
private Material _material;
|
||||
|
||||
[HideInInspector] public Texture2D Texture;
|
||||
|
||||
public static int TotalMaps = 0;
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
_meshRenderer = GetComponent<MeshRenderer>();
|
||||
if (_meshRenderer == null)
|
||||
{
|
||||
Debug.LogWarning("No mesh renderer on this game object! Removing GradientMapper");
|
||||
DestroyImmediate(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
_material = _meshRenderer.sharedMaterial;
|
||||
}
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (Testing)
|
||||
{
|
||||
ApplyGradient(Gradient);
|
||||
}
|
||||
}
|
||||
|
||||
public void ApplyGradient(Gradient gradient)
|
||||
{
|
||||
Texture = new Texture2D(GradientMapDimensions.x, GradientMapDimensions.y);
|
||||
Texture.wrapMode = TextureWrapMode.Clamp;
|
||||
for (int x = 0; x < GradientMapDimensions.x; x++)
|
||||
{
|
||||
for (int y = 0; y < GradientMapDimensions.y; y++)
|
||||
{
|
||||
Texture.SetPixel(x, y, gradient.Evaluate( max((float)x / GradientMapDimensions.x,(float)y / GradientMapDimensions.y)));
|
||||
}
|
||||
}
|
||||
|
||||
Texture.Apply();
|
||||
if (_material.HasProperty("_ColorRamp"))
|
||||
{
|
||||
_material.SetTexture("_ColorRamp", Texture);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
[CustomEditor(typeof(GradientMapper))]
|
||||
public class GradientMapperEditor : Editor
|
||||
{
|
||||
private int _subfolder;
|
||||
private string[] Subfolders = {"Sun", "Gas Giant"};
|
||||
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
GradientMapper gradientMapper = target as GradientMapper;
|
||||
DrawDefaultInspector();
|
||||
if (gradientMapper.Testing)
|
||||
{
|
||||
EditorGUILayout.HelpBox("Testing is active.", MessageType.Warning, true);
|
||||
}
|
||||
|
||||
_subfolder = EditorGUILayout.Popup("Subfolder", _subfolder, Subfolders);
|
||||
|
||||
if (GUILayout.Button("Make Gradient Map"))
|
||||
{
|
||||
gradientMapper.Testing = false;
|
||||
if (!AssetDatabase.IsValidFolder("Assets/Resources/Gradients"))
|
||||
{
|
||||
AssetDatabase.CreateFolder("Assets/Resources/", "Gradients");
|
||||
AssetDatabase.SaveAssets();
|
||||
}
|
||||
|
||||
if (!Directory.Exists($"{Application.dataPath}Resources/Gradients/{Subfolders[_subfolder]}"))
|
||||
{
|
||||
Directory.CreateDirectory($"{Application.dataPath}/Resources/Gradients/{Subfolders[_subfolder]}");
|
||||
GradientMapper.TotalMaps = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
GradientMapper.TotalMaps = Directory.GetFiles(Application.dataPath + "/Resources/Gradients/").Length;
|
||||
}
|
||||
|
||||
byte[] bytes = gradientMapper.Texture.EncodeToPNG();
|
||||
|
||||
string fileName;
|
||||
do fileName = $"{Application.dataPath}/Resources/Gradients/{Subfolders[_subfolder] + '/'}gradient_{GradientMapper.TotalMaps++}.png";
|
||||
while (File.Exists(fileName));
|
||||
|
||||
File.WriteAllBytes(fileName, bytes);
|
||||
AssetDatabase.Refresh();
|
||||
|
||||
Debug.Log("Gradient map saved!");
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
11
Assets/Scripts/GradientMapper.cs.meta
Normal file
11
Assets/Scripts/GradientMapper.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 6d2f8d4338ab9044cb603b1d3e8f189a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
129
Assets/Scripts/Gravity.cs
Normal file
129
Assets/Scripts/Gravity.cs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
public class Gravity : MonoBehaviour
|
||||
{
|
||||
public float GlobalGravityMultiplier;
|
||||
public GravityForceMode ForceMode = GravityForceMode.Gradient;
|
||||
public float GradientStepSize = .01f;
|
||||
public float NormalMultiplier = 100f;
|
||||
public List<GravityObject> GravityObjects = new List<GravityObject>();
|
||||
|
||||
private static Gravity _instance;
|
||||
|
||||
public static Gravity Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance != null)
|
||||
return _instance;
|
||||
|
||||
_instance = (Gravity)FindObjectOfType(typeof(Gravity));
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
public static float GetHeight(Vector2 position)
|
||||
{
|
||||
float result = 0;
|
||||
foreach (var go in Instance.GravityObjects)
|
||||
{
|
||||
if (((Vector2) go.transform.InverseTransformPoint(position.Flatland())).sqrMagnitude < .25f)
|
||||
result = result - GetHeight(go.GravityMaterial, go.Shader,
|
||||
(Vector2) go.transform.InverseTransformPoint(position.Flatland()) + Vector2.one * .5f);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Vector2 GetForce(Vector2 position)
|
||||
{
|
||||
if (Instance.ForceMode == GravityForceMode.Sign)
|
||||
{
|
||||
var hits = Instance.GravityObjects.Where(go => (go.transform.position.Flatland() - position).sqrMagnitude < go.transform.lossyScale.x)
|
||||
// var hits = Physics.RaycastAll(new Ray(new Vector3(position.x, 10, position.y), Vector3.down), 20, LayerMask.GetMask("Displacement"))
|
||||
.Where(h => !h.CompareTag("IgnoreGravity"));
|
||||
|
||||
Vector2 force = Vector2.zero;
|
||||
foreach (var hit in hits)
|
||||
{
|
||||
force += (new Vector2(hit.transform.position.x, hit.transform.position.z) - position) *
|
||||
GetHeight(hit.GravityMaterial, hit.Shader, hit.transform.InverseTransformPoint(position.Flatland()).Flatland());
|
||||
}
|
||||
return force * Instance.GlobalGravityMultiplier;
|
||||
}
|
||||
|
||||
var normal = GetNormal(position);
|
||||
var f = new Vector2(normal.x, normal.z);
|
||||
return f * Instance.GlobalGravityMultiplier * f.sqrMagnitude;// * Mathf.Abs(GetHeight(position));
|
||||
}
|
||||
|
||||
private static float GetHeight(Material mat, string shader, Vector2 textureCoord)
|
||||
{
|
||||
// var mat = hit.transform.GetComponent<MeshRenderer>().material;
|
||||
|
||||
switch (shader)
|
||||
{
|
||||
case "Brushes/Cubic Pulse Brush":
|
||||
return mat.GetFloat("_Depth") * CubicPulse(0, .5f, (textureCoord - Vector2.one * .5f).magnitude);
|
||||
|
||||
case "Brushes/Power Brush":
|
||||
return mat.GetFloat("_Depth") * PowerPulse((textureCoord - Vector2.one * .5f).magnitude * 2, mat.GetFloat("_Power"));
|
||||
case "Brushes/Radial Wave Brush":
|
||||
{
|
||||
float dist = (textureCoord - Vector2.one * .5f).magnitude;
|
||||
return mat.GetFloat("_Depth") * PowerPulse(dist * 2, mat.GetFloat("_Power")) *
|
||||
Mathf.Cos(Mathf.Pow(dist*2, mat.GetFloat("_SinePower")) * mat.GetFloat("_Frequency") + mat.GetFloat("_Phase"));
|
||||
}
|
||||
case "Brushes/Linear Wave Brush":
|
||||
{
|
||||
float dist = (textureCoord - Vector2.one * .5f).magnitude;
|
||||
return mat.GetFloat("_Depth") * PowerPulse(dist * 2, mat.GetFloat("_Power")) *
|
||||
Mathf.Cos((textureCoord.y - .5f) * mat.GetFloat("_Frequency") + mat.GetFloat("_Phase"));
|
||||
}
|
||||
default:
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static float CubicPulse(float c, float w, float x)
|
||||
{
|
||||
x = Mathf.Abs(x - c);
|
||||
if (x > w) return 0;
|
||||
x /= w;
|
||||
return 1.0f - x * x * (3.0f - 2.0f * x);
|
||||
}
|
||||
|
||||
public static float PowerPulse(float x, float pow)
|
||||
{
|
||||
x = Mathf.Clamp(x, -1, 1);
|
||||
return Mathf.Pow((x + 1) * (1 - x), pow);
|
||||
}
|
||||
|
||||
public static Vector3 GetNormal(Vector2 pos, float step, float mul)
|
||||
{
|
||||
float hL = GetHeight(new Vector2(pos.x - step, pos.y)) * mul;
|
||||
float hR = GetHeight(new Vector2(pos.x + step, pos.y)) * mul;
|
||||
float hD = GetHeight(new Vector2(pos.x, pos.y - step)) * mul;
|
||||
float hU = GetHeight(new Vector2(pos.x, pos.y + step)) * mul;
|
||||
|
||||
// Deduce terrain normal
|
||||
Vector3 normal = new Vector3((hL - hR), (hD - hU), 2);
|
||||
normal.Normalize();
|
||||
return new Vector3(normal.x, normal.z, normal.y);
|
||||
}
|
||||
|
||||
public static Vector3 GetNormal(Vector2 pos)
|
||||
{
|
||||
return GetNormal(pos, Instance.GradientStepSize, Instance.NormalMultiplier);
|
||||
}
|
||||
}
|
||||
|
||||
public enum GravityForceMode
|
||||
{
|
||||
Sign,
|
||||
Gradient
|
||||
}
|
||||
11
Assets/Scripts/Gravity.cs.meta
Normal file
11
Assets/Scripts/Gravity.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: d30227341391e764b87bcc7096c35470
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: -30
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
18
Assets/Scripts/GravityObject.cs
Normal file
18
Assets/Scripts/GravityObject.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class GravityObject : MonoBehaviour
|
||||
{
|
||||
[HideInInspector]
|
||||
public Material GravityMaterial;
|
||||
|
||||
[HideInInspector]
|
||||
public string Shader;
|
||||
|
||||
void Start () {
|
||||
Gravity.Instance.GravityObjects.Add(this);
|
||||
GravityMaterial = GetComponent<MeshRenderer>().material;
|
||||
Shader = GravityMaterial.shader.name;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/GravityObject.cs.meta
Normal file
11
Assets/Scripts/GravityObject.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a13344dbee46f384881bd54203513967
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -30,7 +30,7 @@ public static class RethinkConnection
|
|||
}
|
||||
};
|
||||
|
||||
var connection = R.Connection().Hostname(connectionString).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
|
||||
var connection = R.Connection().Hostname(connectionString).Port(RethinkDBConstants.DefaultPort+1).Timeout(60).Connect();
|
||||
Debug.Log("Connected to RethinkDB");
|
||||
|
||||
if (syncLocalChanges)
|
||||
|
|
|
|||
8
Assets/Scripts/Sector Display.meta
Normal file
8
Assets/Scripts/Sector Display.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 3488d7d419145494fa13c8ba53eac6c0
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
11
Assets/Scripts/Sector Display/GasGiantObject.cs
Normal file
11
Assets/Scripts/Sector Display/GasGiantObject.cs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class GasGiantObject : PlanetObject
|
||||
{
|
||||
public SunMaterial SunMaterial;
|
||||
public GradientMapper GradientMapper;
|
||||
public MeshRenderer GravityWaves;
|
||||
public WaveScroll WaveScroll;
|
||||
}
|
||||
11
Assets/Scripts/Sector Display/GasGiantObject.cs.meta
Normal file
11
Assets/Scripts/Sector Display/GasGiantObject.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 71ac44e29296d7541afb153524b80e14
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
11
Assets/Scripts/Sector Display/PlanetObject.cs
Normal file
11
Assets/Scripts/Sector Display/PlanetObject.cs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class PlanetObject : MonoBehaviour
|
||||
{
|
||||
public MeshRenderer Body;
|
||||
public SnapToGrid GridSnap;
|
||||
public MeshRenderer GravityWell;
|
||||
public MeshRenderer Icon;
|
||||
}
|
||||
11
Assets/Scripts/Sector Display/PlanetObject.cs.meta
Normal file
11
Assets/Scripts/Sector Display/PlanetObject.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a4734f48262f7de46b0a34d7f3fdbe90
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
21
Assets/Scripts/Sector Display/SectorDisplayProperties.cs
Normal file
21
Assets/Scripts/Sector Display/SectorDisplayProperties.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
[CreateAssetMenu(fileName = "Sector Display Properties", menuName = "Aetheria/Sector Display Properties")]
|
||||
public class SectorDisplayProperties : ScriptableObject
|
||||
{
|
||||
public float DefaultViewDistance;
|
||||
public float DefaultMinimapDistance;
|
||||
public ExponentialCurve BodyDiameter;
|
||||
public ExponentialCurve GravityDepth;
|
||||
public ExponentialCurve GravityRadius;
|
||||
public ExponentialCurve WaveDepth;
|
||||
public ExponentialCurve WaveRadius;
|
||||
public ExponentialCurve WaveFrequency;
|
||||
public ExponentialCurve WaveSpeed;
|
||||
public ExponentialCurve FogTintRadius;
|
||||
public ExponentialCurve LightRadius;
|
||||
public Gradient DefaultGradient;
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0d957fc3cdc9310499a3a494a317fe0a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
141
Assets/Scripts/Sector Display/SectorRenderer.cs
Normal file
141
Assets/Scripts/Sector Display/SectorRenderer.cs
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Cinemachine;
|
||||
using UnityEngine;
|
||||
|
||||
public class SectorRenderer : MonoBehaviour
|
||||
{
|
||||
public Transform FogCameraParent;
|
||||
public SectorDisplayProperties Properties;
|
||||
public Transform SectorRoot;
|
||||
public Transform SectorBrushes;
|
||||
public CinemachineVirtualCamera SceneCamera;
|
||||
public Camera[] FogCameras;
|
||||
public Camera[] MinimapCameras;
|
||||
public Material FogMaterial;
|
||||
public ActionGameManager Manager;
|
||||
public float FogFarFadeFraction = .125f;
|
||||
public float FarPlaneDistanceMultiplier = 2;
|
||||
|
||||
[Header("Prefabs")]
|
||||
public GameObject Belt;
|
||||
public PlanetObject Planet;
|
||||
public GasGiantObject GasGiant;
|
||||
public SunObject Sun;
|
||||
|
||||
[Header("Icons")]
|
||||
public Texture2D PlanetoidIcon;
|
||||
public Texture2D PlanetIcon;
|
||||
|
||||
private Dictionary<Guid, Transform> _planets = new Dictionary<Guid, Transform>();
|
||||
private Zone _zone;
|
||||
private float _viewDistance;
|
||||
|
||||
public float ViewDistance
|
||||
{
|
||||
set
|
||||
{
|
||||
_viewDistance = value;
|
||||
foreach (var camera in FogCameras)
|
||||
camera.orthographicSize = value;
|
||||
SceneCamera.m_Lens.FarClipPlane = value * FarPlaneDistanceMultiplier;
|
||||
FogMaterial.SetFloat("_DepthCeiling", value - FogFarFadeFraction * value);
|
||||
FogMaterial.SetFloat("_DepthBlend", FogFarFadeFraction * value);
|
||||
}
|
||||
}
|
||||
|
||||
public float MinimapDistance
|
||||
{
|
||||
set
|
||||
{
|
||||
foreach(var camera in MinimapCameras)
|
||||
camera.orthographicSize = value * 2;
|
||||
}
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
LoadZone(Manager.CurrentZone);
|
||||
ViewDistance = Properties.DefaultViewDistance;
|
||||
MinimapDistance = Properties.DefaultMinimapDistance;
|
||||
Manager.ZoneChanged += (_, args) => LoadZone(args.NewZone);
|
||||
}
|
||||
|
||||
void LoadZone(Zone zone)
|
||||
{
|
||||
_zone = zone;
|
||||
SectorBrushes.localScale = zone.Data.Radius * 2 * Vector3.one;
|
||||
if (_planets.Count > 0)
|
||||
{
|
||||
foreach (var planet in _planets.Values)
|
||||
{
|
||||
Destroy(planet.gameObject);
|
||||
}
|
||||
_planets.Clear();
|
||||
}
|
||||
foreach(var p in zone.Planets.Values)
|
||||
LoadPlanet(p);
|
||||
}
|
||||
|
||||
void LoadPlanet(PlanetData planetData)
|
||||
{
|
||||
if (planetData is AsteroidBeltData beltData)
|
||||
{
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
PlanetObject planet;
|
||||
if (planetData is GasGiantData gasGiantData)
|
||||
{
|
||||
if (planetData is SunData sunData)
|
||||
{
|
||||
planet = Instantiate(Sun, SectorRoot);
|
||||
var sun = (SunObject) planet;
|
||||
sun.Light.color = sunData.LightColor;
|
||||
sun.Light.range = Properties.LightRadius.Evaluate(sunData.Mass);
|
||||
sun.FogTint.material.SetColor("_Color", sunData.FogTintColor);
|
||||
sun.FogTint.transform.localScale = Properties.FogTintRadius.Evaluate(sunData.Mass) * Vector3.one;
|
||||
}
|
||||
else planet = Instantiate(GasGiant, SectorRoot);
|
||||
|
||||
var gas = (GasGiantObject) planet;
|
||||
gas.GradientMapper.ApplyGradient(gasGiantData.Colors);
|
||||
gas.SunMaterial.AlbedoRotationSpeed = gasGiantData.AlbedoRotationSpeed;
|
||||
gas.SunMaterial.FirstOffsetRotationSpeed = gasGiantData.AlbedoRotationSpeed;
|
||||
gas.SunMaterial.SecondOffsetRotationSpeed = gasGiantData.AlbedoRotationSpeed;
|
||||
gas.SunMaterial.FirstOffsetDomainRotationSpeed = gasGiantData.AlbedoRotationSpeed;
|
||||
gas.SunMaterial.SecondOffsetDomainRotationSpeed = gasGiantData.AlbedoRotationSpeed;
|
||||
gas.GravityWaves.material.SetFloat("_Depth", Properties.WaveDepth.Evaluate(planetData.Mass));
|
||||
gas.GravityWaves.material.SetFloat("_Frequency", Properties.WaveFrequency.Evaluate(planetData.Mass));
|
||||
gas.WaveScroll.Speed = Properties.WaveSpeed.Evaluate(planetData.Mass);
|
||||
gas.GravityWaves.transform.localScale = Properties.WaveRadius.Evaluate(planetData.Mass) * Vector3.one;
|
||||
}
|
||||
else
|
||||
{
|
||||
planet = Instantiate(Planet, SectorRoot);
|
||||
planet.Icon.material.mainTexture = planetData.Mass > Manager.Context.GlobalData.PlanetMass ? PlanetIcon : PlanetoidIcon;
|
||||
}
|
||||
|
||||
var diameter = Properties.BodyDiameter.Evaluate(planetData.Mass);
|
||||
planet.Body.transform.localScale = diameter * Vector3.one;
|
||||
planet.GravityWell.transform.localScale = Properties.GravityRadius.Evaluate(planetData.Mass) * Vector3.one;
|
||||
planet.GravityWell.material.SetFloat("_Depth", Properties.GravityDepth.Evaluate(planetData.Mass));
|
||||
planet.GridSnap.Offset = diameter * 2;
|
||||
|
||||
_planets.Add(planetData.ID, planet.transform);
|
||||
}
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
foreach (var planet in _planets)
|
||||
{
|
||||
planet.Value.position = ((Vector2) _zone.GetOrbitPosition(_zone.Planets[planet.Key].Orbit)).Flatland();
|
||||
}
|
||||
|
||||
var pos = FogCameraParent.position;
|
||||
FogMaterial.SetVector("_GridTransform", new Vector4(pos.x,pos.z,_viewDistance*2));
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/Sector Display/SectorRenderer.cs.meta
Normal file
11
Assets/Scripts/Sector Display/SectorRenderer.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: bed3b49fe74863340b2a75f3d0517e86
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 300
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
45
Assets/Scripts/Sector Display/SnapToGrid.cs
Normal file
45
Assets/Scripts/Sector Display/SnapToGrid.cs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class SnapToGrid : MonoBehaviour
|
||||
{
|
||||
public bool SnapPosition = false;
|
||||
public bool SnapRotation = false;
|
||||
public bool ApplyForces = false;
|
||||
|
||||
// public float RotationDamping = .5f;
|
||||
// public float PositionDamping = .1f;
|
||||
public float ForceScale = 1;
|
||||
public float Offset = 0;
|
||||
public float NormalMultiplier = 100;
|
||||
public float GravityGradientStep = .01f;
|
||||
|
||||
private Rigidbody _body;
|
||||
|
||||
// Use this for initialization
|
||||
void Start () {
|
||||
_body = GetComponent<Rigidbody>();
|
||||
}
|
||||
|
||||
// Update is called once per frame
|
||||
void LateUpdate () {
|
||||
var pos = new Vector2(transform.position.x,transform.position.z);
|
||||
|
||||
if(SnapPosition)
|
||||
transform.position = new Vector3(pos.x, Gravity.GetHeight(pos) + Offset,pos.y);
|
||||
if (SnapRotation)
|
||||
{
|
||||
var normal = Gravity.GetNormal(pos, GravityGradientStep, NormalMultiplier);
|
||||
var forward = Vector3.Cross(transform.right, normal);
|
||||
transform.rotation = Quaternion.LookRotation(forward, normal);
|
||||
}
|
||||
|
||||
if (ApplyForces)
|
||||
{
|
||||
//var currentVelocity = _body.velocity;
|
||||
var force = Gravity.GetForce(pos) * ForceScale;
|
||||
_body.AddForce(force.x,0,force.y,ForceMode.Acceleration);
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/Sector Display/SnapToGrid.cs.meta
Normal file
11
Assets/Scripts/Sector Display/SnapToGrid.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: ac1be54714e52c640b08fe5059519a37
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
58
Assets/Scripts/Sector Display/SunMaterial.cs
Normal file
58
Assets/Scripts/Sector Display/SunMaterial.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
//[ExecuteInEditMode]
|
||||
public class SunMaterial : MonoBehaviour
|
||||
{
|
||||
public float SpeedMultiplier = 1;
|
||||
public float FirstOffsetDomainRotationSpeed = .01f;
|
||||
public float FirstOffsetRotationSpeed = .01f;
|
||||
public float SecondOffsetDomainRotationSpeed = .01f;
|
||||
public float SecondOffsetRotationSpeed = .01f;
|
||||
public float AlbedoRotationSpeed = .01f;
|
||||
public Vector3 LightingDirection;
|
||||
|
||||
private float _firstOffsetDomainRotation;
|
||||
private float _firstOffsetRotation;
|
||||
private float _secondOffsetDomainRotation;
|
||||
private float _secondOffsetRotation;
|
||||
private float _albedoRotation;
|
||||
|
||||
private Material _material;
|
||||
private Orbit _orbit;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
var mesh = GetComponent<MeshRenderer>();
|
||||
if (mesh == null)
|
||||
{
|
||||
enabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
_material = mesh.material;
|
||||
|
||||
_firstOffsetDomainRotation = Random.value * Mathf.PI;
|
||||
_firstOffsetRotation = Random.value * Mathf.PI;
|
||||
_secondOffsetDomainRotation = Random.value * Mathf.PI;
|
||||
_secondOffsetRotation = Random.value * Mathf.PI;
|
||||
_albedoRotation = Random.value * Mathf.PI;
|
||||
}
|
||||
|
||||
private void OnWillRenderObject()
|
||||
{
|
||||
_firstOffsetDomainRotation = FirstOffsetDomainRotationSpeed * SpeedMultiplier * Time.time;
|
||||
_firstOffsetRotation = FirstOffsetRotationSpeed * SpeedMultiplier * Time.time;
|
||||
_secondOffsetDomainRotation = SecondOffsetDomainRotationSpeed * SpeedMultiplier * Time.time;
|
||||
_secondOffsetRotation = SecondOffsetRotationSpeed * SpeedMultiplier * Time.time;
|
||||
_albedoRotation = AlbedoRotationSpeed * SpeedMultiplier * Time.time;
|
||||
|
||||
_material.SetVector("_LightingDirection", LightingDirection);
|
||||
_material.SetMatrix("_FirstOffsetDomainRotation", Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, Mathf.Rad2Deg * _firstOffsetDomainRotation, 0), Vector3.one));
|
||||
_material.SetMatrix("_FirstOffsetRotation", Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(Mathf.Rad2Deg * Mathf.Sin(_firstOffsetRotation), Mathf.Rad2Deg * Mathf.Cos(_firstOffsetRotation), 0), Vector3.one));
|
||||
_material.SetMatrix("_SecondOffsetDomainRotation", Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, Mathf.Rad2Deg * _secondOffsetDomainRotation, 0), Vector3.one));
|
||||
_material.SetMatrix("_SecondOffsetRotation", Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(Mathf.Rad2Deg * Mathf.Sin(_secondOffsetRotation), Mathf.Rad2Deg * Mathf.Cos(_secondOffsetRotation), 0), Vector3.one));
|
||||
_material.SetMatrix("_AlbedoRotation", Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, Mathf.Rad2Deg * _albedoRotation, 0), Vector3.one));
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/Sector Display/SunMaterial.cs.meta
Normal file
11
Assets/Scripts/Sector Display/SunMaterial.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 3c2eb8fe081f14940a7208cbdc3d97f9
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
9
Assets/Scripts/Sector Display/SunObject.cs
Normal file
9
Assets/Scripts/Sector Display/SunObject.cs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class SunObject : GasGiantObject
|
||||
{
|
||||
public MeshRenderer FogTint;
|
||||
public Light Light;
|
||||
}
|
||||
11
Assets/Scripts/Sector Display/SunObject.cs.meta
Normal file
11
Assets/Scripts/Sector Display/SunObject.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4eb3240728e3b024db554fa4f864dda7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
39
Assets/Scripts/Sector Display/VolumeSampling.cs
Normal file
39
Assets/Scripts/Sector Display/VolumeSampling.cs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Drives the volume render.
|
||||
/// </summary>
|
||||
//[ExecuteInEditMode]
|
||||
[RequireComponent( typeof( Camera ) ), ImageEffectAllowedInSceneView]
|
||||
public class VolumeSampling : MonoBehaviour
|
||||
{
|
||||
public Material _volMaterial;
|
||||
public Transform GridTransform;
|
||||
private Camera _camera;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_camera = GetComponent<Camera>();
|
||||
}
|
||||
|
||||
[ImageEffectOpaque]
|
||||
void OnRenderImage(RenderTexture source, RenderTexture destination)
|
||||
{
|
||||
// check for no shader / shader compile error
|
||||
if( _volMaterial == null )
|
||||
{
|
||||
Graphics.Blit(source, destination);
|
||||
return;
|
||||
}
|
||||
|
||||
// Shader needs this matrix to generate world space rays
|
||||
_volMaterial.SetMatrix("_CamProj", (_camera.projectionMatrix * _camera.worldToCameraMatrix).inverse);
|
||||
|
||||
// Shader needs to know the position and scale of cameras used to render input textures
|
||||
if(GridTransform != null)
|
||||
_volMaterial.SetVector("_GridTransform", new Vector4(GridTransform.position.x,GridTransform.position.z,GridTransform.localScale.x*4));
|
||||
|
||||
Graphics.Blit( source, destination, _volMaterial, 0 );
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/Sector Display/VolumeSampling.cs.meta
Normal file
11
Assets/Scripts/Sector Display/VolumeSampling.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8c03374f22d0a3d4882018de66894a84
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
20
Assets/Scripts/Sector Display/WaveScroll.cs
Normal file
20
Assets/Scripts/Sector Display/WaveScroll.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class WaveScroll : MonoBehaviour
|
||||
{
|
||||
public float Speed = 1;
|
||||
|
||||
private Material _material;
|
||||
private float _phase;
|
||||
|
||||
void Start ()
|
||||
{
|
||||
_material = GetComponent<MeshRenderer>().material;
|
||||
}
|
||||
|
||||
void Update () {
|
||||
_material.SetFloat("_Phase", _phase+=Time.deltaTime*Speed);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/Sector Display/WaveScroll.cs.meta
Normal file
11
Assets/Scripts/Sector Display/WaveScroll.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 59ee45f9f67763845b92c04c774eaaf9
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -56,7 +56,7 @@ public interface IController
|
|||
{
|
||||
bool Available { get; }
|
||||
TaskType TaskType { get; }
|
||||
Guid Zone { get; }
|
||||
Zone Zone { get; }
|
||||
void AssignTask(Guid task);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ public abstract class ControllerBase : IBehavior, IController, IInitializableBeh
|
|||
protected Guid HomeEntity => (_entity as Ship)?.HomeEntity ?? Guid.Empty;
|
||||
public bool Available => _spaceworthy && Task == Guid.Empty;
|
||||
public abstract TaskType TaskType { get; }
|
||||
public Guid Zone => _entity.Zone;
|
||||
public Zone Zone => _entity.Zone;
|
||||
public BehaviorData Data => _controllerData;
|
||||
|
||||
protected Locomotion Locomotion;
|
||||
|
|
@ -182,7 +182,7 @@ public abstract class ControllerBase : IBehavior, IController, IInitializableBeh
|
|||
_context.SetParent(_entity, homeEntity);
|
||||
onFinish?.Invoke();
|
||||
});
|
||||
else MoveTo(homeEntity.Zone, () => MoveTo(homeEntity, true, () =>
|
||||
else MoveTo(homeEntity.Zone.Data.ID, () => MoveTo(homeEntity, true, () =>
|
||||
{
|
||||
_context.SetParent(_entity, homeEntity);
|
||||
onFinish?.Invoke();
|
||||
|
|
@ -228,14 +228,14 @@ public abstract class ControllerBase : IBehavior, IController, IInitializableBeh
|
|||
|
||||
public void MoveTo(Guid zone, Action onFinish = null)
|
||||
{
|
||||
var path = _context.FindPath(_context.GalaxyZones[Zone], _context.GalaxyZones[zone]);
|
||||
var path = _context.FindPath(_context.GalaxyZones[Zone.Data.ID], _context.GalaxyZones[zone]);
|
||||
|
||||
void OnNextZone()
|
||||
{
|
||||
path.RemoveAt(0);
|
||||
if (path.Count > 0)
|
||||
{
|
||||
MoveTo(_context.WormholePosition(_entity.Zone, Path[0].ZoneID), false, OnNextZone);
|
||||
MoveTo(Zone.WormholePosition(Path[0].ZoneID), false, OnNextZone);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ public class HaulingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
void OnPickup()
|
||||
{
|
||||
var haulingTask = _context.Cache.Get<HaulingTask>(Task);
|
||||
var target = _context.ZoneEntities[_entity.Zone][haulingTask.Origin] as OrbitalEntity;
|
||||
var target = Zone.Entities[haulingTask.Origin] as OrbitalEntity;
|
||||
|
||||
_context.SetParent(_entity, target);
|
||||
var itemData = _context.Cache.Get<ItemData>(haulingTask.ItemType);
|
||||
|
|
@ -101,7 +101,7 @@ public class HaulingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
|
||||
var target = _context.Cache.Get<Entity>(haulingTask.Target);
|
||||
|
||||
MoveTo(target.Zone, OnTargetZoneArrival);
|
||||
MoveTo(target.Zone.Data.ID, OnTargetZoneArrival);
|
||||
}
|
||||
|
||||
void OnTargetZoneArrival()
|
||||
|
|
@ -114,7 +114,7 @@ public class HaulingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
void OnDelivery()
|
||||
{
|
||||
var haulingTask = _context.Cache.Get<HaulingTask>(Task);
|
||||
var target = _context.ZoneEntities[_entity.Zone][haulingTask.Target] as OrbitalEntity;
|
||||
var target = Zone.Entities[haulingTask.Target] as OrbitalEntity;
|
||||
|
||||
_context.SetParent(_entity, target);
|
||||
|
||||
|
|
|
|||
|
|
@ -61,22 +61,22 @@ public class MiningController : ControllerBase, IBehavior, IPersistentBehavior,
|
|||
{
|
||||
if (_entity.OccupiedCapacity < _entity.Capacity - 1)
|
||||
{
|
||||
var asteroidTransform = _context.GetAsteroidTransform(miningTask.Asteroids, _asteroid);
|
||||
var asteroidTransform = Zone.GetAsteroidTransform(miningTask.Asteroids, _asteroid);
|
||||
if (length(_entity.Position - asteroidTransform.xy) - asteroidTransform.w > _miningTool.Range)
|
||||
{
|
||||
_entity.SetMessage("Moving to target asteroid.");
|
||||
MoveTo(() => _context.GetAsteroidTransform(miningTask.Asteroids, _asteroid).xy,
|
||||
() => _context.GetAsteroidVelocity(miningTask.Asteroids, _asteroid));
|
||||
MoveTo(() => Zone.GetAsteroidTransform(miningTask.Asteroids, _asteroid).xy,
|
||||
() => Zone.GetAsteroidVelocity(miningTask.Asteroids, _asteroid));
|
||||
_toolSwitch.Activated = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_context.AsteroidExists(miningTask.Asteroids, _asteroid))
|
||||
if (Zone.AsteroidExists(miningTask.Asteroids, _asteroid))
|
||||
{
|
||||
_miningTool.AsteroidBelt = miningTask.Asteroids;
|
||||
_miningTool.Asteroid = _asteroid;
|
||||
_toolSwitch.Activated = true;
|
||||
Aim.Objective = _context.GetAsteroidTransform(miningTask.Asteroids, _asteroid).xy;
|
||||
Aim.Objective = Zone.GetAsteroidTransform(miningTask.Asteroids, _asteroid).xy;
|
||||
Aim.Update(delta);
|
||||
}
|
||||
else NextAsteroid();
|
||||
|
|
@ -119,7 +119,7 @@ public class MiningController : ControllerBase, IBehavior, IPersistentBehavior,
|
|||
private void NextAsteroid()
|
||||
{
|
||||
var miningTask = _context.Cache.Get<Mining>(Task);
|
||||
_asteroid = _context.NearestAsteroid(miningTask.Asteroids, _entity.Position);
|
||||
_asteroid = Zone.NearestAsteroid(miningTask.Asteroids, _entity.Position);
|
||||
_entity.SetMessage("Selecting new asteroid.");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -51,12 +51,12 @@ public class MiningTool : IBehavior
|
|||
public bool Update(float delta)
|
||||
{
|
||||
Range = Context.Evaluate(_data.Range, Item, Entity);
|
||||
var asteroidTransform = Context.GetAsteroidTransform(AsteroidBelt, Asteroid);
|
||||
var asteroidTransform = Entity.Zone.GetAsteroidTransform(AsteroidBelt, Asteroid);
|
||||
if (AsteroidBelt != Guid.Empty &&
|
||||
Context.AsteroidExists(AsteroidBelt, Asteroid) &&
|
||||
Entity.Zone.AsteroidExists(AsteroidBelt, Asteroid) &&
|
||||
length(Entity.Position - asteroidTransform.xy) - asteroidTransform.w < Range)
|
||||
{
|
||||
Context.MineAsteroid(
|
||||
Entity.Zone.MineAsteroid(
|
||||
Entity,
|
||||
AsteroidBelt,
|
||||
Asteroid,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
|
|
@ -19,7 +20,7 @@ public class PatrolController : IBehavior, IController, IInitializableBehavior
|
|||
{
|
||||
public TaskType TaskType => TaskType.None;
|
||||
public bool Available => false;
|
||||
public Guid Zone => _entity.Zone;
|
||||
public Zone Zone => _entity.Zone;
|
||||
public BehaviorData Data => _data;
|
||||
|
||||
private PatrolControllerData _data;
|
||||
|
|
@ -45,7 +46,7 @@ public class PatrolController : IBehavior, IController, IInitializableBehavior
|
|||
|
||||
public bool Update(float delta)
|
||||
{
|
||||
_locomotion.Objective = _context.GetOrbitPosition(_targetOrbit);
|
||||
_locomotion.Objective = Zone.GetOrbitPosition(_targetOrbit);
|
||||
_locomotion.Update(delta);
|
||||
|
||||
if(length(_entity.Position - _locomotion.Objective) < _data.TargetDistance)
|
||||
|
|
@ -61,7 +62,6 @@ public class PatrolController : IBehavior, IController, IInitializableBehavior
|
|||
|
||||
private void RandomTarget()
|
||||
{
|
||||
var entities = _context.ZonePlanets[_entity.Zone];
|
||||
_targetOrbit = _context.Cache.Get<PlanetData>(entities[_context.Random.NextInt(entities.Length)]).Orbit;
|
||||
_targetOrbit = Zone.Planets.Keys.ToArray()[_context.Random.NextInt(Zone.Planets.Count)];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,11 +66,11 @@ public class ResourceScanner : IBehavior, IAlwaysUpdatedBehavior
|
|||
var planetData = Context.Cache.Get<PlanetData>(ScanTarget);
|
||||
if (planetData != null)
|
||||
{
|
||||
if (planetData.Belt)
|
||||
if (planetData is AsteroidBeltData beltData)
|
||||
{
|
||||
if(Asteroid > -1 &&
|
||||
Asteroid < planetData.Asteroids.Length &&
|
||||
length(Entity.Position - Context.GetAsteroidTransform(ScanTarget, Asteroid).xy) < Range)
|
||||
Asteroid < beltData.Asteroids.Length &&
|
||||
length(Entity.Position - Entity.Zone.GetAsteroidTransform(ScanTarget, Asteroid).xy) < Range)
|
||||
{
|
||||
_scanTime += delta;
|
||||
if (_scanTime > ScanDuration)
|
||||
|
|
@ -83,7 +83,7 @@ public class ResourceScanner : IBehavior, IAlwaysUpdatedBehavior
|
|||
}
|
||||
else
|
||||
{
|
||||
if(length(Entity.Position - Context.GetOrbitPosition(planetData.Orbit)) < Range)
|
||||
if(length(Entity.Position - Entity.Zone.GetOrbitPosition(planetData.Orbit)) < Range)
|
||||
{
|
||||
_scanTime += delta;
|
||||
if (_scanTime > ScanDuration)
|
||||
|
|
|
|||
|
|
@ -35,6 +35,11 @@ public class StatModifier : IBehavior, IInitializableBehavior, IDisposableBehavi
|
|||
public BehaviorData Data => _data;
|
||||
|
||||
private PerformanceStat[] _stats;
|
||||
|
||||
private static Type[] _statObjects;
|
||||
|
||||
private static Type[] StatObjects => _statObjects ?? (_statObjects = typeof(BehaviorData).GetAllChildClasses()
|
||||
.Concat(typeof(EquippableItemData).GetAllChildClasses()).ToArray());
|
||||
|
||||
public StatModifier(GameContext context, StatModifierData data, Entity entity, Gear item)
|
||||
{
|
||||
|
|
@ -46,7 +51,7 @@ public class StatModifier : IBehavior, IInitializableBehavior, IDisposableBehavi
|
|||
|
||||
public void Initialize()
|
||||
{
|
||||
var targetType = Context.StatObjects.FirstOrDefault(so => so.Name == _data.Stat.Target);
|
||||
var targetType = StatObjects.FirstOrDefault(so => so.Name == _data.Stat.Target);
|
||||
if (targetType != null)
|
||||
{
|
||||
var statField = targetType.GetFields()
|
||||
|
|
|
|||
|
|
@ -111,30 +111,30 @@ public class SurveyController : ControllerBase, IBehavior, IPersistentBehavior,
|
|||
private void NextPlanet()
|
||||
{
|
||||
var surveyTask = _context.Cache.Get<Survey>(Task);
|
||||
var planets = surveyTask.Planets.Select(id => _context.Cache.Get<PlanetData>(id));
|
||||
var planets = surveyTask.Planets.Select(id => Zone.Planets[id]);
|
||||
var nearestPlanet = planets.MinBy(p => lengthsq(_entity.Position - GetPosition(p)));
|
||||
_asteroid = nearestPlanet.Belt ? _context.NearestAsteroid(nearestPlanet.ID, _entity.Position) : -1;
|
||||
_asteroid = nearestPlanet is AsteroidBeltData ? Zone.NearestAsteroid(nearestPlanet.ID, _entity.Position) : -1;
|
||||
_targetPlanet = nearestPlanet.ID;
|
||||
}
|
||||
|
||||
private float2 GetPosition(PlanetData planet, int asteroid = -1)
|
||||
{
|
||||
if (planet.Belt)
|
||||
if (planet is AsteroidBeltData)
|
||||
{
|
||||
if(asteroid == -1) asteroid = _context.NearestAsteroid(planet.ID, _entity.Position);
|
||||
return _context.GetAsteroidTransform(planet.ID, asteroid).xy;
|
||||
if(asteroid == -1) asteroid = Zone.NearestAsteroid(planet.ID, _entity.Position);
|
||||
return Zone.GetAsteroidTransform(planet.ID, asteroid).xy;
|
||||
}
|
||||
return _context.GetOrbitPosition(planet.Orbit);
|
||||
return Zone.GetOrbitPosition(planet.Orbit);
|
||||
}
|
||||
|
||||
private float2 GetVelocity(PlanetData planet, int asteroid = -1)
|
||||
{
|
||||
if (planet.Belt)
|
||||
if (planet is AsteroidBeltData)
|
||||
{
|
||||
if(asteroid == -1) asteroid = _context.NearestAsteroid(planet.ID, _entity.Position);
|
||||
return _context.GetAsteroidVelocity(planet.ID, asteroid);
|
||||
if(asteroid == -1) asteroid = Zone.NearestAsteroid(planet.ID, _entity.Position);
|
||||
return Zone.GetAsteroidVelocity(planet.ID, asteroid);
|
||||
}
|
||||
return _context.GetOrbitVelocity(planet.Orbit);
|
||||
return Zone.GetOrbitVelocity(planet.Orbit);
|
||||
}
|
||||
|
||||
public PersistentBehaviorData Store()
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ public class TowingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
void OnPickup()
|
||||
{
|
||||
var towingTask = _context.Cache.Get<StationTowing>(Task);
|
||||
var target = _context.ZoneEntities[_entity.Zone][towingTask.Station] as OrbitalEntity;
|
||||
var target = Zone.Entities[towingTask.Station] as OrbitalEntity;
|
||||
|
||||
_context.SetParent(target, _entity);
|
||||
|
||||
|
|
@ -69,22 +69,22 @@ public class TowingController : ControllerBase, IBehavior, IPersistentBehavior
|
|||
|
||||
MoveTo(() =>
|
||||
{
|
||||
var orbitParent = _context.GetOrbitPosition(towingTask.OrbitParent);
|
||||
var orbitParent = Zone.GetOrbitPosition(towingTask.OrbitParent);
|
||||
var parentToUs = _entity.Position - orbitParent;
|
||||
return orbitParent + normalize(parentToUs) * towingTask.OrbitDistance;
|
||||
}, () => _context.GetOrbitVelocity(towingTask.OrbitParent), OnDelivery);
|
||||
}, () => Zone.GetOrbitVelocity(towingTask.OrbitParent), OnDelivery);
|
||||
}
|
||||
|
||||
void OnDelivery()
|
||||
{
|
||||
var towingTask = _context.Cache.Get<StationTowing>(Task);
|
||||
var target = _context.ZoneEntities[_entity.Zone][towingTask.Station] as OrbitalEntity;
|
||||
var target = Zone.Entities[towingTask.Station] as OrbitalEntity;
|
||||
|
||||
_context.RemoveParent(target);
|
||||
|
||||
_entity.SetMessage("Target delivered. Returning Home.");
|
||||
|
||||
var orbit = _context.CreateOrbit(towingTask.Zone, towingTask.OrbitParent, _entity.Position);
|
||||
var orbit = Zone.CreateOrbit(towingTask.OrbitParent, _entity.Position);
|
||||
target.OrbitData = orbit.ID;
|
||||
|
||||
FinishTask();
|
||||
|
|
|
|||
|
|
@ -57,13 +57,13 @@ public class WanderController : ControllerBase, IBehavior
|
|||
{
|
||||
if (WanderTarget == WanderTarget.Planets)
|
||||
{
|
||||
var planets = _context.ZonePlanets[_entity.Zone];
|
||||
var randomPlanet = _context.Cache.Get<PlanetData>(planets[_context.Random.NextInt(planets.Length)]);
|
||||
MoveTo(() => _context.GetOrbitPosition(randomPlanet.Orbit), () => _context.GetOrbitVelocity(randomPlanet.Orbit));
|
||||
var planets = Zone.Planets.Values.ToArray();
|
||||
var randomPlanet = planets[_context.Random.NextInt(planets.Length)];
|
||||
MoveTo(() => Zone.GetOrbitPosition(randomPlanet.Orbit), () => Zone.GetOrbitVelocity(randomPlanet.Orbit));
|
||||
}
|
||||
else if (WanderTarget == WanderTarget.Orbitals)
|
||||
{
|
||||
var entities = _context.ZoneEntities[_entity.Zone].Values.ToArray();
|
||||
var entities = Zone.Entities.Values.ToArray();
|
||||
var randomEntity = entities[_context.Random.NextInt(entities.Length)];
|
||||
MoveTo(randomEntity, true, () =>
|
||||
{
|
||||
|
|
|
|||
|
|
@ -42,6 +42,9 @@ public interface INamedEntry
|
|||
Union(22, typeof(StationTowing)),
|
||||
Union(23, typeof(Survey)),
|
||||
Union(24, typeof(HaulingTask)),
|
||||
Union(25, typeof(AsteroidBeltData)),
|
||||
Union(26, typeof(GasGiantData)),
|
||||
Union(27, typeof(SunData)),
|
||||
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
|
||||
//[Union(21, typeof(ContractData))]
|
||||
//[Union(22, typeof(Station))]
|
||||
|
|
|
|||
|
|
@ -89,7 +89,7 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
|
|||
}
|
||||
//public List<IncompleteItem> IncompleteCargo = new List<IncompleteItem>();
|
||||
|
||||
[IgnoreMember] public Guid Zone;
|
||||
[IgnoreMember] public Zone Zone;
|
||||
[IgnoreMember] public List<Hardpoint> Hardpoints;
|
||||
[IgnoreMember] public readonly Dictionary<object, float> VisibilitySources = new Dictionary<object, float>();
|
||||
[IgnoreMember] public readonly Dictionary<string, float> Messages = new Dictionary<string, float>();
|
||||
|
|
@ -138,7 +138,7 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
|
|||
}
|
||||
|
||||
|
||||
public Entity(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid zone, Guid corporation)
|
||||
public Entity(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Zone zone, Guid corporation)
|
||||
{
|
||||
Context = context;
|
||||
Zone = zone;
|
||||
|
|
|
|||
22
Assets/Scripts/ServerShared/ExponentialCurve.cs
Normal file
22
Assets/Scripts/ServerShared/ExponentialCurve.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
[Serializable, MessagePackObject, JsonObject]
|
||||
public class ExponentialCurve
|
||||
{
|
||||
[JsonProperty("exponent"), Key(0)]
|
||||
public float Exponent;
|
||||
|
||||
[JsonProperty("multiplier"), Key(1)]
|
||||
public float Multiplier;
|
||||
|
||||
[JsonProperty("constant"), Key(2)]
|
||||
public float Constant;
|
||||
|
||||
public float Evaluate(float value) => Multiplier * pow(value, Exponent) + Constant;
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/ExponentialCurve.cs.meta
Normal file
11
Assets/Scripts/ServerShared/ExponentialCurve.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8e3680eb7ef815d4d8babd7bd3ae2276
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -12,9 +12,8 @@ using float4 = Unity.Mathematics.float4;
|
|||
public class GameContext
|
||||
{
|
||||
public Random Random = new Random((uint) (DateTime.Now.Ticks%uint.MaxValue));
|
||||
public Dictionary<Guid, Guid[]> ZonePlanets = new Dictionary<Guid, Guid[]>();
|
||||
public Dictionary<Guid, Dictionary<Guid, Entity>> ZoneEntities = new Dictionary<Guid, Dictionary<Guid, Entity>>();
|
||||
public Dictionary<string, GalaxyMapLayerData> MapLayers = new Dictionary<string, GalaxyMapLayerData>();
|
||||
public SimpleCommodityData[] Resources;
|
||||
public Dictionary<Guid, List<IController>> CorporationControllers = new Dictionary<Guid, List<IController>>();
|
||||
public Dictionary<Guid, SimplifiedZoneData> GalaxyZones;
|
||||
|
||||
|
|
@ -26,37 +25,24 @@ public class GameContext
|
|||
private double _time;
|
||||
private float _deltaTime;
|
||||
private GlobalData _globalData;
|
||||
private HashSet<Guid> _loadedZones = new HashSet<Guid>();
|
||||
private HashSet<Guid> _orbits = new HashSet<Guid>();
|
||||
private Dictionary<Guid, float2> _orbitVelocities = new Dictionary<Guid, float2>();
|
||||
private Dictionary<Guid, float2> _orbitPositions = new Dictionary<Guid, float2>();
|
||||
private Dictionary<Guid, float2> _previousOrbitPositions = new Dictionary<Guid, float2>();
|
||||
private Dictionary<Guid, float4[]> _asteroidTransforms = new Dictionary<Guid, float4[]>(); // x, y, rotation, scale
|
||||
private Dictionary<Guid, float4[]> _previousAsteroidTransforms = new Dictionary<Guid, float4[]>(); // x, y, rotation, scale
|
||||
private Dictionary<(Guid, int), float> _asteroidRespawnTimers = new Dictionary<(Guid, int), float>();
|
||||
private Dictionary<(Guid, int), float> _asteroidDamage = new Dictionary<(Guid, int), float>();
|
||||
private Dictionary<(Guid, Guid, int), float> _asteroidMiningAccumulator = new Dictionary<(Guid, Guid, int), float>();
|
||||
private Guid _forceLoadZone;
|
||||
private Type[] _statObjects;
|
||||
private Dictionary<Guid, Zone> _zones = new Dictionary<Guid, Zone>();
|
||||
// private Guid _forceLoadZone;
|
||||
|
||||
public GlobalData GlobalData => _globalData ?? (_globalData = Cache.GetAll<GlobalData>().FirstOrDefault());
|
||||
public DatabaseCache Cache { get; }
|
||||
|
||||
public Type[] StatObjects => _statObjects ?? (_statObjects = typeof(BehaviorData).GetAllChildClasses()
|
||||
.Concat(typeof(EquippableItemData).GetAllChildClasses()).ToArray());
|
||||
|
||||
public Guid ForceLoadZone
|
||||
{
|
||||
get => _forceLoadZone;
|
||||
set
|
||||
{
|
||||
if(_forceLoadZone != Guid.Empty && ZoneEntities[_forceLoadZone].Count == 0)
|
||||
UnloadZone(_forceLoadZone);
|
||||
_forceLoadZone = value;
|
||||
if(!_loadedZones.Contains(_forceLoadZone))
|
||||
LoadZone(_forceLoadZone);
|
||||
}
|
||||
}
|
||||
// public Guid ForceLoadZone
|
||||
// {
|
||||
// get => _forceLoadZone;
|
||||
// set
|
||||
// {
|
||||
// if(_forceLoadZone != Guid.Empty && ZoneEntities[_forceLoadZone].Count == 0)
|
||||
// UnloadZone(_forceLoadZone);
|
||||
// _forceLoadZone = value;
|
||||
// if(!_loadedZones.Contains(_forceLoadZone))
|
||||
// LoadZone(_forceLoadZone);
|
||||
// }
|
||||
// }
|
||||
|
||||
public double Time
|
||||
{
|
||||
|
|
@ -69,18 +55,13 @@ public class GameContext
|
|||
}
|
||||
}
|
||||
|
||||
public float2 WormholePosition(Guid zone, Guid other)
|
||||
{
|
||||
var zoneData = Cache.Get<ZoneData>(zone);
|
||||
var direction = Cache.Get<ZoneData>(other).Position - zoneData.Position;
|
||||
return normalize(direction) * zoneData.Radius * .95f;
|
||||
}
|
||||
|
||||
// private readonly Dictionary<CraftedItemData, int> Tier = new Dictionary<CraftedItemData, int>();
|
||||
|
||||
public GameContext(DatabaseCache cache, Action<string> logger)
|
||||
{
|
||||
Cache = cache;
|
||||
MapLayers = cache.GetAll<GalaxyMapLayerData>().ToDictionary(ml => ml.Name);
|
||||
Resources = cache.GetAll<SimpleCommodityData>().Where(i => i.ResourceDensity.Any()).ToArray();
|
||||
_logger = logger;
|
||||
// var globalData = Cache.GetAll<GlobalData>().FirstOrDefault();
|
||||
// if (globalData == null)
|
||||
|
|
@ -97,20 +78,9 @@ public class GameContext
|
|||
|
||||
public void Update()
|
||||
{
|
||||
_previousOrbitPositions = _orbitPositions;
|
||||
_orbitPositions = new Dictionary<Guid, float2>(_orbits.Count);
|
||||
foreach(var zone in _zones.Values)
|
||||
zone.Update(_deltaTime);
|
||||
|
||||
foreach(var orbit in _orbits)
|
||||
{
|
||||
_orbitPositions[orbit] = GetOrbitPosition(orbit);
|
||||
_orbitVelocities[orbit] = _previousOrbitPositions.ContainsKey(orbit)
|
||||
? (_orbitPositions[orbit] - _previousOrbitPositions[orbit]) / _deltaTime
|
||||
: float2.zero;
|
||||
}
|
||||
|
||||
foreach (var asteroids in _asteroidTransforms.Keys)
|
||||
UpdateAsteroidTransforms(asteroids);
|
||||
|
||||
foreach (var corporation in Cache.GetAll<Corporation>())
|
||||
{
|
||||
foreach (var tasks in corporation.Tasks
|
||||
|
|
@ -127,10 +97,10 @@ public class GameContext
|
|||
{
|
||||
// Find the nearest controller for this task
|
||||
IController nearestController = availableControllers[0];
|
||||
List<SimplifiedZoneData> nearestControllerPath = FindPath(GalaxyZones[availableControllers.First().Zone], GalaxyZones[task.Zone], true);
|
||||
List<SimplifiedZoneData> nearestControllerPath = FindPath(GalaxyZones[availableControllers.First().Zone.Data.ID], GalaxyZones[task.Zone], true);
|
||||
foreach (var controller in availableControllers.Skip(1))
|
||||
{
|
||||
var path = FindPath(GalaxyZones[controller.Zone], GalaxyZones[task.Zone], true);
|
||||
var path = FindPath(GalaxyZones[controller.Zone.Data.ID], GalaxyZones[task.Zone], true);
|
||||
if (path.Count < nearestControllerPath.Count)
|
||||
{
|
||||
nearestControllerPath = path;
|
||||
|
|
@ -143,208 +113,53 @@ public class GameContext
|
|||
}
|
||||
}
|
||||
|
||||
foreach (var kvp in ZoneEntities)
|
||||
{
|
||||
foreach (var entity in kvp.Value.Values) entity.Update(_deltaTime);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<Entity> GetEntities(Guid zone)
|
||||
public Zone GetZone(Guid zone)
|
||||
{
|
||||
return ZoneEntities[zone].Values;
|
||||
if (_zones.ContainsKey(zone)) return _zones[zone];
|
||||
|
||||
// var zoneData = Cache.Get<ZoneData>(zone);
|
||||
// if (zoneData == null) throw new ArgumentException("Zone parameter is not a valid zone ID!", nameof(zone));
|
||||
//
|
||||
// return GetZone(zoneData);
|
||||
return null;
|
||||
}
|
||||
|
||||
public void LoadZone(Guid zone)
|
||||
public Zone GetZone(ZonePack zonePack)
|
||||
{
|
||||
var zoneData = Cache.Get<ZoneData>(zone);
|
||||
|
||||
_loadedZones.Add(zone);
|
||||
|
||||
foreach (var orbit in zoneData.Orbits) _orbits.Add(orbit);
|
||||
|
||||
// TODO: Associate planets with stored entities for planetary colonies
|
||||
ZonePlanets[zone] = zoneData.Planets;
|
||||
|
||||
foreach (var belt in zoneData.Planets
|
||||
.Select(id => Cache.Get<PlanetData>(id))
|
||||
.Where(p => p.Belt))
|
||||
{
|
||||
_asteroidTransforms[belt.ID] = new float4[belt.Asteroids.Length];
|
||||
_previousAsteroidTransforms[belt.ID] = new float4[belt.Asteroids.Length];
|
||||
}
|
||||
|
||||
// TODO: Load stored entities
|
||||
ZoneEntities[zone] = new Dictionary<Guid, Entity>();
|
||||
var z = new Zone(this, zonePack);
|
||||
_zones.Add(zonePack.Data.ID, z);
|
||||
return z;
|
||||
}
|
||||
|
||||
public void UnloadZone(Guid zone)
|
||||
{
|
||||
var zoneData = Cache.Get<ZoneData>(zone);
|
||||
|
||||
_loadedZones.Remove(zone);
|
||||
ZoneEntities.Remove(zone);
|
||||
ZonePlanets.Remove(zone);
|
||||
foreach (var orbit in zoneData.Orbits) _orbits.Remove(orbit);
|
||||
foreach (var belt in zoneData.Planets
|
||||
.Select(id => Cache.Get<PlanetData>(id))
|
||||
.Where(p => p.Belt))
|
||||
{
|
||||
_asteroidTransforms.Remove(belt.ID);
|
||||
_previousAsteroidTransforms.Remove(belt.ID);
|
||||
}
|
||||
_zones.Remove(zone);
|
||||
}
|
||||
|
||||
public void Warp(Entity entity, Guid targetZone)
|
||||
{
|
||||
if (length(entity.Position - WormholePosition(entity.Zone, targetZone)) < GlobalData.WarpDistance)
|
||||
{
|
||||
var sourceZone = entity.Zone;
|
||||
|
||||
// Remove entity from source zone
|
||||
ZoneEntities[sourceZone].Remove(entity.ID);
|
||||
|
||||
// Unload source zone if empty and unobserved
|
||||
if(ForceLoadZone != sourceZone && ZoneEntities[sourceZone].Count == 0)
|
||||
UnloadZone(sourceZone);
|
||||
|
||||
// Load target zone if not yet loaded
|
||||
if(!_loadedZones.Contains(targetZone))
|
||||
LoadZone(targetZone);
|
||||
|
||||
entity.Zone = targetZone;
|
||||
entity.Position = WormholePosition(targetZone, sourceZone);
|
||||
ZoneEntities[targetZone][entity.ID] = entity;
|
||||
}
|
||||
}
|
||||
|
||||
// Determine orbital position recursively, caching parent positions to avoid repeated calculations
|
||||
public float2 GetOrbitPosition(Guid orbit)
|
||||
{
|
||||
// Root orbit is fixed at center
|
||||
if(orbit==Guid.Empty)
|
||||
return float2.zero;
|
||||
|
||||
if (!_orbitPositions.ContainsKey(orbit))
|
||||
{
|
||||
var orbitData = Cache.Get<OrbitData>(orbit);
|
||||
float2 pos = float2.zero;
|
||||
if (orbitData.Period > .01f)
|
||||
{
|
||||
var phase = (float) frac(Time / orbitData.Period * GlobalData.OrbitSpeedMultiplier);
|
||||
pos = OrbitData.Evaluate(frac(phase + orbitData.Phase)) * orbitData.Distance;
|
||||
}
|
||||
|
||||
_orbitPositions[orbit] = GetOrbitPosition(orbitData.Parent) + pos;
|
||||
}
|
||||
|
||||
var position = _orbitPositions[orbit];
|
||||
if (float.IsNaN(position.x))
|
||||
{
|
||||
Log("Orbit position is NaN, something went very wrong!");
|
||||
return float2.zero;
|
||||
}
|
||||
return _orbitPositions[orbit];
|
||||
}
|
||||
|
||||
public float2 GetOrbitVelocity(Guid orbit)
|
||||
{
|
||||
return _orbitVelocities.ContainsKey(orbit) ? _orbitVelocities[orbit] : float2.zero;
|
||||
}
|
||||
|
||||
public int NearestAsteroid(Guid planetDataID, float2 position)
|
||||
{
|
||||
var planetData = Cache.Get<PlanetData>(planetDataID);
|
||||
|
||||
var asteroidPositions = GetAsteroidTransforms(planetDataID);
|
||||
|
||||
int nearest = 0;
|
||||
float nearestDistance = Single.MaxValue;
|
||||
for (int i = 0; i < planetData.Asteroids.Length; i++)
|
||||
{
|
||||
var dist = lengthsq(asteroidPositions[i].xy - position);
|
||||
if (AsteroidExists(planetDataID, i) && dist < nearestDistance)
|
||||
{
|
||||
nearest = i;
|
||||
nearestDistance = dist;
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
|
||||
public bool AsteroidExists(Guid planetDataID, int asteroid) =>
|
||||
!_asteroidRespawnTimers.ContainsKey((planetDataID, asteroid));
|
||||
|
||||
public float2 GetAsteroidVelocity(Guid planetDataID, int asteroid)
|
||||
{
|
||||
return (_asteroidTransforms[planetDataID][asteroid].xy - _previousAsteroidTransforms[planetDataID][asteroid].xy) / _deltaTime;
|
||||
}
|
||||
|
||||
public float4 GetAsteroidTransform(Guid planetDataID, int asteroid)
|
||||
{
|
||||
return _asteroidTransforms[planetDataID][asteroid];
|
||||
}
|
||||
|
||||
public float4[] GetAsteroidTransforms(Guid planetDataID)
|
||||
{
|
||||
return _asteroidTransforms[planetDataID];
|
||||
}
|
||||
|
||||
private void UpdateAsteroidTransforms(Guid planetDataID)
|
||||
{
|
||||
var planetData = Cache.Get<PlanetData>(planetDataID);
|
||||
|
||||
Array.Copy(_asteroidTransforms[planetDataID], _previousAsteroidTransforms[planetDataID], planetData.Asteroids.Length);
|
||||
|
||||
var orbitData = Cache.Get<OrbitData>(planetData.Orbit);
|
||||
var orbitPosition = GetOrbitPosition(orbitData.Parent);
|
||||
for (var i = 0; i < planetData.Asteroids.Length; i++)
|
||||
{
|
||||
var size = planetData.Asteroids[i].Size;
|
||||
if(_asteroidRespawnTimers.ContainsKey((planetDataID, i))) size = 0;
|
||||
else if (_asteroidDamage.ContainsKey((planetDataID, i)))
|
||||
{
|
||||
var hpLerp = unlerp(GlobalData.AsteroidSizeMin, GlobalData.AsteroidSizeMax, size);
|
||||
var asteroidHitpoints = lerp(GlobalData.AsteroidHitpointsMin, GlobalData.AsteroidHitpointsMax, pow(hpLerp, GlobalData.AsteroidHitpointsPower));
|
||||
var sizeLerp = (asteroidHitpoints - _asteroidDamage[(planetDataID, i)]) / asteroidHitpoints;
|
||||
size = lerp(GlobalData.AsteroidSizeMin, size, sizeLerp);
|
||||
}
|
||||
|
||||
_asteroidTransforms[planetDataID][i] = float4(
|
||||
OrbitData.Evaluate((float) frac(Time / OrbitalPeriod(planetData.Asteroids[i].Distance) * GlobalData.OrbitSpeedMultiplier +
|
||||
planetData.Asteroids[i].Phase)) * planetData.Asteroids[i].Distance + orbitPosition,
|
||||
(float) (Time * planetData.Asteroids[i].RotationSpeed % 360.0), size);
|
||||
}
|
||||
}
|
||||
|
||||
public OrbitData CreateOrbit(Guid zone, Guid parent, float2 position)
|
||||
{
|
||||
var parentPosition = GetOrbitPosition(parent);
|
||||
var delta = position - parentPosition;
|
||||
var distance = length(delta);
|
||||
var period = OrbitalPeriod(distance);
|
||||
var phase = atan2(delta.y, delta.x) / (PI * 2);
|
||||
var currentPhase = frac(Time / period * GlobalData.OrbitSpeedMultiplier);
|
||||
var storedPhase = (float) frac(phase - currentPhase);
|
||||
|
||||
var orbit = new OrbitData
|
||||
{
|
||||
Context = this,
|
||||
Distance = distance,
|
||||
Parent = parent,
|
||||
Period = period,
|
||||
Phase = storedPhase,
|
||||
Zone = zone
|
||||
};
|
||||
Cache.Add(orbit);
|
||||
_orbits.Add(orbit.ID);
|
||||
return orbit;
|
||||
}
|
||||
|
||||
public float OrbitalPeriod(float distance)
|
||||
{
|
||||
return pow(distance, GlobalData.OrbitPeriodExponent) * GlobalData.OrbitPeriodMultiplier;
|
||||
}
|
||||
// public void Warp(Entity entity, Guid targetZone)
|
||||
// {
|
||||
// if (length(entity.Position - WormholePosition(entity.Zone, targetZone)) < GlobalData.WarpDistance)
|
||||
// {
|
||||
// var sourceZone = entity.Zone;
|
||||
//
|
||||
// // Remove entity from source zone
|
||||
// ZoneEntities[sourceZone].Remove(entity.ID);
|
||||
//
|
||||
// // Unload source zone if empty and unobserved
|
||||
// if(ForceLoadZone != sourceZone && ZoneEntities[sourceZone].Count == 0)
|
||||
// UnloadZone(sourceZone);
|
||||
//
|
||||
// // Load target zone if not yet loaded
|
||||
// if(!_loadedZones.Contains(targetZone))
|
||||
// LoadZone(targetZone);
|
||||
//
|
||||
// entity.Zone = targetZone;
|
||||
// entity.Position = WormholePosition(targetZone, sourceZone);
|
||||
// ZoneEntities[targetZone][entity.ID] = entity;
|
||||
// }
|
||||
// }
|
||||
|
||||
public void PlaceMegas()
|
||||
{
|
||||
|
|
@ -368,28 +183,28 @@ public class GameContext
|
|||
mega.HomeZone = zone.ID;
|
||||
}
|
||||
break;
|
||||
case MegaPlacementType.Planets:
|
||||
foreach (var mega in megaPlacement)
|
||||
{
|
||||
var zone = availableZones
|
||||
.MaxBy(z => z.Planets.Length);
|
||||
availableZones.Remove(zone);
|
||||
mega.HomeZone = zone.ID;
|
||||
}
|
||||
break;
|
||||
case MegaPlacementType.Resources:
|
||||
foreach (var mega in megaPlacement)
|
||||
{
|
||||
var zone = availableZones
|
||||
.MaxBy(z => z.Planets
|
||||
.SelectMany(id=>Cache.Get<PlanetData>(id).Resources
|
||||
.Select(r=>r.Key))
|
||||
.Distinct()
|
||||
.Count());
|
||||
availableZones.Remove(zone);
|
||||
mega.HomeZone = zone.ID;
|
||||
}
|
||||
break;
|
||||
// case MegaPlacementType.Planets:
|
||||
// foreach (var mega in megaPlacement)
|
||||
// {
|
||||
// var zone = availableZones
|
||||
// .MaxBy(z => z.Planets.Length);
|
||||
// availableZones.Remove(zone);
|
||||
// mega.HomeZone = zone.ID;
|
||||
// }
|
||||
// break;
|
||||
// case MegaPlacementType.Resources:
|
||||
// foreach (var mega in megaPlacement)
|
||||
// {
|
||||
// var zone = availableZones
|
||||
// .MaxBy(z => z.Planets
|
||||
// .SelectMany(id=>Cache.Get<PlanetData>(id).Resources
|
||||
// .Select(r=>r.Key))
|
||||
// .Distinct()
|
||||
// .Count());
|
||||
// availableZones.Remove(zone);
|
||||
// mega.HomeZone = zone.ID;
|
||||
// }
|
||||
// break;
|
||||
case MegaPlacementType.Connected:
|
||||
foreach (var mega in megaPlacement)
|
||||
{
|
||||
|
|
@ -623,7 +438,7 @@ public class GameContext
|
|||
return result;
|
||||
}
|
||||
|
||||
public Entity CreateEntity(Guid zone, Guid corporation, Guid loadout)
|
||||
public Entity CreateEntity(Guid zoneID, Guid corporation, Guid loadout)
|
||||
{
|
||||
if (!(Cache.Get(loadout) is LoadoutData loadoutData))
|
||||
{
|
||||
|
|
@ -637,7 +452,7 @@ public class GameContext
|
|||
return null;
|
||||
}
|
||||
|
||||
if (!(Cache.Get(zone) is ZoneData zoneData))
|
||||
if (!(Cache.Get(zoneID) is ZoneData zoneData))
|
||||
{
|
||||
_logger("Attempted to spawn entity with invalid zone ID");
|
||||
return null;
|
||||
|
|
@ -703,9 +518,8 @@ public class GameContext
|
|||
if(hull==null)
|
||||
return null;
|
||||
|
||||
// Load target zone if not yet loaded
|
||||
if (!_loadedZones.Contains(zone))
|
||||
LoadZone(zone);
|
||||
// Get target zone
|
||||
var zone = _zones[zoneID];
|
||||
|
||||
if (hullData.HullType == HullType.Ship)
|
||||
{
|
||||
|
|
@ -722,15 +536,12 @@ public class GameContext
|
|||
{
|
||||
Context = this,
|
||||
Distance = distance,
|
||||
Parent = _orbits
|
||||
.Select(id => Cache.Get<OrbitData>(id))
|
||||
.First(orbitData => orbitData.Zone == zone && orbitData.Parent == Guid.Empty).ID,
|
||||
Period = OrbitalPeriod(distance),
|
||||
Phase = Random.NextFloat(),
|
||||
Zone = zone
|
||||
Parent = zone.Orbits.Values.Select(o=>o.Data)
|
||||
.First(orbitData => orbitData.Parent == Guid.Empty).ID,
|
||||
Period = _globalData.OrbitalPeriod(distance),
|
||||
Phase = Random.NextFloat()
|
||||
};
|
||||
Cache.Add(orbit);
|
||||
_orbits.Add(orbit.ID);
|
||||
zone.AddOrbit(orbit);
|
||||
|
||||
var entity = new OrbitalEntity(this, hull.ID, gear.Select(g => g.ID),
|
||||
cargo.Select(c => c.ID).Concat(simpleCargo.Select(c => c.ID)), orbit.ID, zone, corporation)
|
||||
|
|
@ -745,14 +556,14 @@ public class GameContext
|
|||
entity.Personality[attribute.Key] = attribute.Value;
|
||||
Cache.Add(entity);
|
||||
|
||||
ZoneEntities[zone][entity.ID] = entity;
|
||||
zone.Entities[entity.ID] = entity;
|
||||
return entity;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public Ship CreateShip(Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid zone, Guid corporation, Guid homeEntity, string typeName)
|
||||
public Ship CreateShip(Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Zone zone, Guid corporation, Guid homeEntity, string typeName)
|
||||
{
|
||||
|
||||
var ship = new Ship(this, hull, gear, cargo, zone, corporation)
|
||||
|
|
@ -762,7 +573,7 @@ public class GameContext
|
|||
};
|
||||
Cache.Add(ship);
|
||||
|
||||
ZoneEntities[zone][ship.ID] = ship;
|
||||
zone.Entities[ship.ID] = ship;
|
||||
return ship;
|
||||
}
|
||||
|
||||
|
|
@ -920,46 +731,6 @@ public class GameContext
|
|||
child.Parent = Guid.Empty;
|
||||
}
|
||||
|
||||
public void MineAsteroid(Entity miner, Guid asteroidBelt, int asteroid, float damage, float efficiency, float penetration)
|
||||
{
|
||||
var planetData = Cache.Get<PlanetData>(asteroidBelt);
|
||||
var asteroidTransform = GetAsteroidTransform(asteroidBelt, asteroid);
|
||||
var hpLerp = unlerp(GlobalData.AsteroidSizeMin, GlobalData.AsteroidSizeMax, asteroidTransform.w);
|
||||
var asteroidHitpoints = lerp(GlobalData.AsteroidHitpointsMin, GlobalData.AsteroidHitpointsMax, pow(hpLerp, GlobalData.AsteroidHitpointsPower));
|
||||
|
||||
if (!_asteroidDamage.ContainsKey((asteroidBelt, asteroid)))
|
||||
_asteroidDamage[(asteroidBelt, asteroid)] = 0;
|
||||
_asteroidDamage[(asteroidBelt, asteroid)] = _asteroidDamage[(asteroidBelt, asteroid)] + damage;
|
||||
|
||||
if (!_asteroidMiningAccumulator.ContainsKey((asteroidBelt, miner.ID, asteroid)))
|
||||
_asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] = 0;
|
||||
_asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] = _asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] + damage;
|
||||
|
||||
if (_asteroidDamage[(asteroidBelt, asteroid)] > asteroidHitpoints)
|
||||
{
|
||||
_asteroidRespawnTimers[(asteroidBelt, asteroid)] =
|
||||
lerp(GlobalData.AsteroidRespawnMin, GlobalData.AsteroidRespawnMax, hpLerp);
|
||||
_asteroidDamage.Remove((asteroidBelt, asteroid));
|
||||
_asteroidMiningAccumulator.Remove((asteroidBelt, miner.ID, asteroid));
|
||||
return;
|
||||
}
|
||||
|
||||
var resourceCount = planetData.Resources.Sum(x => x.Value);
|
||||
var resource = planetData.Resources.MaxBy(x => pow(x.Value, 1f / penetration) * Random.NextFloat());
|
||||
if (efficiency * Random.NextFloat() * _asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] * resourceCount / GlobalData.MiningDifficulty > 1 && miner.OccupiedCapacity < miner.Capacity - 1)
|
||||
{
|
||||
_asteroidMiningAccumulator.Remove((asteroidBelt, miner.ID, asteroid));
|
||||
var newSimpleCommodity = new SimpleCommodity
|
||||
{
|
||||
Context = this,
|
||||
Data = resource.Key,
|
||||
Quantity = 1
|
||||
};
|
||||
Cache.Add(newSimpleCommodity);
|
||||
miner.AddCargo(newSimpleCommodity);
|
||||
}
|
||||
}
|
||||
|
||||
// public bool MoveCargo(Entity source, Entity target, ItemInstance item, int quantity = int.MaxValue)
|
||||
// {
|
||||
// if (item is CraftedItemInstance craftedItemInstance)
|
||||
|
|
|
|||
|
|
@ -171,6 +171,11 @@ public class GlobalData : DatabaseEntry
|
|||
{
|
||||
return pow(mass, 1 / RadiusPower);
|
||||
}
|
||||
|
||||
public float OrbitalPeriod(float distance)
|
||||
{
|
||||
return pow(distance, OrbitPeriodExponent) * OrbitPeriodMultiplier;
|
||||
}
|
||||
}
|
||||
|
||||
[Inspectable, Serializable, RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ public class OrbitalEntity : Entity
|
|||
{
|
||||
public Guid OrbitData;
|
||||
|
||||
public OrbitalEntity(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid orbit, Guid zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation)
|
||||
public OrbitalEntity(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid orbit, Zone zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation)
|
||||
{
|
||||
OrbitData = orbit;
|
||||
}
|
||||
|
|
@ -18,8 +18,8 @@ public class OrbitalEntity : Entity
|
|||
{
|
||||
if (OrbitData != Guid.Empty)
|
||||
{
|
||||
Position = Context.GetOrbitPosition(OrbitData);
|
||||
Velocity = Context.GetOrbitVelocity(OrbitData);
|
||||
Position = Zone.GetOrbitPosition(OrbitData);
|
||||
Velocity = Zone.GetOrbitVelocity(OrbitData);
|
||||
}
|
||||
|
||||
base.Update(delta);
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ public class Ship : Entity
|
|||
[JsonProperty("homeEntity"), Key(19)]
|
||||
public Guid HomeEntity;
|
||||
|
||||
public Ship(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Guid zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation)
|
||||
public Ship(GameContext context, Guid hull, IEnumerable<Guid> gear, IEnumerable<Guid> cargo, Zone zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation)
|
||||
{
|
||||
}
|
||||
|
||||
|
|
|
|||
280
Assets/Scripts/ServerShared/Zone.cs
Normal file
280
Assets/Scripts/ServerShared/Zone.cs
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
using float2 = Unity.Mathematics.float2;
|
||||
|
||||
public class Zone
|
||||
{
|
||||
//public HashSet<Guid> Planets = new HashSet<Guid>();
|
||||
public Dictionary<Guid, Entity> Entities = new Dictionary<Guid, Entity>();
|
||||
//public Dictionary<Guid, OrbitData> Orbits = new Dictionary<Guid, OrbitData>();
|
||||
public Dictionary<Guid, PlanetData> Planets = new Dictionary<Guid, PlanetData>();
|
||||
|
||||
public Dictionary<Guid, Orbit> Orbits = new Dictionary<Guid, Orbit>();
|
||||
public Dictionary<Guid, AsteroidBelt> AsteroidBelts = new Dictionary<Guid, AsteroidBelt>();
|
||||
|
||||
private HashSet<Guid> _updatedOrbits;
|
||||
|
||||
private GameContext _context;
|
||||
|
||||
public ZoneData Data { get; }
|
||||
|
||||
public Zone(GameContext context, ZonePack pack)
|
||||
{
|
||||
Data = pack.Data;
|
||||
_context = context;
|
||||
|
||||
foreach (var orbit in pack.Orbits)
|
||||
{
|
||||
Orbits.Add(orbit.ID, new Orbit(orbit));
|
||||
}
|
||||
foreach (var planet in pack.Planets) Planets.Add(planet.ID, planet);
|
||||
foreach (var entity in pack.Entities) Entities.Add(entity.ID, entity);
|
||||
|
||||
foreach (var belt in pack.Planets.Where(p => p is AsteroidBeltData).Cast<AsteroidBeltData>())
|
||||
AsteroidBelts[belt.ID] = new AsteroidBelt(belt.Asteroids.Length);
|
||||
|
||||
// TODO: Associate planets with stored entities for planetary colonies
|
||||
}
|
||||
|
||||
public ZonePack Pack()
|
||||
{
|
||||
return new ZonePack
|
||||
{
|
||||
Data = Data,
|
||||
Entities = Entities.Values.ToList(),
|
||||
Orbits = Orbits.Values.Select(o=>o.Data).ToList(),
|
||||
Planets = Planets.Values.ToList()
|
||||
};
|
||||
}
|
||||
|
||||
public void AddOrbit(OrbitData orbit)
|
||||
{
|
||||
Orbits.Add(orbit.ID, new Orbit(orbit));
|
||||
}
|
||||
|
||||
public void Update(float deltaTime)
|
||||
{
|
||||
_updatedOrbits = new HashSet<Guid>();
|
||||
foreach (var orbit in Orbits)
|
||||
{
|
||||
orbit.Value.PreviousPosition = orbit.Value.Position;
|
||||
orbit.Value.Position = GetOrbitPosition(orbit.Key);
|
||||
orbit.Value.Velocity = (orbit.Value.Position - orbit.Value.PreviousPosition) / deltaTime;
|
||||
}
|
||||
|
||||
foreach (var asteroids in AsteroidBelts.Keys)
|
||||
UpdateAsteroidTransforms(asteroids);
|
||||
|
||||
foreach (var entity in Entities.Values) entity.Update(deltaTime);
|
||||
}
|
||||
|
||||
public float2 WormholePosition(Guid target)
|
||||
{
|
||||
var direction = _context.Cache.Get<ZoneData>(target).Position - Data.Position;
|
||||
return normalize(direction) * Data.Radius * .95f;
|
||||
}
|
||||
|
||||
// Determine orbital position recursively, caching parent positions to avoid repeated calculations
|
||||
public float2 GetOrbitPosition(Guid orbit)
|
||||
{
|
||||
// Root orbit is fixed at center
|
||||
if(orbit==Guid.Empty)
|
||||
return float2.zero;
|
||||
|
||||
if (!_updatedOrbits.Contains(orbit))
|
||||
{
|
||||
var orbitData = Orbits[orbit].Data;
|
||||
float2 pos = float2.zero;
|
||||
if (orbitData.Period > .01f)
|
||||
{
|
||||
var phase = (float) frac(_context.Time / orbitData.Period * _context.GlobalData.OrbitSpeedMultiplier);
|
||||
pos = OrbitData.Evaluate(frac(phase + orbitData.Phase)) * orbitData.Distance;
|
||||
|
||||
if (float.IsNaN(pos.x))
|
||||
{
|
||||
_context.Log("Orbit position is NaN, something went very wrong!");
|
||||
pos = float2.zero;
|
||||
}
|
||||
}
|
||||
|
||||
_updatedOrbits.Add(orbit);
|
||||
return GetOrbitPosition(orbitData.Parent) + pos;
|
||||
}
|
||||
|
||||
return Orbits[orbit].Position;
|
||||
}
|
||||
|
||||
public float2 GetOrbitVelocity(Guid orbit)
|
||||
{
|
||||
if (Orbits.ContainsKey(orbit))
|
||||
return Orbits[orbit].Velocity;
|
||||
return float2.zero;
|
||||
}
|
||||
|
||||
public int NearestAsteroid(Guid planetDataID, float2 position)
|
||||
{
|
||||
var beltData = Planets[planetDataID] as AsteroidBeltData;
|
||||
|
||||
var asteroidPositions = GetAsteroidTransforms(planetDataID);
|
||||
|
||||
int nearest = 0;
|
||||
float nearestDistance = Single.MaxValue;
|
||||
for (int i = 0; i < beltData.Asteroids.Length; i++)
|
||||
{
|
||||
var dist = lengthsq(asteroidPositions[i].xy - position);
|
||||
if (AsteroidExists(planetDataID, i) && dist < nearestDistance)
|
||||
{
|
||||
nearest = i;
|
||||
nearestDistance = dist;
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
|
||||
public bool AsteroidExists(Guid planetDataID, int asteroid) => ((AsteroidBeltData) Planets[planetDataID]).Asteroids.Length > asteroid && asteroid >= 0;
|
||||
|
||||
public float2 GetAsteroidVelocity(Guid planetDataID, int asteroid)
|
||||
{
|
||||
return (AsteroidBelts[planetDataID].Transforms[asteroid].xy - AsteroidBelts[planetDataID].PreviousTransforms[asteroid].xy);
|
||||
}
|
||||
|
||||
public float4 GetAsteroidTransform(Guid planetDataID, int asteroid)
|
||||
{
|
||||
return AsteroidBelts[planetDataID].Transforms[asteroid];
|
||||
}
|
||||
|
||||
public float4[] GetAsteroidTransforms(Guid planetDataID)
|
||||
{
|
||||
return AsteroidBelts[planetDataID].Transforms;
|
||||
}
|
||||
|
||||
private void UpdateAsteroidTransforms(Guid planetDataID)
|
||||
{
|
||||
var beltData = Planets[planetDataID] as AsteroidBeltData;
|
||||
|
||||
var belt = AsteroidBelts[planetDataID];
|
||||
|
||||
Array.Copy(belt.Transforms, belt.PreviousTransforms, beltData.Asteroids.Length);
|
||||
|
||||
var orbitData = Orbits[beltData.Orbit].Data;
|
||||
var orbitPosition = GetOrbitPosition(orbitData.Parent);
|
||||
for (var i = 0; i < beltData.Asteroids.Length; i++)
|
||||
{
|
||||
var size = beltData.Asteroids[i].Size;
|
||||
if(belt.RespawnTimers.ContainsKey(i)) size = 0;
|
||||
else if (belt.Damage.ContainsKey(i))
|
||||
{
|
||||
var hpLerp = unlerp(_context.GlobalData.AsteroidSizeMin, _context.GlobalData.AsteroidSizeMax, size);
|
||||
var asteroidHitpoints = lerp(_context.GlobalData.AsteroidHitpointsMin, _context.GlobalData.AsteroidHitpointsMax, pow(hpLerp, _context.GlobalData.AsteroidHitpointsPower));
|
||||
var sizeLerp = (asteroidHitpoints - belt.Damage[i]) / asteroidHitpoints;
|
||||
size = lerp(_context.GlobalData.AsteroidSizeMin, size, sizeLerp);
|
||||
}
|
||||
|
||||
belt.Transforms[i] = float4(
|
||||
OrbitData.Evaluate((float) frac(_context.Time / _context.GlobalData.OrbitalPeriod(beltData.Asteroids[i].Distance) * _context.GlobalData.OrbitSpeedMultiplier +
|
||||
beltData.Asteroids[i].Phase)) * beltData.Asteroids[i].Distance + orbitPosition,
|
||||
(float) (_context.Time * beltData.Asteroids[i].RotationSpeed % 360.0), size);
|
||||
}
|
||||
}
|
||||
|
||||
public OrbitData CreateOrbit(Guid parent, float2 position)
|
||||
{
|
||||
var parentPosition = GetOrbitPosition(parent);
|
||||
var delta = position - parentPosition;
|
||||
var distance = length(delta);
|
||||
var period = _context.GlobalData.OrbitalPeriod(distance);
|
||||
var phase = atan2(delta.y, delta.x) / (PI * 2);
|
||||
var currentPhase = frac(_context.Time / period * _context.GlobalData.OrbitSpeedMultiplier);
|
||||
var storedPhase = (float) frac(phase - currentPhase);
|
||||
|
||||
var orbit = new OrbitData
|
||||
{
|
||||
Context = _context,
|
||||
Distance = distance,
|
||||
Parent = parent,
|
||||
Period = period,
|
||||
Phase = storedPhase
|
||||
};
|
||||
Orbits.Add(orbit.ID, new Orbit(orbit));
|
||||
return orbit;
|
||||
}
|
||||
|
||||
public void MineAsteroid(Entity miner, Guid asteroidBelt, int asteroid, float damage, float efficiency, float penetration)
|
||||
{
|
||||
var planetData = Planets[asteroidBelt];
|
||||
var belt = AsteroidBelts[asteroidBelt];
|
||||
var asteroidTransform = belt.Transforms[asteroid];
|
||||
var hpLerp = unlerp(_context.GlobalData.AsteroidSizeMin, _context.GlobalData.AsteroidSizeMax, asteroidTransform.w);
|
||||
var asteroidHitpoints = lerp(_context.GlobalData.AsteroidHitpointsMin, _context.GlobalData.AsteroidHitpointsMax, pow(hpLerp, _context.GlobalData.AsteroidHitpointsPower));
|
||||
|
||||
if (!belt.Damage.ContainsKey(asteroid))
|
||||
belt.Damage[asteroid] = 0;
|
||||
belt.Damage[asteroid] = belt.Damage[asteroid] + damage;
|
||||
|
||||
if (!belt.MiningAccumulator.ContainsKey((miner.ID, asteroid)))
|
||||
belt.MiningAccumulator[(miner.ID, asteroid)] = 0;
|
||||
belt.MiningAccumulator[(miner.ID, asteroid)] = belt.MiningAccumulator[(miner.ID, asteroid)] + damage;
|
||||
|
||||
if (belt.Damage[asteroid] > asteroidHitpoints)
|
||||
{
|
||||
belt.RespawnTimers[asteroid] =
|
||||
lerp(_context.GlobalData.AsteroidRespawnMin, _context.GlobalData.AsteroidRespawnMax, hpLerp);
|
||||
belt.Damage.Remove(asteroid);
|
||||
belt.MiningAccumulator.Remove((miner.ID, asteroid));
|
||||
return;
|
||||
}
|
||||
|
||||
var resourceCount = planetData.Resources.Sum(x => x.Value);
|
||||
var resource = planetData.Resources.MaxBy(x => pow(x.Value, 1f / penetration) * _context.Random.NextFloat());
|
||||
if (efficiency * _context.Random.NextFloat() * belt.MiningAccumulator[(miner.ID, asteroid)] * resourceCount / _context.GlobalData.MiningDifficulty > 1 && miner.OccupiedCapacity < miner.Capacity - 1)
|
||||
{
|
||||
belt.MiningAccumulator.Remove((miner.ID, asteroid));
|
||||
var newSimpleCommodity = new SimpleCommodity
|
||||
{
|
||||
Context = _context,
|
||||
Data = resource.Key,
|
||||
Quantity = 1
|
||||
};
|
||||
_context.Cache.Add(newSimpleCommodity);
|
||||
miner.AddCargo(newSimpleCommodity);
|
||||
}
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Data.ID.GetHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
public class AsteroidBelt
|
||||
{
|
||||
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)
|
||||
{
|
||||
Transforms = new float4[count];
|
||||
PreviousTransforms = new float4[count];
|
||||
}
|
||||
}
|
||||
|
||||
public class Orbit
|
||||
{
|
||||
public OrbitData Data { get; }
|
||||
public float2 Velocity = float2.zero;
|
||||
public float2 Position = float2.zero;
|
||||
public float2 PreviousPosition = float2.zero;
|
||||
|
||||
public Orbit(OrbitData data)
|
||||
{
|
||||
Data = data;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Zone.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Zone.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: dde69e76badd79c4c8d73cf89be4f0e8
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -4,6 +4,7 @@ using System.Collections.Generic;
|
|||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
|
|
@ -21,17 +22,17 @@ public class ZoneData : DatabaseEntry, INamedEntry
|
|||
[JsonProperty("mass"), Key(4)]
|
||||
public float Mass = 10000;
|
||||
|
||||
[JsonProperty("visited"), Key(5)]
|
||||
public bool Visited;
|
||||
// [JsonProperty("visited"), Key(5)]
|
||||
// public bool Visited;
|
||||
|
||||
[JsonProperty("wormholes"), Key(6)]
|
||||
[JsonProperty("wormholes"), Key(5)]
|
||||
public List<Guid> Wormholes = new List<Guid>();
|
||||
|
||||
[JsonProperty("planets"), Key(7)]
|
||||
public Guid[] Planets;// = new List<Guid>();
|
||||
|
||||
[JsonProperty("orbits"), Key(8)]
|
||||
public List<Guid> Orbits = new List<Guid>();
|
||||
// [JsonProperty("planets"), Key(7)]
|
||||
// public Guid[] Planets;// = new List<Guid>();
|
||||
//
|
||||
// [JsonProperty("orbits"), Key(8)]
|
||||
// public List<Guid> Orbits = new List<Guid>();
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
|
|
@ -40,6 +41,28 @@ public class ZoneData : DatabaseEntry, INamedEntry
|
|||
}
|
||||
}
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class ZonePack : INamedEntry
|
||||
{
|
||||
[JsonProperty("data"), Key(0)]
|
||||
public ZoneData Data;
|
||||
|
||||
[JsonProperty("planets"), Key(1)]
|
||||
public List<PlanetData> Planets = new List<PlanetData>();
|
||||
|
||||
[JsonProperty("orbits"), Key(2)]
|
||||
public List<OrbitData> Orbits = new List<OrbitData>();
|
||||
|
||||
[JsonProperty("entities"), Key(3)]
|
||||
public List<Entity> Entities = new List<Entity>();
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
get => Data.Name;
|
||||
set => Data.Name = value;
|
||||
}
|
||||
}
|
||||
|
||||
// [RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
// public class StationData : DatabaseEntry, INamedEntry
|
||||
// {
|
||||
|
|
@ -72,7 +95,11 @@ public class ZoneData : DatabaseEntry, INamedEntry
|
|||
// }
|
||||
// }
|
||||
|
||||
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
[MessagePackObject,
|
||||
JsonObject(MemberSerialization.OptIn),
|
||||
Union(1, typeof(AsteroidBeltData)),
|
||||
Union(2, typeof(GasGiantData)),
|
||||
Union(3, typeof(SunData))]
|
||||
public class PlanetData : DatabaseEntry, INamedEntry
|
||||
{
|
||||
[JsonProperty("name"), Key(1)]
|
||||
|
|
@ -84,20 +111,14 @@ public class PlanetData : DatabaseEntry, INamedEntry
|
|||
[JsonProperty("mass"), Key(3)]
|
||||
public float Mass;
|
||||
|
||||
[JsonProperty("zone"), Key(4)]
|
||||
public Guid Zone;
|
||||
|
||||
[JsonProperty("belt"), Key(5)]
|
||||
public bool Belt;
|
||||
|
||||
[JsonProperty("resources"), Key(6)]
|
||||
[JsonProperty("resources"), Key(4)]
|
||||
public Dictionary<Guid, float> Resources = new Dictionary<Guid, float>();
|
||||
|
||||
[JsonProperty("asteroids"), Key(7)]
|
||||
public Asteroid[] Asteroids; // Distance, Phase, Size, RotationSpeed
|
||||
|
||||
// [JsonProperty("radius")] [Key(5)]
|
||||
// public float GravityRadius;
|
||||
[JsonProperty("radiusMul")] [Key(5)]
|
||||
public float GravityRadiusMultiplier = 1;
|
||||
|
||||
[JsonProperty("depthMul")] [Key(6)]
|
||||
public float GravityDepthMultiplier = 1;
|
||||
|
||||
[IgnoreMember] public string EntryName
|
||||
{
|
||||
|
|
@ -106,6 +127,45 @@ public class PlanetData : DatabaseEntry, INamedEntry
|
|||
}
|
||||
}
|
||||
|
||||
public class AsteroidBeltData : PlanetData
|
||||
{
|
||||
[JsonProperty("asteroids"), Key(7)]
|
||||
public Asteroid[] Asteroids;
|
||||
}
|
||||
|
||||
public class GasGiantData : PlanetData
|
||||
{
|
||||
[JsonProperty("firstOffsetDomainRotationSpeed"), Key(7)]
|
||||
public float FirstOffsetDomainRotationSpeed;
|
||||
|
||||
[JsonProperty("firstOffsetRotationSpeed"), Key(8)]
|
||||
public float FirstOffsetRotationSpeed;
|
||||
|
||||
[JsonProperty("secondOffsetDomainRotationSpeed"), Key(9)]
|
||||
public float SecondOffsetDomainRotationSpeed;
|
||||
|
||||
[JsonProperty("secondOffsetRotationSpeed"), Key(10)]
|
||||
public float SecondOffsetRotationSpeed;
|
||||
|
||||
[JsonProperty("albedoRotationSpeed"), Key(11)]
|
||||
public float AlbedoRotationSpeed;
|
||||
|
||||
[JsonProperty("materialOverrides"), Key(12)]
|
||||
public List<string> MaterialOverrides = new List<string>();
|
||||
|
||||
[JsonProperty("colors"), Key(13)]
|
||||
public Gradient Colors;
|
||||
}
|
||||
|
||||
public class SunData : GasGiantData
|
||||
{
|
||||
[JsonProperty("lightColor"), Key(17)]
|
||||
public Color LightColor;
|
||||
|
||||
[JsonProperty("fogTintColor"), Key(18)]
|
||||
public Color FogTintColor;
|
||||
}
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class Asteroid
|
||||
{
|
||||
|
|
@ -115,7 +175,7 @@ public class Asteroid
|
|||
public float RotationSpeed;
|
||||
}
|
||||
|
||||
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class OrbitData : DatabaseEntry
|
||||
{
|
||||
[JsonProperty("parent"), Key(1)]
|
||||
|
|
@ -130,9 +190,6 @@ public class OrbitData : DatabaseEntry
|
|||
[JsonProperty("period"), Key(4)]
|
||||
public float Period;
|
||||
|
||||
[JsonProperty("zone"), Key(5)]
|
||||
public Guid Zone;
|
||||
|
||||
public static float2 Evaluate(float phase)
|
||||
{
|
||||
phase *= PI * 2;
|
||||
|
|
|
|||
|
|
@ -5,21 +5,33 @@ using System.Globalization;
|
|||
using System.Linq;
|
||||
using MessagePack;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
using static Unity.Mathematics.math;
|
||||
using Random = Unity.Mathematics.Random;
|
||||
|
||||
public class ZoneGenerator
|
||||
{
|
||||
|
||||
public static void GenerateZone(
|
||||
public static ZonePack GenerateZone(
|
||||
GameContext context,
|
||||
ZoneData zone,
|
||||
string name,
|
||||
float2 position,
|
||||
IEnumerable<GalaxyMapLayerData> mapLayers,
|
||||
IEnumerable<SimpleCommodityData> resources,
|
||||
out OrbitData[] orbitData,
|
||||
out PlanetData[] planetsData)
|
||||
float mass = 0,
|
||||
float radius = 0)
|
||||
{
|
||||
var zoneRadius = context.Random.NextPowerDistribution(
|
||||
var zone = new ZoneData
|
||||
{
|
||||
Name = name,
|
||||
Position = position
|
||||
};
|
||||
|
||||
var pack = new ZonePack
|
||||
{
|
||||
Data = zone
|
||||
};
|
||||
|
||||
var zoneRadius = radius != 0 ? radius : context.Random.NextPowerDistribution(
|
||||
context.GlobalData.MinimumZoneRadius,
|
||||
context.GlobalData.MaximumZoneRadius,
|
||||
context.GlobalData.ZoneRadiusExponent,
|
||||
|
|
@ -31,7 +43,7 @@ public class ZoneGenerator
|
|||
.Evaluate(zone.Position, context.GlobalData)));
|
||||
zone.Radius = zoneRadius;
|
||||
|
||||
var zoneMass = context.Random.NextPowerDistribution(
|
||||
var zoneMass = mass != 0 ? mass : context.Random.NextPowerDistribution(
|
||||
context.GlobalData.MinimumZoneMass,
|
||||
context.GlobalData.MaximumZoneMass,
|
||||
context.GlobalData.ZoneMassExponent,
|
||||
|
|
@ -48,26 +60,25 @@ public class ZoneGenerator
|
|||
var planets = GenerateEntities(context, zone, zoneMass, zoneRadius);
|
||||
|
||||
// Create collections to map between zone generator output and database entries
|
||||
var orbitMap = new Dictionary<Planet, OrbitData>();
|
||||
var orbitInverseMap = new Dictionary<OrbitData, Planet>();
|
||||
var orbitMap = new Dictionary<GeneratorPlanet, OrbitData>();
|
||||
var orbitInverseMap = new Dictionary<OrbitData, GeneratorPlanet>();
|
||||
|
||||
// Create orbit database entries
|
||||
orbitData = planets.Select(planet =>
|
||||
pack.Orbits = planets.Select(planet =>
|
||||
{
|
||||
var data = new OrbitData
|
||||
{
|
||||
Distance = planet.Distance,
|
||||
Period = planet.Period,
|
||||
Phase = planet.Phase,
|
||||
Zone = zone.ID
|
||||
Phase = planet.Phase
|
||||
};
|
||||
orbitMap[planet] = data;
|
||||
orbitInverseMap[data] = planet;
|
||||
return data;
|
||||
}).ToArray();
|
||||
}).ToList();
|
||||
|
||||
// Link OrbitData parents to database GUIDs
|
||||
foreach (var data in orbitData)
|
||||
foreach (var data in pack.Orbits)
|
||||
data.Parent = orbitInverseMap[data].Parent != null
|
||||
? orbitMap[orbitInverseMap[data].Parent].ID
|
||||
: Guid.Empty;
|
||||
|
|
@ -75,34 +86,50 @@ public class ZoneGenerator
|
|||
// Cache resource densities
|
||||
var resourceMaps = mapLayers.ToDictionary(m => m.ID, m => m.Evaluate(zone.Position, context.GlobalData));
|
||||
|
||||
planetsData = planets.Where(p=>!p.Empty).Select(planet =>
|
||||
pack.Planets = planets.Where(p=>!p.Empty).Select(planet =>
|
||||
{
|
||||
Dictionary<Guid, float> dictionary = new Dictionary<Guid, float>();
|
||||
Dictionary<Guid, float> planetResources = new Dictionary<Guid, float>();
|
||||
BodyType bodyType = planet.Belt ? BodyType.Asteroid :
|
||||
planet.Mass > context.GlobalData.SunMass ? BodyType.Sun :
|
||||
planet.Mass > context.GlobalData.GasGiantMass ? BodyType.GasGiant :
|
||||
planet.Mass > context.GlobalData.PlanetMass ? BodyType.Planet : BodyType.Planetoid;
|
||||
|
||||
foreach (var r in resources)
|
||||
{
|
||||
var bodyType = (planet.Belt ? BodyType.Asteroid :
|
||||
planet.Mass > context.GlobalData.SunMass ? BodyType.Sun :
|
||||
planet.Mass > context.GlobalData.GasGiantMass ? BodyType.GasGiant :
|
||||
planet.Mass > context.GlobalData.PlanetMass ? BodyType.Planet : BodyType.Planetoid);
|
||||
if ((bodyType & r.ResourceBodyType) != 0)
|
||||
{
|
||||
float quantity = ResourceValue(r, context, r.ResourceDensity.Aggregate(1f, (m, rdm) => m * resourceMaps[rdm]));
|
||||
if (r.Floor < quantity) dictionary.Add(r.ID, quantity);
|
||||
if (r.Floor < quantity) planetResources.Add(r.ID, quantity);
|
||||
}
|
||||
}
|
||||
|
||||
var planetData = new PlanetData
|
||||
{
|
||||
Mass = planet.Mass,
|
||||
Orbit = orbitMap[planet].ID,
|
||||
Zone = zone.ID,
|
||||
Belt = planet.Belt,
|
||||
Resources = dictionary
|
||||
};
|
||||
PlanetData planetData;
|
||||
switch (bodyType)
|
||||
{
|
||||
case BodyType.Asteroid:
|
||||
planetData = new AsteroidBeltData();
|
||||
break;
|
||||
case BodyType.Planetoid:
|
||||
case BodyType.Planet:
|
||||
planetData = new PlanetData();
|
||||
break;
|
||||
case BodyType.GasGiant:
|
||||
planetData = new GasGiantData();
|
||||
break;
|
||||
case BodyType.Sun:
|
||||
planetData = new SunData();
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
|
||||
planetData.Mass = planet.Mass;
|
||||
planetData.Orbit = orbitMap[planet].ID;
|
||||
planetData.Resources = planetResources;
|
||||
planetData.Name = planetData.ID.ToString().Substring(0, 8);
|
||||
if (planet.Belt)
|
||||
if (planetData is AsteroidBeltData beltData)
|
||||
{
|
||||
planetData.Asteroids =
|
||||
beltData.Asteroids =
|
||||
Enumerable.Range(0, (int) (pow(planetData.Mass, context.GlobalData.BeltMassExponent) / context.GlobalData.BeltMassRatio * orbitMap[planet].Distance))
|
||||
.Select(_ => new Asteroid
|
||||
{
|
||||
|
|
@ -114,11 +141,27 @@ public class ZoneGenerator
|
|||
RotationSpeed = context.Random.NextFloat() * context.GlobalData.AsteroidRotationSpeed
|
||||
}).ToArray();
|
||||
}
|
||||
else if (planetData is GasGiantData gas)
|
||||
{
|
||||
var grad = new Gradient();
|
||||
var times = Enumerable.Range(0, 5).Select(i => (float) i / 4).ToArray();
|
||||
grad.alphaKeys = times.Select(f => new GradientAlphaKey(1, f)).ToArray();
|
||||
grad.colorKeys = times.Select(f => new GradientColorKey(UnityEngine.Random.ColorHSV(), f)).ToArray();
|
||||
gas.Colors = grad;
|
||||
gas.AlbedoRotationSpeed = 1;
|
||||
gas.FirstOffsetRotationSpeed = 1;
|
||||
gas.FirstOffsetDomainRotationSpeed = 1;
|
||||
gas.SecondOffsetRotationSpeed = 1;
|
||||
gas.SecondOffsetDomainRotationSpeed = 1;
|
||||
if (planetData is SunData sun)
|
||||
{
|
||||
sun.FogTintColor = sun.LightColor = UnityEngine.Random.ColorHSV();
|
||||
}
|
||||
}
|
||||
return planetData;
|
||||
}).ToArray();
|
||||
}).ToList();
|
||||
|
||||
zone.Planets = planetsData.Select(pd => pd.ID).ToArray();
|
||||
zone.Orbits = orbitData.Select(od => od.ID).ToList();
|
||||
return pack;
|
||||
}
|
||||
|
||||
static float ResourceValue(SimpleCommodityData resource, GameContext context, float density)
|
||||
|
|
@ -127,15 +170,15 @@ public class ZoneGenerator
|
|||
1 / lerp(context.GlobalData.ResourceDensityMinimum, context.GlobalData.ResourceDensityMaximum, density));
|
||||
}
|
||||
|
||||
public static Planet[] GenerateEntities(GameContext context, ZoneData data, float mass, float radius)
|
||||
public static GeneratorPlanet[] GenerateEntities(GameContext context, ZoneData data, float mass, float radius)
|
||||
{
|
||||
var random = new Random();
|
||||
random.InitState(unchecked((uint)data.Name.GetHashCode()));
|
||||
|
||||
var root = new Planet
|
||||
var root = new GeneratorPlanet
|
||||
{
|
||||
Context = context,
|
||||
Mass = mass,
|
||||
Mass = mass,
|
||||
ChildDistanceMaximum = radius * .75f,
|
||||
ChildDistanceMinimum = context.GlobalData.PlanetRadius(mass)
|
||||
};
|
||||
|
|
@ -194,7 +237,7 @@ public class ZoneGenerator
|
|||
? root.AllPlanets().Where(p => p != root && p.Parent != root && p.Mass > context.GlobalData.SatelliteCreationMassFloor)
|
||||
: root.AllPlanets().Where(p => p != root && p.Mass > context.GlobalData.SatelliteCreationMassFloor);
|
||||
|
||||
var binaries = new List<Planet>();
|
||||
var binaries = new List<GeneratorPlanet>();
|
||||
foreach (var planet in satelliteCandidates)
|
||||
{
|
||||
// There's a chance of generating satellites for each qualified planet
|
||||
|
|
@ -233,7 +276,7 @@ public class ZoneGenerator
|
|||
// All orbiting bodies are referred to here as "Planets"
|
||||
// This goes back to the original etymology for the word planet, which is traveler,
|
||||
// Because they were objects we observed to move in the sky instead of remaining fixed like the stars
|
||||
public class Planet
|
||||
public class GeneratorPlanet
|
||||
{
|
||||
public GameContext Context;
|
||||
public float Distance;
|
||||
|
|
@ -244,11 +287,11 @@ public class Planet
|
|||
public float ChildDistanceMaximum;
|
||||
public bool Empty = false;
|
||||
public bool Belt = false;
|
||||
public List<Planet> Children = new List<Planet>(); // Planets orbiting this one are referred to as children
|
||||
public Planet Parent;
|
||||
public List<GeneratorPlanet> Children = new List<GeneratorPlanet>(); // Planets orbiting this one are referred to as children
|
||||
public GeneratorPlanet Parent;
|
||||
|
||||
// Recursively gather all planets in the hierarchy
|
||||
public IEnumerable<Planet> AllPlanets()
|
||||
public IEnumerable<GeneratorPlanet> AllPlanets()
|
||||
{
|
||||
return new[]{this}.Concat(Children.SelectMany(c=>c.AllPlanets()));
|
||||
}
|
||||
|
|
@ -283,7 +326,7 @@ public class Planet
|
|||
|
||||
for (int i = 0; i < vertices; i++)
|
||||
{
|
||||
var child = new Planet
|
||||
var child = new GeneratorPlanet
|
||||
{
|
||||
Context = Context,
|
||||
Parent = this,
|
||||
|
|
@ -293,7 +336,7 @@ public class Planet
|
|||
ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist)
|
||||
};
|
||||
child.ChildDistanceMinimum = Context.GlobalData.PlanetRadius(child.Mass) * 2;
|
||||
child.Period = Context.OrbitalPeriod(child.Distance);
|
||||
child.Period = Context.GlobalData.OrbitalPeriod(child.Distance);
|
||||
Children.Add(child);
|
||||
}
|
||||
|
||||
|
|
@ -346,7 +389,7 @@ public class Planet
|
|||
// Only instantiate children above the mass floor
|
||||
if (masses[i] > Context.GlobalData.MassFloor)
|
||||
{
|
||||
var child = new Planet
|
||||
var child = new GeneratorPlanet
|
||||
{
|
||||
Context = Context,
|
||||
Parent = this,
|
||||
|
|
@ -354,7 +397,7 @@ public class Planet
|
|||
Distance = distances[i],
|
||||
Phase = Context.Random.NextFloat()
|
||||
};
|
||||
child.Period = Context.OrbitalPeriod(child.Distance);
|
||||
child.Period = Context.GlobalData.OrbitalPeriod(child.Distance);
|
||||
child.ChildDistanceMinimum = Context.GlobalData.PlanetRadius(child.Mass) * 2;
|
||||
// Maximum child distance of child is the smallest distance to either of its neighbors
|
||||
child.ChildDistanceMaximum = min(i == 0 ? child.Distance - ChildDistanceMinimum : child.Distance - distances[i - 1],
|
||||
|
|
|
|||
|
|
@ -9,9 +9,9 @@ using NaughtyAttributes;
|
|||
using RethinkDb.Driver.Net;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.UI;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
using float2 = Unity.Mathematics.float2;
|
||||
using Random = UnityEngine.Random;
|
||||
|
|
@ -84,7 +84,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
// private GalaxyResponseMessage _galaxyResponse;
|
||||
private TabButton _currentTab;
|
||||
private bool _galaxyPopulated;
|
||||
private Guid _populatedZone;
|
||||
private Zone _currentZone;
|
||||
private Guid _selectedZone;
|
||||
private GalaxyZone _selectedGalaxyZone;
|
||||
private Dictionary<Guid, GalaxyZone> _galaxyZoneObjects = new Dictionary<Guid, GalaxyZone>();
|
||||
|
|
@ -124,7 +124,6 @@ public class StrategyGameManager : MonoBehaviour
|
|||
ColonyTab.Context = _context;
|
||||
TechTree.Context = _context;
|
||||
PropertiesPanel.Context = _context;
|
||||
_context.MapLayers = _cache.GetAll<GalaxyMapLayerData>().ToDictionary(ml => ml.Name);
|
||||
_context.GalaxyZones = _cache.GetAll<ZoneData>()
|
||||
.ToDictionary(z => z.ID, z => new SimplifiedZoneData
|
||||
{
|
||||
|
|
@ -260,7 +259,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
if(_currentTab==GalaxyTabButton && _selectedZone == zone.Zone.ID)
|
||||
Select(_selectedZone);
|
||||
|
||||
if (_currentTab == ZoneTabButton && _populatedZone != zone.Zone.ID) PopulateZone();
|
||||
if (_currentTab == ZoneTabButton && _currentZone.Data.ID != zone.Zone.ID) PopulateZone();
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -280,9 +279,9 @@ public class StrategyGameManager : MonoBehaviour
|
|||
{
|
||||
PropertiesPanelView.gameObject.SetActive(true);
|
||||
var zone = _cache.Get<ZoneData>(_selectedZone);
|
||||
if (_populatedZone != _selectedZone && zone != null)
|
||||
if (zone != null && (_currentZone == null || _currentZone.Data.ID != _selectedZone))
|
||||
PopulateZone();
|
||||
Select(_populatedZone);
|
||||
Select(_currentZone.Data.ID);
|
||||
Camera.transform.position = -Vector3.forward;
|
||||
if (zone != null)
|
||||
Camera.orthographicSize = zone.Radius * ZoneSizeScale;
|
||||
|
|
@ -329,7 +328,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
OrbitDistance = _orbitRadius,
|
||||
OrbitParent = _selectedOrbit,
|
||||
Station = _selectedTowingTarget,
|
||||
Zone = _populatedZone
|
||||
Zone = _currentZone.Data.ID
|
||||
};
|
||||
_cache.Add(towingTask);
|
||||
playerCorp.Tasks.Add(towingTask.ID);
|
||||
|
|
@ -337,10 +336,10 @@ public class StrategyGameManager : MonoBehaviour
|
|||
OrbitLineRenderer.gameObject.SetActive(false);
|
||||
}
|
||||
else
|
||||
Select(_populatedZone);
|
||||
Select(_currentZone.Data.ID);
|
||||
}
|
||||
else if (data.button == PointerEventData.InputButton.Right)
|
||||
ShowContextMenu(_populatedZone);
|
||||
ShowContextMenu(_currentZone.Data.ID);
|
||||
}
|
||||
else if (_currentTab == TechTabButton) PopulateTechProperties();
|
||||
};
|
||||
|
|
@ -380,11 +379,11 @@ public class StrategyGameManager : MonoBehaviour
|
|||
_galaxyCameraPos = Camera.transform.position;
|
||||
_galaxyOrthoSize = Camera.orthographicSize;
|
||||
}
|
||||
if (_currentTab == ZoneTabButton && _populatedZone == _selectedZone)
|
||||
if (_currentTab == ZoneTabButton && _currentZone.Data.ID == _selectedZone)
|
||||
{
|
||||
foreach (var planet in _zoneGravityObjects)
|
||||
{
|
||||
planet.Value.transform.position = float3(_context.GetOrbitPosition(planet.Key) * ZoneSizeScale, .1f);
|
||||
planet.Value.transform.position = float3(_currentZone.GetOrbitPosition(planet.Key) * ZoneSizeScale, .1f);
|
||||
planet.Value.Message.text = "";
|
||||
}
|
||||
|
||||
|
|
@ -403,7 +402,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
// ship.Value.Thruster.localScale = thrusterScale;
|
||||
// }
|
||||
|
||||
var entities = _context.GetEntities(_populatedZone);
|
||||
var entities = _currentZone.Entities.Values;
|
||||
var shipGameObjects = _zoneShips.Keys.ToList();
|
||||
var orbitalGameObjects = _zoneOrbitals.Keys.ToList();
|
||||
var zoneShips = entities.Where(e => e is Ship && e.Parent == Guid.Empty).Cast<Ship>();
|
||||
|
|
@ -519,7 +518,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
|
||||
if (_orbitSelectMode)
|
||||
{
|
||||
var center = _context.GetOrbitPosition(_selectedOrbit) * ZoneSizeScale;
|
||||
var center = _currentZone.GetOrbitPosition(_selectedOrbit) * ZoneSizeScale;
|
||||
var mousePos = Camera.ScreenToWorldPoint(Input.mousePosition);
|
||||
var radius = length(float2(mousePos.x, mousePos.y) - center);
|
||||
_orbitRadius = radius / ZoneSizeScale;
|
||||
|
|
@ -576,7 +575,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
ContextMenu.Clear();
|
||||
if (targetObject is PlanetData planet)
|
||||
{
|
||||
if (planet.Belt)
|
||||
if (planet is AsteroidBeltData)
|
||||
{
|
||||
ContextMenu.AddOption("Create Mining Task", () =>
|
||||
{
|
||||
|
|
@ -584,7 +583,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
{
|
||||
Asteroids = clickTarget,
|
||||
Context = _context,
|
||||
Zone = _populatedZone
|
||||
Zone = _currentZone.Data.ID
|
||||
};
|
||||
_cache.Add(task);
|
||||
_cache.Get<Corporation>(_playerCorporation).Tasks.Add(task.ID);
|
||||
|
|
@ -596,7 +595,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
{
|
||||
Planets = new List<Guid>(new []{clickTarget}),
|
||||
Context = _context,
|
||||
Zone = _populatedZone
|
||||
Zone = _currentZone.Data.ID
|
||||
};
|
||||
_cache.Add(task);
|
||||
_cache.Get<Corporation>(_playerCorporation).Tasks.Add(task.ID);
|
||||
|
|
@ -632,39 +631,39 @@ public class StrategyGameManager : MonoBehaviour
|
|||
{
|
||||
ContextMenu.AddOption("Survey All", () =>
|
||||
{
|
||||
var planets = zone.Planets.ToList();
|
||||
var task = new Survey
|
||||
{
|
||||
Planets = planets,
|
||||
Context = _context,
|
||||
Zone = _populatedZone
|
||||
};
|
||||
_cache.Add(task);
|
||||
_cache.Get<Corporation>(_playerCorporation).Tasks.Add(task.ID);
|
||||
// var planets = zone.Planets.ToList();
|
||||
// var task = new Survey
|
||||
// {
|
||||
// Planets = planets,
|
||||
// Context = _context,
|
||||
// Zone = _currentZone.Data.ID
|
||||
// };
|
||||
// _cache.Add(task);
|
||||
// _cache.Get<Corporation>(_playerCorporation).Tasks.Add(task.ID);
|
||||
});
|
||||
ContextMenu.AddOption("Survey Planets", () =>
|
||||
{
|
||||
var planets = zone.Planets.Where(id => !_cache.Get<PlanetData>(id).Belt).ToList();
|
||||
var task = new Survey
|
||||
{
|
||||
Planets = planets,
|
||||
Context = _context,
|
||||
Zone = _populatedZone
|
||||
};
|
||||
_cache.Add(task);
|
||||
_cache.Get<Corporation>(_playerCorporation).Tasks.Add(task.ID);
|
||||
// var planets = zone.Planets.Where(id => !_cache.Get<PlanetData>(id).Belt).ToList();
|
||||
// var task = new Survey
|
||||
// {
|
||||
// Planets = planets,
|
||||
// Context = _context,
|
||||
// Zone = _currentZone.Data.ID
|
||||
// };
|
||||
// _cache.Add(task);
|
||||
// _cache.Get<Corporation>(_playerCorporation).Tasks.Add(task.ID);
|
||||
});
|
||||
ContextMenu.AddOption("Survey Asteroids", () =>
|
||||
{
|
||||
var planets = zone.Planets.Where(id => _cache.Get<PlanetData>(id).Belt).ToList();
|
||||
var task = new Survey
|
||||
{
|
||||
Planets = planets,
|
||||
Context = _context,
|
||||
Zone = _populatedZone
|
||||
};
|
||||
_cache.Add(task);
|
||||
_cache.Get<Corporation>(_playerCorporation).Tasks.Add(task.ID);
|
||||
// var planets = zone.Planets.Where(id => _cache.Get<PlanetData>(id).Belt).ToList();
|
||||
// var task = new Survey
|
||||
// {
|
||||
// Planets = planets,
|
||||
// Context = _context,
|
||||
// Zone = _currentZone.Data.ID
|
||||
// };
|
||||
// _cache.Add(task);
|
||||
// _cache.Get<Corporation>(_playerCorporation).Tasks.Add(task.ID);
|
||||
});
|
||||
|
||||
}
|
||||
|
|
@ -691,7 +690,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
{
|
||||
PropertiesPanel.Clear();
|
||||
PropertiesPanel.Title.text = planet.Name;
|
||||
if(planet.Belt)
|
||||
if(planet is AsteroidBeltData)
|
||||
PropertiesPanel.AddSection("Asteroid Belt");
|
||||
else
|
||||
PropertiesPanel.AddSection(
|
||||
|
|
@ -735,7 +734,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
PropertiesPanel.Clear();
|
||||
PropertiesPanel.Title.text = zone.Name;
|
||||
PropertiesPanel.AddSection("Sector");
|
||||
PropertiesPanel.AddProperty("Planets", () => $"{zone.Planets.Length}");
|
||||
// PropertiesPanel.AddProperty("Planets", () => $"{zone.Planets.Length}");
|
||||
}
|
||||
|
||||
PropertiesPanel.RefreshValues();
|
||||
|
|
@ -814,25 +813,26 @@ public class StrategyGameManager : MonoBehaviour
|
|||
|
||||
void GenerateZone(Guid zone)
|
||||
{
|
||||
var zoneData = _cache.Get<ZoneData>(zone);
|
||||
float2 position;
|
||||
do
|
||||
{
|
||||
position = float2(Random.value, Random.value);
|
||||
} while (_context.MapLayers["StarDensity"].Evaluate(position, _context.GlobalData) < .1f);
|
||||
|
||||
OrbitData[] orbits;
|
||||
PlanetData[] planets;
|
||||
ZoneGenerator.GenerateZone(
|
||||
context: _context,
|
||||
zone: zoneData,
|
||||
mapLayers: _context.MapLayers.Values,
|
||||
resources: _cache.GetAll<SimpleCommodityData>().Where(i=>i.ResourceDensity.Any()),
|
||||
orbitData: out orbits,
|
||||
planetsData: out planets);
|
||||
_cache.AddAll(orbits);
|
||||
_cache.AddAll(planets);
|
||||
zoneData.Visited = true;
|
||||
// var zoneData = _cache.Get<ZoneData>(zone);
|
||||
//
|
||||
// // float2 position;
|
||||
// // do
|
||||
// // {
|
||||
// // position = float2(Random.value, Random.value);
|
||||
// // } while (_context.MapLayers["StarDensity"].Evaluate(position, _context.GlobalData) < .1f);
|
||||
//
|
||||
// OrbitData[] orbits;
|
||||
// PlanetData[] planets;
|
||||
// ZoneGenerator.GenerateZone(
|
||||
// context: _context,
|
||||
// zone: zoneData,
|
||||
// mapLayers: _context.MapLayers.Values,
|
||||
// resources: _cache.GetAll<SimpleCommodityData>().Where(i=>i.ResourceDensity.Any()),
|
||||
// orbitData: out orbits,
|
||||
// planetsData: out planets);
|
||||
// _cache.AddAll(orbits);
|
||||
// _cache.AddAll(planets);
|
||||
// zoneData.Visited = true;
|
||||
}
|
||||
|
||||
void PopulateZone()
|
||||
|
|
@ -847,23 +847,15 @@ public class StrategyGameManager : MonoBehaviour
|
|||
foreach (var ship in _zoneShips.Values) Destroy(ship.gameObject);
|
||||
_zoneShips.Clear();
|
||||
|
||||
_populatedZone = _selectedZone;
|
||||
_currentZone = _context.GetZone(_selectedZone);
|
||||
|
||||
var zoneData = _cache.Get<ZoneData>(_populatedZone);
|
||||
|
||||
if (TestMode && !zoneData.Visited)
|
||||
{
|
||||
GenerateZone(_populatedZone);
|
||||
}
|
||||
|
||||
_context.ForceLoadZone = _populatedZone;
|
||||
//_context.ForceLoadZone = _populatedZone;
|
||||
|
||||
float zoneDepth = 0;
|
||||
|
||||
foreach (var planet in _context.ZonePlanets[_populatedZone])
|
||||
foreach (var planetData in _currentZone.Planets.Values)
|
||||
{
|
||||
var planetData = _cache.Get<PlanetData>(planet);
|
||||
if (!planetData.Belt)
|
||||
if (!(planetData is AsteroidBeltData))
|
||||
{
|
||||
var planetObject = Instantiate(ZoneGravityObjectPrefab, ZoneRoot);
|
||||
_zoneGravityObjects[planetData.Orbit] = planetObject;
|
||||
|
|
@ -893,7 +885,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
{
|
||||
var beltObject = Instantiate(BeltPrefab, ZoneRoot);
|
||||
var collider = beltObject.GetComponent<MeshCollider>();
|
||||
var belt = new AsteroidBelt(_context, beltObject, collider, planetData.ID, AsteroidSpritesheetWidth, AsteroidSpritesheetHeight, ZoneSizeScale);
|
||||
var belt = new AsteroidBelt(_context, _currentZone, beltObject, collider, planetData.ID, AsteroidSpritesheetWidth, AsteroidSpritesheetHeight, ZoneSizeScale);
|
||||
_zoneBelts[_cache.Get<OrbitData>(planetData.Orbit).Parent] = belt;
|
||||
beltObject.GetComponent<ClickableCollider>().OnClick += (_, data) =>
|
||||
{
|
||||
|
|
@ -905,17 +897,17 @@ public class StrategyGameManager : MonoBehaviour
|
|||
}
|
||||
}
|
||||
|
||||
var radius = (zoneData.Radius * ZoneSizeScale * 2);
|
||||
var radius = (_currentZone.Data.Radius * ZoneSizeScale * 2);
|
||||
_backgroundMaterial.SetFloat("_ClipDistance", radius);
|
||||
_backgroundMaterial.SetFloat("_HeightRange", zoneDepth + _boundaryMaterial.GetFloat("_Depth"));
|
||||
ZoneBoundary.transform.localScale = Vector3.one * radius;
|
||||
|
||||
foreach (var wormhole in zoneData.Wormholes)
|
||||
foreach (var wormhole in _currentZone.Data.Wormholes)
|
||||
{
|
||||
var otherZone = _context.GalaxyZones[wormhole];
|
||||
var wormholeObject = Instantiate(ZoneGravityObjectPrefab, ZoneRoot);
|
||||
_wormholes.Add(wormholeObject);
|
||||
wormholeObject.transform.position = (Vector2) (_context.WormholePosition(zoneData.ID, wormhole) * ZoneSizeScale);
|
||||
wormholeObject.transform.position = (Vector2) (_currentZone.WormholePosition(wormhole) * ZoneSizeScale);
|
||||
wormholeObject.GravityMesh.gameObject.SetActive(false);
|
||||
wormholeObject.Icon.material.SetTexture("_MainTex", WormholeSprite);
|
||||
wormholeObject.Label.text = otherZone.Name;
|
||||
|
|
@ -949,10 +941,8 @@ public class StrategyGameManager : MonoBehaviour
|
|||
Debug.Log("Expected arguments: Wanderer count, Patroller count, Orbital count!");
|
||||
return;
|
||||
}
|
||||
|
||||
var zoneData = _cache.Get<ZoneData>(_populatedZone);
|
||||
|
||||
if (zoneData == null)
|
||||
if (_currentZone == null)
|
||||
{
|
||||
Debug.Log("Attempted to spawn ship but no zone is populated!");
|
||||
return;
|
||||
|
|
@ -974,7 +964,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
return;
|
||||
}
|
||||
|
||||
colonyList.Add(_context.CreateEntity(_populatedZone, _playerCorporation, loadoutData.ID));
|
||||
colonyList.Add(_context.CreateEntity(_currentZone.Data.ID, _playerCorporation, loadoutData.ID));
|
||||
}
|
||||
|
||||
int wanderers;
|
||||
|
|
@ -992,7 +982,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
return;
|
||||
}
|
||||
|
||||
var entity = _context.CreateEntity(_populatedZone, _playerCorporation, loadoutData.ID);
|
||||
var entity = _context.CreateEntity(_currentZone.Data.ID, _playerCorporation, loadoutData.ID);
|
||||
entity.GetBehaviors<WanderController>().First().WanderTarget = _context.Random.NextFloat() > .5f
|
||||
? WanderTarget.Planets
|
||||
: WanderTarget.Orbitals;
|
||||
|
|
@ -1014,7 +1004,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
return;
|
||||
}
|
||||
|
||||
var entity = _context.CreateEntity(_populatedZone, _playerCorporation, loadoutData.ID);
|
||||
var entity = _context.CreateEntity(_currentZone.Data.ID, _playerCorporation, loadoutData.ID);
|
||||
//_context.SetParent(entity, colonyList[_context.Random.NextInt(colonyList.Count)]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1024,9 +1014,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
if (!TestMode)
|
||||
return;
|
||||
|
||||
var zoneData = _cache.Get<ZoneData>(_populatedZone);
|
||||
|
||||
if (zoneData == null)
|
||||
if (_currentZone == null)
|
||||
{
|
||||
Debug.Log("Attempted to spawn ship but no zone is populated!");
|
||||
return;
|
||||
|
|
@ -1039,7 +1027,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
return;
|
||||
}
|
||||
|
||||
_context.CreateEntity(_populatedZone, _playerCorporation, loadoutData.ID);
|
||||
_context.CreateEntity(_currentZone.Data.ID, _playerCorporation, loadoutData.ID);
|
||||
|
||||
// Parse first argument as hull name, default to Fighter if argument missing
|
||||
// HullData hullData;
|
||||
|
|
@ -1109,15 +1097,14 @@ public class StrategyGameManager : MonoBehaviour
|
|||
return;
|
||||
}
|
||||
|
||||
if(_populatedZone!=Guid.Empty)
|
||||
_context.UnloadZone(_populatedZone);
|
||||
if(_currentZone.Data.ID == zoneData.ID)
|
||||
_context.UnloadZone(_currentZone.Data.ID);
|
||||
_cache.Delete(zoneData);
|
||||
_context.GalaxyZones.Remove(zoneData.ID);
|
||||
|
||||
var newZone = zoneData.Copy();
|
||||
newZone.ID = Guid.NewGuid();
|
||||
newZone.Name = newZone.ID.ToString().Substring(0, 8);
|
||||
newZone.Visited = false;
|
||||
|
||||
var linkedZones = _cache.GetAll<ZoneData>().Where(z => z.Wormholes.Any(w => w == zoneData.ID)).ToArray();
|
||||
foreach (var linkedZone in linkedZones)
|
||||
|
|
@ -1160,7 +1147,7 @@ public class StrategyGameManager : MonoBehaviour
|
|||
_cache.Add(newZone);
|
||||
|
||||
_selectedZone = newZone.ID;
|
||||
_populatedZone = Guid.Empty;
|
||||
_currentZone = null;
|
||||
|
||||
if(_currentTab == ZoneTabButton)
|
||||
PopulateZone();
|
||||
|
|
@ -1182,16 +1169,18 @@ public class AsteroidBelt
|
|||
private Mesh _mesh;
|
||||
private float _zoneScale;
|
||||
private float _size;
|
||||
private Zone _zone;
|
||||
|
||||
public AsteroidBelt(GameContext context, MeshFilter meshFilter, MeshCollider collider, Guid data, int spritesheetWidth, int spritesheetHeight, float zoneScale)
|
||||
public AsteroidBelt(GameContext context, Zone zone, MeshFilter meshFilter, MeshCollider collider, Guid data, int spritesheetWidth, int spritesheetHeight, float zoneScale)
|
||||
{
|
||||
Transform = collider.transform;
|
||||
_context = context;
|
||||
_zone = zone;
|
||||
_data = data;
|
||||
_filter = meshFilter;
|
||||
_collider = collider;
|
||||
_zoneScale = zoneScale;
|
||||
var planetData = context.Cache.Get<PlanetData>(data);
|
||||
var planetData = context.Cache.Get<AsteroidBeltData>(data);
|
||||
var orbitData = context.Cache.Get<OrbitData>(planetData.Orbit);
|
||||
_orbit = orbitData.Parent;
|
||||
_vertices = new Vector3[planetData.Asteroids.Length*4];
|
||||
|
|
@ -1241,8 +1230,8 @@ public class AsteroidBelt
|
|||
|
||||
public void Update()
|
||||
{
|
||||
var planetData = _context.Cache.Get<PlanetData>(_data);
|
||||
var asteroidTransforms = _context.GetAsteroidTransforms(_data);
|
||||
var planetData = _context.Cache.Get<AsteroidBeltData>(_data);
|
||||
var asteroidTransforms = _zone.GetAsteroidTransforms(_data);
|
||||
for (var i = 0; i < planetData.Asteroids.Length; i++)
|
||||
{
|
||||
var rotation = Quaternion.Euler(0, 0, asteroidTransforms[i].z);
|
||||
|
|
@ -1253,7 +1242,7 @@ public class AsteroidBelt
|
|||
_vertices[i * 4 + 3] = rotation * new Vector3(asteroidTransforms[i].w * _zoneScale,-asteroidTransforms[i].w * _zoneScale,0) + position;
|
||||
}
|
||||
|
||||
_mesh.bounds = new Bounds((Vector2) _context.GetOrbitPosition(_orbit) * _zoneScale, Vector3.one * (_size * _zoneScale * 2));
|
||||
_mesh.bounds = new Bounds((Vector2) _zone.GetOrbitPosition(_orbit) * _zoneScale, Vector3.one * (_size * _zoneScale * 2));
|
||||
_mesh.vertices = _vertices;
|
||||
_collider.sharedMesh = _mesh;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -265,7 +265,7 @@ public class ColonyTab : MonoBehaviour
|
|||
Origin = entity.ID,
|
||||
Quantity = quantity,
|
||||
Target = colonies[selectedColony].ID,
|
||||
Zone = entity.Zone
|
||||
Zone = entity.Zone.Data.ID
|
||||
};
|
||||
Context.Cache.Add(haulingTask);
|
||||
var corp = Context.Cache.Get<Corporation>(entity.Corporation);
|
||||
|
|
|
|||
|
|
@ -83,4 +83,7 @@ public static class UnityExtensions
|
|||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Vector3 Flatland(this Vector2 v) => new Vector3(v.x,0,v.y);
|
||||
public static Vector2 Flatland(this Vector3 v) => new Vector2(v.x,v.z);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue