-
-
Save kawashirov/71fb0a3d8abe62206db87807c7ea0397 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using System.Linq; | |
using System; | |
#if UNITY_EDITOR | |
using UnityEditor; | |
#endif | |
[ExecuteInEditMode] | |
public class DistanceMetrics : MonoBehaviour | |
{ | |
#if UNITY_EDITOR | |
[CustomEditor(typeof(DistanceMetrics))] | |
[CanEditMultipleObjects] | |
public class DistanceMetricsEditor : Editor | |
{ | |
public override void OnInspectorGUI() | |
{ | |
base.DrawDefaultInspector(); | |
if (GUILayout.Button("Update distance")) | |
{ | |
foreach (var x in this.targets.Cast<DistanceMetrics>().Where(x => x != null)) | |
x.UpdateDistance(); | |
} | |
} | |
} | |
#endif | |
public float avgValue; | |
public float minValue; | |
public float maxValue; | |
private Texture2D reader; | |
private void Awake() | |
{ | |
avgValue = 0; | |
minValue = 0; | |
maxValue = 0; | |
} | |
void UpdateDistance() | |
{ | |
Debug.Log("UpdateDistance"); | |
var cam = this.GetComponent<Camera>(); | |
cam.Render(); | |
var rt = cam.targetTexture; | |
if (reader == null || reader.width != rt.width || reader.height != rt.height) | |
{ | |
reader = new Texture2D(rt.width, rt.height, TextureFormat.R16, false); | |
} | |
var prev_active = RenderTexture.active; | |
try | |
{ | |
RenderTexture.active = rt; | |
reader.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); | |
reader.Apply(); | |
} | |
finally | |
{ | |
RenderTexture.active = prev_active; | |
} | |
double avg = 0; | |
float min = float.MaxValue, max = float.MinValue; | |
var c = 0; | |
foreach (var color in reader.GetPixels(0, 0, reader.width, reader.height)) | |
{ | |
var v = color.r; | |
min = Mathf.Min(min, v); | |
max = Mathf.Max(max, v); | |
avg += v; | |
++c; | |
} | |
avgValue = (float) (avg / c); | |
minValue = min; | |
maxValue = max; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment