Trailer Stuff & More

Changed title font to Montserrat
Added trailer-specific camera transitions
Added key to hide UI
Fixed input listening while console is open
Added animated zone reveal effect in galaxy map
Added Ping action for sensors
Added debug console commands (e.g. give command to get any item in legendary+ quality)
Temporarily disabled wwise
Fixed infinite loop in weapon penetration code
Guided missiles now predict target position
Fixed hitscan weapons
Fixed invisible enemies bug
Fixed various loadout generator issues (can now generate turrets!)
Fixed wormhole crash when enemy is targeted
Saving/loading current zone time when exiting game (planets keep their positions)
Created slime simulation in test scene - WIP
This commit is contained in:
Reinier Vens 2021-03-27 10:03:24 +00:00
commit 11a9365f91
108 changed files with 10049 additions and 856 deletions

View file

@ -0,0 +1,34 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
[ExecuteInEditMode]
public class BlueNoiseProvider : MonoBehaviour
{
public Texture2D NoiseTexture;
private Camera _camera;
private 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
));
}
}

View file

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

View file

@ -0,0 +1,51 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.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);
}
}
}

View file

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

View file

@ -0,0 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GasGiantObject : PlanetObject
{
public SunMaterial SunMaterial;
public MeshRenderer GravityWaves;
}

View file

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

View file

@ -0,0 +1,123 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.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

View file

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

View file

@ -0,0 +1,22 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.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;
}
}

View file

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

View file

@ -0,0 +1,111 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Serialization;
public class MapView : MonoBehaviour
{
public Camera Main;
public Camera MinimapGravity;
public Camera Minimap;
public MeshRenderer GravityRenderer;
public float ZoomSpeed;
[FormerlySerializedAs("SectorRenderer")] public ZoneRenderer ZoneRenderer;
private Transform _minimapTransform;
private CopyTransform _minimapCopyTransform;
private RenderTexture _minimapTexture;
private Transform _minimapGravityTransform;
private CopyTransform _minimapGravityCopyTransform;
private RenderTexture _minimapGravityTexture;
private Transform _gravityRendererTransform;
private CopyTransform _gravityRendererCopyTransform;
private RenderTexture _fullscreenGravityTexture;
private AetheriaInput.UIActions _input;
private float _viewDistance = 1024;
private float _aspectRatio;
private Vector3 _previousGravityRendererScale;
void OnEnable()
{
_aspectRatio = (float) Screen.width / Screen.height;
Main.gameObject.SetActive(false);
_minimapTexture = Minimap.targetTexture;
_minimapTransform = Minimap.transform;
_minimapCopyTransform = Minimap.GetComponent<CopyTransform>();
_minimapCopyTransform.enabled = false;
_minimapGravityTexture = MinimapGravity.targetTexture;
_minimapGravityTransform = MinimapGravity.transform;
_minimapGravityCopyTransform = MinimapGravity.GetComponent<CopyTransform>();
_minimapGravityCopyTransform.enabled = false;
_gravityRendererTransform = GravityRenderer.transform;
_gravityRendererCopyTransform = GravityRenderer.GetComponent<CopyTransform>();
_gravityRendererCopyTransform.enabled = false;
_previousGravityRendererScale = _gravityRendererTransform.localScale;
_fullscreenGravityTexture = new RenderTexture(Screen.width / 2, Screen.height / 2, 1, RenderTextureFormat.RFloat);
GravityRenderer.material.mainTexture = _fullscreenGravityTexture;
MinimapGravity.targetTexture = _fullscreenGravityTexture;
Minimap.targetTexture = null;
SetZoom();
}
void SetZoom()
{
ZoneRenderer.ViewDistance = _viewDistance * _aspectRatio;
Minimap.orthographicSize = MinimapGravity.orthographicSize = _viewDistance;
_gravityRendererTransform.localScale = new Vector3(_viewDistance*_aspectRatio*2, _viewDistance*2, 1);
}
public void BindInput(AetheriaInput.UIActions input)
{
_input = input;
_input.ScrollWheel.performed += OnScroll;
}
private void OnScroll(InputAction.CallbackContext context)
{
_viewDistance *= (1 - context.ReadValue<Vector2>().y * ZoomSpeed);
SetZoom();
}
void Update()
{
if (_input.Click.ReadValue<float>() > .5f)
{
var delta = _input.Drag.ReadValue<Vector2>();
var pos = _minimapTransform.position;
pos.x -= delta.x * _viewDistance / Screen.height;
pos.z -= delta.y * _viewDistance / Screen.height;
var gravPos = _gravityRendererTransform.position;
gravPos.x = pos.x;
gravPos.z = pos.z;
_gravityRendererTransform.position = gravPos;
Main.transform.position = _minimapTransform.position = _minimapGravityTransform.position = pos;
}
}
private void OnDisable()
{
_input.ScrollWheel.performed -= OnScroll;
Main.gameObject.SetActive(true);
_minimapGravityCopyTransform.enabled = true;
_minimapCopyTransform.enabled = true;
_gravityRendererCopyTransform.enabled = true;
Minimap.targetTexture = _minimapTexture;
MinimapGravity.targetTexture = _minimapGravityTexture;
GravityRenderer.material.mainTexture = _minimapGravityTexture;
_fullscreenGravityTexture.Release();
}
}

View file

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

View file

@ -0,0 +1,15 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlanetObject : MonoBehaviour
{
public MeshRenderer Body;
public MeshRenderer GravityWell;
public MeshRenderer Icon;
public CelestialBodyGenerator Generator;
}

View file

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

View file

@ -0,0 +1,49 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.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);
}
}
}

View file

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

View file

@ -0,0 +1,72 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Unity.Mathematics.math;
//[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;
}
public void ApplyGradient(Gradient gradient)
{
var tex = gradient.ToTexture();
if (_material.HasProperty("_ColorRamp"))
{
_material.SetTexture("_ColorRamp", tex);
}
}
private void OnWillRenderObject()
{
_firstOffsetDomainRotation += FirstOffsetDomainRotationSpeed * SpeedMultiplier * Time.deltaTime;
_firstOffsetRotation += FirstOffsetRotationSpeed * SpeedMultiplier * Time.deltaTime;
_secondOffsetDomainRotation += SecondOffsetDomainRotationSpeed * SpeedMultiplier * Time.deltaTime;
_secondOffsetRotation += SecondOffsetRotationSpeed * SpeedMultiplier * Time.deltaTime;
_albedoRotation += AlbedoRotationSpeed * SpeedMultiplier * Time.deltaTime;
_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));
}
}

View file

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

View file

@ -0,0 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SunObject : GasGiantObject
{
public MeshRenderer FogTint;
public Light Light;
}

View file

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

View file

@ -0,0 +1,48 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using UnityEngine;
using Unity.Mathematics;
using UnityEngine.Experimental.Rendering;
using static Unity.Mathematics.math;
using static Unity.Mathematics.noise;
/// <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);
_volMaterial.SetMatrix("_CamInvProj", (_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));
Graphics.Blit( source, destination, _volMaterial, 0 );
}
}

View file

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

View file

@ -0,0 +1,24 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.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.time*Speed);
}
}

View file

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

View file

@ -0,0 +1,564 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Cinemachine;
using UniRx;
using UnityEngine;
using UnityEngine.Serialization;
using Object = UnityEngine.Object;
using Random = UnityEngine.Random;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
public class ZoneRenderer : MonoBehaviour
{
public Transform WormholePrefab;
public float EntityFadeTime;
public Transform FogCameraParent;
public GameSettings Settings;
public Transform ZoneRoot;
public Transform SectorBrushes;
public MeshRenderer SectorBoundaryBrush;
public CinemachineVirtualCamera SceneCamera;
public Camera[] FogCameras;
public Camera[] MinimapCameras;
public Material FogMaterial;
public float FogFarFadeFraction = .125f;
public float FarPlaneDistanceMultiplier = 2;
public InstancedMesh[] AsteroidMeshes;
public int AsteroidSpritesheetWidth = 4;
public int AsteroidSpritesheetHeight = 4;
public LODHandler LODHandler;
public Slime SlimeRenderer;
public Camera SlimeGravityCamera;
[Header("Tour")]
public bool Tour;
public float TourSwitchTime = 5f;
public float TourFollowDistance = 30f;
public float TourHeightOffset = 15;
public float TourFollowOffsetDegrees;
// public Mesh[] AsteroidMeshes;
// public Material AsteroidMaterial;
[Header("Prefabs")]
public MeshFilter AsteroidBeltUI;
public PlanetObject Planet;
public GasGiantObject GasGiant;
public SunObject Sun;
[Header("Icons")]
public Texture2D PlanetoidIcon;
public Texture2D PlanetIcon;
[HideInInspector]
public Dictionary<Entity, EntityInstance> EntityInstances = new Dictionary<Entity, EntityInstance>();
[HideInInspector]
public Dictionary<Guid, PlanetObject> Planets = new Dictionary<Guid, PlanetObject>();
private Dictionary<Guid, AsteroidBeltUI> _beltObjects = new Dictionary<Guid, AsteroidBeltUI>();
private Dictionary<Guid, InstancedMesh[]> _beltMeshes = new Dictionary<Guid, InstancedMesh[]>();
private Dictionary<Guid, Matrix4x4[][]> _beltMatrices = new Dictionary<Guid, Matrix4x4[][]>();
private float _viewDistance;
private float _maxDepth;
private int _tourIndex = -1;
private float _tourTimer;
private List<(Transform, Transform)> _tourPlanets = new List<(Transform, Transform)>();
private CinemachineTransposer _transposer;
private PlanetObject _root;
private bool _rootFound;
private Entity _perspectiveEntity;
private IDisposable[] _perspectiveSubscriptions = new IDisposable[2];
private List<IDisposable> _zoneSubscriptions = new List<IDisposable>();
public Dictionary<Wormhole, GameObject> WormholeInstances = new Dictionary<Wormhole, GameObject>();
public Zone Zone { get; private set; }
public ItemManager ItemManager { get; set; }
public Entity PerspectiveEntity
{
get => _perspectiveEntity;
set
{
//if (_perspectiveEntity == value) return;
_perspectiveEntity = value;
_perspectiveSubscriptions[0]?.Dispose();
_perspectiveSubscriptions[1]?.Dispose();
if (value == null)
{
foreach (var e in EntityInstances.Values)
e.FadeOut(EntityFadeTime);
}
else
{
foreach(var entity in EntityInstances.Values)
entity.FadeOut(EntityFadeTime);
foreach(var entity in value.VisibleEntities)
EntityInstances[entity].FadeIn(EntityFadeTime);
EntityInstances[value].FadeIn(EntityFadeTime);
_perspectiveSubscriptions[0] = value.VisibleEntities.ObserveAdd()
.Subscribe(add => EntityInstances[add.Value].FadeIn(EntityFadeTime));
_perspectiveSubscriptions[1] = value.VisibleEntities.ObserveRemove()
.Where(removeEvent => EntityInstances.ContainsKey(removeEvent.Value))
.Subscribe(removeEvent => EntityInstances[removeEvent.Value].FadeOut(EntityFadeTime));
}
}
}
public float ViewDistance
{
set
{
_viewDistance = value;
foreach (var camera in FogCameras)
camera.orthographicSize = value;
SceneCamera.m_Lens.FarClipPlane = value * FarPlaneDistanceMultiplier;
FogMaterial.SetFloat("_DepthCeiling", value);
FogMaterial.SetFloat("_DepthBlend", FogFarFadeFraction * value);
}
}
public float MinimapDistance
{
set
{
foreach(var camera in MinimapCameras)
camera.orthographicSize = value;
// MinimapGravityQuad.transform.localScale = value * 2 * Vector3.one;
}
}
void Start()
{
ViewDistance = Settings.DefaultViewDistance;
MinimapDistance = Settings.MinimapZoomLevels[Settings.DefaultMinimapZoom];
_tourTimer = TourSwitchTime;
_transposer = SceneCamera.GetCinemachineComponent<CinemachineTransposer>();
}
public void LoadZone(Zone zone)
{
ClearZone();
_maxDepth = 0;
Zone = zone;
SectorBrushes.localScale = zone.Pack.Radius * 2 * Vector3.one;
SlimeGravityCamera.orthographicSize = zone.Pack.Radius;
SlimeRenderer.ZoneRadius = zone.Pack.Radius;
foreach(var p in zone.Planets.Values)
LoadPlanet(p);
foreach (var x in Planets)
{
if (!(zone.Planets[x.Key] is GasGiantData))
{
var parentOrbit = Zone.Orbits[Zone.Planets[x.Key].Orbit].Data.Parent;
PlanetObject parent;
if (parentOrbit == Guid.Empty)
parent = _root;
else
{
var parentPlanetData = Zone.Planets.Values.FirstOrDefault(p => p.Orbit == parentOrbit);
if(parentPlanetData == null)
{
parentOrbit = Zone.Orbits[parentOrbit].Data.Parent;
parentPlanetData = Zone.Planets.Values.FirstOrDefault(p => p.Orbit == parentOrbit);
}
if (parentPlanetData == null)
parent = _root;
else if (!Planets.TryGetValue(parentPlanetData.ID, out parent))
{
Debug.Log("WTF!");
}
}
//_tourPlanets.Add((x.Value.Body.transform, parent.Body.transform));
}
}
foreach(var entity in zone.Entities)
{
Debug.Log($"Loading entity {entity.Name} from existing zone entity collection");
LoadEntity(entity);
}
_zoneSubscriptions.Add(zone.Entities.ObserveAdd().Subscribe(e =>
{
//Debug.Log($"Loading entity {e.Value.Name} from zone add event");
LoadEntity(e.Value);
}));
_zoneSubscriptions.Add(zone.Entities.ObserveRemove().Subscribe(e =>
{
//Debug.Log($"Unloading entity {e.Value.Name} from zone remove event");
UnloadEntity(e.Value);
}));
if(zone.SectorZone != null)
{
foreach (var adjacentZone in zone.SectorZone.AdjacentZones)
{
var dir = normalize(adjacentZone.Position - zone.SectorZone.Position);
AddWormhole(new Wormhole
{
Target = adjacentZone,
Position = dir * zone.Pack.Radius * Settings.WormholeDistanceRatio
});
}
}
}
public void AddWormhole(Wormhole wormhole)
{
var instance = Instantiate(WormholePrefab);
instance.position = new Vector3(wormhole.Position.x, 0, wormhole.Position.y);
WormholeInstances.Add(wormhole, instance.gameObject);
}
public void ClearZone()
{
if (Zone == null) return;
foreach (var wormhole in WormholeInstances.Values) Destroy(wormhole);
WormholeInstances.Clear();
foreach(var subscription in _zoneSubscriptions)
subscription.Dispose();
_zoneSubscriptions.Clear();
foreach (var entity in Zone.Entities)
{
Debug.Log($"Unloading entity {entity.Name} from entities remaining during clear!");
UnloadEntity(entity);
}
if (Planets.Count > 0)
{
foreach (var planet in Planets.Values)
{
DestroyImmediate(planet.gameObject);
}
Planets.Clear();
foreach (var beltObject in _beltObjects.Values)
{
Destroy(beltObject.Filter);
}
_beltObjects.Clear();
_beltMeshes.Clear();
_beltMatrices.Clear();
_tourPlanets.Clear();
}
}
void LoadEntity(Entity entity)
{
var hullData = ItemManager.GetData(entity.Hull) as HullData;
EntityInstance instance;
if (entity is Ship)
{
instance = Instantiate(UnityHelpers.LoadAsset<GameObject>(hullData.Prefab), ZoneRoot).GetComponent<ShipInstance>();
if (instance == null)
{
ItemManager.Log($"Failed to instantiate {hullData.Name} ship with invalid prefab: no ShipInstance component!");
return;
}
}
else
{
instance = Instantiate(UnityHelpers.LoadAsset<GameObject>(hullData.Prefab), ZoneRoot).GetComponent<EntityInstance>();
if (instance == null)
{
ItemManager.Log($"Failed to instantiate {hullData.Name} entity with invalid prefab: no EntityInstance component!");
return;
}
}
instance.SetEntity(this, entity);
EntityInstances.Add(entity, instance);
}
public void UnloadEntity(Entity entity)
{
foreach (var item in entity.Equipment)
{
foreach (var behavior in item.Behaviors)
{
if(behavior is IEventBehavior eventBehavior)
eventBehavior.ResetEvents();
}
}
Destroy(EntityInstances[entity].gameObject);
EntityInstances.Remove(entity);
}
void LoadPlanet(BodyData planetData)
{
if (planetData is AsteroidBeltData beltData)
{
var meshes = AsteroidMeshes.ToList();
while(meshes.Count > Settings.AsteroidMeshCount)
meshes.RemoveAt(Random.Range(0,meshes.Count));
_beltMeshes[planetData.ID] = meshes.ToArray();
_beltMatrices[planetData.ID] = new Matrix4x4[meshes.Count][];
var count = beltData.Asteroids.Length / meshes.Count;
var remainder = beltData.Asteroids.Length - count * meshes.Count;
for (int i = 0; i < meshes.Count; i++)
{
_beltMatrices[planetData.ID][i] = new Matrix4x4[i<meshes.Count-1 ? count : count+remainder];
}
var beltObject = Instantiate(AsteroidBeltUI, ZoneRoot);
var collider = beltObject.GetComponent<MeshCollider>();
var belt = new AsteroidBeltUI(Zone, Zone.AsteroidBelts[beltData.ID], beltObject, collider, AsteroidSpritesheetWidth, AsteroidSpritesheetHeight, Settings.MinimapAsteroidSize);
_beltObjects[beltData.ID] = belt;
}
else
{
PlanetObject planet;
if (planetData is GasGiantData gasGiantData)
{
if (planetData is SunData sunData)
{
planet = Instantiate(Sun, ZoneRoot);
var sun = (SunObject) planet;
sunData.LightColor.Subscribe(c => sun.Light.color = c.ToColor());
sunData.Mass.Subscribe(m => sun.Light.range = Settings.PlanetSettings.LightRadius.Evaluate(m));
sunData.FogTintColor.Subscribe(c => sun.FogTint.material.SetColor("_Color", c.ToColor()));
sunData.Mass.Subscribe(m => sun.FogTint.transform.localScale = Settings.PlanetSettings.FogTintRadius.Evaluate(m) * Vector3.one);
}
else planet = Instantiate(GasGiant, ZoneRoot);
var gas = (GasGiantObject) planet;
var gasGiant = Zone.PlanetInstances[planetData.ID] as GasGiant;
gasGiantData.Colors.Subscribe(c => gas.Body.material.SetTexture("_ColorRamp", c.ToGradient(!(planetData is SunData)).ToTexture()));
gasGiantData.AlbedoRotationSpeed.Subscribe(f => gas.SunMaterial.AlbedoRotationSpeed = f);
gasGiantData.FirstOffsetRotationSpeed.Subscribe(f => gas.SunMaterial.FirstOffsetRotationSpeed = f);
gasGiantData.SecondOffsetRotationSpeed.Subscribe(f => gas.SunMaterial.SecondOffsetRotationSpeed = f);
gasGiantData.FirstOffsetDomainRotationSpeed.Subscribe(f => gas.SunMaterial.FirstOffsetDomainRotationSpeed = f);
gasGiantData.SecondOffsetDomainRotationSpeed.Subscribe(f => gas.SunMaterial.SecondOffsetDomainRotationSpeed = f);
gasGiant.GravityWavesRadius.Subscribe(f => gas.GravityWaves.transform.localScale = f * Vector3.one);
gasGiant.GravityWavesDepth.Subscribe(f => gas.GravityWaves.material.SetFloat("_Depth", f));
planetData.Mass.Subscribe(f => gas.GravityWaves.material.SetFloat("_Frequency", Settings.PlanetSettings.WaveFrequency.Evaluate(f)));
//gas.WaveScroll.Speed = Properties.GravitySettings.WaveSpeed.Evaluate(f);
}
else
{
planet = Instantiate(Planet, ZoneRoot);
var possibleSettings = Settings.BodySettingsCollections
.Where(p => p.MinimumMass < planetData.Mass.Value)
.MaxBy(p => p.MinimumMass).BodySettings;
planet.Generator.body = possibleSettings[Random.Range(0, possibleSettings.Length)];
//Debug.Log($"Generating planet with {planetData.Mass} mass! Choosing {planet.Generator.body.name} settings!");
//planet.Icon.material.mainTexture = planetData.Mass > Context.GlobalData.PlanetMass ? PlanetIcon : PlanetoidIcon;
}
var planetInstance = Zone.PlanetInstances[planetData.ID];
planetInstance.BodyRadius.Subscribe(f =>
{
planet.Body.transform.localScale = f * Vector3.one;
});
planetInstance.GravityWellRadius.Subscribe(f => planet.GravityWell.transform.localScale = f * Vector3.one);
planetInstance.GravityWellDepth.Subscribe(f =>
{
if (f > _maxDepth) _maxDepth = f;
planet.GravityWell.material.SetFloat("_Depth", f);
planet.Icon.transform.position = new Vector3(0, -f, 0);
});
planetInstance.BodyData.Mass.Subscribe(f => planet.Icon.transform.localScale = Settings.IconSize.Evaluate(f) * Vector3.one);
Planets[planetData.ID] = planet;
if (!_rootFound)
{
_rootFound = true;
_root = planet;
}
}
LODHandler.FindPlanets();
}
// private void Update()
// {
// if (Tour)
// {
// _tourTimer -= UnityEngine.Time.deltaTime;
// if (_tourTimer < 0)
// {
// _tourTimer = TourSwitchTime;
// _tourIndex = (_tourIndex + 1) % _tourPlanets.Count;
// SceneCamera.Follow = _tourPlanets[_tourIndex].Item1;
// SceneCamera.LookAt = _tourPlanets[_tourIndex].Item2;
// if(_tourIndex==0) Debug.Log("Tour Complete!");
// }
// // if(_tourIndex>=0)
// // {
// // var offset = (SceneCamera.Follow.position - SceneCamera.LookAt.position);
// // offset.y = 0;
// // offset = offset.normalized * TourFollowDistance;
// // offset.y = TourHeightOffset;
// // offset = Quaternion.AngleAxis(TourFollowOffsetDegrees, Vector3.up) * offset;
// // _transposer.m_FollowOffset = offset;
// // }
// }
// }
void Update()
{
foreach(var belt in Zone.AsteroidBelts)
{
var meshes = _beltMeshes[belt.Key];
var count = belt.Value.Positions.Length / meshes.Length;
for (int i = 0; i < meshes.Length; i++)
{
for (int t = 0; t < _beltMatrices[belt.Key][i].Length; t++)
{
var tx = t + i * count;
_beltMatrices[belt.Key][i][t] = Matrix4x4.TRS(belt.Value.Positions[tx],
Quaternion.Euler(
cos(belt.Value.Rotations[tx] + (float) i / meshes.Length) * 100,
sin(belt.Value.Rotations[tx] + (float) i / meshes.Length) * 100,
(float) tx / belt.Value.Positions.Length * 360),
Vector3.one * belt.Value.Scales[tx]);
}
Graphics.DrawMeshInstanced(meshes[i].Mesh, 0, meshes[i].Material, _beltMatrices[belt.Key][i]);
}
_beltObjects[belt.Key].Update(belt.Value.Positions);
}
foreach (var planet in Planets)
{
var planetInstance = Zone.PlanetInstances[planet.Key];
var p = Zone.GetOrbitPosition(planetInstance.BodyData.Orbit);
planet.Value.transform.position = new Vector3(p.x, 0, p.y);
planet.Value.Body.transform.localPosition = new Vector3(0, Zone.GetHeight(p) + planetInstance.BodyRadius.Value * 2, 0);
if(planet.Value is GasGiantObject gasGiantObject)
{
gasGiantObject.GravityWaves.material.SetFloat("_Phase", Zone.Time * ((GasGiant) Zone.PlanetInstances[planet.Key]).GravityWavesSpeed.Value);
if(!(planet.Value is SunObject))
{
var toParent = normalize(Zone.GetOrbitPosition(Zone.Orbits[planetInstance.BodyData.Orbit].Data.Parent) - p);
gasGiantObject.SunMaterial.LightingDirection = new Vector3(toParent.x, 0, toParent.y);
}
}
else planet.Value.Body.transform.rotation *= Quaternion.AngleAxis(Settings.PlanetRotationSpeed, Vector3.up);
}
var fogPos = FogCameraParent.position;
SectorBoundaryBrush.material.SetFloat("_Power", Settings.PlanetSettings.ZoneDepthExponent);
SectorBoundaryBrush.material.SetFloat("_Depth", Settings.PlanetSettings.ZoneDepth + Settings.PlanetSettings.ZoneBoundaryFog);
var startDepth = Zone.PowerPulse(Settings.MinimapZoneGravityRange, Settings.PlanetSettings.ZoneDepthExponent) * Settings.PlanetSettings.ZoneDepth;
var depthRange = Settings.PlanetSettings.ZoneDepth - startDepth + _maxDepth;
// MinimapGravityQuad.material.SetFloat("_StartDepth", startDepth);
// MinimapGravityQuad.material.SetFloat("_DepthRange", depthRange);
FogMaterial.SetFloat("_GridOffset", Settings.PlanetSettings.ZoneBoundaryFog);
FogMaterial.SetVector("_GridTransform", new Vector4(fogPos.x,fogPos.z,_viewDistance*2));
// var gravPos = MinimapGravityQuad.transform.position;
// gravPos.y = -Settings.PlanetSettings.ZoneDepth - _maxDepth;
// MinimapGravityQuad.transform.position = gravPos;
// MinimapTintQuad.transform.position = gravPos - Vector3.up*10;
}
}
[Serializable]
public class InstancedMesh
{
public Mesh Mesh;
public Material Material;
}
public class AsteroidBeltUI
{
public MeshFilter Filter;
private MeshCollider _collider;
private Vector3[] _vertices;
private Vector3[] _normals;
private Vector2[] _uvs;
private int[] _indices;
private Guid _orbitParent;
private Mesh _mesh;
private float _size;
private Zone _zone;
private AsteroidBelt _belt;
private float _scale;
public AsteroidBeltUI(Zone zone, AsteroidBelt belt, MeshFilter meshFilter, MeshCollider collider, int spritesheetWidth, int spritesheetHeight, float scale)
{
_belt = belt;
_zone = zone;
Filter = meshFilter;
_collider = collider;
var orbit = zone.Orbits[belt.Data.Orbit];
_orbitParent = orbit.Data.Parent;
_vertices = new Vector3[_belt.Data.Asteroids.Length*4];
_normals = new Vector3[_belt.Data.Asteroids.Length*4];
_uvs = new Vector2[_belt.Data.Asteroids.Length*4];
_indices = new int[_belt.Data.Asteroids.Length*6];
_scale = scale;
var maxDist = 0f;
var spriteSize = float2(1f / spritesheetWidth, 1f / spritesheetHeight);
// vertex order: bottom left, top left, top right, bottom right
for (var i = 0; i < belt.Data.Asteroids.Length; i++)
{
if (belt.Data.Asteroids[i].Distance > maxDist)
maxDist = belt.Data.Asteroids[i].Distance;
var spriteX = Random.Range(0, spritesheetWidth);
var spriteY = Random.Range(0, spritesheetHeight);
_uvs[i * 4] = new Vector2(spriteX * spriteSize.x, spriteY * spriteSize.y);
_uvs[i * 4 + 1] = new Vector2(spriteX * spriteSize.x, spriteY * spriteSize.y + spriteSize.y);
_uvs[i * 4 + 2] = new Vector2(spriteX * spriteSize.x + spriteSize.x, spriteY * spriteSize.y + spriteSize.y);
_uvs[i * 4 + 3] = new Vector2(spriteX * spriteSize.x + spriteSize.x, spriteY * spriteSize.y);
_indices[i * 6] = i * 4;
_indices[i * 6 + 1] = i * 4 + 1;
_indices[i * 6 + 2] = i * 4 + 3;
_indices[i * 6 + 3] = i * 4 + 3;
_indices[i * 6 + 4] = i * 4 + 1;
_indices[i * 6 + 5] = i * 4 + 2;
}
for (var i = 0; i < _normals.Length; i++)
{
_normals[i] = -Vector3.forward;
}
_mesh = new Mesh();
_mesh.vertices = _vertices;
_mesh.uv = _uvs;
_mesh.triangles = _indices;
_mesh.normals = _normals;
_mesh.bounds = new Bounds(Vector3.zero, Vector3.one * maxDist);
_size = maxDist;
Filter.mesh = _mesh;
//_collider.sharedMesh = _mesh;
}
public void Update(float3[] positions)
{
var parentPosition = _zone.GetOrbitPosition(_orbitParent);
for (var i = 0; i < _belt.Data.Asteroids.Length; i++)
{
var rotation = Quaternion.Euler(90, _belt.Rotations[i], 0);
//var position = new Vector3(_belt.Transforms[i].x, _zone.GetHeight(parentPosition), _belt.Transforms[i].y);
_vertices[i * 4] = rotation * new Vector3(-_belt.Scales[i] * _scale,-_belt.Scales[i] * _scale,0) + (Vector3) positions[i];
_vertices[i * 4 + 1] = rotation * new Vector3(-_belt.Scales[i] * _scale,_belt.Scales[i] * _scale,0) + (Vector3) positions[i];
_vertices[i * 4 + 2] = rotation * new Vector3(_belt.Scales[i] * _scale,_belt.Scales[i] * _scale,0) + (Vector3) positions[i];
_vertices[i * 4 + 3] = rotation * new Vector3(_belt.Scales[i] * _scale,-_belt.Scales[i] * _scale,0) + (Vector3) positions[i];
}
_mesh.bounds = new Bounds(new Vector3(parentPosition.x, 0, parentPosition.y), Vector3.one * (_size * 2));
_mesh.vertices = _vertices;
//_collider.sharedMesh = _mesh;
}
}

View file

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