This commit is contained in:
2025-11-29 18:20:47 +08:00
parent a4d6eb6605
commit 455c13a678
1946 changed files with 150035 additions and 133 deletions

View File

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

View File

@@ -0,0 +1,21 @@
using System;
using System.Reflection;
namespace IngameDebugConsole
{
public abstract class ConsoleAttribute : Attribute
{
public MethodInfo Method { get; private set; }
public abstract int Order { get; }
public void SetMethod(MethodInfo method)
{
if (Method != null)
throw new Exception("Method was already initialized.");
Method = method;
}
public abstract void Load();
}
}

View File

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

View File

@@ -0,0 +1,24 @@
using System;
namespace IngameDebugConsole
{
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public class ConsoleCustomTypeParserAttribute : ConsoleAttribute
{
public readonly Type type;
public readonly string readableName;
public override int Order { get { return 0; } }
public ConsoleCustomTypeParserAttribute(Type type, string readableName = null)
{
this.type = type;
this.readableName = readableName;
}
public override void Load()
{
DebugLogConsole.AddCustomParameterType(type, (DebugLogConsole.ParseFunction)Delegate.CreateDelegate(typeof(DebugLogConsole.ParseFunction), Method), readableName);
}
}
}

View File

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

View File

@@ -0,0 +1,30 @@
using System;
namespace IngameDebugConsole
{
[AttributeUsage( AttributeTargets.Method, Inherited = false, AllowMultiple = true )]
public class ConsoleMethodAttribute : ConsoleAttribute
{
private string m_command;
private string m_description;
private string[] m_parameterNames;
public string Command { get { return m_command; } }
public string Description { get { return m_description; } }
public string[] ParameterNames { get { return m_parameterNames; } }
public override int Order { get { return 1; } }
public ConsoleMethodAttribute( string command, string description, params string[] parameterNames )
{
m_command = command;
m_description = description;
m_parameterNames = parameterNames;
}
public override void Load()
{
DebugLogConsole.AddCommand(Command, Description, Method, null, ParameterNames);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 324bb39c0bff0f74fa42f83e91f07e3a
timeCreated: 1520710946
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,313 @@
using System;
using UnityEngine;
namespace IngameDebugConsole
{
public class CircularBuffer<T>
{
private readonly T[] array;
private int startIndex;
public int Count { get; private set; }
public T this[int index] { get { return array[( startIndex + index ) % array.Length]; } }
public CircularBuffer( int capacity )
{
array = new T[capacity];
}
// Old elements are overwritten when capacity is reached
public void Add( T value )
{
if( Count < array.Length )
array[Count++] = value;
else
{
array[startIndex] = value;
if( ++startIndex >= array.Length )
startIndex = 0;
}
}
public T[] ToArray()
{
T[] result = new T[Count];
for (int i = 0; i < Count; i++)
result[i] = this[i];
return result;
}
}
public class DynamicCircularBuffer<T>
{
private T[] array;
private int startIndex;
public int Count { get; private set; }
public int Capacity { get { return array.Length; } }
public T this[int index]
{
get { return array[( startIndex + index ) % array.Length]; }
set { array[( startIndex + index ) % array.Length] = value; }
}
public DynamicCircularBuffer( int initialCapacity = 2 )
{
array = new T[initialCapacity];
}
private void SetCapacity( int capacity )
{
T[] newArray = new T[capacity];
if( Count > 0 )
{
int elementsBeforeWrap = Mathf.Min( Count, array.Length - startIndex );
Array.Copy( array, startIndex, newArray, 0, elementsBeforeWrap );
if( elementsBeforeWrap < Count )
Array.Copy( array, 0, newArray, elementsBeforeWrap, Count - elementsBeforeWrap );
}
array = newArray;
startIndex = 0;
}
/// <summary>Inserts the value to the beginning of the collection.</summary>
public void AddFirst( T value )
{
if( array.Length == Count )
SetCapacity( Mathf.Max( array.Length * 2, 4 ) );
startIndex = ( startIndex > 0 ) ? ( startIndex - 1 ) : ( array.Length - 1 );
array[startIndex] = value;
Count++;
}
/// <summary>Adds the value to the end of the collection.</summary>
public void Add( T value )
{
if( array.Length == Count )
SetCapacity( Mathf.Max( array.Length * 2, 4 ) );
this[Count++] = value;
}
public void AddRange( DynamicCircularBuffer<T> other )
{
if( other.Count == 0 )
return;
if( array.Length < Count + other.Count )
SetCapacity( Mathf.Max( array.Length * 2, Count + other.Count ) );
int insertStartIndex = ( startIndex + Count ) % array.Length;
int elementsBeforeWrap = Mathf.Min( other.Count, array.Length - insertStartIndex );
int otherElementsBeforeWrap = Mathf.Min( other.Count, other.array.Length - other.startIndex );
Array.Copy( other.array, other.startIndex, array, insertStartIndex, Mathf.Min( elementsBeforeWrap, otherElementsBeforeWrap ) );
if( elementsBeforeWrap < otherElementsBeforeWrap ) // This array wrapped before the other array
Array.Copy( other.array, other.startIndex + elementsBeforeWrap, array, 0, otherElementsBeforeWrap - elementsBeforeWrap );
else if( elementsBeforeWrap > otherElementsBeforeWrap ) // The other array wrapped before this array
Array.Copy( other.array, 0, array, insertStartIndex + otherElementsBeforeWrap, elementsBeforeWrap - otherElementsBeforeWrap );
int copiedElements = Mathf.Max( elementsBeforeWrap, otherElementsBeforeWrap );
if( copiedElements < other.Count ) // Both arrays wrapped and there's still some elements left to copy
Array.Copy( other.array, copiedElements - otherElementsBeforeWrap, array, copiedElements - elementsBeforeWrap, other.Count - copiedElements );
Count += other.Count;
}
public T RemoveFirst()
{
T element = array[startIndex];
array[startIndex] = default( T );
if( ++startIndex == array.Length )
startIndex = 0;
Count--;
return element;
}
public T RemoveLast()
{
int index = ( startIndex + Count - 1 ) % array.Length;
T element = array[index];
array[index] = default( T );
Count--;
return element;
}
public int RemoveAll( Predicate<T> shouldRemoveElement )
{
return RemoveAll<T>( shouldRemoveElement, null, null );
}
public int RemoveAll<Y>( Predicate<T> shouldRemoveElement, Action<T, int> onElementIndexChanged, DynamicCircularBuffer<Y> synchronizedBuffer )
{
Y[] synchronizedArray = ( synchronizedBuffer != null ) ? synchronizedBuffer.array : null;
int elementsBeforeWrap = Mathf.Min( Count, array.Length - startIndex );
int removedElements = 0;
int i = startIndex, newIndex = startIndex, endIndex = startIndex + elementsBeforeWrap;
for( ; i < endIndex; i++ )
{
if( shouldRemoveElement( array[i] ) )
removedElements++;
else
{
if( removedElements > 0 )
{
T element = array[i];
array[newIndex] = element;
if( synchronizedArray != null )
synchronizedArray[newIndex] = synchronizedArray[i];
if( onElementIndexChanged != null )
onElementIndexChanged( element, newIndex - startIndex );
}
newIndex++;
}
}
i = 0;
endIndex = Count - elementsBeforeWrap;
if( newIndex < array.Length )
{
for( ; i < endIndex; i++ )
{
if( shouldRemoveElement( array[i] ) )
removedElements++;
else
{
T element = array[i];
array[newIndex] = element;
if( synchronizedArray != null )
synchronizedArray[newIndex] = synchronizedArray[i];
if( onElementIndexChanged != null )
onElementIndexChanged( element, newIndex - startIndex );
if( ++newIndex == array.Length )
{
i++;
break;
}
}
}
}
if( newIndex == array.Length )
{
newIndex = 0;
for( ; i < endIndex; i++ )
{
if( shouldRemoveElement( array[i] ) )
removedElements++;
else
{
if( removedElements > 0 )
{
T element = array[i];
array[newIndex] = element;
if( synchronizedArray != null )
synchronizedArray[newIndex] = synchronizedArray[i];
if( onElementIndexChanged != null )
onElementIndexChanged( element, newIndex + elementsBeforeWrap );
}
newIndex++;
}
}
}
TrimEnd( removedElements );
if( synchronizedBuffer != null )
synchronizedBuffer.TrimEnd( removedElements );
return removedElements;
}
public void TrimStart( int trimCount, Action<T> perElementCallback = null )
{
TrimInternal( trimCount, startIndex, perElementCallback );
startIndex = ( startIndex + trimCount ) % array.Length;
}
public void TrimEnd( int trimCount, Action<T> perElementCallback = null )
{
TrimInternal( trimCount, ( startIndex + Count - trimCount ) % array.Length, perElementCallback );
}
private void TrimInternal( int trimCount, int startIndex, Action<T> perElementCallback )
{
int elementsBeforeWrap = Mathf.Min( trimCount, array.Length - startIndex );
if( perElementCallback == null )
{
Array.Clear( array, startIndex, elementsBeforeWrap );
if( elementsBeforeWrap < trimCount )
Array.Clear( array, 0, trimCount - elementsBeforeWrap );
}
else
{
for( int i = startIndex, endIndex = startIndex + elementsBeforeWrap; i < endIndex; i++ )
{
perElementCallback( array[i] );
array[i] = default( T );
}
for( int i = 0, endIndex = trimCount - elementsBeforeWrap; i < endIndex; i++ )
{
perElementCallback( array[i] );
array[i] = default( T );
}
}
Count -= trimCount;
}
public void Clear()
{
int elementsBeforeWrap = Mathf.Min( Count, array.Length - startIndex );
Array.Clear( array, startIndex, elementsBeforeWrap );
if( elementsBeforeWrap < Count )
Array.Clear( array, 0, Count - elementsBeforeWrap );
startIndex = 0;
Count = 0;
}
public int IndexOf( T value )
{
int elementsBeforeWrap = Mathf.Min( Count, array.Length - startIndex );
int index = Array.IndexOf( array, value, startIndex, elementsBeforeWrap );
if( index >= 0 )
return index - startIndex;
if( elementsBeforeWrap < Count )
{
index = Array.IndexOf( array, value, 0, Count - elementsBeforeWrap );
if( index >= 0 )
return index + elementsBeforeWrap;
}
return -1;
}
public void ForEach( Action<T> action )
{
int elementsBeforeWrap = Mathf.Min( Count, array.Length - startIndex );
for( int i = startIndex, endIndex = startIndex + elementsBeforeWrap; i < endIndex; i++ )
action( array[i] );
for( int i = 0, endIndex = Count - elementsBeforeWrap; i < endIndex; i++ )
action( array[i] );
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6136cb3c00eac0149901b8e7f2fecef8
timeCreated: 1550943949
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,34 @@
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
namespace IngameDebugConsole
{
public class CopyLogsOnResizeButtonClick : MonoBehaviour, IPointerClickHandler
{
[SerializeField]
private int maxLogCount = int.MaxValue;
[SerializeField]
private float maxElapsedTime = float.PositiveInfinity;
void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
{
if (!eventData.dragging && eventData.eligibleForClick && DebugLogManager.Instance.copyAllLogsOnResizeButtonClick)
{
GUIUtility.systemCopyBuffer = DebugLogManager.Instance.GetAllLogs(maxLogCount, maxElapsedTime);
StartCoroutine(ScaleAnimationCoroutine());
}
}
private IEnumerator ScaleAnimationCoroutine()
{
for (float t = 0f; t < 1f; t += Time.unscaledDeltaTime * 3f)
{
transform.localScale = Vector3.one * (1f + Mathf.PingPong(t, 0.5f));
yield return null;
}
transform.localScale = Vector3.one;
}
}
}

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: d15693a03d0d33b4892c6365a2a97e19
timeCreated: 1472036503
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,187 @@
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using UnityEngine;
// Container for a simple debug entry
namespace IngameDebugConsole
{
public class DebugLogEntry
{
private const int HASH_NOT_CALCULATED = -623218;
public string logString;
public string stackTrace;
private string completeLog;
// Sprite to show with this entry
public LogType logType;
// Collapsed count
public int count;
// Index of this entry among all collapsed entries
public int collapsedIndex;
private int hashValue;
public void Initialize( string logString, string stackTrace )
{
this.logString = logString;
this.stackTrace = stackTrace;
completeLog = null;
count = 1;
hashValue = HASH_NOT_CALCULATED;
}
public void Clear()
{
logString = null;
stackTrace = null;
completeLog = null;
}
// Checks if logString or stackTrace contains the search term
public bool MatchesSearchTerm( string searchTerm )
{
return ( logString != null && DebugLogConsole.caseInsensitiveComparer.IndexOf( logString, searchTerm, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace ) >= 0 ) ||
( stackTrace != null && DebugLogConsole.caseInsensitiveComparer.IndexOf( stackTrace, searchTerm, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace ) >= 0 );
}
// Return a string containing complete information about this debug entry
public override string ToString()
{
if( completeLog == null )
completeLog = string.Concat( logString, "\n", stackTrace );
return completeLog;
}
// Credit: https://stackoverflow.com/a/19250516/2373034
public int GetContentHashCode()
{
if( hashValue == HASH_NOT_CALCULATED )
{
unchecked
{
hashValue = 17;
hashValue = hashValue * 23 + ( logString == null ? 0 : logString.GetHashCode() );
hashValue = hashValue * 23 + ( stackTrace == null ? 0 : stackTrace.GetHashCode() );
}
}
return hashValue;
}
}
public struct QueuedDebugLogEntry
{
public readonly string logString;
public readonly string stackTrace;
public readonly LogType logType;
public QueuedDebugLogEntry( string logString, string stackTrace, LogType logType )
{
this.logString = logString;
this.stackTrace = stackTrace;
this.logType = logType;
}
// Checks if logString or stackTrace contains the search term
public bool MatchesSearchTerm( string searchTerm )
{
return ( logString != null && DebugLogConsole.caseInsensitiveComparer.IndexOf( logString, searchTerm, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace ) >= 0 ) ||
( stackTrace != null && DebugLogConsole.caseInsensitiveComparer.IndexOf( stackTrace, searchTerm, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace ) >= 0 );
}
}
public struct DebugLogEntryTimestamp
{
public readonly System.DateTime dateTime;
#if !IDG_OMIT_ELAPSED_TIME
public readonly float elapsedSeconds;
#endif
#if !IDG_OMIT_FRAMECOUNT
public readonly int frameCount;
#endif
#if !IDG_OMIT_ELAPSED_TIME && !IDG_OMIT_FRAMECOUNT
public DebugLogEntryTimestamp( System.DateTime dateTime, float elapsedSeconds, int frameCount )
#elif !IDG_OMIT_ELAPSED_TIME
public DebugLogEntryTimestamp( System.DateTime dateTime, float elapsedSeconds )
#elif !IDG_OMIT_FRAMECOUNT
public DebugLogEntryTimestamp( System.DateTime dateTime, int frameCount )
#else
public DebugLogEntryTimestamp( System.DateTime dateTime )
#endif
{
this.dateTime = dateTime;
#if !IDG_OMIT_ELAPSED_TIME
this.elapsedSeconds = elapsedSeconds;
#endif
#if !IDG_OMIT_FRAMECOUNT
this.frameCount = frameCount;
#endif
}
public void AppendTime( StringBuilder sb )
{
// Add DateTime in format: [HH:mm:ss]
sb.Append( "[" );
int hour = dateTime.Hour;
if( hour >= 10 )
sb.Append( hour );
else
sb.Append( "0" ).Append( hour );
sb.Append( ":" );
int minute = dateTime.Minute;
if( minute >= 10 )
sb.Append( minute );
else
sb.Append( "0" ).Append( minute );
sb.Append( ":" );
int second = dateTime.Second;
if( second >= 10 )
sb.Append( second );
else
sb.Append( "0" ).Append( second );
sb.Append( "]" );
}
public void AppendFullTimestamp( StringBuilder sb )
{
AppendTime( sb );
#if !IDG_OMIT_ELAPSED_TIME && !IDG_OMIT_FRAMECOUNT
// Append elapsed seconds and frame count in format: [1.0s at #Frame]
sb.Append( "[" ).Append( elapsedSeconds.ToString( "F1" ) ).Append( "s at " ).Append( "#" ).Append( frameCount ).Append( "]" );
#elif !IDG_OMIT_ELAPSED_TIME
// Append elapsed seconds in format: [1.0s]
sb.Append( "[" ).Append( elapsedSeconds.ToString( "F1" ) ).Append( "s]" );
#elif !IDG_OMIT_FRAMECOUNT
// Append frame count in format: [#Frame]
sb.Append( "[#" ).Append( frameCount ).Append( "]" );
#endif
}
}
public class DebugLogEntryContentEqualityComparer : EqualityComparer<DebugLogEntry>
{
public override bool Equals( DebugLogEntry x, DebugLogEntry y )
{
return x.logString == y.logString && x.stackTrace == y.stackTrace;
}
public override int GetHashCode( DebugLogEntry obj )
{
return obj.GetContentHashCode();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e7b1a420c564be040bf73b8a377fc2c2
timeCreated: 1466375168
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,260 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Text;
using TMPro;
#if UNITY_EDITOR
using UnityEditor;
using System.Text.RegularExpressions;
#endif
// A UI element to show information about a debug entry
namespace IngameDebugConsole
{
public class DebugLogItem : MonoBehaviour, IPointerClickHandler
{
#pragma warning disable 0649
// Cached components
[SerializeField]
private RectTransform transformComponent;
public RectTransform Transform { get { return transformComponent; } }
[SerializeField]
private Image imageComponent;
public Image Image { get { return imageComponent; } }
[SerializeField]
private CanvasGroup canvasGroupComponent;
public CanvasGroup CanvasGroup { get { return canvasGroupComponent; } }
[SerializeField]
private TextMeshProUGUI logText;
[SerializeField]
private Image logTypeImage;
// Objects related to the collapsed count of the debug entry
[SerializeField]
private GameObject logCountParent;
[SerializeField]
private TextMeshProUGUI logCountText;
[SerializeField]
private Button copyLogButton;
#pragma warning restore 0649
// Debug entry to show with this log item
private DebugLogEntry logEntry;
public DebugLogEntry Entry { get { return logEntry; } }
private DebugLogEntryTimestamp? logEntryTimestamp;
public DebugLogEntryTimestamp? Timestamp { get { return logEntryTimestamp; } }
// Index of the entry in the list of entries
[System.NonSerialized] public int Index;
private bool isExpanded;
public bool Expanded { get { return isExpanded; } }
private Vector2 logTextOriginalPosition;
private Vector2 logTextOriginalSize;
private float copyLogButtonHeight;
private DebugLogRecycledListView listView;
public void Initialize( DebugLogRecycledListView listView )
{
this.listView = listView;
logTextOriginalPosition = logText.rectTransform.anchoredPosition;
logTextOriginalSize = logText.rectTransform.sizeDelta;
copyLogButtonHeight = ( copyLogButton.transform as RectTransform ).anchoredPosition.y + ( copyLogButton.transform as RectTransform ).sizeDelta.y + 2f; // 2f: space between text and button
if (listView.manager.logItemFontOverride != null)
logText.font = listView.manager.logItemFontOverride;
copyLogButton.onClick.AddListener( CopyLog );
#if !UNITY_EDITOR && UNITY_WEBGL
copyLogButton.gameObject.AddComponent<DebugLogItemCopyWebGL>().Initialize( this );
#endif
}
public void SetContent( DebugLogEntry logEntry, DebugLogEntryTimestamp? logEntryTimestamp, int entryIndex, bool isExpanded )
{
this.logEntry = logEntry;
this.logEntryTimestamp = logEntryTimestamp;
this.Index = entryIndex;
this.isExpanded = isExpanded;
Vector2 size = transformComponent.sizeDelta;
if( isExpanded )
{
size.y = listView.SelectedItemHeight;
if( !copyLogButton.gameObject.activeSelf )
{
copyLogButton.gameObject.SetActive( true );
logText.rectTransform.anchoredPosition = new Vector2( logTextOriginalPosition.x, logTextOriginalPosition.y + copyLogButtonHeight * 0.5f );
logText.rectTransform.sizeDelta = logTextOriginalSize - new Vector2( 0f, copyLogButtonHeight );
}
}
else
{
size.y = listView.ItemHeight;
if( copyLogButton.gameObject.activeSelf )
{
copyLogButton.gameObject.SetActive( false );
logText.rectTransform.anchoredPosition = logTextOriginalPosition;
logText.rectTransform.sizeDelta = logTextOriginalSize;
}
}
transformComponent.sizeDelta = size;
SetText( logEntry, logEntryTimestamp, isExpanded );
logTypeImage.sprite = DebugLogManager.logSpriteRepresentations[(int) logEntry.logType];
}
// Show the collapsed count of the debug entry
public void ShowCount()
{
logCountText.SetText( "{0}", logEntry.count );
if( !logCountParent.activeSelf )
logCountParent.SetActive( true );
}
// Hide the collapsed count of the debug entry
public void HideCount()
{
if( logCountParent.activeSelf )
logCountParent.SetActive( false );
}
// Update the debug entry's displayed timestamp
public void UpdateTimestamp( DebugLogEntryTimestamp timestamp )
{
logEntryTimestamp = timestamp;
if( isExpanded || listView.manager.alwaysDisplayTimestamps )
SetText( logEntry, timestamp, isExpanded );
}
private void SetText(DebugLogEntry logEntry, DebugLogEntryTimestamp? logEntryTimestamp, bool isExpanded)
{
string text = isExpanded ? logEntry.ToString() : logEntry.logString;
int maxLogLength = isExpanded ? listView.manager.maxExpandedLogLength : listView.manager.maxCollapsedLogLength;
if (!logEntryTimestamp.HasValue || (!isExpanded && !listView.manager.alwaysDisplayTimestamps))
{
if (text.Length <= maxLogLength)
logText.text = text;
else
{
if (listView.manager.textBuffer.Length < maxLogLength)
listView.manager.textBuffer = new char[maxLogLength];
text.CopyTo(0, listView.manager.textBuffer, 0, maxLogLength);
logText.SetText(listView.manager.textBuffer, 0, maxLogLength);
}
}
else
{
StringBuilder sb = listView.manager.sharedStringBuilder;
sb.Length = 0;
if (isExpanded)
{
logEntryTimestamp.Value.AppendFullTimestamp(sb);
sb.Append(": ").Append(text, 0, Mathf.Min(text.Length, maxLogLength - sb.Length));
}
else
{
logEntryTimestamp.Value.AppendTime(sb);
sb.Append(" ").Append(text, 0, Mathf.Min(text.Length, maxLogLength - sb.Length));
}
if (listView.manager.textBuffer.Length < sb.Length)
listView.manager.textBuffer = new char[sb.Length];
sb.CopyTo(0, listView.manager.textBuffer, 0, sb.Length);
logText.SetText(listView.manager.textBuffer, 0, sb.Length);
}
}
// This log item is clicked, show the debug entry's stack trace
public void OnPointerClick( PointerEventData eventData )
{
#if UNITY_EDITOR
if( eventData.button == PointerEventData.InputButton.Right )
{
Match regex = Regex.Match( logEntry.stackTrace, @"\(at .*\.cs:[0-9]+\)$", RegexOptions.Multiline );
if( regex.Success )
{
string line = logEntry.stackTrace.Substring( regex.Index + 4, regex.Length - 5 );
int lineSeparator = line.IndexOf( ':' );
MonoScript script = AssetDatabase.LoadAssetAtPath<MonoScript>( line.Substring( 0, lineSeparator ) );
if( script != null )
AssetDatabase.OpenAsset( script, int.Parse( line.Substring( lineSeparator + 1 ) ) );
}
}
else
listView.OnLogItemClicked( this );
#else
listView.OnLogItemClicked( this );
#endif
}
private void CopyLog()
{
#if UNITY_EDITOR || !UNITY_WEBGL
string log = GetCopyContent();
if( !string.IsNullOrEmpty( log ) )
GUIUtility.systemCopyBuffer = log;
#endif
}
internal string GetCopyContent()
{
if( !logEntryTimestamp.HasValue )
return logEntry.ToString();
else
{
StringBuilder sb = listView.manager.sharedStringBuilder;
sb.Length = 0;
logEntryTimestamp.Value.AppendFullTimestamp( sb );
sb.Append( ": " ).Append( logEntry.ToString() );
return sb.ToString();
}
}
/// Here, we're using <see cref="TMP_Text.GetRenderedValues(bool)"/> instead of <see cref="TMP_Text.preferredHeight"/> because the latter doesn't take
/// <see cref="TMP_Text.maxVisibleCharacters"/> into account. However, for <see cref="TMP_Text.GetRenderedValues(bool)"/> to work, we need to give it
/// enough space (increase log item's height) and let it regenerate its mesh <see cref="TMP_Text.ForceMeshUpdate"/>.
public float CalculateExpandedHeight( DebugLogEntry logEntry, DebugLogEntryTimestamp? logEntryTimestamp )
{
string text = logText.text;
Vector2 size = ( transform as RectTransform ).sizeDelta;
( transform as RectTransform ).sizeDelta = new Vector2( size.x, 10000f );
SetText( logEntry, logEntryTimestamp, true );
logText.ForceMeshUpdate();
float result = logText.GetRenderedValues( true ).y + copyLogButtonHeight;
( transform as RectTransform ).sizeDelta = size;
logText.text = text;
return Mathf.Max( listView.ItemHeight, result );
}
// Return a string containing complete information about the debug entry
public override string ToString()
{
return logEntry.ToString();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: d2ea291be9de70a4abfec595203c96c1
timeCreated: 1465919949
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
#if !UNITY_EDITOR && UNITY_WEBGL
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.EventSystems;
namespace IngameDebugConsole
{
public class DebugLogItemCopyWebGL : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
[DllImport( "__Internal" )]
private static extern void IngameDebugConsoleStartCopy( string textToCopy );
[DllImport( "__Internal" )]
private static extern void IngameDebugConsoleCancelCopy();
private DebugLogItem logItem;
public void Initialize( DebugLogItem logItem )
{
this.logItem = logItem;
}
public void OnPointerDown( PointerEventData eventData )
{
string log = logItem.GetCopyContent();
if( !string.IsNullOrEmpty( log ) )
IngameDebugConsoleStartCopy( log );
}
public void OnPointerUp( PointerEventData eventData )
{
if( eventData.dragging )
IngameDebugConsoleCancelCopy();
}
}
}
#endif

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6a4f16ed905adcd4ab0d7c8c11f0d72c
timeCreated: 1522092746
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: -9869
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,282 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using TMPro;
#if UNITY_EDITOR && UNITY_2021_1_OR_NEWER
using Screen = UnityEngine.Device.Screen; // To support Device Simulator on Unity 2021.1+
#endif
// Manager class for the debug popup
namespace IngameDebugConsole
{
public class DebugLogPopup : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IDragHandler, IEndDragHandler
{
private RectTransform popupTransform;
// Dimensions of the popup divided by 2
private Vector2 halfSize;
// Background image that will change color to indicate an alert
private Image backgroundImage;
// Canvas group to modify visibility of the popup
private CanvasGroup canvasGroup;
#pragma warning disable 0649
[SerializeField]
private DebugLogManager debugManager;
[SerializeField]
private TextMeshProUGUI newInfoCountText;
[SerializeField]
private TextMeshProUGUI newWarningCountText;
[SerializeField]
private TextMeshProUGUI newErrorCountText;
[SerializeField]
private Color alertColorInfo;
[SerializeField]
private Color alertColorWarning;
[SerializeField]
private Color alertColorError;
#pragma warning restore 0649
// Number of new debug entries since the log window has been closed
private int newInfoCount = 0, newWarningCount = 0, newErrorCount = 0;
private Color normalColor;
private bool isPopupBeingDragged = false;
private Vector2 normalizedPosition;
// Coroutines for simple code-based animations
private IEnumerator moveToPosCoroutine = null;
public bool IsVisible { get; private set; }
private void Awake()
{
popupTransform = (RectTransform) transform;
backgroundImage = GetComponent<Image>();
canvasGroup = GetComponent<CanvasGroup>();
normalColor = backgroundImage.color;
halfSize = popupTransform.sizeDelta * 0.5f;
Vector2 pos = popupTransform.anchoredPosition;
if( pos.x != 0f || pos.y != 0f )
normalizedPosition = pos.normalized; // Respect the initial popup position set in the prefab
else
normalizedPosition = new Vector2( 0.5f, 0f ); // Right edge by default
}
public void NewLogsArrived( int newInfo, int newWarning, int newError )
{
if( newInfo > 0 )
{
newInfoCount += newInfo;
newInfoCountText.text = newInfoCount.ToString();
}
if( newWarning > 0 )
{
newWarningCount += newWarning;
newWarningCountText.text = newWarningCount.ToString();
}
if( newError > 0 )
{
newErrorCount += newError;
newErrorCountText.text = newErrorCount.ToString();
}
if( newErrorCount > 0 )
backgroundImage.color = alertColorError;
else if( newWarningCount > 0 )
backgroundImage.color = alertColorWarning;
else
backgroundImage.color = alertColorInfo;
}
private void ResetValues()
{
newInfoCount = 0;
newWarningCount = 0;
newErrorCount = 0;
newInfoCountText.text = "0";
newWarningCountText.text = "0";
newErrorCountText.text = "0";
backgroundImage.color = normalColor;
}
// A simple smooth movement animation
private IEnumerator MoveToPosAnimation( Vector2 targetPos )
{
float modifier = 0f;
Vector2 initialPos = popupTransform.anchoredPosition;
while( modifier < 1f )
{
modifier += 4f * Time.unscaledDeltaTime;
popupTransform.anchoredPosition = Vector2.Lerp( initialPos, targetPos, modifier );
yield return null;
}
}
// Popup is clicked
public void OnPointerClick( PointerEventData data )
{
// Hide the popup and show the log window
if( !isPopupBeingDragged )
debugManager.ShowLogWindow();
}
// Hides the log window and shows the popup
public void Show()
{
canvasGroup.blocksRaycasts = true;
canvasGroup.alpha = debugManager.popupOpacity;
IsVisible = true;
// Reset the counters
ResetValues();
// Update position in case resolution was changed while the popup was hidden
UpdatePosition( true );
}
// Hide the popup
public void Hide()
{
canvasGroup.blocksRaycasts = false;
canvasGroup.alpha = 0f;
IsVisible = false;
isPopupBeingDragged = false;
}
public void OnBeginDrag( PointerEventData data )
{
isPopupBeingDragged = true;
// If a smooth movement animation is in progress, cancel it
if( moveToPosCoroutine != null )
{
StopCoroutine( moveToPosCoroutine );
moveToPosCoroutine = null;
}
}
// Reposition the popup
public void OnDrag( PointerEventData data )
{
Vector2 localPoint;
if( RectTransformUtility.ScreenPointToLocalPointInRectangle( debugManager.canvasTR, data.position, data.pressEventCamera, out localPoint ) )
popupTransform.anchoredPosition = localPoint;
}
// Smoothly translate the popup to the nearest edge
public void OnEndDrag( PointerEventData data )
{
isPopupBeingDragged = false;
UpdatePosition( false );
}
// There are 2 different spaces used in these calculations:
// RectTransform space: raw anchoredPosition of the popup that's in range [-canvasSize/2, canvasSize/2]
// Safe area space: Screen.safeArea space that's in range [safeAreaBottomLeft, safeAreaTopRight] where these corner positions
// are all positive (calculated from bottom left corner of the screen instead of the center of the screen)
public void UpdatePosition( bool immediately )
{
Vector2 canvasRawSize = debugManager.canvasTR.rect.size;
// Calculate safe area bounds
float canvasWidth = canvasRawSize.x;
float canvasHeight = canvasRawSize.y;
float canvasBottomLeftX = 0f;
float canvasBottomLeftY = 0f;
if( debugManager.popupAvoidsScreenCutout )
{
#if UNITY_EDITOR || UNITY_ANDROID || UNITY_IOS
Rect safeArea = Screen.safeArea;
int screenWidth = Screen.width;
int screenHeight = Screen.height;
canvasWidth *= safeArea.width / screenWidth;
canvasHeight *= safeArea.height / screenHeight;
canvasBottomLeftX = canvasRawSize.x * ( safeArea.x / screenWidth );
canvasBottomLeftY = canvasRawSize.y * ( safeArea.y / screenHeight );
#endif
}
// Calculate safe area position of the popup
// normalizedPosition allows us to glue the popup to a specific edge of the screen. It becomes useful when
// the popup is at the right edge and we switch from portrait screen orientation to landscape screen orientation.
// Without normalizedPosition, popup could jump to bottom or top edges instead of staying at the right edge
Vector2 pos = canvasRawSize * 0.5f + ( immediately ? new Vector2( normalizedPosition.x * canvasWidth, normalizedPosition.y * canvasHeight ) : ( popupTransform.anchoredPosition - new Vector2( canvasBottomLeftX, canvasBottomLeftY ) ) );
// Find distances to all four edges of the safe area
float distToLeft = pos.x;
float distToRight = canvasWidth - distToLeft;
float distToBottom = pos.y;
float distToTop = canvasHeight - distToBottom;
float horDistance = Mathf.Min( distToLeft, distToRight );
float vertDistance = Mathf.Min( distToBottom, distToTop );
// Find the nearest edge's safe area coordinates
if( horDistance < vertDistance )
{
if( distToLeft < distToRight )
pos = new Vector2( halfSize.x, pos.y );
else
pos = new Vector2( canvasWidth - halfSize.x, pos.y );
pos.y = Mathf.Clamp( pos.y, halfSize.y, canvasHeight - halfSize.y );
}
else
{
if( distToBottom < distToTop )
pos = new Vector2( pos.x, halfSize.y );
else
pos = new Vector2( pos.x, canvasHeight - halfSize.y );
pos.x = Mathf.Clamp( pos.x, halfSize.x, canvasWidth - halfSize.x );
}
pos -= canvasRawSize * 0.5f;
normalizedPosition.Set( pos.x / canvasWidth, pos.y / canvasHeight );
// Safe area's bottom left coordinates are added to pos only after normalizedPosition's value
// is set because normalizedPosition is in range [-canvasWidth / 2, canvasWidth / 2]
pos += new Vector2( canvasBottomLeftX, canvasBottomLeftY );
// If another smooth movement animation is in progress, cancel it
if( moveToPosCoroutine != null )
{
StopCoroutine( moveToPosCoroutine );
moveToPosCoroutine = null;
}
if( immediately )
popupTransform.anchoredPosition = pos;
else
{
// Smoothly translate the popup to the specified position
moveToPosCoroutine = MoveToPosAnimation( pos );
StartCoroutine( moveToPosCoroutine );
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 05cc4b1999716644c9308528e38e7081
timeCreated: 1466533184
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,485 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// Handles the log items in an optimized way such that existing log items are
// recycled within the list instead of creating a new log item at each chance
namespace IngameDebugConsole
{
public class DebugLogRecycledListView : MonoBehaviour
{
#pragma warning disable 0649
// Cached components
[SerializeField]
private RectTransform transformComponent;
[SerializeField]
private RectTransform viewportTransform;
[SerializeField]
private Color logItemNormalColor1;
[SerializeField]
private Color logItemNormalColor2;
[SerializeField]
private Color logItemSelectedColor;
#pragma warning restore 0649
internal DebugLogManager manager;
private ScrollRect scrollView;
private float logItemHeight;
private DynamicCircularBuffer<DebugLogEntry> entriesToShow = null;
private DynamicCircularBuffer<DebugLogEntryTimestamp> timestampsOfEntriesToShow = null;
private DebugLogEntry selectedLogEntry;
private int indexOfSelectedLogEntry = int.MaxValue;
private float heightOfSelectedLogEntry;
private float DeltaHeightOfSelectedLogEntry { get { return heightOfSelectedLogEntry - logItemHeight; } }
/// These properties are used by <see cref="OnBeforeFilterLogs"/> and <see cref="OnAfterFilterLogs"/>.
private int collapsedOrderOfSelectedLogEntry;
private float scrollDistanceToSelectedLogEntry;
// Log items used to visualize the visible debug entries
private readonly DynamicCircularBuffer<DebugLogItem> visibleLogItems = new DynamicCircularBuffer<DebugLogItem>( 32 );
private bool isCollapseOn = false;
// Current indices of debug entries shown on screen
private int currentTopIndex = -1, currentBottomIndex = -1;
private System.Predicate<DebugLogItem> shouldRemoveLogItemPredicate;
private System.Action<DebugLogItem> poolLogItemAction;
public float ItemHeight { get { return logItemHeight; } }
public float SelectedItemHeight { get { return heightOfSelectedLogEntry; } }
private void Awake()
{
scrollView = viewportTransform.GetComponentInParent<ScrollRect>();
scrollView.onValueChanged.AddListener( ( pos ) =>
{
if( manager.IsLogWindowVisible )
UpdateItemsInTheList( false );
} );
}
public void Initialize( DebugLogManager manager, DynamicCircularBuffer<DebugLogEntry> entriesToShow, DynamicCircularBuffer<DebugLogEntryTimestamp> timestampsOfEntriesToShow, float logItemHeight )
{
this.manager = manager;
this.entriesToShow = entriesToShow;
this.timestampsOfEntriesToShow = timestampsOfEntriesToShow;
this.logItemHeight = logItemHeight;
shouldRemoveLogItemPredicate = ShouldRemoveLogItem;
poolLogItemAction = manager.PoolLogItem;
}
public void SetCollapseMode( bool collapse )
{
isCollapseOn = collapse;
}
// A log item is clicked, highlight it
public void OnLogItemClicked( DebugLogItem item )
{
OnLogItemClickedInternal( item.Index, item );
}
// Force expand the log item at specified index
public void SelectAndFocusOnLogItemAtIndex( int itemIndex )
{
if( indexOfSelectedLogEntry != itemIndex ) // Make sure that we aren't deselecting the target log item
OnLogItemClickedInternal( itemIndex );
float viewportHeight = viewportTransform.rect.height;
float transformComponentCenterYAtTop = viewportHeight * 0.5f;
float transformComponentCenterYAtBottom = transformComponent.sizeDelta.y - viewportHeight * 0.5f;
float transformComponentTargetCenterY = itemIndex * logItemHeight + viewportHeight * 0.5f;
if( transformComponentCenterYAtTop == transformComponentCenterYAtBottom )
scrollView.verticalNormalizedPosition = 0.5f;
else
scrollView.verticalNormalizedPosition = Mathf.Clamp01( Mathf.InverseLerp( transformComponentCenterYAtBottom, transformComponentCenterYAtTop, transformComponentTargetCenterY ) );
manager.SnapToBottom = false;
}
private void OnLogItemClickedInternal( int itemIndex, DebugLogItem referenceItem = null )
{
int indexOfPreviouslySelectedLogEntry = indexOfSelectedLogEntry;
DeselectSelectedLogItem();
if( indexOfPreviouslySelectedLogEntry != itemIndex )
{
selectedLogEntry = entriesToShow[itemIndex];
indexOfSelectedLogEntry = itemIndex;
CalculateSelectedLogEntryHeight( referenceItem );
manager.SnapToBottom = false;
}
CalculateContentHeight();
UpdateItemsInTheList( true );
manager.ValidateScrollPosition();
}
// Deselect the currently selected log item
public void DeselectSelectedLogItem()
{
selectedLogEntry = null;
indexOfSelectedLogEntry = int.MaxValue;
heightOfSelectedLogEntry = 0f;
}
/// <summary>
/// Cache the currently selected log item's properties so that its position can be restored after <see cref="OnAfterFilterLogs"/> is called.
/// </summary>
public void OnBeforeFilterLogs()
{
collapsedOrderOfSelectedLogEntry = 0;
scrollDistanceToSelectedLogEntry = 0f;
if( selectedLogEntry != null )
{
if( !isCollapseOn )
{
for( int i = 0; i < indexOfSelectedLogEntry; i++ )
{
if( entriesToShow[i] == selectedLogEntry )
collapsedOrderOfSelectedLogEntry++;
}
}
scrollDistanceToSelectedLogEntry = indexOfSelectedLogEntry * ItemHeight - transformComponent.anchoredPosition.y;
}
}
/// <summary>
/// See <see cref="OnBeforeFilterLogs"/>.
/// </summary>
public void OnAfterFilterLogs()
{
// Refresh selected log entry's index
int newIndexOfSelectedLogEntry = -1;
if( selectedLogEntry != null )
{
for( int i = 0; i < entriesToShow.Count; i++ )
{
if( entriesToShow[i] == selectedLogEntry && collapsedOrderOfSelectedLogEntry-- == 0 )
{
newIndexOfSelectedLogEntry = i;
break;
}
}
}
if( newIndexOfSelectedLogEntry < 0 )
DeselectSelectedLogItem();
else
{
indexOfSelectedLogEntry = newIndexOfSelectedLogEntry;
transformComponent.anchoredPosition = new Vector2( 0f, newIndexOfSelectedLogEntry * ItemHeight - scrollDistanceToSelectedLogEntry );
}
}
// Number of debug entries may have changed, update the list
public void OnLogEntriesUpdated( bool updateAllVisibleItemContents )
{
CalculateContentHeight();
UpdateItemsInTheList( updateAllVisibleItemContents );
}
// A single collapsed log entry at specified index is updated, refresh its item if visible
public void OnCollapsedLogEntryAtIndexUpdated( int index )
{
if( index >= currentTopIndex && index <= currentBottomIndex )
{
DebugLogItem logItem = GetLogItemAtIndex( index );
logItem.ShowCount();
if( timestampsOfEntriesToShow != null )
logItem.UpdateTimestamp( timestampsOfEntriesToShow[index] );
}
}
public void RefreshCollapsedLogEntryCounts()
{
for( int i = 0; i < visibleLogItems.Count; i++ )
visibleLogItems[i].ShowCount();
}
public void OnLogEntriesRemoved( int removedLogCount )
{
if( selectedLogEntry != null )
{
bool isSelectedLogEntryRemoved = isCollapseOn ? ( selectedLogEntry.count == 0 ) : ( indexOfSelectedLogEntry < removedLogCount );
if( isSelectedLogEntryRemoved )
DeselectSelectedLogItem();
else
indexOfSelectedLogEntry = isCollapseOn ? FindIndexOfLogEntryInReverseDirection( selectedLogEntry, indexOfSelectedLogEntry ) : ( indexOfSelectedLogEntry - removedLogCount );
}
if( !manager.IsLogWindowVisible && manager.SnapToBottom )
{
// When log window becomes visible, it refreshes all logs. So unless snap to bottom is disabled, we don't need to
// keep track of either the scroll position or the visible log items' positions.
visibleLogItems.TrimStart( visibleLogItems.Count, poolLogItemAction );
}
else if( !isCollapseOn )
visibleLogItems.TrimStart( Mathf.Clamp( removedLogCount - currentTopIndex, 0, visibleLogItems.Count ), poolLogItemAction );
else
{
visibleLogItems.RemoveAll( shouldRemoveLogItemPredicate );
if( visibleLogItems.Count > 0 )
removedLogCount = currentTopIndex - FindIndexOfLogEntryInReverseDirection( visibleLogItems[0].Entry, visibleLogItems[0].Index );
}
if( visibleLogItems.Count == 0 )
{
currentTopIndex = -1;
if( !manager.SnapToBottom )
transformComponent.anchoredPosition = Vector2.zero;
}
else
{
currentTopIndex = Mathf.Max( 0, currentTopIndex - removedLogCount );
currentBottomIndex = currentTopIndex + visibleLogItems.Count - 1;
float firstVisibleLogItemInitialYPos = visibleLogItems[0].Transform.anchoredPosition.y;
for( int i = 0; i < visibleLogItems.Count; i++ )
{
DebugLogItem logItem = visibleLogItems[i];
logItem.Index = currentTopIndex + i;
// If log window is visible, we need to manually refresh the visible items' visual properties. Otherwise, all log items will be refreshed when log window is opened
if( manager.IsLogWindowVisible )
{
RepositionLogItem( logItem );
ColorLogItem( logItem );
// Update collapsed count of the log items in collapsed mode
if( isCollapseOn )
logItem.ShowCount();
}
}
// Shift the ScrollRect
if( !manager.SnapToBottom )
transformComponent.anchoredPosition = new Vector2( 0f, Mathf.Max( 0f, transformComponent.anchoredPosition.y - ( visibleLogItems[0].Transform.anchoredPosition.y - firstVisibleLogItemInitialYPos ) ) );
}
}
private bool ShouldRemoveLogItem( DebugLogItem logItem )
{
if( logItem.Entry.count == 0 )
{
poolLogItemAction( logItem );
return true;
}
return false;
}
private int FindIndexOfLogEntryInReverseDirection( DebugLogEntry logEntry, int startIndex )
{
for( int i = Mathf.Min( startIndex, entriesToShow.Count - 1 ); i >= 0; i-- )
{
if( entriesToShow[i] == logEntry )
return i;
}
return -1;
}
// Log window's width has changed, update the expanded (currently selected) log's height
public void OnViewportWidthChanged()
{
if( indexOfSelectedLogEntry >= entriesToShow.Count )
return;
CalculateSelectedLogEntryHeight();
CalculateContentHeight();
UpdateItemsInTheList( true );
manager.ValidateScrollPosition();
}
// Log window's height has changed, update the list
public void OnViewportHeightChanged()
{
UpdateItemsInTheList( false );
}
private void CalculateContentHeight()
{
float newHeight = Mathf.Max( 1f, entriesToShow.Count * logItemHeight );
if( selectedLogEntry != null )
newHeight += DeltaHeightOfSelectedLogEntry;
transformComponent.sizeDelta = new Vector2( 0f, newHeight );
}
private void CalculateSelectedLogEntryHeight( DebugLogItem referenceItem = null )
{
if( !referenceItem )
{
if( visibleLogItems.Count == 0 )
{
UpdateItemsInTheList( false ); // Try to generate some DebugLogItems, we need one DebugLogItem to calculate the text height
if( visibleLogItems.Count == 0 ) // No DebugLogItems are generated, weird
return;
}
referenceItem = visibleLogItems[0];
}
heightOfSelectedLogEntry = referenceItem.CalculateExpandedHeight( selectedLogEntry, ( timestampsOfEntriesToShow != null ) ? timestampsOfEntriesToShow[indexOfSelectedLogEntry] : (DebugLogEntryTimestamp?) null );
}
// Calculate the indices of log entries to show
// and handle log items accordingly
private void UpdateItemsInTheList( bool updateAllVisibleItemContents )
{
if( entriesToShow.Count > 0 )
{
float contentPosTop = transformComponent.anchoredPosition.y - 1f;
float contentPosBottom = contentPosTop + viewportTransform.rect.height + 2f;
float positionOfSelectedLogEntry = indexOfSelectedLogEntry * logItemHeight;
if( positionOfSelectedLogEntry <= contentPosBottom )
{
if( positionOfSelectedLogEntry <= contentPosTop )
{
contentPosTop = Mathf.Max( contentPosTop - DeltaHeightOfSelectedLogEntry, positionOfSelectedLogEntry - 1f );
contentPosBottom = Mathf.Max( contentPosBottom - DeltaHeightOfSelectedLogEntry, contentPosTop + 2f );
}
else
contentPosBottom = Mathf.Max( contentPosBottom - DeltaHeightOfSelectedLogEntry, positionOfSelectedLogEntry + 1f );
}
int newBottomIndex = Mathf.Min( (int) ( contentPosBottom / logItemHeight ), entriesToShow.Count - 1 );
int newTopIndex = Mathf.Clamp( (int) ( contentPosTop / logItemHeight ), 0, newBottomIndex );
if( currentTopIndex == -1 )
{
// There are no log items visible on screen,
// just create the new log items
updateAllVisibleItemContents = true;
for( int i = 0, count = newBottomIndex - newTopIndex + 1; i < count; i++ )
visibleLogItems.Add( manager.PopLogItem() );
}
else
{
// There are some log items visible on screen
if( newBottomIndex < currentTopIndex || newTopIndex > currentBottomIndex )
{
// If user scrolled a lot such that, none of the log items are now within
// the bounds of the scroll view, pool all the previous log items and create
// new log items for the new list of visible debug entries
updateAllVisibleItemContents = true;
visibleLogItems.TrimStart( visibleLogItems.Count, poolLogItemAction );
for( int i = 0, count = newBottomIndex - newTopIndex + 1; i < count; i++ )
visibleLogItems.Add( manager.PopLogItem() );
}
else
{
// User did not scroll a lot such that, there are still some log items within
// the bounds of the scroll view. Don't destroy them but update their content,
// if necessary
if( newTopIndex > currentTopIndex )
visibleLogItems.TrimStart( newTopIndex - currentTopIndex, poolLogItemAction );
if( newBottomIndex < currentBottomIndex )
visibleLogItems.TrimEnd( currentBottomIndex - newBottomIndex, poolLogItemAction );
if( newTopIndex < currentTopIndex )
{
for( int i = 0, count = currentTopIndex - newTopIndex; i < count; i++ )
visibleLogItems.AddFirst( manager.PopLogItem() );
// If it is not necessary to update all the log items,
// then just update the newly created log items. Otherwise,
// wait for the major update
if( !updateAllVisibleItemContents )
UpdateLogItemContentsBetweenIndices( newTopIndex, currentTopIndex - 1, newTopIndex );
}
if( newBottomIndex > currentBottomIndex )
{
for( int i = 0, count = newBottomIndex - currentBottomIndex; i < count; i++ )
visibleLogItems.Add( manager.PopLogItem() );
// If it is not necessary to update all the log items,
// then just update the newly created log items. Otherwise,
// wait for the major update
if( !updateAllVisibleItemContents )
UpdateLogItemContentsBetweenIndices( currentBottomIndex + 1, newBottomIndex, newTopIndex );
}
}
}
currentTopIndex = newTopIndex;
currentBottomIndex = newBottomIndex;
if( updateAllVisibleItemContents )
{
// Update all the log items
UpdateLogItemContentsBetweenIndices( currentTopIndex, currentBottomIndex, newTopIndex );
}
}
else if( currentTopIndex != -1 )
{
// There is nothing to show but some log items are still visible; pool them
visibleLogItems.TrimStart( visibleLogItems.Count, poolLogItemAction );
currentTopIndex = -1;
}
}
private DebugLogItem GetLogItemAtIndex( int index )
{
return visibleLogItems[index - currentTopIndex];
}
private void UpdateLogItemContentsBetweenIndices( int topIndex, int bottomIndex, int logItemOffset )
{
for( int i = topIndex; i <= bottomIndex; i++ )
{
DebugLogItem logItem = visibleLogItems[i - logItemOffset];
logItem.SetContent( entriesToShow[i], ( timestampsOfEntriesToShow != null ) ? timestampsOfEntriesToShow[i] : (DebugLogEntryTimestamp?) null, i, i == indexOfSelectedLogEntry );
RepositionLogItem( logItem );
ColorLogItem( logItem );
if( isCollapseOn )
logItem.ShowCount();
else
logItem.HideCount();
}
}
private void RepositionLogItem( DebugLogItem logItem )
{
int index = logItem.Index;
Vector2 anchoredPosition = new Vector2( 1f, -index * logItemHeight );
if( index > indexOfSelectedLogEntry )
anchoredPosition.y -= DeltaHeightOfSelectedLogEntry;
logItem.Transform.anchoredPosition = anchoredPosition;
}
private void ColorLogItem( DebugLogItem logItem )
{
int index = logItem.Index;
if( index == indexOfSelectedLogEntry )
logItem.Image.color = logItemSelectedColor;
else if( index % 2 == 0 )
logItem.Image.color = logItemNormalColor1;
else
logItem.Image.color = logItemNormalColor2;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ce231987d32488f43b6fb798f7df43f6
timeCreated: 1466373025
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,24 @@
using UnityEngine;
using UnityEngine.EventSystems;
// Listens to drag event on the DebugLogManager's resize button
namespace IngameDebugConsole
{
public class DebugLogResizeListener : MonoBehaviour, IBeginDragHandler, IDragHandler
{
#pragma warning disable 0649
[SerializeField]
private DebugLogManager debugManager;
#pragma warning restore 0649
// This interface must be implemented in order to receive drag events
void IBeginDragHandler.OnBeginDrag( PointerEventData eventData )
{
}
void IDragHandler.OnDrag( PointerEventData eventData )
{
debugManager.Resize( eventData );
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6565f2084f5aef44abe57c988745b9c3
timeCreated: 1601221093
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
// Listens to scroll events on the scroll rect that debug items are stored
// and decides whether snap to bottom should be true or not
//
// Procedure: if, after a user input (drag or scroll), scrollbar is at the bottom, then
// snap to bottom shall be true, otherwise it shall be false
namespace IngameDebugConsole
{
public class DebugsOnScrollListener : MonoBehaviour, IScrollHandler, IBeginDragHandler, IEndDragHandler
{
public ScrollRect debugsScrollRect;
public DebugLogManager debugLogManager;
public void OnScroll( PointerEventData data )
{
debugLogManager.SnapToBottom = IsScrollbarAtBottom();
}
public void OnBeginDrag( PointerEventData data )
{
debugLogManager.SnapToBottom = false;
}
public void OnEndDrag( PointerEventData data )
{
debugLogManager.SnapToBottom = IsScrollbarAtBottom();
}
public void OnScrollbarDragStart( BaseEventData data )
{
debugLogManager.SnapToBottom = false;
}
public void OnScrollbarDragEnd( BaseEventData data )
{
debugLogManager.SnapToBottom = IsScrollbarAtBottom();
}
private bool IsScrollbarAtBottom()
{
return debugsScrollRect.verticalNormalizedPosition <= 1E-6f;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: cb564dcb180e586429c57456166a76b5
timeCreated: 1466004663
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,73 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
using UnityEngine.InputSystem.UI;
#endif
namespace IngameDebugConsole
{
// Avoid multiple EventSystems in the scene by activating the embedded EventSystem only if one doesn't already exist in the scene
[DefaultExecutionOrder( 1000 )]
public class EventSystemHandler : MonoBehaviour
{
#pragma warning disable 0649
[SerializeField]
private GameObject embeddedEventSystem;
#pragma warning restore 0649
#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
private void Awake()
{
StandaloneInputModule legacyInputModule = embeddedEventSystem.GetComponent<StandaloneInputModule>();
if( legacyInputModule )
{
DestroyImmediate( legacyInputModule );
embeddedEventSystem.AddComponent<InputSystemUIInputModule>();
}
}
#endif
private void OnEnable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
SceneManager.sceneLoaded += OnSceneLoaded;
SceneManager.sceneUnloaded -= OnSceneUnloaded;
SceneManager.sceneUnloaded += OnSceneUnloaded;
ActivateEventSystemIfNeeded();
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
SceneManager.sceneUnloaded -= OnSceneUnloaded;
DeactivateEventSystem();
}
private void OnSceneLoaded( Scene scene, LoadSceneMode mode )
{
DeactivateEventSystem();
ActivateEventSystemIfNeeded();
}
private void OnSceneUnloaded( Scene current )
{
// Deactivate the embedded EventSystem before changing scenes because the new scene might have its own EventSystem
DeactivateEventSystem();
}
private void ActivateEventSystemIfNeeded()
{
if( embeddedEventSystem && !EventSystem.current )
embeddedEventSystem.SetActive( true );
}
private void DeactivateEventSystem()
{
if( embeddedEventSystem )
embeddedEventSystem.SetActive( false );
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: c3cc1b407f337e641ad32a2e91d5b478
timeCreated: 1658741613
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: