3.0 - unitypackage

This commit is contained in:
monitor1394
2022-01-05 21:40:48 +08:00
parent c160867765
commit 228a4b2840
846 changed files with 105 additions and 467693 deletions

View File

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

View File

@@ -0,0 +1,23 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class ComponentHandlerAttribute : Attribute
{
public readonly Type handler;
public readonly bool allowMultiple = true;
public ComponentHandlerAttribute(Type handler)
{
this.handler = handler;
this.allowMultiple = true;
}
public ComponentHandlerAttribute(Type handler, bool allowMultiple)
{
this.handler = handler;
this.allowMultiple = allowMultiple;
}
}
}

View File

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

View File

@@ -0,0 +1,42 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class CoordOptionsAttribute : Attribute
{
public readonly Type type0;
public readonly Type type1;
public readonly Type type2;
public readonly Type type3;
public CoordOptionsAttribute(Type coord)
{
type0 = coord;
}
public CoordOptionsAttribute(Type coord, Type coord2)
{
type0 = coord;
type1 = coord2;
}
public CoordOptionsAttribute(Type coord, Type coord2, Type coord3)
{
type0 = coord;
type1 = coord2;
type2 = coord3;
}
public CoordOptionsAttribute(Type coord, Type coord2, Type coord3, Type coord4)
{
type0 = coord;
type1 = coord2;
type2 = coord3;
type3 = coord4;
}
public bool Contains<T>() where T : CoordSystem
{
var type = typeof(T);
return (type == type0 || type == type1 || type == type2 || type == type3);
}
}
}

View File

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

View File

@@ -0,0 +1,15 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class DefaultAnimationAttribute : Attribute
{
public readonly AnimationType type;
public DefaultAnimationAttribute(AnimationType handler)
{
this.type = handler;
}
}
}

View File

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

View File

@@ -0,0 +1,15 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ListFor : Attribute
{
public readonly Type type;
public ListFor(Type type)
{
this.type = type;
}
}
}

View File

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

View File

@@ -0,0 +1,12 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class ListForComponent : ListFor
{
public ListForComponent(Type type) : base(type)
{
}
}
}

View File

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

View File

@@ -0,0 +1,12 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class ListForSerie : ListFor
{
public ListForSerie(Type type) : base(type)
{
}
}
}

View File

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

View File

@@ -0,0 +1,28 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class RequireChartComponentAttribute : Attribute
{
public readonly Type type0;
public readonly Type type1;
public readonly Type type2;
public RequireChartComponentAttribute(Type requiredComponent)
{
type0 = requiredComponent;
}
public RequireChartComponentAttribute(Type requiredComponent, Type requiredComponent2)
{
type0 = requiredComponent;
type1 = requiredComponent2;
}
public RequireChartComponentAttribute(Type requiredComponent, Type requiredComponent2, Type requiredComponent3)
{
type0 = requiredComponent;
type1 = requiredComponent2;
type2 = requiredComponent3;
}
}
}

View File

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

View File

@@ -0,0 +1,49 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
/// <summary>
/// What serie can convert to me
/// </summary>
public sealed class SerieConvertAttribute : Attribute
{
public readonly Type type0;
public readonly Type type1;
public readonly Type type2;
public readonly Type type3;
public SerieConvertAttribute(Type serie)
{
type0 = serie;
}
public SerieConvertAttribute(Type serie, Type serie2)
{
type0 = serie;
type1 = serie2;
}
public SerieConvertAttribute(Type serie, Type serie2, Type serie3)
{
type0 = serie;
type1 = serie2;
type2 = serie3;
}
public SerieConvertAttribute(Type serie, Type serie2, Type serie3, Type serie4)
{
type0 = serie;
type1 = serie2;
type2 = serie3;
type3 = serie4;
}
public bool Contains<T>() where T : Serie
{
return Contains(typeof(T));
}
public bool Contains(Type type)
{
return (type == type0 || type == type1 || type == type2 || type == type3);
}
}
}

View File

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

View File

@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class SerieExtraComponentAttribute : Attribute
{
public readonly List<Type> types = new List<Type>();
public SerieExtraComponentAttribute()
{
}
public SerieExtraComponentAttribute(Type type1)
{
types.Add(type1);
}
public SerieExtraComponentAttribute(Type type1, Type type2)
{
types.Add(type1);
types.Add(type2);
}
public SerieExtraComponentAttribute(Type type1, Type type2, Type type3)
{
types.Add(type1);
types.Add(type2);
types.Add(type3);
}
public SerieExtraComponentAttribute(Type type1, Type type2, Type type3, Type type4)
{
types.Add(type1);
types.Add(type2);
types.Add(type3);
types.Add(type4);
}
public SerieExtraComponentAttribute(Type type1, Type type2, Type type3, Type type4, Type type5)
{
types.Add(type1);
types.Add(type2);
types.Add(type3);
types.Add(type4);
types.Add(type5);
}
public SerieExtraComponentAttribute(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6)
{
types.Add(type1);
types.Add(type2);
types.Add(type3);
types.Add(type4);
types.Add(type5);
types.Add(type6);
}
public SerieExtraComponentAttribute(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7)
{
types.Add(type1);
types.Add(type2);
types.Add(type3);
types.Add(type4);
types.Add(type5);
types.Add(type6);
types.Add(type7);
}
public bool Contains<T>() where T : ISerieExtraComponent
{
return Contains(typeof(T));
}
public bool Contains(Type type)
{
return types.Contains(type);
}
}
}

View File

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

View File

@@ -0,0 +1,23 @@
using System;
namespace XCharts
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class SerieHandlerAttribute : Attribute
{
public readonly Type handler;
public readonly bool allowMultiple = true;
public SerieHandlerAttribute(Type handler)
{
this.handler = handler;
this.allowMultiple = true;
}
public SerieHandlerAttribute(Type handler, bool allowMultiple)
{
this.handler = handler;
this.allowMultiple = allowMultiple;
}
}
}

View File

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

View File

@@ -0,0 +1,421 @@

using UnityEngine;
using System.Collections.Generic;
using System;
namespace XCharts
{
public partial class BaseChart
{
public bool TryAddChartComponent<T>() where T : MainComponent
{
return TryAddChartComponent(typeof(T));
}
public bool TryAddChartComponent(Type type)
{
if (CanAddChartComponent(type))
{
AddChartComponent(type);
return true;
}
else
{
return false;
}
}
public bool TryAddChartComponent<T>(out T component) where T : MainComponent
{
var type = typeof(T);
if (CanAddChartComponent(type))
{
component = AddChartComponent(type) as T;
return true;
}
else
{
component = null;
return false;
}
}
public T AddChartComponent<T>() where T : MainComponent
{
return (T)AddChartComponent(typeof(T));
}
public T AddChartComponentWhenNoExist<T>() where T : MainComponent
{
if (HasChartComponent<T>()) return null;
return AddChartComponent<T>();
}
public MainComponent AddChartComponent(Type type)
{
if (!CanAddChartComponent(type))
{
throw new InvalidOperationException("DisallowMultipleComponent:" + type.Name);
}
CheckAddRequireChartComponent(type);
var component = Activator.CreateInstance(type) as MainComponent;
if (component == null)
throw new InvalidOperationException("DisallowMultipleComponent:" + type.Name);
component.SetDefaultValue();
if (component is IUpdateRuntimeData)
(component as IUpdateRuntimeData).UpdateRuntimeData(chartX, chartY, chartWidth, chartHeight);
AddComponent(component);
m_Components.Sort();
CreateComponentHandler(component);
return component;
}
private void AddComponent(MainComponent component)
{
var type = component.GetType();
m_Components.Add(component);
List<MainComponent> list;
if (!m_ComponentMaps.TryGetValue(type, out list))
{
list = new List<MainComponent>();
m_ComponentMaps[type] = list;
}
component.index = list.Count;
list.Add(component);
}
private void CheckAddRequireChartComponent(Type type)
{
if (Attribute.IsDefined(type, typeof(RequireChartComponentAttribute)))
{
foreach (var obj in type.GetCustomAttributes(typeof(RequireChartComponentAttribute), false))
{
var attribute = obj as RequireChartComponentAttribute;
if (attribute.type0 != null && !HasChartComponent(attribute.type0))
AddChartComponent(attribute.type0);
if (attribute.type1 != null && !HasChartComponent(attribute.type1))
AddChartComponent(attribute.type1);
if (attribute.type2 != null && !HasChartComponent(attribute.type2))
AddChartComponent(attribute.type2);
}
}
}
private void CreateComponentHandler(MainComponent component)
{
if (!component.GetType().IsDefined(typeof(ComponentHandlerAttribute), false))
{
Debug.LogError("MainComponent no Handler:" + component.GetType());
return;
}
var attrubte = component.GetType().GetAttribute<ComponentHandlerAttribute>();
if (attrubte.handler == null)
return;
var handler = (MainComponentHandler)Activator.CreateInstance(attrubte.handler);
handler.attribute = attrubte;
handler.chart = this;
handler.SetComponent(component);
component.handler = handler;
m_ComponentHandlers.Add(handler);
}
public bool RemoveChartComponent<T>(int index = 0)
where T : MainComponent
{
return RemoveChartComponent(typeof(T), index);
}
public int RemoveChartComponents<T>()
where T : MainComponent
{
return RemoveChartComponents(typeof(T));
}
public void RemoveAllChartComponent()
{
m_Components.Clear();
InitComponentHandlers();
}
public bool RemoveChartComponent(Type type, int index = 0)
{
MainComponent toRemove = null;
for (int i = 0; i < m_Components.Count; i++)
{
if (m_Components[i].GetType() == type && m_Components[i].index == index)
{
toRemove = m_Components[i];
break;
}
}
return RemoveChartComponent(toRemove);
}
public int RemoveChartComponents(Type type)
{
int count = 0;
for (int i = m_Components.Count - 1; i > 0; i--)
{
if (m_Components[i].GetType() == type)
{
RemoveChartComponent(m_Components[i]);
count++;
}
}
return count;
}
public bool RemoveChartComponent(MainComponent component)
{
if (component == null) return false;
if (m_Components.Remove(component))
{
if (component.gameObject != null)
ChartHelper.SetActive(component.gameObject, false);
InitComponentHandlers();
RefreshChart();
return true;
}
return false;
}
public bool CanAddChartComponent(Type type)
{
if (!type.IsSubclassOf(typeof(MainComponent))) return false;
if (!m_TypeListForComponent.ContainsKey(type)) return false;
if (CanMultipleComponent(type)) return !HasChartComponent(type);
else return true;
}
public bool HasChartComponent<T>()
where T : MainComponent
{
return HasChartComponent(typeof(T));
}
public bool HasChartComponent(Type type)
{
foreach (var component in m_Components)
{
if (component == null) continue;
if (component.GetType() == type)
return true;
}
return false;
}
public bool CanMultipleComponent(Type type)
{
return Attribute.IsDefined(type, typeof(DisallowMultipleComponent));
}
public int GetChartComponentNum<T>() where T : MainComponent
{
return GetChartComponentNum(typeof(T));
}
public int GetChartComponentNum(Type type)
{
List<MainComponent> list;
if (m_ComponentMaps.TryGetValue(type, out list))
return list.Count;
else
return 0;
}
public T GetChartComponent<T>(int index = 0) where T : MainComponent
{
foreach (var component in m_Components)
{
if (component is T && component.index == index)
return component as T;
}
return null;
}
public List<MainComponent> GetChartComponents<T>() where T : MainComponent
{
return m_ComponentMaps[typeof(T)];
}
public T GetOrAddChartComponent<T>() where T : MainComponent
{
var component = GetChartComponent<T>();
if (component == null)
return AddChartComponent<T>();
else
return component;
}
public bool TryGetChartComponent<T>(out T component, int index = 0)
where T : MainComponent
{
component = null;
foreach (var com in m_Components)
{
if (com is T && com.index == index)
{
component = (T)com;
return true;
}
}
return false;
}
public GridCoord GetGrid(Vector2 local)
{
List<MainComponent> list;
if (m_ComponentMaps.TryGetValue(typeof(GridCoord), out list))
{
foreach (var component in list)
{
var grid = component as GridCoord;
if (grid.Contains(local)) return grid;
}
}
return null;
}
public GridCoord GetGridOfDataZoom(DataZoom dataZoom)
{
GridCoord grid = null;
if (dataZoom.xAxisIndexs != null && dataZoom.xAxisIndexs.Count > 0)
{
var xAxis = GetChartComponent<XAxis>(dataZoom.xAxisIndexs[0]);
grid = GetChartComponent<GridCoord>(xAxis.gridIndex);
}
else if (dataZoom.yAxisIndexs != null && dataZoom.yAxisIndexs.Count > 0)
{
var yAxis = GetChartComponent<YAxis>(dataZoom.yAxisIndexs[0]);
grid = GetChartComponent<GridCoord>(yAxis.gridIndex);
}
if (grid == null) return GetChartComponent<GridCoord>();
else return grid;
}
public DataZoom GetDataZoomOfAxis(Axis axis)
{
foreach (var component in m_Components)
{
if (component is DataZoom)
{
var dataZoom = component as DataZoom;
if (!dataZoom.enable) continue;
if (dataZoom.IsContainsAxis(axis)) return dataZoom;
}
}
return null;
}
public VisualMap GetVisualMapOfSerie(Serie serie)
{
foreach (var component in m_Components)
{
if (component is VisualMap)
{
var visualMap = component as VisualMap;
if (visualMap.serieIndex == serie.index) return visualMap;
}
}
return null;
}
public void GetDataZoomOfSerie(Serie serie, out DataZoom xDataZoom, out DataZoom yDataZoom)
{
xDataZoom = null;
yDataZoom = null;
if (serie == null) return;
foreach (var component in m_Components)
{
if (component is DataZoom)
{
var dataZoom = component as DataZoom;
if (!dataZoom.enable) continue;
if (dataZoom.IsContainsXAxis(serie.xAxisIndex))
{
xDataZoom = dataZoom;
}
if (dataZoom.IsContainsYAxis(serie.yAxisIndex))
{
yDataZoom = dataZoom;
}
}
}
}
/// <summary>
/// reutrn true when all the show axis is `Value` type.
/// 纯数值坐标轴(数值轴或对数轴)。
/// </summary>
public bool IsAllAxisValue()
{
foreach (var component in m_Components)
{
if (component is Axis)
{
var axis = component as Axis;
if (axis.show && !axis.IsValue() && !axis.IsLog() && !axis.IsTime()) return false;
}
}
return true;
}
/// <summary>
/// 纯类目轴。
/// </summary>
public bool IsAllAxisCategory()
{
foreach (var component in m_Components)
{
if (component is Axis)
{
var axis = component as Axis;
if (axis.show && !axis.IsCategory()) return false;
}
}
return true;
}
public bool IsInAnyGrid(Vector2 local)
{
List<MainComponent> list;
if (m_ComponentMaps.TryGetValue(typeof(GridCoord), out list))
{
foreach (var grid in list)
{
if ((grid as GridCoord).Contains(local)) return true;
}
}
return false;
}
internal string GetTooltipCategory(int dataIndex, DataZoom dataZoom = null)
{
var xAxis = GetChartComponent<XAxis>();
var yAxis = GetChartComponent<YAxis>();
if (yAxis.IsCategory())
{
return yAxis.GetData((int)yAxis.context.pointerValue, dataZoom);
}
else if (xAxis.IsCategory())
{
return xAxis.GetData((int)xAxis.context.pointerValue, dataZoom);
}
return null;
}
internal string GetTooltipCategory(int dataIndex, Serie serie, DataZoom dataZoom = null)
{
var xAxis = GetChartComponent<XAxis>(serie.xAxisIndex);
var yAxis = GetChartComponent<YAxis>(serie.yAxisIndex);
if (yAxis.IsCategory())
{
return yAxis.GetData((int)yAxis.context.pointerValue, dataZoom);
}
else if (xAxis.IsCategory())
{
return xAxis.GetData((int)xAxis.context.pointerValue, dataZoom);
}
return null;
}
}
}

View File

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

View File

@@ -0,0 +1,34 @@

using UnityEngine;
using System.Collections.Generic;
using System;
namespace XCharts
{
public partial class BaseChart
{
public virtual void InitAxisRuntimeData(Axis axis)
{
}
public virtual void GetSeriesMinMaxValue(Axis axis, int axisIndex, out double tempMinValue, out double tempMaxValue)
{
if (IsAllAxisValue())
{
if (axis is XAxis)
{
SeriesHelper.GetXMinMaxValue(m_Series, null, axisIndex, true, axis.inverse, out tempMinValue, out tempMaxValue);
}
else
{
SeriesHelper.GetYMinMaxValue(m_Series, null, axisIndex, true, axis.inverse, out tempMinValue, out tempMaxValue);
}
}
else
{
SeriesHelper.GetYMinMaxValue(m_Series, null, axisIndex, false, axis.inverse, out tempMinValue, out tempMaxValue);
}
AxisHelper.AdjustMinMaxValue(axis, ref tempMinValue, ref tempMaxValue, true);
}
}
}

View File

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

View File

@@ -0,0 +1,131 @@

using UnityEngine;
using UnityEngine.UI;
using XUGL;
namespace XCharts
{
public partial class BaseChart
{
public void DrawClipPolygon(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4,
Color32 color, bool clip, GridCoord grid)
{
DrawClipPolygon(vh, p1, p2, p3, p4, color, color, clip, grid);
}
public void DrawClipPolygon(VertexHelper vh, Vector3 p, float radius, Color32 color,
bool clip, bool vertical, GridCoord grid)
{
if (!IsInChart(p)) return;
if (!clip || (clip && (grid.Contains(p))))
UGL.DrawSquare(vh, p, radius, color);
}
public void DrawClipPolygon(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4,
Color32 startColor, Color32 toColor, bool clip, GridCoord grid)
{
ClampInChart(ref p1);
ClampInChart(ref p2);
ClampInChart(ref p3);
ClampInChart(ref p4);
if (clip)
{
p1 = ClampInGrid(grid, p1);
p2 = ClampInGrid(grid, p2);
p3 = ClampInGrid(grid, p3);
p4 = ClampInGrid(grid, p4);
}
if (!clip || (clip && (grid.Contains(p1) && grid.Contains(p2) && grid.Contains(p3)
&& grid.Contains(p4))))
UGL.DrawQuadrilateral(vh, p1, p2, p3, p4, startColor, toColor);
}
public void DrawClipPolygon(VertexHelper vh, ref Vector3 p1, ref Vector3 p2, ref Vector3 p3, ref Vector3 p4,
Color32 startColor, Color32 toColor, bool clip, GridCoord grid)
{
ClampInChart(ref p1);
ClampInChart(ref p2);
ClampInChart(ref p3);
ClampInChart(ref p4);
if (clip)
{
p1 = ClampInGrid(grid, p1);
p2 = ClampInGrid(grid, p2);
p3 = ClampInGrid(grid, p3);
p4 = ClampInGrid(grid, p4);
}
if (!clip
|| (clip && (grid.Contains(p1) && grid.Contains(p2) && grid.Contains(p3)
&& grid.Contains(p4))))
UGL.DrawQuadrilateral(vh, p1, p2, p3, p4, startColor, toColor);
}
public void DrawClipTriangle(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Color32 color,
bool clip, GridCoord grid)
{
DrawClipTriangle(vh, p1, p2, p3, color, color, color, clip, grid);
}
public void DrawClipTriangle(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Color32 color,
Color32 color2, Color32 color3, bool clip, GridCoord grid)
{
if (!IsInChart(p1) || !IsInChart(p2) || !IsInChart(p3)) return;
if (!clip || (clip && (grid.Contains(p1) || grid.Contains(p2) || grid.Contains(p3))))
UGL.DrawTriangle(vh, p1, p2, p3, color, color2, color3);
}
public void DrawClipLine(VertexHelper vh, Vector3 p1, Vector3 p2, float size, Color32 color,
bool clip, GridCoord grid)
{
if (!IsInChart(p1) || !IsInChart(p2)) return;
if (!clip || (clip && (grid.Contains(p1) || grid.Contains(p2))))
UGL.DrawLine(vh, p1, p2, size, color);
}
public void DrawClipSymbol(VertexHelper vh, SymbolType type, float symbolSize, float tickness,
Vector3 pos, Color32 color, Color32 toColor, Color32 emptyColor, float gap, bool clip, float[] cornerRadius, GridCoord grid,
Vector3 startPos)
{
if (!IsInChart(pos)) return;
if (!clip || (clip && (grid.Contains(pos))))
DrawSymbol(vh, type, symbolSize, tickness, pos, color, toColor, emptyColor, gap, cornerRadius, startPos);
}
public void DrawClipZebraLine(VertexHelper vh, Vector3 p1, Vector3 p2, float size, float zebraWidth,
float zebraGap, Color32 color, Color32 toColor, bool clip, GridCoord grid)
{
ClampInChart(ref p1);
ClampInChart(ref p2);
UGL.DrawZebraLine(vh, p1, p2, size, zebraWidth, zebraGap, color, toColor);
}
public void DrawSymbol(VertexHelper vh, SymbolType type, float symbolSize,
float tickness, Vector3 pos, Color32 color, Color32 toColor, Color32 emptyColor, float gap, float[] cornerRadius)
{
DrawSymbol(vh, type, symbolSize, tickness, pos, color, toColor, emptyColor, gap, cornerRadius, Vector3.zero);
}
public void DrawSymbol(VertexHelper vh, SymbolType type, float symbolSize,
float tickness, Vector3 pos, Color32 color, Color32 toColor, Color32 emptyColor, float gap, float[] cornerRadius, Vector3 startPos)
{
var backgroundColor = theme.GetBackgroundColor(GetChartComponent<Background>());
if (ChartHelper.IsClearColor(emptyColor))
emptyColor = backgroundColor;
var smoothness = settings.cicleSmoothness;
ChartDrawer.DrawSymbol(vh, type, symbolSize, tickness, pos, color, toColor, gap,
cornerRadius, emptyColor, backgroundColor, smoothness, startPos);
}
public Color32 GetXLerpColor(Color32 areaColor, Color32 areaToColor, Vector3 pos, GridCoord grid)
{
if (ChartHelper.IsValueEqualsColor(areaColor, areaToColor)) return areaColor;
return Color32.Lerp(areaToColor, areaColor, (pos.y - grid.context.y) / grid.context.height);
}
public Color32 GetYLerpColor(Color32 areaColor, Color32 areaToColor, Vector3 pos, GridCoord grid)
{
if (ChartHelper.IsValueEqualsColor(areaColor, areaToColor)) return areaColor;
return Color32.Lerp(areaToColor, areaColor, (pos.x - grid.context.x) / grid.context.width);
}
}
}

View File

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

View File

@@ -0,0 +1,847 @@

using UnityEngine;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace XCharts
{
public partial class BaseChart
{
public T AddSerie<T>(string serieName = null, bool show = true, bool addToHead = false) where T : Serie
{
if (!CanAddSerie<T>()) return null;
var index = -1;
var serie = InsertSerie(index, typeof(T), serieName, show, addToHead) as T;
CreateSerieHandler(serie);
return serie;
}
public T InsertSerie<T>(int index, string serieName = null, bool show = true) where T : Serie
{
if (!CanAddSerie<T>()) return null;
return InsertSerie(index, typeof(T), serieName, show) as T;
}
public void InsertSerie(Serie serie, int index = -1, bool addToHead = false)
{
serie.AnimationRestart();
if (addToHead) m_Series.Insert(0, serie);
else if (index >= 0) m_Series.Insert(index, serie);
else m_Series.Add(serie);
ResetSeriesIndex();
SeriesHelper.UpdateSerieNameList(this, ref m_LegendRealShowName);
}
public bool MoveUpSerie(int serieIndex)
{
if (serieIndex < 0 || serieIndex > m_Series.Count - 1) return false;
if (serieIndex == 0) return false;
var up = GetSerie(serieIndex - 1);
var temp = GetSerie(serieIndex);
m_Series[serieIndex - 1] = temp;
m_Series[serieIndex] = up;
ResetSeriesIndex();
InitSerieHandlers();
RefreshChart();
return true;
}
public bool MoveDownSerie(int serieIndex)
{
if (serieIndex < 0 || serieIndex > m_Series.Count - 1) return false;
if (serieIndex == m_Series.Count - 1) return false;
var down = GetSerie(serieIndex + 1);
var temp = GetSerie(serieIndex);
m_Series[serieIndex + 1] = temp;
m_Series[serieIndex] = down;
ResetSeriesIndex();
InitSerieHandlers();
RefreshChart();
return true;
}
public bool CanAddSerie<T>() where T : Serie
{
return CanAddSerie(typeof(T));
}
public bool CanAddSerie(Type type)
{
return m_TypeListForSerie.ContainsKey(type);
}
public bool HasSerie<T>() where T : Serie
{
return HasSerie(typeof(T));
}
public bool HasSerie(Type type)
{
if (!type.IsSubclassOf(typeof(Serie))) return false;
foreach (var serie in m_Series)
{
if (serie.GetType() == type)
return true;
}
return false;
}
public T GetSerie<T>() where T : Serie
{
foreach (var serie in m_Series)
{
if (serie is T) return serie as T;
}
return null;
}
public Serie GetSerie(string serieName)
{
foreach (var serie in m_Series)
{
if (serie.serieName.Equals(serieName)) return serie;
}
return null;
}
public Serie GetSerie(int serieIndex)
{
if (serieIndex < 0 || serieIndex > m_Series.Count - 1) return null;
return m_Series[serieIndex];
}
public T GetSerie<T>(int serieIndex) where T : Serie
{
if (serieIndex < 0 || serieIndex > m_Series.Count - 1) return null;
return m_Series[serieIndex] as T;
}
public void RemoveSerie(string serieName)
{
for (int i = m_Series.Count - 1; i >= 0; i--)
{
var serie = m_Series[i];
if (string.IsNullOrEmpty(serie.serieName) && serie.serieName.Equals(serieName))
RemoveSerie(serie);
}
}
public void RemoveSerie(int serieIndex)
{
if (serieIndex < 0 || serieIndex > m_Series.Count - 1) return;
RemoveSerie(m_Series[serieIndex]);
}
public void RemoveSerie<T>() where T : Serie
{
for (int i = m_Series.Count - 1; i >= 0; i--)
{
var serie = m_Series[i];
if (serie is T)
RemoveSerie(serie);
}
}
public void RemoveSerie(Serie serie)
{
serie.OnRemove();
m_Series.Remove(serie);
RefreshChart();
}
public bool CovertSerie<T>(Serie serie) where T : Serie
{
return CovertSerie(serie, typeof(T));
}
public bool CovertSerie(Serie serie, Type type)
{
try
{
var newSerie = type.InvokeMember("CovertSerie",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null,
new object[] { serie }) as Serie;
return ReplaceSerie(serie, newSerie);
}
catch
{
Debug.LogError(string.Format("CovertSerie Failed: can't found {0}.CovertSerie(Serie serie)", type.Name));
return false;
}
}
public bool ReplaceSerie(Serie oldSerie, Serie newSerie)
{
if (oldSerie == null || newSerie == null)
return false;
var index = m_Series.IndexOf(oldSerie);
if (index < 0)
return false;
oldSerie.OnRemove();
m_Series.RemoveAt(index);
m_Series.Insert(index, newSerie);
ResetSeriesIndex();
InitSerieHandlers();
RefreshAllComponent();
RefreshChart();
return true;
}
/// <summary>
/// Add a data to serie.
/// If serieName doesn't exist in legend,will be add to legend.
/// 添加一个数据到指定的系列中。
/// </summary>
/// <param name="serieName">the name of serie</param>
/// <param name="data">the data to add</param>
/// <param name="dataName">the name of data</param>
/// <returns>Returns True on success</returns>
public SerieData AddData(string serieName, double data, string dataName = null)
{
var serie = GetSerie(serieName);
if (serie != null)
{
var serieData = serie.AddYData(data, dataName);
RefreshPainter(serie.painter);
return serieData;
}
return null;
}
/// <summary>
/// Add a data to serie.
/// 添加一个数据到指定的系列中。
/// </summary>
/// <param name="serieIndex">the index of serie</param>
/// <param name="data">the data to add</param>
/// <param name="dataName">the name of data</param>
/// <returns>Returns True on success</returns>
public SerieData AddData(int serieIndex, double data, string dataName = null)
{
var serie = GetSerie(serieIndex);
if (serie != null)
{
var serieData = serie.AddYData(data, dataName);
RefreshPainter(serie.painter);
return serieData;
}
return null;
}
/// <summary>
/// Add an arbitray dimension data to serie,such as (x,y,z,...).
/// 添加多维数据x,y,z...)到指定的系列中。
/// </summary>
/// <param name="serieName">the name of serie</param>
/// <param name="multidimensionalData">the (x,y,z,...) data</param>
/// <param name="dataName">the name of data</param>
/// <returns>Returns True on success</returns>
public SerieData AddData(string serieName, List<double> multidimensionalData, string dataName = null)
{
var serie = GetSerie(serieName);
if (serie != null)
{
var serieData = serie.AddData(multidimensionalData, dataName);
RefreshPainter(serie.painter);
return serieData;
}
return null;
}
/// <summary>
/// Add an arbitray dimension data to serie,such as (x,y,z,...).
/// 添加多维数据x,y,z...)到指定的系列中。
/// </summary>
/// <param name="serieIndex">the index of serie,index starts at 0</param>
/// <param name="multidimensionalData">the (x,y,z,...) data</param>
/// <param name="dataName">the name of data</param>
/// <returns>Returns True on success</returns>
public SerieData AddData(int serieIndex, List<double> multidimensionalData, string dataName = null)
{
var serie = GetSerie(serieIndex);
if (serie != null)
{
var serieData = serie.AddData(multidimensionalData, dataName);
RefreshPainter(serie.painter);
return serieData;
}
return null;
}
/// <summary>
/// Add a (x,y) data to serie.
/// 添加x,y数据到指定系列中。
/// </summary>
/// <param name="serieName">the name of serie</param>
/// <param name="xValue">x data</param>
/// <param name="yValue">y data</param>
/// <param name="dataName">the name of data</param>
/// <returns>Returns True on success</returns>
public SerieData AddData(string serieName, double xValue, double yValue, string dataName = null)
{
var serie = GetSerie(serieName);
if (serie != null)
{
var serieData = serie.AddXYData(xValue, yValue, dataName);
RefreshPainter(serie.painter);
return serieData;
}
return null;
}
/// <summary>
/// Add a (x,y) data to serie.
/// 添加x,y数据到指定系列中。
/// </summary>
/// <param name="serieIndex">the index of serie</param>
/// <param name="xValue">x data</param>
/// <param name="yValue">y data</param>
/// <param name="dataName">the name of data</param>
/// <returns>Returns True on success</returns>
public SerieData AddData(int serieIndex, double xValue, double yValue, string dataName = null)
{
var serie = GetSerie(serieIndex);
if (serie != null)
{
var serieData = serie.AddXYData(xValue, yValue, dataName);
RefreshPainter(serie.painter);
return serieData;
}
return null;
}
public SerieData AddData(int serieIndex, double open, double close, double lowest, double heighest, string dataName = null)
{
var serie = GetSerie(serieIndex);
if (serie != null)
{
var serieData = serie.AddData(open, close, lowest, heighest, dataName);
RefreshPainter(serie.painter);
return serieData;
}
return null;
}
public SerieData AddData(string serieName, double open, double close, double lowest, double heighest, string dataName = null)
{
var serie = GetSerie(serieName);
if (serie != null)
{
var serieData = serie.AddData(open, close, lowest, heighest, dataName);
RefreshPainter(serie.painter);
return serieData;
}
return null;
}
/// <summary>
/// Update serie data by serie name.
/// 更新指定系列中的指定索引数据。
/// </summary>
/// <param name="serieName">the name of serie</param>
/// <param name="dataIndex">the index of data</param>
/// <param name="value">the data will be update</param>
public bool UpdateData(string serieName, int dataIndex, double value)
{
var serie = GetSerie(serieName);
if (serie != null)
{
serie.UpdateYData(dataIndex, value);
RefreshPainter(serie);
return true;
}
return false;
}
/// <summary>
/// Update serie data by serie index.
/// 更新指定系列中的指定索引数据。
/// </summary>
/// <param name="serieIndex">the index of serie</param>
/// <param name="dataIndex">the index of data</param>
/// <param name="value">the data will be update</param>
public bool UpdateData(int serieIndex, int dataIndex, double value)
{
var serie = GetSerie(serieIndex);
if (serie != null)
{
serie.UpdateYData(dataIndex, value);
RefreshPainter(serie);
return true;
}
return false;
}
/// <summary>
/// 更新指定系列指定索引的数据项的多维数据。
/// </summary>
/// <param name="serieName"></param>
/// <param name="dataIndex"></param>
/// <param name="multidimensionalData">一个数据项的多维数据列表,而不是多个数据项的数据</param>
public bool UpdateData(string serieName, int dataIndex, List<double> multidimensionalData)
{
var serie = GetSerie(serieName);
if (serie != null)
{
serie.UpdateData(dataIndex, multidimensionalData);
RefreshPainter(serie);
return true;
}
return false;
}
/// <summary>
/// 更新指定系列指定索引的数据项的多维数据。
/// </summary>
/// <param name="serieIndex"></param>
/// <param name="dataIndex"></param>
/// <param name="multidimensionalData">一个数据项的多维数据列表,而不是多个数据项的数据</param>
public bool UpdateData(int serieIndex, int dataIndex, List<double> multidimensionalData)
{
var serie = GetSerie(serieIndex);
if (serie != null)
{
serie.UpdateData(dataIndex, multidimensionalData);
RefreshPainter(serie);
return true;
}
return false;
}
/// <summary>
/// 更新指定系列指定索引指定维数的数据。维数从0开始。
/// </summary>
/// <param name="serieName"></param>
/// <param name="dataIndex"></param>
/// <param name="dimension">指定维数从0开始</param>
/// <param name="value"></param>
public bool UpdateData(string serieName, int dataIndex, int dimension, double value)
{
var serie = GetSerie(serieName);
if (serie != null)
{
serie.UpdateData(dataIndex, dimension, value);
RefreshPainter(serie);
return true;
}
return false;
}
/// <summary>
/// 更新指定系列指定索引指定维数的数据。维数从0开始。
/// </summary>
/// <param name="serieIndex"></param>
/// <param name="dataIndex"></param>
/// <param name="dimension">指定维数从0开始</param>
/// <param name="value"></param>
public bool UpdateData(int serieIndex, int dataIndex, int dimension, double value)
{
var serie = GetSerie(serieIndex);
if (serie != null)
{
serie.UpdateData(dataIndex, dimension, value);
RefreshPainter(serie);
return true;
}
return false;
}
/// <summary>
/// Update serie data name.
/// 更新指定系列中的指定索引数据名称。
/// </summary>
/// <param name="serieName"></param>
/// <param name="dataIndex"></param>
/// <param name="dataName"></param>
public bool UpdateDataName(string serieName, int dataIndex, string dataName)
{
var serie = GetSerie(serieName);
if (serie != null)
{
serie.UpdateDataName(dataIndex, dataName);
return true;
}
return false;
}
/// <summary>
/// Update serie data name.
/// 更新指定系列中的指定索引数据名称。
/// </summary>
/// <param name="serieIndex"></param>
/// <param name="dataName"></param>
/// <param name="dataIndex"></param>
public bool UpdateDataName(int serieIndex, int dataIndex, string dataName)
{
var serie = GetSerie(serieIndex);
if (serie != null)
{
serie.UpdateDataName(dataIndex, dataName);
return true;
}
return false;
}
public int GetAllSerieDataCount()
{
var total = 0;
foreach (var serie in m_Series)
total += serie.dataCount;
return total;
}
/// <summary>
/// Whether to show serie.
/// 设置指定系列是否显示。
/// </summary>
/// <param name="serieName">the name of serie</param>
/// <param name="active">Active or not</param>
public void SetSerieActive(string serieName, bool active)
{
var serie = GetSerie(serieName);
if (serie != null)
SetSerieActive(serie, active);
}
/// <summary>
/// Whether to show serie.
/// 设置指定系列是否显示。
/// </summary>
/// <param name="serieIndex">the index of serie</param>
/// <param name="active">Active or not</param>
public void SetSerieActive(int serieIndex, bool active)
{
var serie = GetSerie(serieIndex);
if (serie != null)
SetSerieActive(serie, active);
}
public void SetSerieActive(Serie serie, bool active)
{
serie.show = active;
serie.AnimationReset();
if (active) serie.AnimationFadeIn();
UpdateLegendColor(serie.serieName, active);
}
/// <summary>
/// Add a category data to xAxis.
/// 添加一个类目数据到指定的x轴。
/// </summary>
/// <param name="category">the category data</param>
/// <param name="xAxisIndex">which xAxis should category add to</param>
public void AddXAxisData(string category, int xAxisIndex = 0)
{
var xAxis = GetChartComponent<XAxis>(xAxisIndex);
if (xAxis != null)
{
xAxis.AddData(category);
}
}
/// <summary>
/// Update category data.
/// 更新X轴类目数据。
/// </summary>
/// <param name="index">the index of category data</param>
/// <param name="category"></param>
/// <param name="xAxisIndex">which xAxis index to update to</param>
public void UpdateXAxisData(int index, string category, int xAxisIndex = 0)
{
var xAxis = GetChartComponent<XAxis>(xAxisIndex);
if (xAxis != null)
{
xAxis.UpdateData(index, category);
}
}
/// <summary>
/// Add an icon to xAxis.
/// 添加一个图标到指定的x轴。
/// </summary>
/// <param name="icon"></param>
/// <param name="xAxisIndex"></param>
public void AddXAxisIcon(Sprite icon, int xAxisIndex = 0)
{
var xAxis = GetChartComponent<XAxis>(xAxisIndex);
if (xAxis != null)
{
xAxis.AddIcon(icon);
}
}
/// <summary>
/// Update xAxis icon.
/// 更新X轴图标。
/// </summary>
/// <param name="index"></param>
/// <param name="icon"></param>
/// <param name="xAxisIndex"></param>
public void UdpateXAxisIcon(int index, Sprite icon, int xAxisIndex = 0)
{
var xAxis = GetChartComponent<XAxis>(xAxisIndex);
if (xAxis != null)
{
xAxis.UpdateIcon(index, icon);
}
}
/// <summary>
/// Add a category data to yAxis.
/// 添加一个类目数据到指定的y轴。
/// </summary>
/// <param name="category">the category data</param>
/// <param name="yAxisIndex">which yAxis should category add to</param>
public void AddYAxisData(string category, int yAxisIndex = 0)
{
var yAxis = GetChartComponent<YAxis>(yAxisIndex);
if (yAxis != null)
{
yAxis.AddData(category);
}
}
/// <summary>
/// Update category data.
/// 更新Y轴类目数据。
/// </summary>
/// <param name="index">the index of category data</param>
/// <param name="category"></param>
/// <param name="yAxisIndex">which yAxis index to update to</param>
public void UpdateYAxisData(int index, string category, int yAxisIndex = 0)
{
var yAxis = GetChartComponent<YAxis>(yAxisIndex);
if (yAxis != null)
{
yAxis.UpdateData(index, category);
}
}
/// <summary>
/// Add an icon to yAxis.
/// 添加一个图标到指定的y轴。
/// </summary>
/// <param name="icon"></param>
/// <param name="yAxisIndex"></param>
public void AddYAxisIcon(Sprite icon, int yAxisIndex = 0)
{
var yAxis = GetChartComponent<YAxis>(yAxisIndex);
if (yAxis != null)
{
yAxis.AddIcon(icon);
}
}
/// <summary>
/// 更新Y轴图标。
/// </summary>
/// <param name="index"></param>
/// <param name="icon"></param>
/// <param name="yAxisIndex"></param>
public void UpdateYAxisIcon(int index, Sprite icon, int yAxisIndex = 0)
{
var yAxis = GetChartComponent<YAxis>(yAxisIndex);
if (yAxis != null)
{
yAxis.UpdateIcon(index, icon);
}
}
public float GetSerieBarGap<T>() where T : Serie
{
float gap = 0f;
for (int i = 0; i < m_Series.Count; i++)
{
var serie = m_Series[i];
if (serie is T)
{
if (serie.barGap != 0)
{
gap = serie.barGap;
}
}
}
return gap;
}
public double GetSerieSameStackTotalValue<T>(string stack, int dataIndex) where T : Serie
{
if (string.IsNullOrEmpty(stack)) return 0;
double total = 0;
foreach (var serie in m_Series)
{
if (serie is T)
{
if (stack.Equals(serie.stack))
{
total += serie.data[dataIndex].data[1];
}
}
}
return total;
}
private HashSet<string> barStackSet = new HashSet<string>();
public float GetSerieTotalWidth<T>(float categoryWidth, float gap) where T : Serie
{
float total = 0;
float lastGap = 0;
barStackSet.Clear();
for (int i = 0; i < m_Series.Count; i++)
{
var serie = m_Series[i];
if (!serie.show) continue;
if (serie is T)
{
if (!string.IsNullOrEmpty(serie.stack))
{
if (barStackSet.Contains(serie.stack)) continue;
barStackSet.Add(serie.stack);
}
var width = GetStackBarWidth<T>(categoryWidth, serie);
if (gap == -1)
{
if (width > total) total = width;
}
else
{
lastGap = width * gap;
total += width;
total += lastGap;
}
}
}
if (total > 0 && gap != -1) total -= lastGap;
return total;
}
private float GetStackBarWidth<T>(float categoryWidth, Serie now) where T : Serie
{
if (string.IsNullOrEmpty(now.stack)) return now.GetBarWidth(categoryWidth);
float barWidth = 0;
for (int i = 0; i < m_Series.Count; i++)
{
var serie = m_Series[i];
if ((serie is T)
&& serie.show && now.stack.Equals(serie.stack))
{
if (serie.barWidth > barWidth) barWidth = serie.barWidth;
}
}
if (barWidth > 1) return barWidth;
else return barWidth * categoryWidth;
}
private List<string> tempList = new List<string>();
public int GetSerieIndexIfStack<T>(Serie currSerie) where T : Serie
{
tempList.Clear();
int index = 0;
for (int i = 0; i < m_Series.Count; i++)
{
var serie = m_Series[i];
if (!(serie is T)) continue;
if (string.IsNullOrEmpty(serie.stack))
{
if (serie.index == currSerie.index) return index;
tempList.Add(string.Empty);
index++;
}
else
{
if (!tempList.Contains(serie.stack))
{
if (serie.index == currSerie.index) return index;
tempList.Add(serie.stack);
index++;
}
else
{
if (serie.index == currSerie.index) return tempList.IndexOf(serie.stack);
}
}
}
return 0;
}
internal void InitSerieHandlers()
{
m_SerieHandlers.Clear();
for (int i = 0; i < m_Series.Count; i++)
{
var serie = m_Series[i];
serie.index = i;
CreateSerieHandler(serie);
}
}
private void CreateSerieHandler(Serie serie)
{
if (serie == null)
throw new ArgumentNullException("serie is null");
if (!serie.GetType().IsDefined(typeof(SerieHandlerAttribute), false))
{
Debug.LogError("Serie no Handler:" + serie.GetType());
return;
}
var attrubte = serie.GetType().GetAttribute<SerieHandlerAttribute>();
var handler = (SerieHandler)Activator.CreateInstance(attrubte.handler);
handler.attribute = attrubte;
handler.chart = this;
handler.SetSerie(serie);
serie.handler = handler;
m_SerieHandlers.Add(handler);
}
private Serie InsertSerie(int index, Type type, string serieName, bool show = true, bool addToHead = false)
{
CheckAddRequireChartComponent(type);
var serie = Activator.CreateInstance(type) as Serie;
serie.show = show;
serie.serieName = serieName;
serie.serieType = type.Name;
serie.index = m_Series.Count;
if (type == typeof(Scatter))
{
serie.symbol.show = true;
serie.symbol.type = SymbolType.Circle;
}
else if (type == typeof(Line))
{
serie.symbol.show = true;
serie.symbol.type = SymbolType.EmptyCircle;
}
else
{
serie.symbol.show = false;
}
InsertSerie(serie, index, addToHead);
return serie;
}
private void ResetSeriesIndex()
{
for (int i = 0; i < m_Series.Count; i++)
{
m_Series[i].index = i;
}
}
private void InternalAddSerie(Serie serie)
{
m_Series.Add(serie);
}
public string GenerateDefaultSerieName()
{
return "serie" + m_Series.Count;
}
}
}

