using System; using UnityEngine; namespace Rigging.Debugging { public class GLScope : IDisposable { bool bScopeBefore; public GLScope(bool enabled) { bScopeBefore = GLHandle.bScopeEnabled; GLHandle.EnterScope(enabled); } public void Dispose() { GLHandle.EndScope(bScopeBefore); } } [DefaultExecutionOrder(-100)] public class GLHandle : MonoBehaviour { private static GLHandle instance; private static event System.Action onGL; private static event System.Action onGLFixedUpdate; private static Material lineMaterial; public static bool bScopeEnabled; static GLHandle() { bScopeEnabled = true; } static void CreateLineMaterial() { if (!lineMaterial) { // Unity has a built-in shader that is useful for drawing // simple colored things. Shader shader = Shader.Find("Hidden/Internal-Colored"); lineMaterial = new Material(shader); lineMaterial.hideFlags = HideFlags.HideAndDontSave; // Turn on alpha blending lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); // Turn backface culling off lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off); // Turn off depth writes lineMaterial.SetInt("_ZWrite", 0); lineMaterial.SetInt("_ZTest", 0); } } private void FixedUpdate() { onGLFixedUpdate = null; } public void OnRenderObject() { CreateLineMaterial(); // Apply the line material lineMaterial.SetPass(0); onGL?.Invoke(); onGL = null; onGLFixedUpdate?.Invoke(); } static void Check() { if(instance == null) { GameObject gl = new GameObject(); gl.name = "GLHandle"; instance = gl.AddComponent(); } } public static void EnterScope(bool enabled = true) { bScopeEnabled = enabled; } public static void EndScope(bool enabled = true) { bScopeEnabled = true; } public static void DrawSphere(Vector3 pos, float radius, int verticalSegments = 1, int radialSegments = 2) { Check(); if (!bScopeEnabled) return; if(Time.inFixedTimeStep) { onGLFixedUpdate += () => { Draw.Sphere(pos, radius, verticalSegments, radialSegments); }; } else { onGL += () => { Draw.Sphere(pos, radius, verticalSegments, radialSegments); }; } } public static void DrawLine(Vector3 p1, Vector3 p2) { Check(); if (!bScopeEnabled) return; if (Time.inFixedTimeStep) { onGLFixedUpdate += () => { Draw.Line3D(p1, p2); }; } else { onGL += () => { Draw.Line3D(p1, p2); }; } } } }