View File

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

View File

@@ -0,0 +1,672 @@

using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System;
using UnityEngine.EventSystems;
using XUGL;
using System.Reflection;
namespace XCharts
{
[AddComponentMenu("XCharts/EmptyChart", 10)]
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
[DisallowMultipleComponent]
public partial class BaseChart : BaseGraph, ISerializationCallbackReceiver
{
[SerializeField] protected string m_ChartName;
[SerializeField] protected ThemeStyle m_Theme = new ThemeStyle();
[SerializeField] protected Settings m_Settings;
[SerializeField] protected DebugInfo m_DebugInfo = new DebugInfo();
#pragma warning disable 0414
[SerializeField] [ListForComponent(typeof(AngleAxis))] private List<AngleAxis> m_AngleAxes = new List<AngleAxis>();
[SerializeField] [ListForComponent(typeof(Background))] private List<Background> m_Backgrounds = new List<Background>();
[SerializeField] [ListForComponent(typeof(DataZoom))] private List<DataZoom> m_DataZooms = new List<DataZoom>();
[SerializeField] [ListForComponent(typeof(GridCoord))] private List<GridCoord> m_Grids = new List<GridCoord>();
[SerializeField] [ListForComponent(typeof(Legend))] private List<Legend> m_Legends = new List<Legend>();
[SerializeField] [ListForComponent(typeof(MarkLine))] private List<MarkLine> m_MarkLines = new List<MarkLine>();
[SerializeField] [ListForComponent(typeof(MarkArea))] private List<MarkArea> m_MarkAreas = new List<MarkArea>();
[SerializeField] [ListForComponent(typeof(PolarCoord))] private List<PolarCoord> m_Polars = new List<PolarCoord>();
[SerializeField] [ListForComponent(typeof(RadarCoord))] private List<RadarCoord> m_Radars = new List<RadarCoord>();
[SerializeField] [ListForComponent(typeof(RadiusAxis))] private List<RadiusAxis> m_RadiusAxes = new List<RadiusAxis>();
[SerializeField] [ListForComponent(typeof(Title))] private List<Title> m_Titles = new List<Title>();
[SerializeField] [ListForComponent(typeof(Tooltip))] private List<Tooltip> m_Tooltips = new List<Tooltip>();
[SerializeField] [ListForComponent(typeof(Vessel))] private List<Vessel> m_Vessels = new List<Vessel>();
[SerializeField] [ListForComponent(typeof(VisualMap))] private List<VisualMap> m_VisualMaps = new List<VisualMap>();
[SerializeField] [ListForComponent(typeof(XAxis))] private List<XAxis> m_XAxes = new List<XAxis>();
[SerializeField] [ListForComponent(typeof(YAxis))] private List<YAxis> m_YAxes = new List<YAxis>();
[SerializeField] [ListForComponent(typeof(SingleAxis))] private List<SingleAxis> m_SingleAxes = new List<SingleAxis>();
[SerializeField] [ListForComponent(typeof(ParallelCoord))] private List<ParallelCoord> m_Parallels = new List<ParallelCoord>();
[SerializeField] [ListForComponent(typeof(ParallelAxis))] private List<ParallelAxis> m_ParallelAxes = new List<ParallelAxis>();
[SerializeField] [ListForSerie(typeof(Bar))] private List<Bar> m_SerieBars = new List<Bar>();
[SerializeField] [ListForSerie(typeof(Candlestick))] private List<Candlestick> m_SerieCandlesticks = new List<Candlestick>();
[SerializeField] [ListForSerie(typeof(EffectScatter))] private List<EffectScatter> m_SerieEffectScatters = new List<EffectScatter>();
[SerializeField] [ListForSerie(typeof(Heatmap))] private List<Heatmap> m_SerieHeatmaps = new List<Heatmap>();
[SerializeField] [ListForSerie(typeof(Line))] private List<Line> m_SerieLines = new List<Line>();
[SerializeField] [ListForSerie(typeof(Liquid))] private List<Liquid> m_SerieLiquids = new List<Liquid>();
[SerializeField] [ListForSerie(typeof(Pie))] private List<Pie> m_SeriePies = new List<Pie>();
[SerializeField] [ListForSerie(typeof(Radar))] private List<Radar> m_SerieRadars = new List<Radar>();
[SerializeField] [ListForSerie(typeof(Ring))] private List<Ring> m_SerieRings = new List<Ring>();
[SerializeField] [ListForSerie(typeof(Scatter))] private List<Scatter> m_SerieScatters = new List<Scatter>();
[SerializeField] [ListForSerie(typeof(Parallel))] private List<Parallel> m_SerieParallels = new List<Parallel>();
[SerializeField] [ListForSerie(typeof(SimplifiedLine))] private List<SimplifiedLine> m_SerieSimplifiedLines = new List<SimplifiedLine>();
[SerializeField] [ListForSerie(typeof(SimplifiedBar))] private List<SimplifiedBar> m_SerieSimplifiedBars = new List<SimplifiedBar>();
[SerializeField] [ListForSerie(typeof(SimplifiedCandlestick))] private List<SimplifiedCandlestick> m_SerieSimplifiedCandlesticks = new List<SimplifiedCandlestick>();
#pragma warning restore 0414
protected List<Serie> m_Series = new List<Serie>();
protected List<MainComponent> m_Components = new List<MainComponent>();
protected Dictionary<Type, FieldInfo> m_TypeListForComponent = new Dictionary<Type, FieldInfo>();
protected Dictionary<Type, FieldInfo> m_TypeListForSerie = new Dictionary<Type, FieldInfo>();
protected Dictionary<Type, List<MainComponent>> m_ComponentMaps = new Dictionary<Type, List<MainComponent>>();
public Dictionary<Type, FieldInfo> typeListForComponent { get { return m_TypeListForComponent; } }
public Dictionary<Type, FieldInfo> typeListForSerie { get { return m_TypeListForSerie; } }
public List<MainComponent> components { get { return m_Components; } }
public List<Serie> series { get { return m_Series; } }
protected float m_ChartWidth;
protected float m_ChartHeight;
protected float m_ChartX;
protected float m_ChartY;
protected Vector3 m_ChartPosition = Vector3.zero;
protected Vector2 m_ChartMinAnchor;
protected Vector2 m_ChartMaxAnchor;
protected Vector2 m_ChartPivot;
protected Vector2 m_ChartSizeDelta;
protected Rect m_ChartRect = new Rect(0, 0, 0, 0);
protected Action<VertexHelper> m_OnCustomDrawBaseCallback;
protected Action<VertexHelper> m_OnCustomDrawTopCallback;
protected Action<VertexHelper, Serie> m_OnCustomDrawSerieBeforeCallback;
protected Action<VertexHelper, Serie> m_OnCustomDrawSerieAfterCallback;
protected Action<PointerEventData, int, int> m_OnPointerClickPie;
protected Action<PointerEventData, int> m_OnPointerClickBar;
internal bool m_CheckAnimation = false;
internal protected List<string> m_LegendRealShowName = new List<string>();
protected List<Painter> m_PainterList = new List<Painter>();
internal Painter m_PainterTop;
internal int m_BasePainterVertCount;
internal int m_TopPainterVertCount;
private ThemeType m_CheckTheme = 0;
protected List<MainComponentHandler> m_ComponentHandlers = new List<MainComponentHandler>();
protected List<SerieHandler> m_SerieHandlers = new List<SerieHandler>();
protected override void InitComponent()
{
base.InitComponent();
SeriesHelper.UpdateSerieNameList(this, ref m_LegendRealShowName);
foreach (var handler in m_ComponentHandlers)
handler.InitComponent();
foreach (var handler in m_SerieHandlers)
handler.InitComponent();
m_DebugInfo.Init(this);
}
protected override void Awake()
{
if (m_Settings == null)
m_Settings = Settings.DefaultSettings;
CheckTheme();
base.Awake();
InitComponentHandlers();
InitSerieHandlers();
AnimationReset();
AnimationFadeIn();
XChartsMgr.AddChart(this);
}
#if UNITY_EDITOR
protected override void Reset()
{
base.Reset();
RemoveAllChartComponent();
OnBeforeSerialize();
AddChartComponentWhenNoExist<Title>();
AddChartComponentWhenNoExist<Tooltip>();
GetChartComponent<Title>().text = GetType().Name;
if (m_Theme.sharedTheme != null)
m_Theme.sharedTheme.CopyTheme(ThemeType.Default);
else
m_Theme.sharedTheme = XCThemeMgr.GetTheme(ThemeType.Default);
m_Settings = null;
var sizeDelta = rectTransform.sizeDelta;
if (sizeDelta.x < 580 && sizeDelta.y < 300)
{
rectTransform.sizeDelta = new Vector2(580, 300);
}
ChartHelper.HideAllObject(transform);
Awake();
}
#endif
protected override void Start()
{
RefreshChart();
}
protected override void Update()
{
CheckTheme();
base.Update();
CheckPainter();
CheckRefreshChart();
Internal_CheckAnimation();
foreach (var handler in m_SerieHandlers) handler.Update();
foreach (var handler in m_ComponentHandlers) handler.Update();
m_DebugInfo.Update();
}
public Painter GetPainter(int index)
{
if (index >= 0 && index < m_PainterList.Count)
{
return m_PainterList[index];
}
return null;
}
public void RefreshBasePainter()
{
m_Painter.Refresh();
}
public void RefreshTopPainter()
{
m_PainterTop.Refresh();
}
public void RefreshPainter(int index)
{
var painter = GetPainter(index);
RefreshPainter(painter);
}
public void RefreshPainter(Serie serie)
{
RefreshPainter(GetPainterIndexBySerie(serie));
}
internal override void RefreshPainter(Painter painter)
{
base.RefreshPainter(painter);
if (painter != null && painter.type == Painter.Type.Serie)
{
m_PainterTop.Refresh();
}
}
public void SetPainterActive(int index, bool flag)
{
var painter = GetPainter(index);
if (painter == null) return;
painter.SetActive(flag, m_DebugMode);
}
protected virtual void CheckTheme()
{
if (m_Theme.sharedTheme == null)
{
m_Theme.sharedTheme = XCThemeMgr.GetTheme(ThemeType.Default);
}
if (m_CheckTheme != m_Theme.themeType)
{
m_CheckTheme = m_Theme.themeType;
m_Theme.sharedTheme.CopyTheme(m_CheckTheme);
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
SetAllComponentDirty();
OnThemeChanged();
}
}
protected override void CheckComponent()
{
base.CheckComponent();
if (m_Theme.anyDirty)
{
if (m_Theme.componentDirty)
{
SetAllComponentDirty();
}
if (m_Theme.vertsDirty) RefreshChart();
m_Theme.ClearDirty();
}
foreach (var com in m_Components)
CheckComponentDirty(com);
}
protected void CheckComponentDirty(MainComponent component)
{
if (component == null) return;
if (component.anyDirty)
{
if (component.componentDirty && component.refreshComponent != null)
{
component.refreshComponent.Invoke();
}
if (component.vertsDirty)
{
if (component.painter != null)
{
RefreshPainter(component.painter);
}
}
component.ClearDirty();
}
}
protected override void SetAllComponentDirty()
{
base.SetAllComponentDirty();
m_Theme.SetAllDirty();
foreach (var com in m_Components) com.SetAllDirty();
m_RefreshChart = true;
}
protected override void OnDestroy()
{
for (int i = transform.childCount - 1; i >= 0; i--)
{
DestroyImmediate(transform.GetChild(i).gameObject);
}
}
protected virtual void CheckPainter()
{
for (int i = 0; i < m_Series.Count; i++)
{
var serie = m_Series[i];
serie.index = i;
SetPainterActive(i, true);
}
}
protected override void InitPainter()
{
base.InitPainter();
m_Painter.material = settings.basePainterMaterial;
m_PainterList.Clear();
if (settings == null) return;
var sizeDelta = new Vector2(m_GraphWidth, m_GraphHeight);
for (int i = 0; i < settings.maxPainter; i++)
{
var index = settings.reversePainter ? settings.maxPainter - 1 - i : i;
var painter = ChartHelper.AddPainterObject("painter_" + index, transform, m_GraphMinAnchor,
m_GraphMaxAnchor, m_GraphPivot, sizeDelta, chartHideFlags, 2 + index);
painter.index = m_PainterList.Count;
painter.type = Painter.Type.Serie;
painter.onPopulateMesh = OnDrawPainterSerie;
painter.SetActive(false, m_DebugMode);
painter.material = settings.seriePainterMaterial;
painter.transform.SetSiblingIndex(i + 1);
m_PainterList.Add(painter);
}
m_PainterTop = ChartHelper.AddPainterObject("painter_t", transform, m_GraphMinAnchor,
m_GraphMaxAnchor, m_GraphPivot, sizeDelta, chartHideFlags, 2 + settings.maxPainter);
m_PainterTop.type = Painter.Type.Top;
m_PainterTop.onPopulateMesh = OnDrawPainterTop;
m_PainterTop.SetActive(true, m_DebugMode);
m_PainterTop.material = settings.topPainterMaterial;
m_PainterTop.transform.SetSiblingIndex(settings.maxPainter);
}
internal void InitComponentHandlers()
{
m_ComponentHandlers.Clear();
m_Components.Sort();
m_ComponentMaps.Clear();
foreach (var component in m_Components)
{
var type = component.GetType();
List<MainComponent> list;
if (!m_ComponentMaps.TryGetValue(type, out list))
{
list = new List<MainComponent>();
m_ComponentMaps[type] = list;
}
component.index = list.Count;
list.Add(component);
CreateComponentHandler(component);
}
}
protected override void CheckRefreshChart()
{
if (m_Painter == null) return;
if (m_RefreshChart)
{
m_Painter.Refresh();
foreach (var painter in m_PainterList) painter.Refresh();
if (m_PainterTop != null) m_PainterTop.Refresh();
m_RefreshChart = false;
}
}
protected override void CheckRefreshPainter()
{
if (m_Painter == null) return;
m_Painter.CheckRefresh();
foreach (var painter in m_PainterList) painter.CheckRefresh();
if (m_PainterTop != null) m_PainterTop.CheckRefresh();
}
public void Internal_CheckAnimation()
{
if (!m_CheckAnimation)
{
m_CheckAnimation = true;
AnimationFadeIn();
}
}
protected override void OnSizeChanged()
{
base.OnSizeChanged();
m_ChartWidth = m_GraphWidth;
m_ChartHeight = m_GraphHeight;
m_ChartX = m_GraphX;
m_ChartY = m_GraphY;
m_ChartPosition = m_GraphPosition;
m_ChartMinAnchor = m_GraphMinAnchor;
m_ChartMaxAnchor = m_GraphMaxAnchor;
m_ChartPivot = m_GraphPivot;
m_ChartSizeDelta = m_GraphSizeDelta;
m_ChartRect = m_GraphRect;
SetAllComponentDirty();
OnCoordinateChanged();
RefreshChart();
}
internal virtual void OnCoordinateChanged()
{
foreach (var component in m_Components)
{
if (component is Axis)
component.SetAllDirty();
if (component is IUpdateRuntimeData)
(component as IUpdateRuntimeData).UpdateRuntimeData(m_ChartX, m_ChartY, m_ChartWidth, m_ChartHeight);
}
}
protected override void OnLocalPositionChanged()
{
Background background;
if (TryGetChartComponent<Background>(out background))
background.SetAllDirty();
}
protected virtual void OnThemeChanged()
{
}
public virtual void OnDataZoomRangeChanged(DataZoom dataZoom)
{
foreach (var index in dataZoom.xAxisIndexs)
{
var axis = GetChartComponent<XAxis>(index);
if (axis != null && axis.show) axis.SetAllDirty();
}
foreach (var index in dataZoom.yAxisIndexs)
{
var axis = GetChartComponent<YAxis>(index);
if (axis != null && axis.show) axis.SetAllDirty();
}
}
public override void OnPointerClick(PointerEventData eventData)
{
m_DebugInfo.clickChartCount++;
base.OnPointerClick(eventData);
foreach (var handler in m_SerieHandlers) handler.OnPointerClick(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnPointerClick(eventData);
}
public override void OnPointerDown(PointerEventData eventData)
{
base.OnPointerDown(eventData);
foreach (var handler in m_SerieHandlers) handler.OnPointerDown(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnPointerDown(eventData);
}
public override void OnPointerUp(PointerEventData eventData)
{
base.OnPointerUp(eventData);
foreach (var handler in m_SerieHandlers) handler.OnPointerUp(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnPointerUp(eventData);
}
public override void OnPointerEnter(PointerEventData eventData)
{
base.OnPointerEnter(eventData);
foreach (var handler in m_SerieHandlers) handler.OnPointerEnter(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnPointerEnter(eventData);
}
public override void OnPointerExit(PointerEventData eventData)
{
base.OnPointerExit(eventData);
foreach (var handler in m_SerieHandlers) handler.OnPointerExit(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnPointerExit(eventData);
}
public override void OnBeginDrag(PointerEventData eventData)
{
base.OnBeginDrag(eventData);
foreach (var handler in m_SerieHandlers) handler.OnBeginDrag(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnBeginDrag(eventData);
}
public override void OnDrag(PointerEventData eventData)
{
base.OnDrag(eventData);
foreach (var handler in m_SerieHandlers) handler.OnDrag(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnDrag(eventData);
}
public override void OnEndDrag(PointerEventData eventData)
{
base.OnEndDrag(eventData);
foreach (var handler in m_SerieHandlers) handler.OnEndDrag(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnEndDrag(eventData);
}
public override void OnScroll(PointerEventData eventData)
{
base.OnScroll(eventData);
foreach (var handler in m_SerieHandlers) handler.OnScroll(eventData);
foreach (var handler in m_ComponentHandlers) handler.OnScroll(eventData);
}
public virtual void OnLegendButtonClick(int index, string legendName, bool show)
{
foreach (var handler in m_SerieHandlers)
handler.OnLegendButtonClick(index, legendName, show);
}
public virtual void OnLegendButtonEnter(int index, string legendName)
{
foreach (var handler in m_SerieHandlers)
handler.OnLegendButtonEnter(index, legendName);
}
public virtual void OnLegendButtonExit(int index, string legendName)
{
foreach (var handler in m_SerieHandlers)
handler.OnLegendButtonExit(index, legendName);
}
protected override void OnDrawPainterBase(VertexHelper vh, Painter painter)
{
vh.Clear();
DrawBackground(vh);
DrawPainterBase(vh);
foreach (var handler in m_ComponentHandlers) handler.DrawBase(vh);
foreach (var handler in m_SerieHandlers) handler.DrawBase(vh);
if (m_OnCustomDrawBaseCallback != null)
{
m_OnCustomDrawBaseCallback(vh);
}
m_BasePainterVertCount = vh.currentVertCount;
}
protected virtual void OnDrawPainterSerie(VertexHelper vh, Painter painter)
{
vh.Clear();
var maxPainter = settings.maxPainter;
var maxSeries = m_Series.Count;
var rate = Mathf.CeilToInt(maxSeries * 1.0f / maxPainter);
m_PainterTop.Refresh();
m_DebugInfo.refreshCount++;
for (int i = painter.index * rate; i < (painter.index + 1) * rate && i < maxSeries; i++)
{
var serie = m_Series[i];
serie.context.colorIndex = GetLegendRealShowNameIndex(serie.legendName);
serie.context.dataPoints.Clear();
serie.context.dataIgnores.Clear();
AnimationStyleHelper.UpdateSerieAnimation(serie);
if (m_OnCustomDrawSerieBeforeCallback != null)
{
m_OnCustomDrawSerieBeforeCallback.Invoke(vh, serie);
}
DrawPainterSerie(vh, serie);
if (i >= 0 && i < m_SerieHandlers.Count)
{
var handler = m_SerieHandlers[i];
handler.DrawSerie(vh);
handler.RefreshLabelNextFrame();
}
if (m_OnCustomDrawSerieAfterCallback != null)
{
m_OnCustomDrawSerieAfterCallback(vh, serie);
}
serie.context.vertCount = vh.currentVertCount;
}
}
protected virtual void OnDrawPainterTop(VertexHelper vh, Painter painter)
{
vh.Clear();
DrawPainterTop(vh);
foreach (var draw in m_ComponentHandlers) draw.DrawTop(vh);
if (m_OnCustomDrawTopCallback != null)
{
m_OnCustomDrawTopCallback(vh);
}
m_TopPainterVertCount = vh.currentVertCount;
}
protected virtual void DrawPainterSerie(VertexHelper vh, Serie serie)
{
}
protected virtual void DrawPainterTop(VertexHelper vh)
{
foreach (var handler in m_SerieHandlers)
handler.DrawTop(vh);
}
protected virtual void DrawBackground(VertexHelper vh)
{
if (HasChartComponent<Background>()) return;
Vector3 p1 = new Vector3(chartX, chartY + chartHeight);
Vector3 p2 = new Vector3(chartX + chartWidth, chartY + chartHeight);
Vector3 p3 = new Vector3(chartX + chartWidth, chartY);
Vector3 p4 = new Vector3(chartX, chartY);
UGL.DrawQuadrilateral(vh, p1, p2, p3, p4, theme.backgroundColor);
}
protected int GetPainterIndexBySerie(Serie serie)
{
var maxPainter = settings.maxPainter;
var maxSeries = m_Series.Count;
if (maxPainter >= maxSeries) return serie.index;
else
{
var rate = Mathf.CeilToInt(maxSeries * 1.0f / maxPainter);
return serie.index / rate;
}
}
private void InitListForFieldInfos()
{
if (m_TypeListForSerie.Count != 0) return;
m_TypeListForComponent.Clear();
m_TypeListForSerie.Clear();
var fileds1 = GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
var fileds2 = GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
var list = ListPool<FieldInfo>.Get();
list.AddRange(fileds1);
list.AddRange(fileds2);
foreach (var field in list)
{
var attribute1 = field.GetCustomAttribute<ListForSerie>();
if (attribute1 != null)
m_TypeListForSerie.Add(attribute1.type, field);
var attribute2 = field.GetCustomAttribute<ListForComponent>();
if (attribute2 != null)
m_TypeListForComponent.Add(attribute2.type, field);
}
ListPool<FieldInfo>.Release(list);
}
public void OnBeforeSerialize()
{
InitListForFieldInfos();
foreach (var kv in m_TypeListForSerie)
{
ReflectionUtil.InvokeListClear(this, kv.Value);
}
foreach (var kv in m_TypeListForComponent)
{
ReflectionUtil.InvokeListClear(this, kv.Value);
}
foreach (var component in m_Components)
{
FieldInfo field;
if (m_TypeListForComponent.TryGetValue(component.GetType(), out field))
ReflectionUtil.InvokeListAdd(this, field, component);
else
Debug.LogError("No ListForComponent:" + component.GetType());
}
foreach (var serie in m_Series)
{
FieldInfo field;
if (m_TypeListForSerie.TryGetValue(serie.GetType(), out field))
ReflectionUtil.InvokeListAdd(this, field, serie);
else
Debug.LogError("No ListForSerie:" + serie.GetType());
}
}
public void OnAfterDeserialize()
{
InitListForFieldInfos();
m_Components.Clear();
m_Series.Clear();
foreach (var kv in m_TypeListForComponent)
{
ReflectionUtil.InvokeListAddTo<MainComponent>(this, kv.Value, AddComponent);
}
foreach (var kv in m_TypeListForSerie)
{
ReflectionUtil.InvokeListAddTo<Serie>(this, kv.Value, InternalAddSerie);
}
m_Series.Sort();
m_Components.Sort();
InitComponentHandlers();
InitSerieHandlers();
}
}
}

View File

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

View File

@@ -0,0 +1,325 @@

using UnityEngine;
using UnityEngine.UI;
using System;
using UnityEngine.EventSystems;
namespace XCharts
{
[RequireComponent(typeof(CanvasRenderer))]
public partial class BaseGraph : MaskableGraphic, IPointerDownHandler, IPointerUpHandler,
IPointerEnterHandler, IPointerExitHandler, IBeginDragHandler, IPointerClickHandler,
IDragHandler, IEndDragHandler, IScrollHandler
{
[SerializeField] protected bool m_DebugMode = false;
[SerializeField] protected bool m_EnableTextMeshPro = false;
protected Painter m_Painter;
protected int m_SiblingIndex;
protected float m_GraphWidth;
protected float m_GraphHeight;
protected float m_GraphX;
protected float m_GraphY;
protected Vector3 m_GraphPosition = Vector3.zero;
protected Vector2 m_GraphMinAnchor;
protected Vector2 m_GraphMaxAnchor;
protected Vector2 m_GraphPivot;
protected Vector2 m_GraphSizeDelta;
protected Vector2 m_GraphAnchoredPosition;
protected Rect m_GraphRect = new Rect(0, 0, 0, 0);
protected bool m_RefreshChart = false;
protected bool m_ForceOpenRaycastTarget;
protected bool m_IsControlledByLayout = false;
protected bool m_PainerDirty = false;
protected bool m_IsOnValidate = false;
protected Vector3 m_LastLocalPosition;
protected Action<PointerEventData, BaseGraph> m_OnPointerClick;
protected Action<PointerEventData, BaseGraph> m_OnPointerDown;
protected Action<PointerEventData, BaseGraph> m_OnPointerUp;
protected Action<PointerEventData, BaseGraph> m_OnPointerEnter;
protected Action<PointerEventData, BaseGraph> m_OnPointerExit;
protected Action<PointerEventData, BaseGraph> m_OnBeginDrag;
protected Action<PointerEventData, BaseGraph> m_OnDrag;
protected Action<PointerEventData, BaseGraph> m_OnEndDrag;
protected Action<PointerEventData, BaseGraph> m_OnScroll;
protected Vector2 graphAnchorMax { get { return m_GraphMinAnchor; } }
protected Vector2 graphAnchorMin { get { return m_GraphMaxAnchor; } }
protected Vector2 graphPivot { get { return m_GraphPivot; } }
public HideFlags chartHideFlags { get { return m_DebugMode ? HideFlags.None : HideFlags.HideInHierarchy; } }
private ScrollRect m_ScrollRect;
public Painter painter { get { return m_Painter; } }
internal bool debugModel { get { return m_DebugMode; } }
protected virtual void InitComponent()
{
InitPainter();
}
protected override void Awake()
{
CheckTextMeshPro();
m_SiblingIndex = 0;
m_LastLocalPosition = transform.localPosition;
UpdateSize();
InitComponent();
CheckIsInScrollRect();
}
protected override void Start()
{
m_RefreshChart = true;
}
protected virtual void Update()
{
CheckSize();
if (m_IsOnValidate)
{
m_IsOnValidate = false;
m_RefreshChart = true;
CheckTextMeshPro();
InitComponent();
}
else
{
CheckComponent();
}
CheckPointerPos();
CheckRefreshChart();
CheckRefreshPainter();
}
protected virtual void SetAllComponentDirty()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
m_IsOnValidate = true;
Update();
}
#endif
m_PainerDirty = true;
}
protected virtual void CheckComponent()
{
if (m_PainerDirty)
{
InitPainter();
m_PainerDirty = false;
}
}
private void CheckTextMeshPro()
{
#if dUI_TextMeshPro
var enableTextMeshPro = true;
#else
var enableTextMeshPro = false;
#endif
if (m_EnableTextMeshPro != enableTextMeshPro)
{
m_EnableTextMeshPro = enableTextMeshPro;
RemoveChartObject();
}
}
#if UNITY_EDITOR
protected override void Reset()
{
}
protected override void OnValidate()
{
m_IsOnValidate = true;
}
#endif
protected override void OnDestroy()
{
for (int i = transform.childCount - 1; i >= 0; i--)
{
DestroyImmediate(transform.GetChild(i).gameObject);
}
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
}
protected virtual void InitPainter()
{
m_Painter = ChartHelper.AddPainterObject("painter_b", transform, m_GraphMinAnchor,
m_GraphMaxAnchor, m_GraphPivot, new Vector2(m_GraphWidth, m_GraphHeight), chartHideFlags, 1);
m_Painter.type = Painter.Type.Base;
m_Painter.onPopulateMesh = OnDrawPainterBase;
m_Painter.transform.SetSiblingIndex(0);
}
private void CheckSize()
{
var currWidth = rectTransform.rect.width;
var currHeight = rectTransform.rect.height;
if (m_GraphWidth == 0 && m_GraphHeight == 0 && (currWidth != 0 || currHeight != 0))
{
Awake();
}
if (m_GraphWidth != currWidth
|| m_GraphHeight != currHeight
|| m_GraphMinAnchor != rectTransform.anchorMin
|| m_GraphMaxAnchor != rectTransform.anchorMax
|| m_GraphAnchoredPosition != rectTransform.anchoredPosition)
{
UpdateSize();
}
if (!ChartHelper.IsValueEqualsVector3(m_LastLocalPosition, transform.localPosition))
{
m_LastLocalPosition = transform.localPosition;
OnLocalPositionChanged();
}
}
protected void UpdateSize()
{
m_GraphWidth = rectTransform.rect.width;
m_GraphHeight = rectTransform.rect.height;
m_GraphMaxAnchor = rectTransform.anchorMax;
m_GraphMinAnchor = rectTransform.anchorMin;
m_GraphSizeDelta = rectTransform.sizeDelta;
m_GraphAnchoredPosition = rectTransform.anchoredPosition;
rectTransform.pivot = LayerHelper.ResetChartPositionAndPivot(m_GraphMinAnchor, m_GraphMaxAnchor,
m_GraphWidth, m_GraphHeight, ref m_GraphX, ref m_GraphY);
m_GraphPivot = rectTransform.pivot;
m_GraphRect.x = m_GraphX;
m_GraphRect.y = m_GraphY;
m_GraphRect.width = m_GraphWidth;
m_GraphRect.height = m_GraphHeight;
m_GraphPosition.x = m_GraphX;
m_GraphPosition.y = m_GraphY;
OnSizeChanged();
}
private void CheckPointerPos()
{
if (!isPointerInChart) return;
if (canvas == null) return;
Vector2 local;
if (!ScreenPointToChartPoint(Input.mousePosition, out local))
{
pointerPos = Vector2.zero;
}
else
{
pointerPos = local;
}
}
protected virtual void CheckIsInScrollRect()
{
m_ScrollRect = GetComponentInParent<ScrollRect>();
}
protected virtual void CheckRefreshChart()
{
if (m_RefreshChart)
{
m_Painter.Refresh();
m_RefreshChart = false;
}
}
protected virtual void CheckRefreshPainter()
{
m_Painter.CheckRefresh();
}
internal virtual void RefreshPainter(Painter painter)
{
if (painter == null) return;
painter.Refresh();
}
protected virtual void OnSizeChanged()
{
m_RefreshChart = true;
}
protected virtual void OnLocalPositionChanged()
{
}
protected virtual void OnDrawPainterBase(VertexHelper vh, Painter painter)
{
DrawPainterBase(vh);
}
protected virtual void DrawPainterBase(VertexHelper vh)
{
}
public virtual void OnPointerClick(PointerEventData eventData)
{
if (m_OnPointerClick != null) m_OnPointerClick(eventData, this);
}
public virtual void OnPointerDown(PointerEventData eventData)
{
if (m_OnPointerDown != null) m_OnPointerDown(eventData, this);
}
public virtual void OnPointerUp(PointerEventData eventData)
{
if (m_OnPointerUp != null) m_OnPointerUp(eventData, this);
}
public virtual void OnPointerEnter(PointerEventData eventData)
{
isPointerInChart = true;
if (m_OnPointerEnter != null) m_OnPointerEnter(eventData, this);
}
public virtual void OnPointerExit(PointerEventData eventData)
{
isPointerInChart = false;
if (m_OnPointerExit != null) m_OnPointerExit(eventData, this);
}
public virtual void OnBeginDrag(PointerEventData eventData)
{
if (m_ScrollRect != null) m_ScrollRect.OnBeginDrag(eventData);
if (m_OnBeginDrag != null) m_OnBeginDrag(eventData, this);
}
public virtual void OnEndDrag(PointerEventData eventData)
{
if (m_ScrollRect != null) m_ScrollRect.OnEndDrag(eventData);
if (m_OnEndDrag != null) m_OnEndDrag(eventData, this);
}
public virtual void OnDrag(PointerEventData eventData)
{
if (m_ScrollRect != null) m_ScrollRect.OnDrag(eventData);
if (m_OnDrag != null) m_OnDrag(eventData, this);
}
public virtual void OnScroll(PointerEventData eventData)
{
if (m_ScrollRect != null) m_ScrollRect.OnScroll(eventData);
if (m_OnScroll != null) m_OnScroll(eventData, this);
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace XCharts
{
[System.Serializable]
public abstract class BaseSerie
{
public virtual bool vertsDirty { get { return m_VertsDirty; } }
public virtual bool componentDirty { get { return m_ComponentDirty; } }
public virtual bool useDataNameForColor { get { return false; } }
public bool anyDirty { get { return vertsDirty || componentDirty; } }
public Painter painter { get { return m_Painter; } set { m_Painter = value; } }
public Action refreshComponent { get; set; }
public GameObject gameObject { get; set; }
[NonSerialized] protected bool m_VertsDirty;
[NonSerialized] protected bool m_ComponentDirty;
[NonSerialized] protected Painter m_Painter;
[NonSerialized] public SerieContext context = new SerieContext();
[NonSerialized] public InteractData interact = new InteractData();
internal SerieHandler handler { get; set; }
public virtual void SetVerticesDirty()
{
m_VertsDirty = true;
}
public virtual void ClearVerticesDirty()
{
m_VertsDirty = false;
}
public virtual void SetComponentDirty()
{
m_ComponentDirty = true;
}
public virtual void ClearComponentDirty()
{
m_ComponentDirty = false;
}
public virtual void ClearData()
{
}
public virtual void ClearDirty()
{
ClearVerticesDirty();
ClearComponentDirty();
}
public virtual void SetAllDirty()
{
SetVerticesDirty();
SetComponentDirty();
}
public virtual void OnRemove()
{
if (handler != null)
handler.RemoveComponent();
}
public void RefreshLabel()
{
if (handler != null)
handler.RefreshLabelNextFrame();
}
#if UNITY_EDITOR
protected virtual void Reset()
{
}
protected virtual void OnValidate()
{
SetAllDirty();
}
#endif
}
}

View File

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

View File

@@ -0,0 +1,63 @@
using System;
using UnityEngine;
namespace XCharts
{
[System.Serializable]
public class ChildComponent
{
public int index { get; set; }
[NonSerialized] protected bool m_VertsDirty;
[NonSerialized] protected bool m_ComponentDirty;
[NonSerialized] protected Painter m_Painter;
/// <summary>
/// 图表重绘标记。
/// </summary>
public virtual bool vertsDirty { get { return m_VertsDirty; } }
/// <summary>
/// 组件重新初始化标记。
/// </summary>
public virtual bool componentDirty { get { return m_ComponentDirty; } }
/// <summary>
/// 需要重绘图表或重新初始化组件。
/// </summary>
public bool anyDirty { get { return vertsDirty || componentDirty; } }
public Painter painter { get { return m_Painter; } set { m_Painter = value; } }
public Action refreshComponent { get; set; }
public GameObject gameObject { get; set; }
public virtual void SetVerticesDirty()
{
m_VertsDirty = true;
}
public virtual void ClearVerticesDirty()
{
m_VertsDirty = false;
}
public virtual void SetComponentDirty()
{
m_ComponentDirty = true;
}
public virtual void ClearComponentDirty()
{
m_ComponentDirty = false;
}
public virtual void ClearDirty()
{
ClearVerticesDirty();
ClearComponentDirty();
}
public virtual void SetAllDirty()
{
SetVerticesDirty();
SetComponentDirty();
}
}
}

View File

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

View File

@@ -0,0 +1,16 @@
using System;
namespace XCharts
{
/// <summary>
/// Coordinate system component.
///
/// 坐标系系统。
/// </summary>
[Serializable]
public abstract class CoordSystem : MainComponent
{
}
}

View File

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

View File

@@ -0,0 +1,125 @@
using System;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace XCharts
{
[System.Serializable]
public class MainComponent : IComparable
{
public int instanceId { get; internal set; }
public int index { get; internal set; }
protected bool m_VertsDirty;
protected bool m_ComponentDirty;
protected Painter m_Painter;
/// <summary>
/// 图表重绘标记。
/// </summary>
public virtual bool vertsDirty { get { return m_VertsDirty; } }
/// <summary>
/// 组件重新初始化标记。
/// </summary>
public virtual bool componentDirty { get { return m_ComponentDirty; } }
/// <summary>
/// 需要重绘图表或重新初始化组件。
/// </summary>
public bool anyDirty { get { return vertsDirty || componentDirty; } }
public Painter painter { get { return m_Painter; } set { m_Painter = value; } }
public Action refreshComponent { get; set; }
public GameObject gameObject { get; set; }
internal MainComponentHandler handler { get; set; }
public virtual void SetVerticesDirty()
{
m_VertsDirty = true;
}
public virtual void ClearVerticesDirty()
{
m_VertsDirty = false;
}
public virtual void SetComponentDirty()
{
m_ComponentDirty = true;
}
public virtual void ClearComponentDirty()
{
m_ComponentDirty = false;
}
public virtual void ClearData()
{
}
public virtual void ClearDirty()
{
ClearVerticesDirty();
ClearComponentDirty();
}
public virtual void SetAllDirty()
{
SetVerticesDirty();
SetComponentDirty();
}
public virtual void SetDefaultValue()
{
}
public virtual void OnRemove()
{
if (handler != null)
handler.RemoveComponent();
}
public int CompareTo(object obj)
{
var flag = GetType().Name.CompareTo(obj.GetType().Name);
if (flag == 0)
return index.CompareTo((obj as MainComponent).index);
else
return flag;
}
}
public abstract class MainComponentHandler
{
public BaseChart chart { get; internal set; }
public ComponentHandlerAttribute attribute { get; internal set; }
public virtual void InitComponent() { }
public virtual void RemoveComponent() { }
public virtual void CheckComponent(StringBuilder sb) { }
public virtual void Update() { }
public virtual void DrawBase(VertexHelper vh) { }
public virtual void DrawTop(VertexHelper vh) { }
public virtual void OnPointerClick(PointerEventData eventData) { }
public virtual void OnPointerDown(PointerEventData eventData) { }
public virtual void OnPointerUp(PointerEventData eventData) { }
public virtual void OnPointerEnter(PointerEventData eventData) { }
public virtual void OnPointerExit(PointerEventData eventData) { }
public virtual void OnDrag(PointerEventData eventData) { }
public virtual void OnBeginDrag(PointerEventData eventData) { }
public virtual void OnEndDrag(PointerEventData eventData) { }
public virtual void OnScroll(PointerEventData eventData) { }
internal abstract void SetComponent(MainComponent component);
}
public abstract class MainComponentHandler<T> : MainComponentHandler
where T : MainComponent
{
public T component { get; internal set; }
internal override void SetComponent(MainComponent component)
{
this.component = (T)component;
}
}
}

View File

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

View File

@@ -0,0 +1,8 @@
namespace XCharts
{
public class MainComponentContext
{
}
}

View File

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

View File

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

View File

@@ -0,0 +1,22 @@
namespace XCharts
{
/// <summary>
/// The delegate function for AxisLabel's formatter.
/// AxisLabel的formatter自定义委托。
/// </summary>
/// <param name="labelIndex">label索引</param>
/// <param name="value">当前label对应的数值数据Value轴或Time轴有效</param>
/// <param name="category">当前label对应的类目数据Category轴有效</param>
/// <returns>最终显示的文本内容</returns>
public delegate string DelegateAxisLabelFormatter(int labelIndex, double value, string category);
/// <summary>
/// The delegate function for SerieLabels formatter.
/// SerieLabel的formatter自定义委托。
/// </summary>
/// <param name="dataIndex">数据索引</param>
/// <param name="value">数值</param>
/// <returns>最终显示的文本内容</returns>
public delegate string DelegateSerieLabelFormatter(int dataIndex, double value);
}

View File

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

View File

@@ -0,0 +1,20 @@
namespace XCharts
{
/// <summary>
/// the layout is horizontal or vertical.
/// 垂直还是水平布局方式。
/// </summary>
public enum Orient
{
/// <summary>
/// 水平
/// </summary>
Horizonal,
/// <summary>
/// 垂直
/// </summary>
Vertical
}
}

View File

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

View File

@@ -0,0 +1,14 @@
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace XCharts
{
public interface INeedSerieContainer
{
int containerIndex { get; }
int containterInstanceId { get; }
}
}

View File

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

View File

@@ -0,0 +1,12 @@

namespace XCharts
{
/// <summary>
/// 属性变更接口
/// </summary>
public interface IPropertyChanged
{
void OnChanged();
}
}

View File

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

View File

@@ -0,0 +1,14 @@
using UnityEngine;
namespace XCharts
{
public interface IRectContext
{
float x { get; }
float y { get; }
float width { get; }
float height { get; }
Vector3 position { get; }
}
}

View File

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

View File

@@ -0,0 +1,10 @@
namespace XCharts
{
public interface ISerieContainer
{
//bool runtimeIsPointerEnter { get; }
int index { get; }
bool IsPointerEnter();
}
}

View File

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

View File

@@ -0,0 +1,11 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace XCharts
{
public interface ISerieDataComponent
{
}
}

View File

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

View File

@@ -0,0 +1,12 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace XCharts
{
public interface ISerieExtraComponent
{
bool show { get; set; }
}
}

View File

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

View File

@@ -0,0 +1,11 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace XCharts
{
public interface ISimplifiedSerie
{
}
}

View File

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

View File

View File

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

View File

@@ -0,0 +1,12 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace XCharts
{
public interface IUpdateRuntimeData
{
void UpdateRuntimeData(float chartX, float chartY, float chartWidth, float chartHeight);
}
}

View File

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

View File

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

View File

@@ -0,0 +1,257 @@
using UnityEngine;
using UnityEngine.UI;
namespace XCharts
{
public class ChartLabel : Image
{
private bool m_AutoHideIconWhenLabelEmpty = false;
private bool m_LabelAutoSize = true;
private float m_LabelPaddingLeftRight = 3f;
private float m_LabelPaddingTopBottom = 3f;
private ChartText m_LabelText;
private RectTransform m_LabelRect;
private RectTransform m_LabelBackgroundRect;
private RectTransform m_IconRect;
private RectTransform m_ObjectRect;
private Vector3 m_IconOffest;
private Align m_Align = Align.Left;
private Image m_IconImage;
private Image m_LabelBackgroundImage;
public Image icon
{
get { return m_IconImage; }
set { SetIcon(value); }
}
public Image labelBackground
{
get { return m_LabelBackgroundImage; }
set { SetLabelBackground(value); }
}
public ChartText label
{
get { return m_LabelText; }
set
{
m_LabelText = value;
if (value != null) m_LabelRect = m_LabelText.gameObject.GetComponent<RectTransform>();
}
}
public bool autoHideIconWhenLabelEmpty { set { m_AutoHideIconWhenLabelEmpty = value; } }
public bool isIconActive { get; private set; }
protected override void Awake()
{
m_ObjectRect = gameObject.GetComponent<RectTransform>();
raycastTarget = false;
}
public void SetLabel(GameObject labelObj, bool autoSize, float paddingLeftRight, float paddingTopBottom)
{
m_LabelAutoSize = autoSize;
m_LabelPaddingLeftRight = paddingLeftRight;
m_LabelPaddingTopBottom = paddingTopBottom;
m_LabelText = new ChartText(labelObj);
m_LabelRect = m_LabelText.gameObject.GetComponent<RectTransform>();
m_Align = Align.Left;
}
public void SetLabelBackground(Image image)
{
m_LabelBackgroundImage = image;
if (image != null)
{
m_LabelBackgroundRect = m_LabelBackgroundImage.GetComponent<RectTransform>();
}
}
public void SetIcon(Image image)
{
m_IconImage = image;
if (image != null)
{
m_IconRect = m_IconImage.GetComponent<RectTransform>();
}
}
public void SetAutoSize(bool flag)
{
m_LabelAutoSize = flag;
}
public void SetIconSprite(Sprite sprite)
{
if (m_IconImage != null) m_IconImage.sprite = sprite;
}
public void SetIconSize(float width, float height)
{
if (m_IconRect != null) m_IconRect.sizeDelta = new Vector3(width, height);
}
public void UpdateIcon(IconStyle iconStyle, Sprite sprite = null)
{
if (m_IconImage == null || iconStyle == null)
return;
SetIconActive(iconStyle.show);
if (iconStyle.show)
{
m_IconImage.sprite = sprite == null ? iconStyle.sprite : sprite;
m_IconImage.color = iconStyle.color;
m_IconRect.sizeDelta = new Vector2(iconStyle.width, iconStyle.height);
m_IconOffest = iconStyle.offset;
m_Align = iconStyle.align;
m_AutoHideIconWhenLabelEmpty = iconStyle.autoHideWhenLabelEmpty;
AdjustIconPos();
if (iconStyle.layer == IconStyle.Layer.UnderLabel)
m_IconRect.SetSiblingIndex(0);
else
m_IconRect.SetSiblingIndex(transform.childCount - 1);
}
}
public float GetLabelWidth()
{
if (m_LabelRect) return m_LabelRect.sizeDelta.x;
else return 0;
}
public float GetLabelHeight()
{
if (m_LabelRect) return m_LabelRect.sizeDelta.y;
return 0;
}
public void SetTextColor(Color color)
{
if (m_LabelText != null) m_LabelText.SetColor(color);
}
public void SetLabelRotate(float rotate)
{
if (m_LabelText != null) m_LabelText.SetLocalEulerAngles(new Vector3(0, 0, rotate));
}
public void SetPosition(Vector3 position)
{
transform.localPosition = position;
}
public Vector3 GetPosition()
{
return transform.localPosition;
}
public void SetLabelPosition(Vector3 position)
{
if (m_LabelRect) m_LabelRect.localPosition = position;
}
public void SetActive(bool flag)
{
ChartHelper.SetActive(gameObject, flag);
}
public void SetLabelActive(bool flag)
{
if (m_LabelText != null) m_LabelText.SetActive(flag);
}
public void SetIconActive(bool flag)
{
isIconActive = flag;
if (m_IconImage) ChartHelper.SetActive(m_IconImage, flag);
}
public bool SetText(string text)
{
if (m_LabelRect == null || m_LabelText == null)
return false;
if (text == null)
text = "";
if (!m_LabelText.GetText().Equals(text))
{
m_LabelText.SetText(text);
if (m_LabelAutoSize)
{
var newSize = string.IsNullOrEmpty(text) ? Vector2.zero :
new Vector2(m_LabelText.GetPreferredWidth() + m_LabelPaddingLeftRight * 2,
m_LabelText.GetPreferredHeight() + m_LabelPaddingTopBottom * 2);
var sizeChange = newSize.x != m_LabelRect.sizeDelta.x || newSize.y != m_LabelRect.sizeDelta.y;
if (sizeChange)
{
m_LabelRect.sizeDelta = newSize;
if (m_LabelBackgroundRect != null)
m_LabelBackgroundRect.sizeDelta = newSize;
AdjustIconPos();
}
return sizeChange;
}
AdjustIconPos();
if (m_AutoHideIconWhenLabelEmpty && isIconActive)
{
ChartHelper.SetActive(m_IconImage.gameObject, !string.IsNullOrEmpty(text));
}
}
return false;
}
private void AdjustIconPos()
{
if (m_IconImage && m_IconRect && m_LabelText != null && m_ObjectRect != null)
{
var iconX = 0f;
switch (m_Align)
{
case Align.Left:
switch (m_LabelText.alignment)
{
case TextAnchor.LowerLeft:
case TextAnchor.UpperLeft:
case TextAnchor.MiddleLeft:
iconX = -m_ObjectRect.sizeDelta.x / 2 - m_IconRect.sizeDelta.x / 2;
break;
case TextAnchor.LowerRight:
case TextAnchor.UpperRight:
case TextAnchor.MiddleRight:
iconX = m_ObjectRect.sizeDelta.x / 2 - m_LabelText.GetPreferredWidth() - m_IconRect.sizeDelta.x / 2;
break;
case TextAnchor.LowerCenter:
case TextAnchor.UpperCenter:
case TextAnchor.MiddleCenter:
iconX = -m_LabelText.GetPreferredWidth() / 2 - m_IconRect.sizeDelta.x / 2;
break;
}
break;
case Align.Right:
switch (m_LabelText.alignment)
{
case TextAnchor.LowerLeft:
case TextAnchor.UpperLeft:
case TextAnchor.MiddleLeft:
iconX = m_ObjectRect.sizeDelta.x / 2 + m_IconRect.sizeDelta.x / 2;
break;
case TextAnchor.LowerRight:
case TextAnchor.UpperRight:
case TextAnchor.MiddleRight:
iconX = m_IconRect.sizeDelta.x / 2;
break;
case TextAnchor.LowerCenter:
case TextAnchor.UpperCenter:
case TextAnchor.MiddleCenter:
iconX = m_LabelText.GetPreferredWidth() / 2 + m_IconRect.sizeDelta.x / 2;
break;
}
break;
}
m_IconRect.anchoredPosition = m_IconOffest + new Vector3(iconX, 0);
}
}
}
}

View File

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

View File

@@ -0,0 +1,15 @@
using UnityEngine;
namespace XCharts
{
public class ChartObject
{
protected GameObject m_GameObject;
public virtual void Destroy()
{
GameObject.Destroy(m_GameObject);
}
}
}

View File

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

View File

@@ -0,0 +1,312 @@
using UnityEngine;
using UnityEngine.UI;
#if dUI_TextMeshPro
using TMPro;
#endif
namespace XCharts
{
public class ChartText
{
private float m_ExtraWidth;
private Text m_Text;
public Text text
{
get { return m_Text; }
set { m_Text = value; }
}
#if dUI_TextMeshPro
private TextMeshProUGUI m_TMPText;
public TextMeshProUGUI tmpText { get { return m_TMPText; } set { m_TMPText = value; } }
#endif
public GameObject gameObject
{
get
{
#if dUI_TextMeshPro
if (m_TMPText != null) return m_TMPText.gameObject;
#else
if (m_Text != null) return m_Text.gameObject;
#endif
return null;
}
}
public TextAnchor alignment
{
get
{
#if dUI_TextMeshPro
if (m_TMPText == null) return TextAnchor.MiddleCenter;
switch (m_TMPText.alignment)
{
case TextAlignmentOptions.Bottom: return TextAnchor.LowerCenter;
case TextAlignmentOptions.BottomLeft: return TextAnchor.LowerLeft;
case TextAlignmentOptions.BottomRight: return TextAnchor.LowerRight;
case TextAlignmentOptions.Center: return TextAnchor.MiddleCenter;
case TextAlignmentOptions.Left: return TextAnchor.MiddleLeft;
case TextAlignmentOptions.Right: return TextAnchor.MiddleRight;
case TextAlignmentOptions.Top: return TextAnchor.UpperCenter;
case TextAlignmentOptions.TopLeft: return TextAnchor.UpperLeft;
case TextAlignmentOptions.TopRight: return TextAnchor.UpperRight;
default: return TextAnchor.MiddleCenter;
}
#else
if (m_Text != null) return m_Text.alignment;
else return TextAnchor.MiddleCenter;
#endif
}
set
{
SetAlignment(alignment);
}
}
public ChartText()
{
}
public ChartText(GameObject textParent)
{
#if dUI_TextMeshPro
m_TMPText = textParent.GetComponentInChildren<TextMeshProUGUI>();
if (m_TMPText == null)
{
Debug.LogError("can't find TextMeshProUGUI component:" + textParent);
}
#else
m_Text = textParent.GetComponentInChildren<Text>();
if (m_Text == null)
{
Debug.LogError("can't find Text component:" + textParent);
}
#endif
}
public void SetFontSize(float fontSize)
{
#if dUI_TextMeshPro
if (m_TMPText != null) m_TMPText.fontSize = fontSize;
#else
if (m_Text != null) m_Text.fontSize = (int)fontSize;
#endif
}
public void SetText(string text)
{
if (text == null) text = string.Empty;
else text = text.Replace("\\n", "\n");
#if dUI_TextMeshPro
if(m_TMPText != null) m_TMPText.text = text;
#else
if (m_Text != null) m_Text.text = text;
#endif
}
public string GetText()
{
#if dUI_TextMeshPro
if (m_TMPText != null) return m_TMPText.text;
#else
if (m_Text != null) return m_Text.text;
#endif
return string.Empty;
}
public void SetColor(Color color)
{
#if dUI_TextMeshPro
if (m_TMPText != null) m_TMPText.color = color;
#else
if (m_Text != null) m_Text.color = color;
#endif
}
public void SetLineSpacing(float lineSpacing)
{
#if dUI_TextMeshPro
if (m_TMPText != null) m_TMPText.lineSpacing = lineSpacing;
#else
if (m_Text != null) m_Text.lineSpacing = lineSpacing;
#endif
}
public void SetExtraWidth(float width)
{
m_ExtraWidth = width;
}
public void SetActive(bool flag)
{
#if dUI_TextMeshPro
//m_TMPText.gameObject.SetActive(flag);
if (m_TMPText != null) ChartHelper.SetActive(m_TMPText.gameObject, flag);
#else
//m_Text.gameObject.SetActive(flag);
if (m_Text != null) ChartHelper.SetActive(m_Text.gameObject, flag);
#endif
}
public void SetLocalPosition(Vector3 position)
{
#if dUI_TextMeshPro
if (m_TMPText != null) m_TMPText.transform.localPosition = position;
#else
if (m_Text != null) m_Text.transform.localPosition = position;
#endif
}
public void SetRectPosition(Vector3 position)
{
#if dUI_TextMeshPro
if (m_TMPText != null) m_TMPText.GetComponent<RectTransform>().anchoredPosition3D = position;
#else
if (m_Text != null) m_Text.GetComponent<RectTransform>().anchoredPosition3D = position;
#endif
}
public void SetSizeDelta(Vector2 sizeDelta)
{
#if dUI_TextMeshPro
if (m_TMPText != null) m_TMPText.GetComponent<RectTransform>().sizeDelta = sizeDelta;
#else
if (m_Text != null) m_Text.GetComponent<RectTransform>().sizeDelta = sizeDelta;
#endif
}
public void SetLocalEulerAngles(Vector3 position)
{
#if dUI_TextMeshPro
if (m_TMPText != null) m_TMPText.transform.localEulerAngles = position;
#else
if (m_Text != null) m_Text.transform.localEulerAngles = position;
#endif
}
public void SetAlignment(TextAnchor alignment)
{
#if dUI_TextMeshPro
if (m_TMPText == null) return;
switch (alignment)
{
case TextAnchor.LowerCenter: m_TMPText.alignment = TextAlignmentOptions.Bottom; break;
case TextAnchor.LowerLeft: m_TMPText.alignment = TextAlignmentOptions.BottomLeft; break;
case TextAnchor.LowerRight: m_TMPText.alignment = TextAlignmentOptions.BottomRight; break;
case TextAnchor.MiddleCenter: m_TMPText.alignment = TextAlignmentOptions.Center; break;
case TextAnchor.MiddleLeft: m_TMPText.alignment = TextAlignmentOptions.Left; break;
case TextAnchor.MiddleRight: m_TMPText.alignment = TextAlignmentOptions.Right; break;
case TextAnchor.UpperCenter: m_TMPText.alignment = TextAlignmentOptions.Top; break;
case TextAnchor.UpperLeft: m_TMPText.alignment = TextAlignmentOptions.TopLeft; break;
case TextAnchor.UpperRight: m_TMPText.alignment = TextAlignmentOptions.TopRight; break;
}
#else
if (m_Text != null) m_Text.alignment = alignment;
#endif
}
public void SetFont(Font font)
{
if (m_Text) m_Text.font = font;
}
public void SetFontStyle(FontStyle fontStyle)
{
#if dUI_TextMeshPro
if (m_TMPText == null) return;
switch (fontStyle)
{
case FontStyle.Normal: m_TMPText.fontStyle = FontStyles.Normal; break;
case FontStyle.Bold: m_TMPText.fontStyle = FontStyles.Bold; break;
case FontStyle.BoldAndItalic: m_TMPText.fontStyle = FontStyles.Bold | FontStyles.Italic; break;
case FontStyle.Italic: m_TMPText.fontStyle = FontStyles.Italic; break;
}
#else
if (m_Text != null) m_Text.fontStyle = fontStyle;
#endif
}
public void SetFontAndSizeAndStyle(TextStyle textStyle, ComponentTheme theme)
{
#if dUI_TextMeshPro
if (m_TMPText == null) return;
m_TMPText.font = textStyle.tmpFont == null ? theme.tmpFont : textStyle.tmpFont;
m_TMPText.fontSize = textStyle.fontSize == 0 ? theme.fontSize : textStyle.fontSize;
m_TMPText.fontStyle = textStyle.tmpFontStyle;
#else
if (m_Text != null)
{
m_Text.font = textStyle.font == null ? theme.font : textStyle.font;
m_Text.fontSize = textStyle.fontSize == 0 ? theme.fontSize : textStyle.fontSize;
m_Text.fontStyle = textStyle.fontStyle;
}
#endif
}
public float GetPreferredWidth(string content)
{
#if dUI_TextMeshPro
if (m_TMPText != null) return 0; // TODO:
#else
if (m_Text != null)
{
var tg = m_Text.cachedTextGeneratorForLayout;
var setting = m_Text.GetGenerationSettings(Vector2.zero);
return tg.GetPreferredWidth(content, setting) / m_Text.pixelsPerUnit;
}
#endif
return 0;
}
public float GetPreferredWidth()
{
#if dUI_TextMeshPro
if (m_TMPText != null) return m_TMPText.preferredWidth + m_ExtraWidth;
#else
if (m_Text != null) return m_Text.preferredWidth + m_ExtraWidth;
#endif
return 0;
}
public float GetPreferredHeight()
{
#if dUI_TextMeshPro
if (m_TMPText != null) return m_TMPText.preferredHeight;
#else
if (m_Text != null) return m_Text.preferredHeight;
#endif
return 0;
}
public string GetPreferredText(string content, string suffix, float maxWidth)
{
#if dUI_TextMeshPro
if (m_TMPText != null) return content; // TODO:
#else
if (m_Text != null)
{
var sourWid = GetPreferredWidth(content);
if (sourWid < maxWidth) return content;
var suffixWid = GetPreferredWidth(suffix);
var textWid = maxWidth - 1.3f * suffixWid;
for (int i = content.Length; i > 0; i--)
{
var temp = content.Substring(0, i);
if (GetPreferredWidth(temp) < textWid)
{
return temp + suffix;
}
}
}
#endif
return string.Empty;
}
#if dUI_TextMeshPro
public void SetFont(TMP_FontAsset font)
{
if (m_TMPText != null) m_TMPText.font = font;
}
#endif
}
}

View File

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

View File

@@ -0,0 +1,214 @@
using System;
using UnityEngine;
using UnityEngine.UI;
namespace XCharts
{
public class LegendItem
{
private int m_Index;
private string m_Name;
private string m_LegendName;
private GameObject m_GameObject;
private Button m_Button;
private Image m_Icon;
private ChartText m_Text;
private Image m_TextBackground;
private RectTransform m_Rect;
private RectTransform m_IconRect;
private RectTransform m_TextRect;
private RectTransform m_TextBackgroundRect;
private float m_Gap = 0f;
private float m_LabelPaddingLeftRight = 0f;
private float m_LabelPaddingTopBottom = 0f;
private bool m_LabelAutoSize = true;
public int index { get { return m_Index; } set { m_Index = value; } }
public string name { get { return m_Name; } set { m_Name = value; } }
public string legendName { get { return m_LegendName; } set { m_LegendName = value; } }
public GameObject gameObject { get { return m_GameObject; } }
public Button button { get { return m_Button; } }
public float width
{
get
{
if (m_IconRect && m_TextBackgroundRect)
{
return m_IconRect.sizeDelta.x + m_Gap + m_TextBackgroundRect.sizeDelta.x;
}
else
{
return 0;
}
}
}
public float height
{
get
{
if (m_IconRect && m_TextBackgroundRect)
{
return Mathf.Max(m_IconRect.sizeDelta.y, m_TextBackgroundRect.sizeDelta.y);
}
else
{
return 0;
}
}
}
public void SetObject(GameObject obj)
{
m_GameObject = obj;
m_Button = obj.GetComponent<Button>();
m_Rect = obj.GetComponent<RectTransform>();
m_Icon = obj.transform.Find("icon").gameObject.GetComponent<Image>();
m_TextBackground = obj.transform.Find("content").gameObject.GetComponent<Image>();
m_Text = new ChartText(obj);
m_IconRect = m_Icon.gameObject.GetComponent<RectTransform>();
m_TextRect = m_Text.gameObject.GetComponent<RectTransform>();
m_TextBackgroundRect = m_TextBackground.gameObject.GetComponent<RectTransform>();
}
public void SetButton(Button button)
{
m_Button = button;
}
public void SetIcon(Image icon)
{
m_Icon = icon;
}
public void SetText(ChartText text)
{
m_Text = text;
}
public void SetTextBackground(Image image)
{
m_TextBackground = image;
}
public void SetIconSize(float width, float height)
{
if (m_IconRect)
{
m_IconRect.sizeDelta = new Vector2(width, height);
}
}
public Rect GetIconRect()
{
if (m_GameObject && m_IconRect)
{
var pos = m_GameObject.transform.localPosition;
var sizeDelta = m_IconRect.sizeDelta;
var y = pos.y - (m_Rect.sizeDelta.y - sizeDelta.y) / 2 - sizeDelta.y;
return new Rect(pos.x, y, m_IconRect.sizeDelta.x, m_IconRect.sizeDelta.y);
}
else
{
return Rect.zero;
}
}
public Color GetIconColor()
{
if (m_Icon) return m_Icon.color;
else return Color.clear;
}
public void SetIconColor(Color color)
{
if (m_Icon)
{
m_Icon.color = color;
}
}
public void SetIconImage(Sprite image)
{
if (m_Icon)
{
m_Icon.sprite = image;
}
}
public void SetIconActive(bool active)
{
if (m_Icon)
{
m_Icon.gameObject.SetActive(active);
}
}
public void SetContentColor(Color color)
{
if (m_Text != null)
{
m_Text.SetColor(color);
}
}
public void SetContentBackgroundColor(Color color)
{
if (m_TextBackground)
{
m_TextBackground.color = color;
}
}
public void SetContentPosition(Vector3 offset)
{
m_Gap = offset.x;
if (m_TextBackgroundRect)
{
var posX = m_IconRect.sizeDelta.x + offset.x;
m_TextBackgroundRect.anchoredPosition3D = new Vector3(posX, offset.y, 0);
}
}
public bool SetContent(string content)
{
if (m_Text != null && !m_Text.GetText().Equals(content))
{
m_Text.SetText(content);
if (m_LabelAutoSize)
{
var newSize = string.IsNullOrEmpty(content) ? Vector2.zero :
new Vector2(m_Text.GetPreferredWidth(), m_Text.GetPreferredHeight());
var sizeChange = newSize.x != m_TextRect.sizeDelta.x || newSize.y != m_TextRect.sizeDelta.y;
if (sizeChange)
{
m_TextRect.sizeDelta = newSize;
m_TextRect.anchoredPosition3D = new Vector3(m_LabelPaddingLeftRight, 0);
m_TextBackgroundRect.sizeDelta = new Vector2(m_Text.GetPreferredWidth() + m_LabelPaddingLeftRight * 2,
m_Text.GetPreferredHeight() + m_LabelPaddingTopBottom * 2 - 4);
m_Rect.sizeDelta = new Vector3(width, height);
}
return sizeChange;
}
}
return false;
}
public void SetPosition(Vector3 position)
{
if (m_GameObject)
{
m_GameObject.transform.localPosition = position;
}
}
public void SetActive(bool active)
{
if (m_GameObject)
{
m_GameObject.SetActive(active);
}
}
}
}

View File

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

View File

@@ -0,0 +1,73 @@
using UnityEngine;
using UnityEngine.UI;
using System;
namespace XCharts
{
[RequireComponent(typeof(CanvasRenderer))]
public class Painter : MaskableGraphic
{
public enum Type
{
Base,
Serie,
Top
}
protected int m_Index = -1;
protected Type m_Type = Type.Base;
protected bool m_Refresh;
protected Action<VertexHelper, Painter> m_OnPopulateMesh;
public Action<VertexHelper, Painter> onPopulateMesh { set { m_OnPopulateMesh = value; } }
public int index { get { return m_Index; } set { m_Index = value; } }
public Type type { get { return m_Type; } set { m_Type = value; } }
public void Refresh()
{
if (gameObject == null) return;
if (!gameObject.activeSelf) return;
m_Refresh = true;
}
public void Init()
{
raycastTarget = false;
}
public void SetActive(bool flag, bool isDebugMode = false)
{
if (gameObject.activeInHierarchy != flag)
{
gameObject.SetActive(flag);
}
var hideFlags = flag && isDebugMode ? HideFlags.None : HideFlags.HideInHierarchy;
if (gameObject.hideFlags != hideFlags)
{
gameObject.hideFlags = hideFlags;
}
}
protected override void Awake()
{
Init();
}
internal void CheckRefresh()
{
if (m_Refresh && gameObject.activeSelf)
{
m_Refresh = false;
SetVerticesDirty();
}
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
if (m_OnPopulateMesh != null)
{
m_OnPopulateMesh(vh, this);
}
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,33 @@
namespace XCharts
{
internal static class XAxisPool
{
private static readonly ObjectPool<XAxis> s_ListPool = new ObjectPool<XAxis>(null, null);
public static XAxis Get()
{
return s_ListPool.Get();
}
public static void Release(XAxis toRelease)
{
s_ListPool.Release(toRelease);
}
}
internal static class YAxisPool
{
private static readonly ObjectPool<YAxis> s_ListPool = new ObjectPool<YAxis>(null, null);
public static YAxis Get()
{
return s_ListPool.Get();
}
public static void Release(YAxis toRelease)
{
s_ListPool.Release(toRelease);
}
}
}

View File

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

View File

@@ -0,0 +1,37 @@
using System.Collections.Generic;
using UnityEngine;
namespace XCharts
{
internal static class ListPool<T>
{
private static readonly ObjectPool<List<T>> s_ListPool = new ObjectPool<List<T>>(OnGet, OnClear);
static void OnGet(List<T> l)
{
if (l.Capacity < 50)
{
l.Capacity = 50;
}
}
static void OnClear(List<T> l)
{
l.Clear();
}
public static List<T> Get()
{
return s_ListPool.Get();
}
public static void Release(List<T> toRelease)
{
s_ListPool.Release(toRelease);
}
public static void ClearAll()
{
s_ListPool.ClearAll();
}
}
}

View File

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

View File

@@ -0,0 +1,55 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace XCharts
{
internal class ObjectPool<T> where T : new()
{
private readonly Stack<T> m_Stack = new Stack<T>();
private readonly UnityAction<T> m_ActionOnGet;
private readonly UnityAction<T> m_ActionOnRelease;
public int countAll { get; private set; }
public int countActive { get { return countAll - countInactive; } }
public int countInactive { get { return m_Stack.Count; } }
public ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease)
{
m_ActionOnGet = actionOnGet;
m_ActionOnRelease = actionOnRelease;
}
public T Get()
{
T element;
if (m_Stack.Count == 0)
{
element = new T();
countAll++;
}
else
{
element = m_Stack.Pop();
}
if (m_ActionOnGet != null)
m_ActionOnGet(element);
return element;
}
public void Release(T element)
{
if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element))
Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
if (m_ActionOnRelease != null)
m_ActionOnRelease(element);
m_Stack.Push(element);
}
public void ClearAll()
{
m_Stack.Clear();
}
}
}

View File

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

View File

@@ -0,0 +1,29 @@
using UnityEngine;
namespace XCharts
{
internal static class SerieDataPool
{
private static readonly ObjectPool<SerieData> s_ListPool = new ObjectPool<SerieData>(null, OnClear);
static void OnGet(SerieData serieData)
{
}
static void OnClear(SerieData serieData)
{
serieData.Reset();
}
public static SerieData Get()
{
return s_ListPool.Get();
}
public static void Release(SerieData toRelease)
{
s_ListPool.Release(toRelease);
}
}
}

View File

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

View File

@@ -0,0 +1,76 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace XCharts
{
public static class SerieLabelPool
{
private static readonly Stack<GameObject> m_Stack = new Stack<GameObject>(200);
private static Dictionary<int, bool> m_ReleaseDic = new Dictionary<int, bool>(1000);
public static GameObject Get(string name, Transform parent, LabelStyle label, Color color,
float iconWidth, float iconHeight, ThemeStyle theme)
{
GameObject element;
if (m_Stack.Count == 0 || !Application.isPlaying)
{
element = CreateSerieLabel(name, parent, label, color, iconWidth, iconHeight, theme);
}
else
{
element = m_Stack.Pop();
if (element == null)
{
element = CreateSerieLabel(name, parent, label, color, iconWidth, iconHeight, theme);
}
m_ReleaseDic.Remove(element.GetInstanceID());
element.name = name;
element.transform.SetParent(parent);
element.transform.localEulerAngles = new Vector3(0, 0, label.textStyle.rotate);
var text = new ChartText(element);
text.SetColor(color);
text.SetFontAndSizeAndStyle(label.textStyle, theme.common);
ChartHelper.SetActive(element, true);
}
return element;
}
private static GameObject CreateSerieLabel(string name, Transform parent, LabelStyle label, Color color,
float iconWidth, float iconHeight, ThemeStyle theme)
{
var element = ChartHelper.AddSerieLabel(name, parent, label.backgroundWidth, label.backgroundHeight,
color, label.textStyle, theme);
ChartHelper.AddIcon("Icon", element.transform, iconWidth, iconHeight);
return element;
}
public static void Release(GameObject element)
{
if (element == null) return;
ChartHelper.SetActive(element, false);
if (!Application.isPlaying) return;
if (!m_ReleaseDic.ContainsKey(element.GetInstanceID()))
{
m_Stack.Push(element);
m_ReleaseDic.Add(element.GetInstanceID(), true);
}
}
public static void ReleaseAll(Transform parent)
{
int count = parent.childCount;
for (int i = 0; i < count; i++)
{
Release(parent.GetChild(i).gameObject);
}
}
public static void ClearAll()
{
m_Stack.Clear();
m_ReleaseDic.Clear();
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,186 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
namespace XCharts
{
public static class ChartCached
{
private const string NUMERIC_FORMATTER_D = "D";
private const string NUMERIC_FORMATTER_d = "d";
private const string NUMERIC_FORMATTER_X = "X";
private const string NUMERIC_FORMATTER_x = "x";
private static readonly string s_DefaultAxis = "axis_";
private static CultureInfo ci = new CultureInfo("en-us");// "en-us", "zh-cn", "ar-iq", "de-de"
private static Dictionary<Color, string> s_ColorToStr = new Dictionary<Color, string>(100);
private static Dictionary<int, string> s_SerieLabelName = new Dictionary<int, string>(1000);
private static Dictionary<Color, string> s_ColorDotStr = new Dictionary<Color, string>(100);
private static Dictionary<Type, Dictionary<int, string>> s_ComponentObjectName = new Dictionary<Type, Dictionary<int, string>>();
private static Dictionary<int, string> s_AxisLabelName = new Dictionary<int, string>();
private static Dictionary<string, string> s_AxisLabel = new Dictionary<string, string>();
private static Dictionary<Type, string> s_TypeName = new Dictionary<Type, string>();
private static Dictionary<double, Dictionary<string, string>> s_NumberToStr = new Dictionary<double, Dictionary<string, string>>();
private static Dictionary<int, Dictionary<string, string>> s_PrecisionToStr = new Dictionary<int, Dictionary<string, string>>();
public static string FloatToStr(double value, string numericFormatter = "F", int precision = 0)
{
if (precision > 0 && numericFormatter.Length == 1)
{
if (!s_PrecisionToStr.ContainsKey(precision))
{
s_PrecisionToStr[precision] = new Dictionary<string, string>();
}
if (!s_PrecisionToStr[precision].ContainsKey(numericFormatter))
{
s_PrecisionToStr[precision][numericFormatter] = numericFormatter + precision;
}
return NumberToStr(value, s_PrecisionToStr[precision][numericFormatter]);
}
else
{
return NumberToStr(value, numericFormatter);
}
}
public static string NumberToStr(double value, string formatter)
{
if (!s_NumberToStr.ContainsKey(value))
{
s_NumberToStr[value] = new Dictionary<string, string>();
}
if (!s_NumberToStr[value].ContainsKey(formatter))
{
if (string.IsNullOrEmpty(formatter))
{
if (value - (int)value == 0)
s_NumberToStr[value][formatter] = ((int)value).ToString();
else
s_NumberToStr[value][formatter] = value.ToString();
}
else if (formatter.StartsWith(NUMERIC_FORMATTER_D)
|| formatter.StartsWith(NUMERIC_FORMATTER_d)
|| formatter.StartsWith(NUMERIC_FORMATTER_X)
|| formatter.StartsWith(NUMERIC_FORMATTER_x)
)
{
s_NumberToStr[value][formatter] = ((int)value).ToString(formatter, ci);
}
else
{
s_NumberToStr[value][formatter] = value.ToString(formatter, ci);
}
}
return s_NumberToStr[value][formatter];
}
public static string IntToStr(int value, string numericFormatter = "")
{
return NumberToStr(value, numericFormatter);
}
public static string ColorToStr(Color color)
{
if (s_ColorToStr.ContainsKey(color))
{
return s_ColorToStr[color];
}
else
{
s_ColorToStr[color] = ColorUtility.ToHtmlStringRGBA(color);
return s_ColorToStr[color];
}
}
public static string ColorToDotStr(Color color)
{
if (!s_ColorDotStr.ContainsKey(color))
{
s_ColorDotStr[color] = "<color=#" + ColorToStr(color) + ">● </color>";
}
return s_ColorDotStr[color];
}
public static string GetSerieLabelName(string prefix, int i, int j)
{
int key = i * 10000000 + j;
if (s_SerieLabelName.ContainsKey(key))
{
return s_SerieLabelName[key];
}
else
{
string name = prefix + "_" + i + "_" + j;
s_SerieLabelName[key] = name;
return name;
}
}
internal static string GetComponentObjectName(MainComponent component)
{
Dictionary<int, string> dict;
var type = component.GetType();
if (s_ComponentObjectName.TryGetValue(type, out dict))
{
string name;
if (!dict.TryGetValue(component.index, out name))
{
name = GetTypeName(type) + component.index;
dict[component.index] = name;
}
return name;
}
else
{
var name = GetTypeName(type) + component.index;
dict = new Dictionary<int, string>();
dict.Add(component.index, name);
s_ComponentObjectName[type] = dict;
return name;
}
}
internal static string GetAxisLabelName(int index)
{
string name;
if (!s_AxisLabelName.TryGetValue(index, out name))
{
name = s_DefaultAxis + index;
s_AxisLabelName[index] = name;
return name;
}
else
{
return name;
}
}
internal static string GetAxisTooltipLabel(string axisName)
{
if (!s_AxisLabel.ContainsKey(axisName))
{
s_AxisLabel[axisName] = axisName + "_label";
}
return s_AxisLabel[axisName];
}
internal static string GetTypeName<T>()
{
return GetTypeName(typeof(T));
}
internal static string GetTypeName(Type type)
{
if (s_TypeName.ContainsKey(type)) return s_TypeName[type];
else
{
var name = type.Name;
s_TypeName[type] = name;
return name;
}
}
}
}

View File

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

View File

@@ -0,0 +1,12 @@
using UnityEngine;
namespace XCharts
{
public static class ChartConst
{
public static readonly Color32 clearColor32 = new Color32(0, 0, 0, 0);
public static readonly Color32 greyColor32 = new Color32(128, 128, 128, 255);
public static readonly Color clearColor = Color.clear;
}
}

View File

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

View File

@@ -0,0 +1,145 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XUGL;
namespace XCharts
{
public static class ChartDrawer
{
public static void DrawSymbol(VertexHelper vh, SymbolType type, float symbolSize,
float tickness, Vector3 pos, Color32 color, Color32 toColor, float gap, float[] cornerRadius,
Color32 emptyColor, Color32 backgroundColor, float smoothness, Vector3 startPos)
{
switch (type)
{
case SymbolType.None:
break;
case SymbolType.Circle:
if (gap > 0)
{
UGL.DrawDoughnut(vh, pos, symbolSize, symbolSize + gap, backgroundColor, backgroundColor, color, smoothness);
}
else
{
UGL.DrawCricle(vh, pos, symbolSize, color, toColor, smoothness);
}
break;
case SymbolType.EmptyCircle:
if (gap > 0)
{
UGL.DrawCricle(vh, pos, symbolSize + gap, backgroundColor, smoothness);
UGL.DrawEmptyCricle(vh, pos, symbolSize, tickness, color, color, emptyColor, smoothness);
}
else
{
UGL.DrawEmptyCricle(vh, pos, symbolSize, tickness, color, color, emptyColor, smoothness);
}
break;
case SymbolType.Rect:
if (gap > 0)
{
UGL.DrawSquare(vh, pos, symbolSize + gap, backgroundColor);
UGL.DrawSquare(vh, pos, symbolSize, color, toColor);
}
else
{
UGL.DrawRoundRectangle(vh, pos, symbolSize, symbolSize, color, color, 0, cornerRadius, true);
}
break;
case SymbolType.EmptyRect:
if (gap > 0)
{
UGL.DrawSquare(vh, pos, symbolSize + gap, backgroundColor);
UGL.DrawBorder(vh, pos, symbolSize / 2, symbolSize / 2, tickness, color);
}
else
{
UGL.DrawBorder(vh, pos, symbolSize / 2, symbolSize / 2, tickness, color);
}
break;
case SymbolType.Triangle:
if (gap > 0)
{
UGL.DrawTriangle(vh, pos, symbolSize + gap, backgroundColor);
UGL.DrawTriangle(vh, pos, symbolSize, color, toColor);
}
else
{
UGL.DrawTriangle(vh, pos, symbolSize, color, toColor);
}
break;
case SymbolType.Diamond:
if (gap > 0)
{
UGL.DrawDiamond(vh, pos, symbolSize + gap, backgroundColor);
UGL.DrawDiamond(vh, pos, symbolSize, color, toColor);
}
else
{
UGL.DrawDiamond(vh, pos, symbolSize, color, toColor);
}
break;
case SymbolType.Arrow:
var arrowWidth = symbolSize * 2;
var arrowHeight = arrowWidth * 1.5f;
var arrowOffset = 0;
var arrowDent = arrowWidth / 3.3f;
UGL.DrawArrow(vh, startPos, pos, arrowWidth, arrowHeight,
arrowOffset, arrowDent, color);
break;
}
}
public static void DrawLineStyle(VertexHelper vh, LineStyle lineStyle, Vector3 startPos, Vector3 endPos,
Color32 defaultColor, float themeWidth, LineStyle.Type themeType)
{
var type = lineStyle.GetType(themeType);
var width = lineStyle.GetWidth(themeWidth);
var color = lineStyle.GetColor(defaultColor);
DrawLineStyle(vh, type, width, startPos, endPos, color, color);
}
public static void DrawLineStyle(VertexHelper vh, LineStyle lineStyle, Vector3 startPos, Vector3 endPos,
float themeWidth, LineStyle.Type themeType, Color32 defaultColor, Color32 defaultToColor)
{
var type = lineStyle.GetType(themeType);
var width = lineStyle.GetWidth(themeWidth);
var color = lineStyle.GetColor(defaultColor);
var toColor = ChartHelper.IsClearColor(defaultToColor) ? color : defaultToColor;
DrawLineStyle(vh, type, width, startPos, endPos, color, toColor);
}
public static void DrawLineStyle(VertexHelper vh, LineStyle.Type lineType, float lineWidth,
Vector3 startPos, Vector3 endPos, Color32 color)
{
DrawLineStyle(vh, lineType, lineWidth, startPos, endPos, color, color);
}
public static void DrawLineStyle(VertexHelper vh, LineStyle.Type lineType, float lineWidth,
Vector3 startPos, Vector3 endPos, Color32 color, Color32 toColor)
{
switch (lineType)
{
case LineStyle.Type.Dashed:
UGL.DrawDashLine(vh, startPos, endPos, lineWidth, color, toColor);
break;
case LineStyle.Type.Dotted:
UGL.DrawDotLine(vh, startPos, endPos, lineWidth, color, toColor);
break;
case LineStyle.Type.Solid:
UGL.DrawLine(vh, startPos, endPos, lineWidth, color, toColor);
break;
case LineStyle.Type.DashDot:
UGL.DrawDashDotLine(vh, startPos, endPos, lineWidth, color);
break;
case LineStyle.Type.DashDotDot:
UGL.DrawDashDotDotLine(vh, startPos, endPos, lineWidth, color);
break;
}
}
}
}

View File

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

View File

@@ -0,0 +1,927 @@

using System.Text;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
#if dUI_TextMeshPro
using TMPro;
#endif
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace XCharts
{
public static class ChartHelper
{
private static StringBuilder s_Builder = new StringBuilder();
private static Vector3 s_DefaultIngoreDataVector3 = Vector3.zero;
public static StringBuilder sb { get { return s_Builder; } }
public static Vector3 ignoreVector3 { get { return s_DefaultIngoreDataVector3; } }
public static bool IsIngore(Vector3 pos)
{
return pos == s_DefaultIngoreDataVector3;
}
public static string Cancat(string str1, string str2)
{
s_Builder.Length = 0;
s_Builder.Append(str1).Append(str2);
return s_Builder.ToString();
}
public static string Cancat(string str1, int i)
{
s_Builder.Length = 0;
s_Builder.Append(str1).Append(ChartCached.IntToStr(i));
return s_Builder.ToString();
}
public static void SetActive(GameObject gameObject, bool active)
{
if (gameObject == null) return;
SetActive(gameObject.transform, active);
}
public static void SetActive(Image image, bool active)
{
if (image == null) return;
SetActive(image.gameObject, active);
}
public static void SetActive(Text text, bool active)
{
if (text == null) return;
SetActive(text.gameObject, active);
}
/// <summary>
/// 通过设置scale实现是否显示优化性能减少GC
/// </summary>
/// <param name="transform"></param>
/// <param name="active"></param>
public static void SetActive(Transform transform, bool active)
{
if (transform == null) return;
if (active) transform.localScale = Vector3.one;
else transform.localScale = Vector3.zero;
}
public static void HideAllObject(GameObject obj, string match = null)
{
if (obj == null) return;
HideAllObject(obj.transform, match);
}
public static void HideAllObject(Transform parent, string match = null)
{
if (parent == null) return;
ActiveAllObject(parent, false, match);
}
public static void ActiveAllObject(Transform parent, bool active, string match = null)
{
if (parent == null) return;
for (int i = 0; i < parent.childCount; i++)
{
if (match == null)
SetActive(parent.GetChild(i), active);
else
{
var go = parent.GetChild(i);
if (go.name.StartsWith(match))
{
SetActive(go, active);
}
}
}
}
public static void DestroyAllChildren(Transform parent)
{
if (parent == null) return;
var childCount = parent.childCount;
for (int i = childCount - 1; i >= 0; i--)
{
var go = parent.GetChild(i);
if (go != null)
{
GameObject.DestroyImmediate(go.gameObject, true);
}
}
}
public static void DestoryGameObject(Transform parent, string childName)
{
if (parent == null) return;
var go = parent.Find(childName);
if (go != null)
{
GameObject.DestroyImmediate(go.gameObject, true);
}
}
public static void DestoryGameObjectByMatch(Transform parent, string match)
{
if (parent == null) return;
var childCount = parent.childCount;
for (int i = childCount - 1; i >= 0; i--)
{
var go = parent.GetChild(i);
if (go != null && go.name.StartsWith(match))
{
GameObject.DestroyImmediate(go.gameObject, true);
}
}
}
public static void DestoryGameObject(GameObject go)
{
if (go != null) GameObject.DestroyImmediate(go, true);
}
public static string GetFullName(Transform transform)
{
string name = transform.name;
Transform obj = transform;
while (obj.transform.parent)
{
name = obj.transform.parent.name + "/" + name;
obj = obj.transform.parent;
}
return name;
}
public static void RemoveComponent<T>(GameObject gameObject)
{
var component = gameObject.GetComponent<T>();
if (component != null)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
GameObject.DestroyImmediate(component as GameObject, true);
else
GameObject.Destroy(component as GameObject);
#else
GameObject.Destroy(component as GameObject);
#endif
}
}
public static T GetOrAddComponent<T>(Transform transform) where T : Component
{
return GetOrAddComponent<T>(transform.gameObject);
}
public static T GetOrAddComponent<T>(GameObject gameObject) where T : Component
{
if (gameObject.GetComponent<T>() == null)
{
return gameObject.AddComponent<T>();
}
else
{
return gameObject.GetComponent<T>();
}
}
public static GameObject AddObject(string name, Transform parent, Vector2 anchorMin,
Vector2 anchorMax, Vector2 pivot, Vector2 sizeDelta, int replaceIndex = -1)
{
GameObject obj;
if (parent.Find(name))
{
obj = parent.Find(name).gameObject;
SetActive(obj, true);
obj.transform.localPosition = Vector3.zero;
obj.transform.localScale = Vector3.one;
}
else if (replaceIndex >= 0 && replaceIndex < parent.childCount)
{
obj = parent.GetChild(replaceIndex).gameObject;
if (!obj.name.Equals(name)) obj.name = name;
SetActive(obj, true);
}
else
{
obj = new GameObject();
obj.name = name;
obj.transform.SetParent(parent);
obj.transform.localScale = Vector3.one;
obj.transform.localPosition = Vector3.zero;
}
RectTransform rect = GetOrAddComponent<RectTransform>(obj);
rect.localPosition = Vector3.zero;
rect.sizeDelta = sizeDelta;
rect.anchorMin = anchorMin;
rect.anchorMax = anchorMax;
rect.pivot = pivot;
rect.anchoredPosition3D = Vector3.zero;
return obj;
}
public static void UpdateRectTransform(GameObject obj, Vector2 anchorMin,
Vector2 anchorMax, Vector2 pivot, Vector2 sizeDelta)
{
if (obj == null) return;
RectTransform rect = GetOrAddComponent<RectTransform>(obj);
rect.sizeDelta = sizeDelta;
rect.anchorMin = anchorMin;
rect.anchorMax = anchorMax;
rect.pivot = pivot;
}
public static ChartText AddTextObject(string name, Transform parent, Vector2 anchorMin, Vector2 anchorMax,
Vector2 pivot, Vector2 sizeDelta, TextStyle textStyle, ComponentTheme theme)
{
GameObject txtObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
txtObj.transform.localEulerAngles = new Vector3(0, 0, textStyle.rotate);
var chartText = new ChartText();
#if dUI_TextMeshPro
RemoveComponent<Text>(txtObj);
chartText.tmpText = GetOrAddComponent<TextMeshProUGUI>(txtObj);
chartText.tmpText.font = textStyle.tmpFont == null ? theme.tmpFont : textStyle.tmpFont;
chartText.tmpText.fontStyle = textStyle.tmpFontStyle;
chartText.tmpText.alignment = textStyle.tmpAlignment;
chartText.tmpText.richText = true;
chartText.tmpText.raycastTarget = false;
chartText.tmpText.enableWordWrapping = textStyle.autoWrap;
#else
chartText.text = GetOrAddComponent<Text>(txtObj);
chartText.text.font = textStyle.font == null ? theme.font : textStyle.font;
chartText.text.fontStyle = textStyle.fontStyle;
chartText.text.alignment = textStyle.alignment;
chartText.text.horizontalOverflow = textStyle.autoWrap ? HorizontalWrapMode.Wrap : HorizontalWrapMode.Overflow;
chartText.text.verticalOverflow = VerticalWrapMode.Overflow;
chartText.text.supportRichText = true;
chartText.text.raycastTarget = false;
#endif
chartText.SetColor(textStyle.GetColor(theme.textColor));
chartText.SetFontSize(textStyle.GetFontSize(theme));
chartText.SetText("Text");
chartText.SetLineSpacing(textStyle.lineSpacing);
chartText.SetExtraWidth(textStyle.extraWidth);
RectTransform rect = GetOrAddComponent<RectTransform>(txtObj);
rect.localPosition = Vector3.zero;
rect.sizeDelta = sizeDelta;
rect.anchorMin = anchorMin;
rect.anchorMax = anchorMax;
rect.pivot = pivot;
return chartText;
}
public static Text AddTextObject(string name, Transform parent, Font font, Color color,
TextAnchor anchor, Vector2 anchorMin, Vector2 anchorMax, Vector2 pivot, Vector2 sizeDelta,
int fontSize = 14, float rotate = 0, FontStyle fontStyle = FontStyle.Normal, float lineSpacing = 1)
{
GameObject txtObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
var txt = GetOrAddComponent<Text>(txtObj);
txt.font = font;
txt.fontSize = fontSize;
txt.fontStyle = fontStyle;
txt.text = "Text";
txt.alignment = anchor;
txt.horizontalOverflow = HorizontalWrapMode.Overflow;
txt.verticalOverflow = VerticalWrapMode.Overflow;
txt.color = color;
txt.lineSpacing = lineSpacing;
txt.raycastTarget = false;
txtObj.transform.localEulerAngles = new Vector3(0, 0, rotate);
RectTransform rect = GetOrAddComponent<RectTransform>(txtObj);
rect.localPosition = Vector3.zero;
rect.sizeDelta = sizeDelta;
rect.anchorMin = anchorMin;
rect.anchorMax = anchorMax;
rect.pivot = pivot;
return txt;
}
#if dUI_TextMeshPro
public static TextMeshProUGUI AddTMPTextObject(string name, Transform parent, TMP_FontAsset font, Color color,
TextAlignmentOptions anchor, Vector2 anchorMin, Vector2 anchorMax, Vector2 pivot, Vector2 sizeDelta,
int fontSize = 14, float rotate = 0, FontStyles fontStyle = FontStyles.Normal, float lineSpacing = 1)
{
GameObject txtObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
var txt = GetOrAddComponent<TextMeshProUGUI>(txtObj);
txt.font = font;
txt.fontSize = fontSize;
txt.fontStyle = fontStyle;
txt.text = "Text";
txt.alignment = anchor;
txt.color = color;
txt.lineSpacing = lineSpacing;
txt.raycastTarget = false;
txt.enableWordWrapping = false;
txtObj.transform.localEulerAngles = new Vector3(0, 0, rotate);
RectTransform rect = GetOrAddComponent<RectTransform>(txtObj);
rect.localPosition = Vector3.zero;
rect.sizeDelta = sizeDelta;
rect.anchorMin = anchorMin;
rect.anchorMax = anchorMax;
rect.pivot = pivot;
return txt;
}
#endif
public static Button AddButtonObject(string name, Transform parent, Font font, int fontSize,
Color color, TextAnchor anchor, Vector2 anchorMin, Vector2 anchorMax, Vector2 pivot,
Vector2 sizeDelta, float lineSpacing)
{
GameObject btnObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
GetOrAddComponent<Image>(btnObj);
GetOrAddComponent<Button>(btnObj);
Text txt = AddTextObject("Text", btnObj.transform, font, color, TextAnchor.MiddleCenter,
new Vector2(0, 0), new Vector2(1, 1), new Vector2(0.5f, 0.5f),
sizeDelta, fontSize, lineSpacing);
txt.rectTransform.offsetMin = Vector2.zero;
txt.rectTransform.offsetMax = Vector2.zero;
return btnObj.GetComponent<Button>();
}
#if dUI_TextMeshPro
public static Button AddTMPButtonObject(string name, Transform parent, TMP_FontAsset font, int fontSize,
Color color, TextAlignmentOptions anchor, Vector2 anchorMin, Vector2 anchorMax, Vector2 pivot,
Vector2 sizeDelta, float lineSpacing)
{
GameObject btnObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
GetOrAddComponent<Image>(btnObj);
GetOrAddComponent<Button>(btnObj);
var txt = AddTMPTextObject("Text", btnObj.transform, font, color, anchor,
new Vector2(0, 0), new Vector2(1, 1), new Vector2(0.5f, 0.5f),
sizeDelta, fontSize, lineSpacing);
txt.rectTransform.offsetMin = Vector2.zero;
txt.rectTransform.offsetMax = Vector2.zero;
return btnObj.GetComponent<Button>();
}
#endif
internal static GameObject AddTooltipContent(string name, Transform parent, TextStyle textStyle,
ThemeStyle theme)
{
var anchorMax = new Vector2(0, 1);
var anchorMin = new Vector2(0, 1);
var pivot = new Vector2(0, 1);
var sizeDelta = new Vector2(100, 100);
GameObject tooltipObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
var img = GetOrAddComponent<Image>(tooltipObj);
img.color = Color.black;
var txt = AddTextObject("Text", tooltipObj.transform, anchorMin, anchorMax, pivot, sizeDelta,
textStyle, theme.tooltip);
txt.SetAlignment(textStyle.GetAlignment(TextAnchor.UpperLeft));
txt.SetText("Text");
txt.SetLocalPosition(new Vector2(3, -3));
tooltipObj.transform.localPosition = Vector3.zero;
return tooltipObj;
}
internal static Painter AddPainterObject(string name, Transform parent, Vector2 anchorMin, Vector2 anchorMax,
Vector2 pivot, Vector2 sizeDelta, HideFlags hideFlags, int siblingIndex)
{
var painterObj = ChartHelper.AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
painterObj.hideFlags = hideFlags;
painterObj.transform.SetSiblingIndex(siblingIndex);
return ChartHelper.GetOrAddComponent<Painter>(painterObj);
}
public static Image AddIcon(string name, Transform parent, float width, float height, Sprite sprite = null,
Image.Type type = Image.Type.Simple)
{
var anchorMax = new Vector2(0.5f, 0.5f);
var anchorMin = new Vector2(0.5f, 0.5f);
var pivot = new Vector2(0.5f, 0.5f);
var sizeDelta = new Vector2(width, height);
GameObject iconObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
var img = GetOrAddComponent<Image>(iconObj);
img.raycastTarget = false;
img.type = type;
if (sprite != null)
{
img.sprite = sprite;
if (width == 0 || height == 0)
{
img.SetNativeSize();
}
}
return img;
}
public static ChartLabel AddAxisLabelObject(int total, int index, string name, Transform parent,
Vector2 anchorMin, Vector2 anchorMax, Vector2 pivot, Vector2 sizeDelta, Axis axis, ComponentTheme theme,
string content)
{
var textStyle = axis.axisLabel.textStyle;
var iconStyle = axis.iconStyle;
var labelObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
var label = GetOrAddComponent<ChartLabel>(labelObj);
var labelShow = axis.axisLabel.show && (axis.axisLabel.interval == 0 || index % (axis.axisLabel.interval + 1) == 0);
if (labelShow)
{
if (!axis.axisLabel.showStartLabel && index == 0) labelShow = false;
else if (!axis.axisLabel.showEndLabel && index == total - 1) labelShow = false;
}
label.label = AddTextObject("Text", label.gameObject.transform, anchorMin, anchorMax, pivot, sizeDelta, textStyle, theme);
label.icon = ChartHelper.AddIcon("Icon", label.gameObject.transform, iconStyle.width, iconStyle.height);
label.SetAutoSize(false);
label.UpdateIcon(iconStyle, axis.GetIcon(index));
label.label.SetActive(labelShow);
label.SetText(content);
label.color = textStyle.color;
return label;
}
internal static GameObject AddSerieLabel(string name, Transform parent, float width, float height,
Color color, TextStyle textStyle, ThemeStyle theme)
{
var anchorMin = new Vector2(0.5f, 0.5f);
var anchorMax = new Vector2(0.5f, 0.5f);
var pivot = new Vector2(0.5f, 0.5f);
var sizeDelta = (width != 0 && height != 0)
? new Vector2(width, height)
: new Vector2(50, textStyle.GetFontSize(theme.common) + 2);
var labelObj = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
var txt = AddTextObject("Text", labelObj.transform, anchorMin, anchorMax, pivot, sizeDelta, textStyle,
theme.common);
txt.SetColor(color);
txt.SetAlignment(textStyle.alignment);
txt.SetText("Text");
txt.SetLocalPosition(new Vector2(0, 0));
txt.SetLocalEulerAngles(Vector3.zero);
labelObj.transform.localPosition = Vector3.zero;
labelObj.transform.localEulerAngles = new Vector3(0, 0, textStyle.rotate);
return labelObj;
}
internal static ChartLabel AddTooltipLabel(Tooltip tooltip, string name, Transform parent, ThemeStyle theme, Vector2 pivot)
{
var anchorMax = new Vector2(0.5f, 0.5f);
var anchorMin = new Vector2(0.5f, 0.5f);
var sizeDelta = new Vector2(100, 20);
return AddTooltipLabel(tooltip, name, parent, theme, pivot, anchorMin, anchorMax, sizeDelta);
}
internal static ChartLabel AddTooltipLabel(Tooltip tooltip, string name, Transform parent, ThemeStyle theme, Vector2 pivot,
Vector2 anchorMin, Vector2 anchorMax, Vector2 sizeDelta)
{
var textStyle = tooltip.labelTextStyle;
var labelGameObject = AddObject(name, parent, anchorMin, anchorMax, pivot, sizeDelta);
var label = GetOrAddComponent<ChartLabel>(labelGameObject);
label.labelBackground = ChartHelper.AddIcon("Background", label.gameObject.transform, 50, 20);
label.labelBackground.color = Color.black;
label.label = AddTextObject("Text", label.gameObject.transform, anchorMin, anchorMax, pivot, sizeDelta, textStyle, theme.tooltip);
label.SetAutoSize(true);
label.SetText("");
label.color = textStyle.color;
return label;
}
public static void GetPointList(ref List<Vector3> posList, Vector3 sp, Vector3 ep, float k = 30f)
{
Vector3 dir = (ep - sp).normalized;
float dist = Vector3.Distance(sp, ep);
int segment = (int)(dist / k);
posList.Clear();
posList.Add(sp);
for (int i = 1; i < segment; i++)
{
posList.Add(sp + dir * dist * i / segment);
}
posList.Add(ep);
}
public static bool IsValueEqualsColor(Color32 color1, Color32 color2)
{
return color1.a == color2.a &&
color1.b == color2.b &&
color1.g == color2.g &&
color1.r == color2.r;
}
public static bool IsValueEqualsColor(Color color1, Color color2)
{
return color1.a == color2.a &&
color1.b == color2.b &&
color1.g == color2.g &&
color1.r == color2.r;
}
public static bool IsValueEqualsString(string str1, string str2)
{
if (str1 == null && str2 == null) return true;
else if (str1 != null && str2 != null) return str1.Equals(str2);
else return false;
}
public static bool IsValueEqualsVector2(Vector2 v1, Vector2 v2)
{
return v1.x == v2.x && v1.y == v2.y;
}
public static bool IsValueEqualsVector3(Vector3 v1, Vector3 v2)
{
return v1.x == v2.x && v1.y == v2.y && v1.z == v2.z;
}
public static bool IsValueEqualsList<T>(List<T> list1, List<T> list2)
{
if (list1 == null || list2 == null) return false;
if (list1.Count != list2.Count) return false;
for (int i = 0; i < list1.Count; i++)
{
if (list1[i] == null && list2[i] == null) { }
else
{
if (list1[i] != null)
{
if (!list1[i].Equals(list2[i])) return false;
}
else
{
if (!list2[i].Equals(list1[i])) return false;
}
}
}
return true;
}
public static bool IsEquals(double d1, double d2)
{
return Math.Abs(d1 - d2) < 0.000001d;
}
public static bool IsEquals(float d1, float d2)
{
return Math.Abs(d1 - d2) < 0.000001f;
}
public static bool IsClearColor(Color32 color)
{
return color.a == 0 && color.b == 0 && color.g == 0 && color.r == 0;
}
public static bool IsClearColor(Color color)
{
return color.a == 0 && color.b == 0 && color.g == 0 && color.r == 0;
}
public static bool IsZeroVector(Vector3 pos)
{
return pos.x == 0 && pos.y == 0 && pos.z == 0;
}
public static bool CopyList<T>(List<T> toList, List<T> fromList)
{
if (toList == null || fromList == null) return false;
toList.Clear();
foreach (var item in fromList) toList.Add(item);
return true;
}
public static bool CopyArray<T>(T[] toList, T[] fromList)
{
if (toList == null || fromList == null) return false;
if (toList.Length != fromList.Length)
{
toList = new T[fromList.Length];
}
for (int i = 0; i < fromList.Length; i++) toList[i] = fromList[i];
return true;
}
public static List<float> ParseFloatFromString(string jsonData)
{
List<float> list = new List<float>();
if (string.IsNullOrEmpty(jsonData)) return list;
int startIndex = jsonData.IndexOf("[");
int endIndex = jsonData.IndexOf("]");
string temp = jsonData.Substring(startIndex + 1, endIndex - startIndex - 1);
if (temp.IndexOf("],") > -1 || temp.IndexOf("] ,") > -1)
{
string[] datas = temp.Split(new string[] { "],", "] ," }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < datas.Length; i++)
{
temp = datas[i];
}
return list;
}
else
{
string[] datas = temp.Split(',');
for (int i = 0; i < datas.Length; i++)
{
list.Add(float.Parse(datas[i].Trim()));
}
return list;
}
}
public static List<string> ParseStringFromString(string jsonData)
{
List<string> list = new List<string>();
if (string.IsNullOrEmpty(jsonData)) return list;
string pattern = "[\"'](.*?)[\"']";
if (Regex.IsMatch(jsonData, pattern))
{
MatchCollection m = Regex.Matches(jsonData, pattern);
foreach (Match match in m)
{
list.Add(match.Groups[1].Value);
}
}
return list;
}
public static Color32 GetColor(string hexColorStr)
{
Color color;
ColorUtility.TryParseHtmlString(hexColorStr, out color);
return (Color32)color;
}
public static double GetMaxDivisibleValue(double max, int ceilRate)
{
if (max == 0) return 0;
if (max > -1 && max < 1)
{
int count = 1;
int intvalue = (int)(max * Mathf.Pow(10, count));
while (intvalue == 0 && count < 12)
{
count++;
intvalue = (int)(max * Mathf.Pow(10, count));
}
if (max > 0) return 1 / Mathf.Pow(10, count - 1);
else return -1 / Mathf.Pow(10, count);
}
if (ceilRate == 0)
{
var bigger = Math.Ceiling(Math.Abs(max));
int n = 1;
while (bigger / (Mathf.Pow(10, n)) > 10)
{
n++;
}
double mm = bigger;
if (mm > 10 && n < 38)
{
mm = bigger - bigger % (Mathf.Pow(10, n));
mm += max > 0 ? Mathf.Pow(10, n) : -Mathf.Pow(10, n);
}
var mmm = mm - Mathf.Pow(10, n) / 2;
if (max < 0) return -Math.Ceiling(mmm > -max ? mmm : mm);
else return Math.Ceiling(mmm > max ? mmm : mm);
}
else
{
var mod = max % ceilRate;
int rate = (int)(max / ceilRate);
return mod == 0 ? max : (max < 0 ? rate : rate + 1) * ceilRate;
}
}
public static double GetMinDivisibleValue(double min, int ceilRate)
{
if (min == 0) return 0;
if (min > -1 && min < 1)
{
int count = 1;
int intvalue = (int)(min * Mathf.Pow(10, count));
while (intvalue == 0 && count < 12)
{
count++;
intvalue = (int)(min * Mathf.Pow(10, count));
}
if (min > 0) return 1 / Mathf.Pow(10, count);
else return -1 / Mathf.Pow(10, count - 1);
}
if (ceilRate == 0)
{
var bigger = Math.Floor(Math.Abs(min));
int n = 1;
while (bigger / (Mathf.Pow(10, n)) > 10)
{
n++;
}
double mm = bigger;
if (mm > 10 && n < 38)
{
mm = bigger - bigger % (Mathf.Pow(10, n));
mm += min < 0 ? Mathf.Pow(10, n) : -Mathf.Pow(10, n);
}
if (min < 0) return -Math.Floor(mm);
else return Math.Floor(mm);
}
else
{
var mod = min % ceilRate;
int rate = (int)(min / ceilRate);
return mod == 0 ? min : (min < 0 ? rate - 1 : rate) * ceilRate;
}
}
public static double GetMaxLogValue(double value, float logBase, bool isLogBaseE, out int splitNumber)
{
splitNumber = 0;
if (value <= 0) return 0;
double max = 0;
while (max < value)
{
if (isLogBaseE)
{
max = Mathf.Exp(splitNumber);
}
else
{
max = Mathf.Pow(logBase, splitNumber);
}
splitNumber++;
}
return max;
}
public static float GetMinLogValue(double value, float logBase, bool isLogBaseE, out int splitNumber)
{
splitNumber = 0;
if (value > 1) return 1;
float min = 1;
while (min > value)
{
if (isLogBaseE)
{
min = Mathf.Exp(-splitNumber);
}
else
{
min = Mathf.Pow(logBase, -splitNumber);
}
splitNumber++;
}
return min;
}
public static int GetFloatAccuracy(double value)
{
if (value > 1 || value < -1) return 0;
int count = 1;
int intvalue = (int)(value * Mathf.Pow(10, count));
while (intvalue == 0 && count < 38)
{
count++;
intvalue = (int)(value * Mathf.Pow(10, count));
}
if (count == 38 && (value == 0 || value == 1)) return 1;
else return count;
}
public static void AddEventListener(GameObject obj, EventTriggerType type,
UnityEngine.Events.UnityAction<BaseEventData> call)
{
EventTrigger trigger = GetOrAddComponent<EventTrigger>(obj.gameObject);
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = type;
entry.callback = new EventTrigger.TriggerEvent();
entry.callback.AddListener(call);
trigger.triggers.Add(entry);
}
public static void ClearEventListener(GameObject obj)
{
EventTrigger trigger = obj.GetComponent<EventTrigger>();
if (trigger != null)
{
trigger.triggers.Clear();
}
}
public static Vector3 RotateRound(Vector3 position, Vector3 center, Vector3 axis, float angle)
{
Vector3 point = Quaternion.AngleAxis(angle, axis) * (position - center);
Vector3 resultVec3 = center + point;
return resultVec3;
}
public static Vector3 GetPosition(Vector3 center, float angle, float radius)
{
var rad = angle * Mathf.Deg2Rad;
var px = Mathf.Sin(rad) * radius;
var py = Mathf.Cos(rad) * radius;
return center + new Vector3(px, py);
}
/// <summary>
/// 获得0-360的角度12点钟方向为0度
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public static float GetAngle360(Vector2 from, Vector2 to)
{
float angle;
Vector3 cross = Vector3.Cross(from, to);
angle = Vector2.Angle(from, to);
angle = cross.z > 0 ? -angle : angle;
angle = (angle + 360) % 360;
return angle;
}
public static Vector3 GetPos(Vector3 center, float radius, float angle, bool isDegree = false)
{
angle = isDegree ? angle * Mathf.Deg2Rad : angle;
return new Vector3(center.x + radius * Mathf.Sin(angle), center.y + radius * Mathf.Cos(angle));
}
public static Vector3 GetDire(float angle, bool isDegree = false)
{
angle = isDegree ? angle * Mathf.Deg2Rad : angle;
return new Vector3(Mathf.Sin(angle), Mathf.Cos(angle));
}
public static Vector3 GetVertialDire(Vector3 dire)
{
if (dire.x == 0)
{
return new Vector3(-1, 0, 0);
}
if (dire.y == 0)
{
return new Vector3(0, -1, 0);
}
else
{
return new Vector3(-dire.y / dire.x, 1, 0).normalized;
}
}
public static float GetRuntimeRelativeOrAbsoluteValue(float check, float total)
{
if (check <= 0)
{
return 0;
}
else if (check <= 1)
{
return total * check;
}
else
{
return check;
}
}
public static Vector3 GetLastPoint(List<Vector3> list)
{
if (list.Count <= 0) return Vector3.zero;
else return list[list.Count - 1];
}
public static void SetColorOpacity(ref Color32 color, float opacity)
{
if (color.a != 0 && opacity != 1)
{
color.a = (byte)(color.a * opacity);
}
}
public static Color32 GetHighlightColor(Color32 color, float rate = 0.8f)
{
var newColor = color;
newColor.r = (byte)(color.r * rate);
newColor.g = (byte)(color.g * rate);
newColor.b = (byte)(color.b * rate);
return newColor;
}
public static bool IsPointInQuadrilateral(Vector3 P, Vector3 A, Vector3 B, Vector3 C, Vector3 D)
{
Vector3 v0 = Vector3.Cross(A - D, P - D);
Vector3 v1 = Vector3.Cross(B - A, P - A);
Vector3 v2 = Vector3.Cross(C - B, P - B);
Vector3 v3 = Vector3.Cross(D - C, P - C);
if (Vector3.Dot(v0, v1) < 0 || Vector3.Dot(v0, v2) < 0 || Vector3.Dot(v0, v3) < 0)
{
return false;
}
else
{
return true;
}
}
public static bool IsInRect(Vector3 pos, float xMin, float xMax, float yMin, float yMax)
{
return pos.x >= xMin && pos.x <= xMax && pos.y <= yMax && pos.y >= yMin;
}
public static bool IsColorAlphaZero(Color color)
{
return !ChartHelper.IsClearColor(color) && color.a == 0;
}
}
}

View File

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

View File

@@ -0,0 +1,103 @@
using System.Collections.Generic;
using UnityEngine;
namespace XCharts
{
public static class ComponentHelper
{
public static AngleAxis GetAngleAxis(List<MainComponent> components, int polarIndex)
{
foreach (var component in components)
{
if (component is AngleAxis)
{
var axis = component as AngleAxis;
if (axis.polarIndex == polarIndex) return axis;
}
}
return null;
}
public static RadiusAxis GetRadiusAxis(List<MainComponent> components, int polarIndex)
{
foreach (var component in components)
{
if (component is RadiusAxis)
{
var axis = component as RadiusAxis;
if (axis.polarIndex == polarIndex) return axis;
}
}
return null;
}
public static YAxis GetYAxisRelatedWitchXAxis(List<MainComponent> components, XAxis axis)
{
foreach (var component in components)
{
if (component is YAxis)
{
var yAxis = component as YAxis;
if (yAxis.gridIndex == axis.gridIndex) return yAxis;
}
}
return null;
}
public static XAxis GetXAxisRelatedWithYAxis(List<MainComponent> components, YAxis axis)
{
foreach (var component in components)
{
if (component is XAxis)
{
var xAxis = component as XAxis;
if (xAxis.gridIndex == axis.gridIndex) return xAxis;
}
}
return null;
}
public static float GetXAxisOnZeroOffset(List<MainComponent> components, XAxis axis)
{
if (!axis.axisLine.onZero) return 0;
foreach (var component in components)
{
if (component is YAxis)
{
var yAxis = component as YAxis;
if (yAxis.IsValue() && yAxis.gridIndex == axis.gridIndex) return yAxis.context.offset;
}
}
return 0;
}
public static float GetYAxisOnZeroOffset(List<MainComponent> components, YAxis axis)
{
if (!axis.axisLine.onZero) return 0;
foreach (var component in components)
{
if (component is XAxis)
{
var xAxis = component as XAxis;
if (xAxis.IsValue() && xAxis.gridIndex == axis.gridIndex) return xAxis.context.offset;
}
}
return 0;
}
public static bool IsAnyCategoryOfYAxis(List<MainComponent> components)
{
foreach (var component in components)
{
if (component is YAxis)
{
var yAxis = component as YAxis;
if (yAxis.type == Axis.AxisType.Category)
return true;
}
}
return false;
}
}
}

View File

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

Some files were not shown because too many files have changed in this diff Show More