提交FairyGUI

This commit is contained in:
PC-20230316NUNE\Administrator 2024-10-15 20:37:54 +08:00
parent ef1d3dfb2f
commit 9cd469b811
409 changed files with 66228 additions and 4076 deletions

View File

@ -83,6 +83,7 @@
<Compile Include="Assets\Plugins\DLL\Demigiant\DOTween\Modules\DOTweenModuleEPOOutline.cs" /> <Compile Include="Assets\Plugins\DLL\Demigiant\DOTween\Modules\DOTweenModuleEPOOutline.cs" />
<Compile Include="Assets\Plugins\DLL\Demigiant\DOTween\Modules\DOTweenModuleUnityVersion.cs" /> <Compile Include="Assets\Plugins\DLL\Demigiant\DOTween\Modules\DOTweenModuleUnityVersion.cs" />
<None Include="Assets\Plugins\UniTask\package.json" /> <None Include="Assets\Plugins\UniTask\package.json" />
<None Include="Assets\Plugins\FairyGUI\ReadMe - 4.3.0.txt" />
<None Include="Assets\Plugins\DLL\Demigiant\DOTween\readme.txt" /> <None Include="Assets\Plugins\DLL\Demigiant\DOTween\readme.txt" />
<Reference Include="UnityEngine"> <Reference Include="UnityEngine">
<HintPath>D:\Unity\2022.3.1f1\Editor\Data\Managed\UnityEngine\UnityEngine.dll</HintPath> <HintPath>D:\Unity\2022.3.1f1\Editor\Data\Managed\UnityEngine\UnityEngine.dll</HintPath>
@ -899,6 +900,10 @@
<Project>{168b694c-7d58-d228-f9a3-02235c192fc5}</Project> <Project>{168b694c-7d58-d228-f9a3-02235c192fc5}</Project>
<Name>UniTask.Linq</Name> <Name>UniTask.Linq</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="FairyGUI.Runtime.csproj">
<Project>{65d6cac9-6d7d-4b93-ff92-1a5fc94f680c}</Project>
<Name>FairyGUI.Runtime</Name>
</ProjectReference>
<ProjectReference Include="JNGame.Editor.csproj"> <ProjectReference Include="JNGame.Editor.csproj">
<Project>{17b58f54-5d7b-7430-a784-74a4540f4c68}</Project> <Project>{17b58f54-5d7b-7430-a784-74a4540f4c68}</Project>
<Name>JNGame.Editor</Name> <Name>JNGame.Editor</Name>
@ -943,6 +948,10 @@
<Project>{56fe4698-9e38-f97f-0948-b4a412ec01fc}</Project> <Project>{56fe4698-9e38-f97f-0948-b4a412ec01fc}</Project>
<Name>SHFrame</Name> <Name>SHFrame</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="FairyGUI.Editor.csproj">
<Project>{44b47b38-a33f-7d44-f2e0-a6c5f272d235}</Project>
<Name>FairyGUI.Editor</Name>
</ProjectReference>
<ProjectReference Include="UniTask.DOTween.csproj"> <ProjectReference Include="UniTask.DOTween.csproj">
<Project>{694241c5-b793-03a0-1887-6d1b1abd5716}</Project> <Project>{694241c5-b793-03a0-1887-6d1b1abd5716}</Project>
<Name>UniTask.DOTween</Name> <Name>UniTask.DOTween</Name>

View File

@ -1015,6 +1015,10 @@
<Project>{168b694c-7d58-d228-f9a3-02235c192fc5}</Project> <Project>{168b694c-7d58-d228-f9a3-02235c192fc5}</Project>
<Name>UniTask.Linq</Name> <Name>UniTask.Linq</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="FairyGUI.Runtime.csproj">
<Project>{65d6cac9-6d7d-4b93-ff92-1a5fc94f680c}</Project>
<Name>FairyGUI.Runtime</Name>
</ProjectReference>
<ProjectReference Include="JNGame.Editor.csproj"> <ProjectReference Include="JNGame.Editor.csproj">
<Project>{17b58f54-5d7b-7430-a784-74a4540f4c68}</Project> <Project>{17b58f54-5d7b-7430-a784-74a4540f4c68}</Project>
<Name>JNGame.Editor</Name> <Name>JNGame.Editor</Name>
@ -1059,6 +1063,10 @@
<Project>{56fe4698-9e38-f97f-0948-b4a412ec01fc}</Project> <Project>{56fe4698-9e38-f97f-0948-b4a412ec01fc}</Project>
<Name>SHFrame</Name> <Name>SHFrame</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="FairyGUI.Editor.csproj">
<Project>{44b47b38-a33f-7d44-f2e0-a6c5f272d235}</Project>
<Name>FairyGUI.Editor</Name>
</ProjectReference>
<ProjectReference Include="UniTask.DOTween.csproj"> <ProjectReference Include="UniTask.DOTween.csproj">
<Project>{694241c5-b793-03a0-1887-6d1b1abd5716}</Project> <Project>{694241c5-b793-03a0-1887-6d1b1abd5716}</Project>
<Name>UniTask.DOTween</Name> <Name>UniTask.DOTween</Name>

View File

@ -406,3 +406,55 @@ Transform:
m_Father: {fileID: 0} m_Father: {fileID: 0}
m_RootOrder: 1 m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1994723394
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1994723396}
- component: {fileID: 1994723395}
m_Layer: 0
m_Name: UIContentScaler
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &1994723395
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1994723394}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a723f7fd716aac049aa24e9186f18685, type: 3}
m_Name:
m_EditorClassIdentifier:
scaleMode: 1
screenMatchMode: 0
designResolutionX: 1600
designResolutionY: 720
fallbackScreenDPI: 96
defaultSpriteDPI: 96
constantScaleFactor: 1
ignoreOrientation: 0
--- !u!4 &1994723396
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1994723394}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}

View File

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

View File

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

View File

@ -0,0 +1,126 @@
using UnityEngine;
using UnityEditor;
using FairyGUI;
namespace FairyGUIEditor
{
/// <summary>
///
/// </summary>
[CustomEditor(typeof(DisplayObjectInfo))]
public class DisplayObjectEditor : Editor
{
void OnEnable()
{
}
public override void OnInspectorGUI()
{
DisplayObject obj = (target as DisplayObjectInfo).displayObject;
if (obj == null)
return;
EditorGUILayout.LabelField(obj.GetType().Name + ": " + obj.id, (GUIStyle)"OL Title");
EditorGUILayout.Separator();
EditorGUI.BeginChangeCheck();
string name = EditorGUILayout.TextField("Name", obj.name);
if (EditorGUI.EndChangeCheck())
obj.name = name;
if (obj is Container)
{
EditorGUI.BeginChangeCheck();
bool fairyBatching = EditorGUILayout.Toggle("FairyBatching", ((Container)obj).fairyBatching);
if (EditorGUI.EndChangeCheck())
((Container)obj).fairyBatching = fairyBatching;
}
GObject gObj = obj.gOwner;
if (gObj != null)
{
EditorGUILayout.Separator();
EditorGUILayout.LabelField(gObj.GetType().Name + ": " + gObj.id, (GUIStyle)"OL Title");
EditorGUILayout.Separator();
if (!string.IsNullOrEmpty(gObj.resourceURL))
{
PackageItem pi = UIPackage.GetItemByURL(gObj.resourceURL);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Resource");
EditorGUILayout.LabelField(pi.name + "@" + pi.owner.name);
EditorGUILayout.EndHorizontal();
}
EditorGUI.BeginChangeCheck();
name = EditorGUILayout.TextField("Name", gObj.name);
if (EditorGUI.EndChangeCheck())
gObj.name = name;
if (gObj.parent != null)
{
string[] options = new string[gObj.parent.numChildren];
int[] values = new int[options.Length];
for (int i = 0; i < options.Length; i++)
{
options[i] = i.ToString();
values[i] = i;
}
EditorGUI.BeginChangeCheck();
int childIndex = EditorGUILayout.IntPopup("Child Index", gObj.parent.GetChildIndex(gObj), options, values);
if (EditorGUI.EndChangeCheck())
gObj.parent.SetChildIndex(gObj, childIndex);
}
else
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Child Index");
EditorGUILayout.LabelField("No Parent");
EditorGUILayout.EndHorizontal();
}
EditorGUI.BeginChangeCheck();
Vector3 position = EditorGUILayout.Vector3Field("Position", gObj.position);
if (EditorGUI.EndChangeCheck())
gObj.position = position;
EditorGUI.BeginChangeCheck();
Vector3 rotation = EditorGUILayout.Vector3Field("Rotation", new Vector3(gObj.rotationX, gObj.rotationY, gObj.rotation));
if (EditorGUI.EndChangeCheck())
{
gObj.rotationX = rotation.x;
gObj.rotationY = rotation.y;
gObj.rotation = rotation.z;
}
EditorGUI.BeginChangeCheck();
Vector2 scale = EditorGUILayout.Vector2Field("Scale", gObj.scale);
if (EditorGUI.EndChangeCheck())
gObj.scale = scale;
EditorGUI.BeginChangeCheck();
Vector2 skew = EditorGUILayout.Vector2Field("Skew", gObj.skew);
if (EditorGUI.EndChangeCheck())
gObj.skew = skew;
EditorGUI.BeginChangeCheck();
Vector2 size = EditorGUILayout.Vector2Field("Size", gObj.size);
if (EditorGUI.EndChangeCheck())
gObj.size = size;
EditorGUI.BeginChangeCheck();
Vector2 pivot = EditorGUILayout.Vector2Field("Pivot", gObj.pivot);
if (EditorGUI.EndChangeCheck())
gObj.pivot = pivot;
EditorGUI.BeginChangeCheck();
string text = EditorGUILayout.TextField("Text", gObj.text);
if (EditorGUI.EndChangeCheck())
gObj.text = text;
EditorGUI.BeginChangeCheck();
string icon = EditorGUILayout.TextField("Icon", gObj.icon);
if (EditorGUI.EndChangeCheck())
gObj.icon = icon;
}
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: a2f78faa29e5e1547837f976bf4b39f2
timeCreated: 1541149029
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,135 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using FairyGUI;
namespace FairyGUIEditor
{
/// <summary>
///
/// </summary>
public class EditorToolSet
{
public static GUIContent[] packagesPopupContents;
static bool _loaded;
[InitializeOnLoadMethod]
static void Startup()
{
EditorApplication.update += EditorApplication_Update;
}
[MenuItem("GameObject/FairyGUI/UI Panel", false, 0)]
static void CreatePanel()
{
EditorApplication.update -= EditorApplication_Update;
EditorApplication.update += EditorApplication_Update;
StageCamera.CheckMainCamera();
GameObject panelObject = new GameObject("UIPanel");
if (Selection.activeGameObject != null)
{
panelObject.transform.parent = Selection.activeGameObject.transform;
panelObject.layer = Selection.activeGameObject.layer;
}
else
{
int layer = LayerMask.NameToLayer(StageCamera.LayerName);
panelObject.layer = layer;
}
panelObject.AddComponent<FairyGUI.UIPanel>();
Selection.objects = new Object[] { panelObject };
}
[MenuItem("GameObject/FairyGUI/UI Camera", false, 0)]
static void CreateCamera()
{
StageCamera.CheckMainCamera();
Selection.objects = new Object[] { StageCamera.main.gameObject };
}
[MenuItem("Window/FairyGUI - Refresh Packages And Panels")]
static void RefreshPanels()
{
ReloadPackages();
}
static void EditorApplication_Update()
{
if (Application.isPlaying)
return;
if (_loaded || !EMRenderSupport.hasTarget)
return;
LoadPackages();
}
public static void ReloadPackages()
{
if (!Application.isPlaying)
{
_loaded = false;
LoadPackages();
Debug.Log("FairyGUI - Refresh Packages And Panels complete.");
}
else
EditorUtility.DisplayDialog("FairyGUI", "Cannot run in play mode.", "OK");
}
public static void LoadPackages()
{
if (Application.isPlaying || _loaded)
return;
EditorApplication.update -= EditorApplication_Update;
EditorApplication.update += EditorApplication_Update;
_loaded = true;
UIPackage.RemoveAllPackages();
FontManager.Clear();
NTexture.DisposeEmpty();
UIObjectFactory.Clear();
string[] ids = AssetDatabase.FindAssets("_fui t:textAsset");
int cnt = ids.Length;
for (int i = 0; i < cnt; i++)
{
string assetPath = AssetDatabase.GUIDToAssetPath(ids[i]);
int pos = assetPath.LastIndexOf("_fui");
if (pos == -1)
continue;
assetPath = assetPath.Substring(0, pos);
if (AssetDatabase.AssetPathToGUID(assetPath) != null)
UIPackage.AddPackage(assetPath,
(string name, string extension, System.Type type, out DestroyMethod destroyMethod) =>
{
destroyMethod = DestroyMethod.Unload;
return AssetDatabase.LoadAssetAtPath(name + extension, type);
}
);
}
List<UIPackage> pkgs = UIPackage.GetPackages();
pkgs.Sort(CompareUIPackage);
cnt = pkgs.Count;
packagesPopupContents = new GUIContent[cnt + 1];
for (int i = 0; i < cnt; i++)
packagesPopupContents[i] = new GUIContent(pkgs[i].name);
packagesPopupContents[cnt] = new GUIContent("Please Select");
EMRenderSupport.Reload();
}
static int CompareUIPackage(UIPackage u1, UIPackage u2)
{
return u1.name.CompareTo(u2.name);
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 35dcb233f95ffd54c94f09d731db89ae
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,18 @@
{
"name": "FairyGUI.Editor",
"rootNamespace": "",
"references": [
"GUID:f4270d81837019d47b93f11421168dae"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 19cba46ac204fdd48a96c9d9f1471d9c
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,201 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
#if UNITY_5_3_OR_NEWER
using UnityEditor.SceneManagement;
#endif
#if UNITY_2018_3_OR_NEWER
using UnityEditor.Experimental.SceneManagement;
#endif
using FairyGUI;
namespace FairyGUIEditor
{
/// <summary>
///
/// </summary>
public class PackagesWindow : EditorWindow
{
Vector2 scrollPos1;
Vector2 scrollPos2;
GUIStyle itemStyle;
int selectedPackage;
string selectedPackageName;
string selectedComponentName;
public PackagesWindow()
{
this.maxSize = new Vector2(550, 400);
this.minSize = new Vector2(550, 400);
}
public void SetSelection(string packageName, string componentName)
{
selectedPackageName = packageName;
selectedComponentName = componentName;
}
void OnGUI()
{
if (itemStyle == null)
itemStyle = new GUIStyle(GUI.skin.GetStyle("Tag MenuItem"));
EditorGUILayout.BeginHorizontal();
//package list start------
EditorGUILayout.BeginHorizontal();
GUILayout.Space(5);
EditorGUILayout.BeginVertical();
GUILayout.Space(10);
EditorGUILayout.LabelField("Packages", (GUIStyle)"OL Title", GUILayout.Width(300));
GUILayout.Space(5);
EditorGUILayout.BeginHorizontal();
GUILayout.Space(4);
scrollPos1 = EditorGUILayout.BeginScrollView(scrollPos1, (GUIStyle)"CN Box", GUILayout.Height(300), GUILayout.Width(300));
EditorToolSet.LoadPackages();
List<UIPackage> pkgs = UIPackage.GetPackages();
int cnt = pkgs.Count;
if (cnt == 0)
{
selectedPackage = -1;
selectedPackageName = null;
}
else
{
for (int i = 0; i < cnt; i++)
{
EditorGUILayout.BeginHorizontal();
if (GUILayout.Toggle(selectedPackageName == pkgs[i].name, pkgs[i].name, itemStyle, GUILayout.ExpandWidth(true)))
{
selectedPackage = i;
selectedPackageName = pkgs[i].name;
}
EditorGUILayout.EndHorizontal();
}
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
//package list end------
//component list start------
EditorGUILayout.BeginHorizontal();
GUILayout.Space(5);
EditorGUILayout.BeginVertical();
GUILayout.Space(10);
EditorGUILayout.LabelField("Components", (GUIStyle)"OL Title", GUILayout.Width(220));
GUILayout.Space(5);
EditorGUILayout.BeginHorizontal();
GUILayout.Space(4);
scrollPos2 = EditorGUILayout.BeginScrollView(scrollPos2, (GUIStyle)"CN Box", GUILayout.Height(300), GUILayout.Width(220));
if (selectedPackage >= 0)
{
List<PackageItem> items = pkgs[selectedPackage].GetItems();
int i = 0;
foreach (PackageItem pi in items)
{
if (pi.type == PackageItemType.Component && pi.exported)
{
EditorGUILayout.BeginHorizontal();
if (GUILayout.Toggle(selectedComponentName == pi.name, pi.name, itemStyle, GUILayout.ExpandWidth(true)))
selectedComponentName = pi.name;
i++;
EditorGUILayout.EndHorizontal();
}
}
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
//component list end------
GUILayout.Space(10);
EditorGUILayout.EndHorizontal();
GUILayout.Space(20);
//buttons start---
EditorGUILayout.BeginHorizontal();
GUILayout.Space(180);
if (GUILayout.Button("Refresh", GUILayout.Width(100)))
EditorToolSet.ReloadPackages();
GUILayout.Space(20);
if (GUILayout.Button("OK", GUILayout.Width(100)) && selectedPackage >= 0)
{
UIPackage selectedPkg = pkgs[selectedPackage];
string tmp = selectedPkg.assetPath.ToLower();
string packagePath;
int pos = tmp.LastIndexOf("/resources/");
if (pos != -1)
packagePath = selectedPkg.assetPath.Substring(pos + 11);
else
{
pos = tmp.IndexOf("resources/");
if (pos == 0)
packagePath = selectedPkg.assetPath.Substring(pos + 10);
else
packagePath = selectedPkg.assetPath;
}
if (Selection.activeGameObject != null)
{
#if UNITY_2018_3_OR_NEWER
bool isPrefab = PrefabUtility.GetPrefabAssetType(Selection.activeGameObject) != PrefabAssetType.NotAPrefab;
#else
bool isPrefab = PrefabUtility.GetPrefabType(Selection.activeGameObject) == PrefabType.Prefab;
#endif
Selection.activeGameObject.SendMessage("OnUpdateSource",
new object[] { selectedPkg.name, packagePath, selectedComponentName, !isPrefab },
SendMessageOptions.DontRequireReceiver);
}
#if UNITY_2018_3_OR_NEWER
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
EditorSceneManager.MarkSceneDirty(prefabStage.scene);
else
ApplyChange();
#else
ApplyChange();
#endif
this.Close();
}
EditorGUILayout.EndHorizontal();
}
void ApplyChange()
{
#if UNITY_5_3_OR_NEWER
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
#elif UNITY_5
EditorApplication.MarkSceneDirty();
#else
EditorUtility.SetDirty(Selection.activeGameObject);
#endif
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 83ed477a96af9c94f9f2ccc24b5a24c0
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,29 @@
using UnityEditor;
using FairyGUI;
namespace FairyGUIEditor
{
/// <summary>
///
/// </summary>
[CustomEditor(typeof(StageCamera))]
public class StageCameraEditor : Editor
{
string[] propertyToExclude;
void OnEnable()
{
propertyToExclude = new string[] { "m_Script" };
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawPropertiesExcluding(serializedObject, propertyToExclude);
if (serializedObject.ApplyModifiedProperties())
(target as StageCamera).ApplyModifiedProperties();
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 2b99582678b83dc46986b02984c665a3
timeCreated: 1460480287
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,226 @@
using UnityEngine;
using UnityEditor;
using FairyGUI;
namespace FairyGUIEditor
{
/// <summary>
///
/// </summary>
[CustomEditor(typeof(UIConfig))]
public class UIConfigEditor : Editor
{
string[] propertyToExclude;
bool itemsFoldout;
bool packagesFoldOut;
int errorState;
private const float kButtonWidth = 18f;
void OnEnable()
{
propertyToExclude = new string[] { "m_Script", "Items", "PreloadPackages" };
itemsFoldout = EditorPrefs.GetBool("itemsFoldOut");
packagesFoldOut = EditorPrefs.GetBool("packagesFoldOut");
errorState = 0;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawPropertiesExcluding(serializedObject, propertyToExclude);
UIConfig config = (UIConfig)target;
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
itemsFoldout = EditorGUILayout.Foldout(itemsFoldout, "Config Items");
if (EditorGUI.EndChangeCheck())
EditorPrefs.SetBool("itemsFoldOut", itemsFoldout);
EditorGUILayout.EndHorizontal();
bool modified = false;
if (itemsFoldout)
{
Undo.RecordObject(config, "Items");
int len = config.Items.Count;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Add");
UIConfig.ConfigKey selectedKey = (UIConfig.ConfigKey)EditorGUILayout.EnumPopup((System.Enum)UIConfig.ConfigKey.PleaseSelect);
if (selectedKey != UIConfig.ConfigKey.PleaseSelect)
{
int index = (int)selectedKey;
if (index > len - 1)
{
for (int i = len; i < index; i++)
config.Items.Add(new UIConfig.ConfigValue());
UIConfig.ConfigValue value = new UIConfig.ConfigValue();
value.valid = true;
UIConfig.SetDefaultValue(selectedKey, value);
config.Items.Add(value);
}
else
{
UIConfig.ConfigValue value = config.Items[index];
if (value == null)
{
value = new UIConfig.ConfigValue();
value.valid = true;
UIConfig.SetDefaultValue(selectedKey, value);
config.Items[index] = value;
}
else if (!value.valid)
{
value.valid = true;
UIConfig.SetDefaultValue(selectedKey, value);
}
}
}
EditorGUILayout.EndHorizontal();
for (int i = 0; i < len; i++)
{
UIConfig.ConfigValue value = config.Items[i];
if (value == null || !value.valid)
continue;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(((UIConfig.ConfigKey)i).ToString());
switch ((UIConfig.ConfigKey)i)
{
case UIConfig.ConfigKey.ClickDragSensitivity:
case UIConfig.ConfigKey.DefaultComboBoxVisibleItemCount:
case UIConfig.ConfigKey.DefaultScrollStep:
case UIConfig.ConfigKey.TouchDragSensitivity:
case UIConfig.ConfigKey.TouchScrollSensitivity:
case UIConfig.ConfigKey.InputCaretSize:
value.i = EditorGUILayout.IntField(value.i);
break;
case UIConfig.ConfigKey.ButtonSound:
case UIConfig.ConfigKey.GlobalModalWaiting:
case UIConfig.ConfigKey.HorizontalScrollBar:
case UIConfig.ConfigKey.LoaderErrorSign:
case UIConfig.ConfigKey.PopupMenu:
case UIConfig.ConfigKey.PopupMenu_seperator:
case UIConfig.ConfigKey.TooltipsWin:
case UIConfig.ConfigKey.VerticalScrollBar:
case UIConfig.ConfigKey.WindowModalWaiting:
case UIConfig.ConfigKey.DefaultFont:
value.s = EditorGUILayout.TextField(value.s);
break;
case UIConfig.ConfigKey.DefaultScrollBounceEffect:
case UIConfig.ConfigKey.DefaultScrollTouchEffect:
case UIConfig.ConfigKey.RenderingTextBrighterOnDesktop:
case UIConfig.ConfigKey.AllowSoftnessOnTopOrLeftSide:
case UIConfig.ConfigKey.DepthSupportForPaintingMode:
value.b = EditorGUILayout.Toggle(value.b);
break;
case UIConfig.ConfigKey.ButtonSoundVolumeScale:
value.f = EditorGUILayout.Slider(value.f, 0, 1);
break;
case UIConfig.ConfigKey.ModalLayerColor:
case UIConfig.ConfigKey.InputHighlightColor:
value.c = EditorGUILayout.ColorField(value.c);
break;
case UIConfig.ConfigKey.Branch:
EditorGUI.BeginChangeCheck();
value.s = EditorGUILayout.TextField(value.s);
if (EditorGUI.EndChangeCheck())
modified = true;
break;
}
if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30)))
{
config.Items[i].Reset();
UIConfig.SetDefaultValue((UIConfig.ConfigKey)i, config.Items[i]);
modified = true;
}
EditorGUILayout.EndHorizontal();
}
}
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
packagesFoldOut = EditorGUILayout.Foldout(packagesFoldOut, "Preload Packages");
if (EditorGUI.EndChangeCheck())
EditorPrefs.SetBool("packagesFoldOut", packagesFoldOut);
EditorGUILayout.EndHorizontal();
if (packagesFoldOut)
{
Undo.RecordObject(config, "PreloadPackages");
EditorToolSet.LoadPackages();
if (EditorToolSet.packagesPopupContents != null)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Add");
int selected = EditorGUILayout.Popup(EditorToolSet.packagesPopupContents.Length - 1, EditorToolSet.packagesPopupContents);
EditorGUILayout.EndHorizontal();
if (selected != EditorToolSet.packagesPopupContents.Length - 1)
{
UIPackage pkg = UIPackage.GetPackages()[selected];
string tmp = pkg.assetPath.ToLower();
int pos = tmp.LastIndexOf("resources/");
if (pos != -1)
{
string packagePath = pkg.assetPath.Substring(pos + 10);
if (config.PreloadPackages.IndexOf(packagePath) == -1)
config.PreloadPackages.Add(packagePath);
errorState = 0;
}
else
{
errorState = 10;
}
}
}
if (errorState > 0)
{
errorState--;
EditorGUILayout.HelpBox("Package is not in resources folder.", MessageType.Warning);
}
int cnt = config.PreloadPackages.Count;
int pi = 0;
while (pi < cnt)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("" + pi + ".");
config.PreloadPackages[pi] = EditorGUILayout.TextField(config.PreloadPackages[pi]);
if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30)))
{
config.PreloadPackages.RemoveAt(pi);
cnt--;
}
else
pi++;
EditorGUILayout.EndHorizontal();
}
}
else
errorState = 0;
if (serializedObject.ApplyModifiedProperties() || modified)
(target as UIConfig).ApplyModifiedProperties();
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 74df68b10ee56a54a8105d88312571ce
timeCreated: 1460480288
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,64 @@
using UnityEditor;
using FairyGUI;
namespace FairyGUIEditor
{
/// <summary>
///
/// </summary>
[CustomEditor(typeof(UIContentScaler))]
public class UIContentScalerEditor : Editor
{
SerializedProperty scaleMode;
SerializedProperty screenMatchMode;
SerializedProperty designResolutionX;
SerializedProperty designResolutionY;
SerializedProperty fallbackScreenDPI;
SerializedProperty defaultSpriteDPI;
SerializedProperty constantScaleFactor;
SerializedProperty ignoreOrientation;
string[] propertyToExclude;
void OnEnable()
{
scaleMode = serializedObject.FindProperty("scaleMode");
screenMatchMode = serializedObject.FindProperty("screenMatchMode");
designResolutionX = serializedObject.FindProperty("designResolutionX");
designResolutionY = serializedObject.FindProperty("designResolutionY");
fallbackScreenDPI = serializedObject.FindProperty("fallbackScreenDPI");
defaultSpriteDPI = serializedObject.FindProperty("defaultSpriteDPI");
constantScaleFactor = serializedObject.FindProperty("constantScaleFactor");
ignoreOrientation = serializedObject.FindProperty("ignoreOrientation");
propertyToExclude = new string[] { "m_Script", "scaleMode", "screenMatchMode", "designResolutionX", "designResolutionY",
"fallbackScreenDPI", "defaultSpriteDPI", "constantScaleFactor", "ignoreOrientation"};
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawPropertiesExcluding(serializedObject, propertyToExclude);
EditorGUILayout.PropertyField(scaleMode);
if ((UIContentScaler.ScaleMode)scaleMode.enumValueIndex == UIContentScaler.ScaleMode.ScaleWithScreenSize)
{
EditorGUILayout.PropertyField(designResolutionX);
EditorGUILayout.PropertyField(designResolutionY);
EditorGUILayout.PropertyField(screenMatchMode);
EditorGUILayout.PropertyField(ignoreOrientation);
}
else if ((UIContentScaler.ScaleMode)scaleMode.enumValueIndex == UIContentScaler.ScaleMode.ConstantPhysicalSize)
{
EditorGUILayout.PropertyField(fallbackScreenDPI);
EditorGUILayout.PropertyField(defaultSpriteDPI);
}
else
EditorGUILayout.PropertyField(constantScaleFactor);
if (serializedObject.ApplyModifiedProperties())
(target as UIContentScaler).ApplyModifiedProperties();
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 69174d19fa9521b4283e0b8f0e85acc8
timeCreated: 1460480288
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,96 @@
using UnityEngine;
#if UNITY_5_3_OR_NEWER
using UnityEditor.SceneManagement;
#endif
using UnityEditor;
using FairyGUI;
namespace FairyGUIEditor
{
/// <summary>
///
/// </summary>
[CustomEditor(typeof(UIPainter))]
public class UIPainterEditor : Editor
{
SerializedProperty packageName;
SerializedProperty componentName;
SerializedProperty renderCamera;
SerializedProperty fairyBatching;
SerializedProperty touchDisabled;
SerializedProperty sortingOrder;
string[] propertyToExclude;
void OnEnable()
{
packageName = serializedObject.FindProperty("packageName");
componentName = serializedObject.FindProperty("componentName");
renderCamera = serializedObject.FindProperty("renderCamera");
fairyBatching = serializedObject.FindProperty("fairyBatching");
touchDisabled = serializedObject.FindProperty("touchDisabled");
sortingOrder = serializedObject.FindProperty("sortingOrder");
propertyToExclude = new string[] { "m_Script", "packageName", "componentName", "packagePath",
"renderCamera", "fairyBatching", "touchDisabled","sortingOrder"
};
}
public override void OnInspectorGUI()
{
serializedObject.Update();
UIPainter panel = target as UIPainter;
DrawPropertiesExcluding(serializedObject, propertyToExclude);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Package Name");
if (GUILayout.Button(packageName.stringValue, "ObjectField"))
EditorWindow.GetWindow<PackagesWindow>(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue);
if (GUILayout.Button("Clear", GUILayout.Width(50)))
{
#if UNITY_2018_3_OR_NEWER
bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab;
#else
bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab;
#endif
panel.SendMessage("OnUpdateSource", new object[] { null, null, null, !isPrefab });
#if UNITY_5_3_OR_NEWER
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
#elif UNITY_5
EditorApplication.MarkSceneDirty();
#else
EditorUtility.SetDirty(panel);
#endif
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Component Name");
if (GUILayout.Button(componentName.stringValue, "ObjectField"))
EditorWindow.GetWindow<PackagesWindow>(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue);
EditorGUILayout.EndHorizontal();
int oldSortingOrder = panel.sortingOrder;
EditorGUILayout.PropertyField(sortingOrder);
EditorGUILayout.PropertyField(renderCamera);
EditorGUILayout.PropertyField(fairyBatching);
EditorGUILayout.PropertyField(touchDisabled);
if (serializedObject.ApplyModifiedProperties())
{
#if UNITY_2018_3_OR_NEWER
bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab;
#else
bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab;
#endif
if (!isPrefab)
{
panel.ApplyModifiedProperties(sortingOrder.intValue != oldSortingOrder);
}
}
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 5cb0f73c030157845aaa7b42a2b8d577
timeCreated: 1461566835
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,163 @@
using UnityEngine;
#if UNITY_5_3_OR_NEWER
using UnityEditor.SceneManagement;
#endif
using UnityEditor;
namespace FairyGUIEditor
{
/// <summary>
///
/// </summary>
[CustomEditor(typeof(FairyGUI.UIPanel))]
public class UIPanelEditor : Editor
{
SerializedProperty packageName;
SerializedProperty componentName;
SerializedProperty packagePath;
SerializedProperty renderMode;
SerializedProperty renderCamera;
SerializedProperty sortingOrder;
SerializedProperty position;
SerializedProperty scale;
SerializedProperty rotation;
SerializedProperty fairyBatching;
SerializedProperty fitScreen;
SerializedProperty touchDisabled;
SerializedProperty hitTestMode;
SerializedProperty setNativeChildrenOrder;
string[] propertyToExclude;
void OnEnable()
{
packageName = serializedObject.FindProperty("packageName");
componentName = serializedObject.FindProperty("componentName");
packagePath = serializedObject.FindProperty("packagePath");
renderMode = serializedObject.FindProperty("renderMode");
renderCamera = serializedObject.FindProperty("renderCamera");
sortingOrder = serializedObject.FindProperty("sortingOrder");
position = serializedObject.FindProperty("position");
scale = serializedObject.FindProperty("scale");
rotation = serializedObject.FindProperty("rotation");
fairyBatching = serializedObject.FindProperty("fairyBatching");
fitScreen = serializedObject.FindProperty("fitScreen");
touchDisabled = serializedObject.FindProperty("touchDisabled");
hitTestMode = serializedObject.FindProperty("hitTestMode");
setNativeChildrenOrder = serializedObject.FindProperty("setNativeChildrenOrder");
propertyToExclude = new string[] { "m_Script", "packageName", "componentName", "packagePath", "renderMode",
"renderCamera", "sortingOrder", "position", "scale", "rotation", "fairyBatching", "fitScreen","touchDisabled",
"hitTestMode","cachedUISize","setNativeChildrenOrder"
};
}
public override void OnInspectorGUI()
{
serializedObject.Update();
FairyGUI.UIPanel panel = target as FairyGUI.UIPanel;
DrawPropertiesExcluding(serializedObject, propertyToExclude);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Package Name");
if (GUILayout.Button(packageName.stringValue, "ObjectField"))
EditorWindow.GetWindow<PackagesWindow>(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue);
if (GUILayout.Button("Clear", GUILayout.Width(50)))
{
#if UNITY_2018_3_OR_NEWER
bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab;
#else
bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab;
#endif
panel.SendMessage("OnUpdateSource", new object[] { null, null, null, !isPrefab });
#if UNITY_5_3_OR_NEWER
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
#elif UNITY_5
EditorApplication.MarkSceneDirty();
#else
EditorUtility.SetDirty(panel);
#endif
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Component Name");
if (GUILayout.Button(componentName.stringValue, "ObjectField"))
EditorWindow.GetWindow<PackagesWindow>(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Package Path");
EditorGUILayout.LabelField(packagePath.stringValue, (GUIStyle)"helpbox");
EditorGUILayout.EndHorizontal();
if (Application.isPlaying)
EditorGUILayout.EnumPopup("Render Mode", panel.container.renderMode);
else
EditorGUILayout.PropertyField(renderMode);
if ((RenderMode)renderMode.enumValueIndex != RenderMode.ScreenSpaceOverlay)
EditorGUILayout.PropertyField(renderCamera);
int oldSortingOrder = panel.sortingOrder;
EditorGUILayout.PropertyField(sortingOrder);
EditorGUILayout.PropertyField(fairyBatching);
EditorGUILayout.PropertyField(hitTestMode);
EditorGUILayout.PropertyField(touchDisabled);
EditorGUILayout.PropertyField(setNativeChildrenOrder);
EditorGUILayout.Separator();
EditorGUILayout.LabelField("UI Transform", (GUIStyle)"OL Title");
EditorGUILayout.Separator();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(position);
EditorGUILayout.PropertyField(rotation);
EditorGUILayout.PropertyField(scale);
EditorGUILayout.Space();
FairyGUI.FitScreen oldFitScreen = (FairyGUI.FitScreen)fitScreen.enumValueIndex;
EditorGUILayout.PropertyField(fitScreen);
if (serializedObject.ApplyModifiedProperties())
{
#if UNITY_2018_3_OR_NEWER
bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab;
#else
bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab;
#endif
if (!isPrefab)
{
panel.ApplyModifiedProperties(sortingOrder.intValue != oldSortingOrder, (FairyGUI.FitScreen)fitScreen.enumValueIndex != oldFitScreen);
}
}
}
void OnSceneGUI()
{
FairyGUI.UIPanel panel = (target as FairyGUI.UIPanel);
if (panel.container == null)
return;
Vector3 pos = panel.GetUIWorldPosition();
float sizeFactor = HandleUtility.GetHandleSize(pos);
#if UNITY_2017_1_OR_NEWER
var fmh_147_58_638646183197811786 = Quaternion.identity; Vector3 newPos = Handles.FreeMoveHandle(pos, sizeFactor, Vector3.one, Handles.ArrowHandleCap);
#else
Vector3 newPos = Handles.FreeMoveHandle(pos, Quaternion.identity, sizeFactor, Vector3.one, Handles.ArrowCap);
#endif
if (newPos != pos)
{
Vector2 v1 = HandleUtility.WorldToGUIPoint(pos);
Vector2 v2 = HandleUtility.WorldToGUIPoint(newPos);
Vector3 delta = v2 - v1;
delta.x = (int)delta.x;
delta.y = (int)delta.y;
panel.MoveUI(delta);
}
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 94949994c6eda08448145f618d0db72f
timeCreated: 1535374215
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,150 @@
--------------------
FairyGUI
Copyright © 2014-2022 FairyGUI.com
Version 4.3.0
support@fairygui.com
--------------------
FairyGUI is a flexible UI framework for Unity, working with the professional FREE Game UI Editor: FairyGUI Editor.
Download the editor from here: https://www.fairygui.com/
--------------------
Get Started
--------------------
Run demos in Assets/FairyGUI/Examples/Scenes.
The UI project is in Examples-UIProject.zip, unzip it anywhere. Use FairyGUI Editor to open it.
Using FairyGUI in Unity:
* Place a UIPanel in scene by using editor menu GameObject/FairyGUI/UIPanel.
* Or using UIPackage.CreateObject to create UI component dynamically, and then use GRoot.inst.AddChild to show it on screen.
-----------------
Version History
-----------------
4.3.0
1. Support truncating text with ellipsis.
2. Add UIConfig.defaultScrollSnappingThreshold/defaultScrollPagingThreshold.
3. Add support for changing skeleton animation in controller and transition.
4. Increase compatibility of package path detection.
5. Provide a better way for cloning spine materials.
6. Ensure GList.defaultItem to be in normalized format for performance issue.
7. Fixed a shape hit test bug.
8. Fixed a scrolling bug if custom input is enabled.
4.2.0
1. Improve GoWrapper clipping.
2. Fix a bitmap font bug.
3. Add enter/exit sound for GComponent.
4. Add click sound for GCombobox/GLabel/GProgressbar.
5. Fix emoji align issue.
6. Adapt to new TextMeshPro version.
7. Fix a text shrinking behavior bug.
4.1.0
1. Add Stage.GetTouchTarget.
2. Add CustomEase.
3. Add Atlas reference manage mechanism.
4. Fixed: the line settings of polygon is missing.
5. Fixed: nested transitions may not be played.
6. Fixed: wrong parameter for loading Spine/Dragonbones by bundle.
7. Fixed: exceptions when a UIPanel in prefab is being destroyed in editor, since 2018.3.
8. Upgrade example project to Unity 2018.
4.0.1
- FIXED: Selection bug in InputTextField.
- FIXED: Wrong TextMeshPro text color in linear color space.
- FIXED: Set initial color to white of GLoader3D.
- FIXED: Recover text after cancelling typing effect.
- FIXED: Invalid command key status in windows.
4.0.0
- New: New GLoader3D object for loading Spine and DragonBones.
- New: Support TextMeshPro.
- New: Mouse cursor manager.
- New: Key navigation support.
- New: Async loading mechanism of UIPackage (Convenient for Addressable).
- IMPROVED: User's experience of mouse wheel.
3.5.1
- IMPROVED: Outline support for polygon shape.
- FIXED: Branch mechanism not works for GComponent.
- FIXED: Rotated sprite in atlas display incorrectly.
3.5.0
- NEW: Editor 5.0 functions.
- FIXED: Nested stencil masks work incorrectly.
- FIXED: TouchScreenKeyboard bug.
- FIXED: Some issues in RTLSupport.
3.4.1
- FIXED: Text order issue in fairybatching.
- FIXED: A virtual list bug.
- FIXED: A bug in color control of circle shape.
- FIXED: Fixed a bug in fill mesh.
3.4.0
- NEW: Add multi-display support.
- NEW: Add API DynamicFont(name, font).
- IMPROVED: Compatibility with 2018.3.
- FIXED: Incorrect letter spacing on mobile platform.
- FIXED: Same transition hook may be called twice.
- FIXED: Exception raised when texture was disposed before object was disposed.
3.3.0
- NEW: Add textfield maxwidth feature.
- NEW: Add API to query package dependencies.
- IMPROVED: Graphics module refactor. Now it is more convenient to create various shapes(pie, lines, polygon etc) and do mesh deform. Memory usage on building mesh is also dropped. Also supports automatically setup uv for arbitrary quad to avoid seam between 2 triangles. All shaders are updated, don't forget to replace shaders in your project.
- IMPROVED: Text-Brighter mechanism is removed, so FairyGUI-Text-Brighter.shader is removed.
- IMPROVED: Add support for shrinking multi-line text.
- IMPROVED: Improve Lua support.
3.2.0
- NEW: Add DisplayObjectInfo component. Define script symbol FAIRYGUI_TEST to enable it.
- FIXED: A virtual list scrolling bug.
- FIXED: A BlendMode bug.
3.1.0
- NEW: Draw extra 8 directions instead of 4 directions to archive text outline effect. Toggle option is UIConfig.enhancedTextOutlineEffect.
- IMPROVED: Eexecution efficiency optimizations.
- IMPROVED: GoWrapper now supports multiple materials.
- FIXED: Correct cleanup action for RemovePackage.
3.0.0
From this version, we change package data format to binary. Editor version 3.9.0 with 'binary format' option checked in publish dialog is required to generating this kind of format. Old XML format is not supported anymore.
- NEW: Add UIPackage.UnloadAssets and UIPackage.ReloadAssets to allow unload package resources without removing the package.
- NEW: Add TransitionActionType.Text and TransitionActionType.Icon.
2.4.0
- NEW: GTween is introduced, DOTween is no longer used inside FairyGUI.
- NEW: Transitions now support playing partially and pausing.
- IMPROVED: Change the way of registering bitmap font.
- FIXED: A GButton pivot issue.
- FIXED: Correct text align behavior.
2.3.0
- NEW: Allow loader to load component.
- NEW: Add text template feature.
- FIXED: Exclude invisible object in FairyBatching.
2.2.0
- NEW: Modify shaders to fit linear color space.
- IMPROVED: Improve relation system to handle conditions that anchor is set.
- IMPROVED: Eliminate GC in transition.
- FIXED: Fixed a bug of unloading bundle in UIPackage.
- FIXED: Fixed issue that some blend mode(multiply, screen) works improperly.
2.1.0
- NEW: Add GGraph.DrawRoundRect.
- NEW: Add FillType.ScaleNoBorder.
- FIXED: Repair potential problems of virtual list.
- FIXED: Fixed a bug in handling shared materials.
2.0.0
- NEW: RTL Text rendering support. Define scripting symbols RTL_TEXT_SUPPORT to enabled it.
- NEW: Support for setting GObject.data in editor.
- NEW: Support for setting selectedIcon of list item in editor.
- IMPROVED: Add UIConfig.depthSupportForPaitingMode.
- IMPROVED: Set sorting order of popup automatically.
- FIXED: Fixed a text layout bug when line spacing is negative.
- FIXED: Reset ScrollPane.draggingPane when an active scrollPane is being disposed.
- FIXED: Fixed a bug of skew rendering.

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2b25fe107b6204fd680450b22ba79672
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

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

View File

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

View File

@ -0,0 +1,109 @@
#if FAIRYGUI_DRAGONBONES
using UnityEngine;
using DragonBones;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public partial class GLoader3D : GObject
{
UnityArmatureComponent _armatureComponent;
/// <summary>
///
/// </summary>
/// <value></value>
public UnityArmatureComponent armatureComponent
{
get { return _armatureComponent; }
}
/// <summary>
///
/// </summary>
/// <param name="asset"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="anchor"></param>
public void SetDragonBones(DragonBonesData asset, int width, int height, Vector2 anchor)
{
if (_armatureComponent != null)
FreeDragonBones();
_armatureComponent = UnityFactory.factory.BuildArmatureComponent(asset.armatureNames[0], asset.name, null, asset.name);
_armatureComponent.gameObject.transform.localScale = new Vector3(100, 100, 1);
_armatureComponent.gameObject.transform.localPosition = new Vector3(anchor.x, -anchor.y, 0);
SetWrapTarget(_armatureComponent.gameObject, true, width, height);
var ct = _armatureComponent.color;
ct.redMultiplier = _color.r;
ct.greenMultiplier = _color.g;
ct.blueMultiplier = _color.b;
_armatureComponent.color = ct;
OnChangeDragonBones(null);
}
protected void LoadDragonBones()
{
DragonBonesData asset = (DragonBonesData)_contentItem.skeletonAsset;
if (asset == null)
return;
SetDragonBones(asset, _contentItem.width, _contentItem.height, _contentItem.skeletonAnchor);
}
protected void OnChangeDragonBones(string propertyName)
{
if (_armatureComponent == null)
return;
if (propertyName == "color")
{
var ct = _armatureComponent.color;
ct.redMultiplier = _color.r;
ct.greenMultiplier = _color.g;
ct.blueMultiplier = _color.b;
_armatureComponent.color = ct;
return;
}
if (!string.IsNullOrEmpty(_animationName))
{
if (_playing)
_armatureComponent.animation.Play(_animationName, _loop ? 0 : 1);
else
_armatureComponent.animation.GotoAndStopByFrame(_animationName, (uint)_frame);
}
else
_armatureComponent.animation.Reset();
}
protected void FreeDragonBones()
{
if (_armatureComponent != null)
{
_armatureComponent.Dispose();
if (Application.isPlaying)
GameObject.Destroy(_armatureComponent.gameObject);
else
GameObject.DestroyImmediate(_armatureComponent.gameObject);
}
}
protected void OnUpdateDragonBones(UpdateContext context)
{
if (_armatureComponent != null)
{
var ct = _armatureComponent.color;
ct.alphaMultiplier = context.alpha * _content.alpha;
_armatureComponent.color = ct;
}
}
}
}
#endif

View File

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

View File

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

View File

@ -0,0 +1,160 @@
#if FAIRYGUI_SPINE
using System.Collections.Generic;
using UnityEngine;
using Spine.Unity;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public partial class GLoader3D : GObject
{
SkeletonAnimation _spineAnimation;
/// <summary>
///
/// </summary>
/// <value></value>
public SkeletonAnimation spineAnimation
{
get { return _spineAnimation; }
}
/// <summary>
///
/// </summary>
/// <param name="asset"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="anchor"></param>
public void SetSpine(SkeletonDataAsset asset, int width, int height, Vector2 anchor)
{
SetSpine(asset, width, height, anchor, true);
}
/// <summary>
///
/// </summary>
/// <param name="asset"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="anchor"></param>
/// <param name="cloneMaterial"></param>
public void SetSpine(SkeletonDataAsset asset, int width, int height, Vector2 anchor, bool cloneMaterial)
{
if (_spineAnimation != null)
FreeSpine();
_content.customCloneMaterials = MaterialOverride;
_content.customRecoverMaterials = CleanMaterialOverride;
_spineAnimation = SkeletonRenderer.NewSpineGameObject<SkeletonAnimation>(asset);
_spineAnimation.gameObject.name = asset.name;
Spine.SkeletonData dat = asset.GetSkeletonData(false);
_spineAnimation.gameObject.transform.localScale = new Vector3(1 / asset.scale, 1 / asset.scale, 1);
_spineAnimation.gameObject.transform.localPosition = new Vector3(anchor.x, -anchor.y, 0);
SetWrapTarget(_spineAnimation.gameObject, cloneMaterial, width, height);
_spineAnimation.skeleton.R = _color.r;
_spineAnimation.skeleton.G = _color.g;
_spineAnimation.skeleton.B = _color.b;
OnChangeSpine(null);
}
protected void LoadSpine()
{
SkeletonDataAsset asset = (SkeletonDataAsset)_contentItem.skeletonAsset;
if (asset == null)
return;
SetSpine(asset, _contentItem.width, _contentItem.height, _contentItem.skeletonAnchor);
}
protected void OnChangeSpine(string propertyName)
{
if (_spineAnimation == null)
return;
if (propertyName == "color")
{
_spineAnimation.skeleton.R = _color.r;
_spineAnimation.skeleton.G = _color.g;
_spineAnimation.skeleton.B = _color.b;
return;
}
var skeletonData = _spineAnimation.skeleton.Data;
var state = _spineAnimation.AnimationState;
Spine.Animation animationToUse = !string.IsNullOrEmpty(_animationName) ? skeletonData.FindAnimation(_animationName) : null;
if (animationToUse != null)
{
var trackEntry = state.GetCurrent(0);
if (trackEntry == null || trackEntry.Animation.Name != _animationName || trackEntry.IsComplete && !trackEntry.Loop)
trackEntry = state.SetAnimation(0, animationToUse, _loop);
else
trackEntry.Loop = _loop;
if (_playing)
trackEntry.TimeScale = 1;
else
{
trackEntry.TimeScale = 0;
trackEntry.TrackTime = Mathf.Lerp(0, trackEntry.AnimationEnd - trackEntry.AnimationStart, _frame / 100f);
}
}
else
state.ClearTrack(0);
var skin = !string.IsNullOrEmpty(skinName) ? skeletonData.FindSkin(skinName) : skeletonData.DefaultSkin;
if (skin == null && skeletonData.Skins.Count > 0)
skin = skeletonData.Skins.Items[0];
if (_spineAnimation.skeleton.Skin != skin)
{
_spineAnimation.skeleton.SetSkin(skin);
_spineAnimation.skeleton.SetSlotsToSetupPose();
}
}
protected void FreeSpine()
{
if (_spineAnimation != null)
{
if (Application.isPlaying)
GameObject.Destroy(_spineAnimation.gameObject);
else
GameObject.DestroyImmediate(_spineAnimation.gameObject);
_content.customCloneMaterials = null;
_content.customRecoverMaterials = null;
}
}
protected void OnUpdateSpine(UpdateContext context)
{
if (_spineAnimation != null)
_spineAnimation.skeleton.A = context.alpha * _content.alpha;
}
private void MaterialOverride(Dictionary<Material, Material> materials)
{
if (_spineAnimation != null)
{
foreach (var kv in materials)
{
_spineAnimation.CustomMaterialOverride[kv.Key] = kv.Value;
}
}
}
private void CleanMaterialOverride()
{
if (_spineAnimation != null)
_spineAnimation.CustomMaterialOverride.Clear();
}
}
}
#endif

View File

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

View File

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

View File

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

View File

@ -0,0 +1,338 @@
Shader "FairyGUI/TextMeshPro/Distance Field" {
Properties {
_FaceTex ("Face Texture", 2D) = "white" {}
_FaceUVSpeedX ("Face UV Speed X", Range(-5, 5)) = 0.0
_FaceUVSpeedY ("Face UV Speed Y", Range(-5, 5)) = 0.0
_FaceColor ("Face Color", Color) = (1,1,1,1)
_FaceDilate ("Face Dilate", Range(-1,1)) = 0
_OutlineColor ("Outline Color", Color) = (0,0,0,1)
_OutlineTex ("Outline Texture", 2D) = "white" {}
_OutlineUVSpeedX ("Outline UV Speed X", Range(-5, 5)) = 0.0
_OutlineUVSpeedY ("Outline UV Speed Y", Range(-5, 5)) = 0.0
_OutlineWidth ("Outline Thickness", Range(0, 1)) = 0
_OutlineSoftness ("Outline Softness", Range(0,1)) = 0
_Bevel ("Bevel", Range(0,1)) = 0.5
_BevelOffset ("Bevel Offset", Range(-0.5,0.5)) = 0
_BevelWidth ("Bevel Width", Range(-.5,0.5)) = 0
_BevelClamp ("Bevel Clamp", Range(0,1)) = 0
_BevelRoundness ("Bevel Roundness", Range(0,1)) = 0
_LightAngle ("Light Angle", Range(0.0, 6.2831853)) = 3.1416
_SpecularColor ("Specular", Color) = (1,1,1,1)
_SpecularPower ("Specular", Range(0,4)) = 2.0
_Reflectivity ("Reflectivity", Range(5.0,15.0)) = 10
_Diffuse ("Diffuse", Range(0,1)) = 0.5
_Ambient ("Ambient", Range(1,0)) = 0.5
_BumpMap ("Normal map", 2D) = "bump" {}
_BumpOutline ("Bump Outline", Range(0,1)) = 0
_BumpFace ("Bump Face", Range(0,1)) = 0
_ReflectFaceColor ("Reflection Color", Color) = (0,0,0,1)
_ReflectOutlineColor("Reflection Color", Color) = (0,0,0,1)
_Cube ("Reflection Cubemap", Cube) = "black" { /* TexGen CubeReflect */ }
_EnvMatrixRotation ("Texture Rotation", vector) = (0, 0, 0, 0)
_UnderlayColor ("Border Color", Color) = (0,0,0, 0.5)
_UnderlayOffsetX ("Border OffsetX", Range(-1,1)) = 0
_UnderlayOffsetY ("Border OffsetY", Range(-1,1)) = 0
_UnderlayDilate ("Border Dilate", Range(-1,1)) = 0
_UnderlaySoftness ("Border Softness", Range(0,1)) = 0
_GlowColor ("Color", Color) = (0, 1, 0, 0.5)
_GlowOffset ("Offset", Range(-1,1)) = 0
_GlowInner ("Inner", Range(0,1)) = 0.05
_GlowOuter ("Outer", Range(0,1)) = 0.05
_GlowPower ("Falloff", Range(1, 0)) = 0.75
_WeightNormal ("Weight Normal", float) = 0
_WeightBold ("Weight Bold", float) = 0.5
_ShaderFlags ("Flags", float) = 0
_ScaleRatioA ("Scale RatioA", float) = 1
_ScaleRatioB ("Scale RatioB", float) = 1
_ScaleRatioC ("Scale RatioC", float) = 1
_MainTex ("Font Atlas", 2D) = "white" {}
_TextureWidth ("Texture Width", float) = 512
_TextureHeight ("Texture Height", float) = 512
_GradientScale ("Gradient Scale", float) = 5.0
_ScaleX ("Scale X", float) = 1.0
_ScaleY ("Scale Y", float) = 1.0
_PerspectiveFilter ("Perspective Correction", Range(0, 1)) = 0.875
_Sharpness ("Sharpness", Range(-1,1)) = 0
_VertexOffsetX ("Vertex OffsetX", float) = 0
_VertexOffsetY ("Vertex OffsetY", float) = 0
_MaskCoord ("Mask Coordinates", vector) = (0, 0, 32767, 32767)
_ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767)
_MaskSoftnessX ("Mask SoftnessX", float) = 0
_MaskSoftnessY ("Mask SoftnessY", float) = 0
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_ColorMask ("Color Mask", Float) = 15
}
SubShader {
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
}
Stencil
{
Ref [_Stencil]
Comp [_StencilComp]
Pass [_StencilOp]
ReadMask [_StencilReadMask]
WriteMask [_StencilWriteMask]
}
Cull [_CullMode]
ZWrite Off
Lighting Off
Fog { Mode Off }
ZTest [unity_GUIZTestMode]
Blend One OneMinusSrcAlpha
ColorMask [_ColorMask]
Pass {
CGPROGRAM
#pragma target 3.0
#pragma vertex VertShader
#pragma fragment PixShader
#pragma shader_feature __ BEVEL_ON
#pragma shader_feature __ UNDERLAY_ON UNDERLAY_INNER
#pragma shader_feature __ GLOW_ON
//#pragma multi_compile __ UNITY_UI_CLIP_RECT
//#pragma multi_compile __ UNITY_UI_ALPHACLIP
#pragma multi_compile NOT_CLIPPED CLIPPED
#include "UnityCG.cginc"
#include "UnityUI.cginc"
//#include "Assets/TextMesh Pro/Resources/Shaders/TMPro_Properties.cginc"
//#include "Assets/TextMesh Pro/Resources/Shaders/TMPro.cginc"
#include "Assets/TextMesh Pro/Shaders/TMPro_Properties.cginc"
#include "Assets/TextMesh Pro/Shaders/TMPro.cginc"
struct vertex_t {
UNITY_VERTEX_INPUT_INSTANCE_ID
float4 position : POSITION;
float3 normal : NORMAL;
fixed4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct pixel_t {
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
float4 position : SV_POSITION;
fixed4 color : COLOR;
float2 atlas : TEXCOORD0; // Atlas
float4 param : TEXCOORD1; // alphaClip, scale, bias, weight
float2 mask : TEXCOORD2; // Position in object space(xy), pixel Size(zw)
float3 viewDir : TEXCOORD3;
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4 texcoord2 : TEXCOORD4; // u,v, scale, bias
fixed4 underlayColor : COLOR1;
#endif
float4 textures : TEXCOORD5;
};
// Used by Unity internally to handle Texture Tiling and Offset.
float4 _FaceTex_ST;
float4 _OutlineTex_ST;
CBUFFER_START(UnityPerMaterial)
#ifdef CLIPPED
float4 _ClipBox = float4(-2, -2, 0, 0);
#endif
CBUFFER_END
pixel_t VertShader(vertex_t input)
{
pixel_t output;
UNITY_INITIALIZE_OUTPUT(pixel_t, output);
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input,output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
float bold = step(input.texcoord1.y, 0);
float4 vert = input.position;
vert.x += _VertexOffsetX;
vert.y += _VertexOffsetY;
float4 vPosition = UnityObjectToClipPos(vert);
float2 pixelSize = vPosition.w;
pixelSize /= float2(_ScaleX, _ScaleY) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy));
float scale = rsqrt(dot(pixelSize, pixelSize));
scale *= abs(input.texcoord1.y) * _GradientScale * (_Sharpness + 1);
if (UNITY_MATRIX_P[3][3] == 0) scale = lerp(abs(scale) * (1 - _PerspectiveFilter), scale, abs(dot(UnityObjectToWorldNormal(input.normal.xyz), normalize(WorldSpaceViewDir(vert)))));
float weight = lerp(_WeightNormal, _WeightBold, bold) / 4.0;
weight = (weight + _FaceDilate) * _ScaleRatioA * 0.5;
float bias =(.5 - weight) + (.5 / scale);
float alphaClip = (1.0 - _OutlineWidth * _ScaleRatioA - _OutlineSoftness * _ScaleRatioA);
#if GLOW_ON
alphaClip = min(alphaClip, 1.0 - _GlowOffset * _ScaleRatioB - _GlowOuter * _ScaleRatioB);
#endif
alphaClip = alphaClip / 2.0 - ( .5 / scale) - weight;
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4 underlayColor = _UnderlayColor;
underlayColor.rgb *= underlayColor.a;
float bScale = scale;
bScale /= 1 + ((_UnderlaySoftness*_ScaleRatioC) * bScale);
float bBias = (0.5 - weight) * bScale - 0.5 - ((_UnderlayDilate * _ScaleRatioC) * 0.5 * bScale);
float x = -(_UnderlayOffsetX * _ScaleRatioC) * _GradientScale / _TextureWidth;
float y = -(_UnderlayOffsetY * _ScaleRatioC) * _GradientScale / _TextureHeight;
float2 bOffset = float2(x, y);
#endif
// Generate UV for the Masking Texture
// float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
// float2 maskUV = (vert.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy);
// Support for texture tiling and offset
float2 textureUV = UnpackUV(input.texcoord1.x);
float2 faceUV = TRANSFORM_TEX(textureUV, _FaceTex);
float2 outlineUV = TRANSFORM_TEX(textureUV, _OutlineTex);
output.position = vPosition;
#if !defined(UNITY_COLORSPACE_GAMMA) && (UNITY_VERSION >= 550)
output.color.rgb = GammaToLinearSpace(input.color.rgb);
output.color.a = input.color.a;
#else
output.color = input.color;
#endif
output.atlas = input.texcoord0;
output.param = float4(alphaClip, scale, bias, weight);
//output.mask = half4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * half2(_MaskSoftnessX, _MaskSoftnessY) + pixelSize.xy));
output.viewDir = mul((float3x3)_EnvMatrix, _WorldSpaceCameraPos.xyz - mul(unity_ObjectToWorld, vert).xyz);
#if (UNDERLAY_ON || UNDERLAY_INNER)
output.texcoord2 = float4(input.texcoord0 + bOffset, bScale, bBias);
output.underlayColor = underlayColor;
#endif
output.textures = float4(faceUV, outlineUV);
#ifdef CLIPPED
output.mask = mul(unity_ObjectToWorld, input.position).xy * _ClipBox.zw + _ClipBox.xy;
#endif
return output;
}
fixed4 PixShader(pixel_t input) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(input);
float c = tex2D(_MainTex, input.atlas).a;
#ifndef UNDERLAY_ON
clip(c - input.param.x);
#endif
float scale = input.param.y;
float bias = input.param.z;
float weight = input.param.w;
float sd = (bias - c) * scale;
float outline = (_OutlineWidth * _ScaleRatioA) * scale;
float softness = (_OutlineSoftness * _ScaleRatioA) * scale;
half4 faceColor = _FaceColor;
half4 outlineColor = _OutlineColor;
faceColor.rgb *= input.color.rgb;
faceColor *= tex2D(_FaceTex, input.textures.xy + float2(_FaceUVSpeedX, _FaceUVSpeedY) * _Time.y);
outlineColor *= tex2D(_OutlineTex, input.textures.zw + float2(_OutlineUVSpeedX, _OutlineUVSpeedY) * _Time.y);
faceColor = GetColor(sd, faceColor, outlineColor, outline, softness);
#if BEVEL_ON
float3 dxy = float3(0.5 / _TextureWidth, 0.5 / _TextureHeight, 0);
float3 n = GetSurfaceNormal(input.atlas, weight, dxy);
float3 bump = UnpackNormal(tex2D(_BumpMap, input.textures.xy + float2(_FaceUVSpeedX, _FaceUVSpeedY) * _Time.y)).xyz;
bump *= lerp(_BumpFace, _BumpOutline, saturate(sd + outline * 0.5));
n = normalize(n- bump);
float3 light = normalize(float3(sin(_LightAngle), cos(_LightAngle), -1.0));
float3 col = GetSpecular(n, light);
faceColor.rgb += col*faceColor.a;
faceColor.rgb *= 1-(dot(n, light)*_Diffuse);
faceColor.rgb *= lerp(_Ambient, 1, n.z*n.z);
fixed4 reflcol = texCUBE(_Cube, reflect(input.viewDir, -n));
faceColor.rgb += reflcol.rgb * lerp(_ReflectFaceColor.rgb, _ReflectOutlineColor.rgb, saturate(sd + outline * 0.5)) * faceColor.a;
#endif
#if UNDERLAY_ON
float d = tex2D(_MainTex, input.texcoord2.xy).a * input.texcoord2.z;
faceColor += input.underlayColor * saturate(d - input.texcoord2.w) * (1 - faceColor.a);
#endif
#if UNDERLAY_INNER
float d = tex2D(_MainTex, input.texcoord2.xy).a * input.texcoord2.z;
faceColor += input.underlayColor * (1 - saturate(d - input.texcoord2.w)) * saturate(1 - sd) * (1 - faceColor.a);
#endif
#if GLOW_ON
float4 glowColor = GetGlowColor(sd, scale);
faceColor.rgb += glowColor.rgb * glowColor.a;
#endif
// Alternative implementation to UnityGet2DClipping with support for softness.
// #if UNITY_UI_CLIP_RECT
// half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(input.mask.xy)) * input.mask.zw);
// faceColor *= m.x * m.y;
// #endif
// #if UNITY_UI_ALPHACLIP
// clip(faceColor.a - 0.001);
// #endif
#ifdef CLIPPED
float2 factor = abs(input.mask);
clip(1-max(factor.x, factor.y));
#endif
return faceColor * input.color.a;
}
ENDCG
}
}
Fallback "TextMeshPro/Mobile/Distance Field"
CustomEditor "TMPro.EditorUtilities.TMP_SDFShaderGUI"
}

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: de10f84640569464799f0e0bfa1ab7b0
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,542 @@
#if FAIRYGUI_TMPRO
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.TextCore;
using TMPro;
namespace FairyGUI
{
/// <summary>
/// TextMeshPro text adapter for FairyGUI. Most of codes were taken from TextMeshPro!
/// Note that not all of TextMeshPro features are supported.
/// </summary>
public class TMPFont : BaseFont
{
protected TMP_FontAsset _fontAsset;
FontStyles _style;
float _scale;
float _padding;
float _stylePadding;
float _ascent;
float _lineHeight;
float _boldMultiplier;
FontWeight _defaultFontWeight;
FontWeight _fontWeight;
TextFormat _format;
TMP_Character _char;
TMP_Character _lineChar;
Material _material;
MaterialManager _manager;
public TMPFont()
{
this.canTint = true;
this.shader = "FairyGUI/TextMeshPro/Distance Field";
this.keepCrisp = true;
_defaultFontWeight = FontWeight.Medium;
}
override public void Dispose()
{
Release();
}
public TMP_FontAsset fontAsset
{
get { return _fontAsset; }
set
{
_fontAsset = value;
Init();
}
}
public FontWeight fontWeight
{
get { return _defaultFontWeight; }
set { _defaultFontWeight = value; }
}
void Release()
{
if (_manager != null)
{
_manager.onCreateNewMaterial -= OnCreateNewMaterial;
_manager = null;
}
if (mainTexture != null)
{
mainTexture.Dispose();
mainTexture = null;
}
if (_material != null)
{
Material.DestroyImmediate(_material);
_material = null;
}
}
void Init()
{
Release();
mainTexture = new NTexture(_fontAsset.atlasTexture);
mainTexture.destroyMethod = DestroyMethod.None;
_manager = mainTexture.GetMaterialManager(this.shader);
_manager.onCreateNewMaterial += OnCreateNewMaterial;
_material = new Material(_fontAsset.material); //copy
_material.SetFloat(ShaderUtilities.ID_TextureWidth, mainTexture.width);
_material.SetFloat(ShaderUtilities.ID_TextureHeight, mainTexture.height);
_material.SetFloat(ShaderUtilities.ID_GradientScale, fontAsset.atlasPadding + 1);
_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
// _ascent = _fontAsset.faceInfo.ascentLine;
// _lineHeight = _fontAsset.faceInfo.lineHeight;
_ascent = _fontAsset.faceInfo.pointSize;
_lineHeight = _fontAsset.faceInfo.pointSize * 1.25f;
_lineChar = GetCharacterFromFontAsset('_', FontStyles.Normal);
}
void OnCreateNewMaterial(Material mat)
{
mat.SetFloat(ShaderUtilities.ID_TextureWidth, mainTexture.width);
mat.SetFloat(ShaderUtilities.ID_TextureHeight, mainTexture.height);
mat.SetFloat(ShaderUtilities.ID_GradientScale, fontAsset.atlasPadding + 1);
mat.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
mat.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
}
override public void UpdateGraphics(NGraphics graphics)
{
MaterialPropertyBlock block = graphics.materialPropertyBlock;
if (_format.outline > 0)
{
graphics.ToggleKeyword("OUTLINE_ON", true);
block.SetFloat(ShaderUtilities.ID_OutlineWidth, _format.outline);
block.SetColor(ShaderUtilities.ID_OutlineColor, _format.outlineColor);
}
else
{
graphics.ToggleKeyword("OUTLINE_ON", false);
block.SetFloat(ShaderUtilities.ID_OutlineWidth, 0);
}
if (_format.shadowOffset.x != 0 || _format.shadowOffset.y != 0)
{
graphics.ToggleKeyword("UNDERLAY_ON", true);
block.SetColor(ShaderUtilities.ID_UnderlayColor, _format.shadowColor);
block.SetFloat(ShaderUtilities.ID_UnderlayOffsetX, _format.shadowOffset.x);
block.SetFloat(ShaderUtilities.ID_UnderlayOffsetY, -_format.shadowOffset.y);
block.SetFloat(ShaderUtilities.ID_UnderlaySoftness, _format.underlaySoftness);
}
else
{
graphics.ToggleKeyword("UNDERLAY_ON", false);
block.SetFloat(ShaderUtilities.ID_UnderlayOffsetX, 0);
block.SetFloat(ShaderUtilities.ID_UnderlayOffsetY, 0);
block.SetFloat(ShaderUtilities.ID_UnderlaySoftness, 0);
}
block.SetFloat(ShaderUtilities.ID_FaceDilate, _format.faceDilate);
block.SetFloat(ShaderUtilities.ID_OutlineSoftness, _format.outlineSoftness);
if (_material.HasProperty(ShaderUtilities.ID_ScaleRatio_A))
{
//ShaderUtilities.GetPadding does not support handle materialproperyblock, we have to use a temp material
_material.SetFloat(ShaderUtilities.ID_OutlineWidth, block.GetFloat(ShaderUtilities.ID_OutlineWidth));
_material.SetFloat(ShaderUtilities.ID_UnderlayOffsetX, block.GetFloat(ShaderUtilities.ID_UnderlayOffsetX));
_material.SetFloat(ShaderUtilities.ID_UnderlayOffsetY, block.GetFloat(ShaderUtilities.ID_UnderlayOffsetY));
_material.SetFloat(ShaderUtilities.ID_UnderlaySoftness, block.GetFloat(ShaderUtilities.ID_UnderlaySoftness));
_material.SetFloat(ShaderUtilities.ID_FaceDilate, block.GetFloat(ShaderUtilities.ID_FaceDilate));
_material.SetFloat(ShaderUtilities.ID_OutlineSoftness, block.GetFloat(ShaderUtilities.ID_OutlineSoftness));
_padding = ShaderUtilities.GetPadding(_material, false, false);
//and then set back the properteis
block.SetFloat(ShaderUtilities.ID_ScaleRatio_A, _material.GetFloat(ShaderUtilities.ID_ScaleRatio_A));
block.SetFloat(ShaderUtilities.ID_ScaleRatio_B, _material.GetFloat(ShaderUtilities.ID_ScaleRatio_B));
block.SetFloat(ShaderUtilities.ID_ScaleRatio_C, _material.GetFloat(ShaderUtilities.ID_ScaleRatio_C));
}
// Set Padding based on selected font style
#region Handle Style Padding
if (((_style & FontStyles.Bold) == FontStyles.Bold)) // Checks for any combination of Bold Style.
{
if (_material.HasProperty(ShaderUtilities.ID_GradientScale))
{
float gradientScale = _material.GetFloat(ShaderUtilities.ID_GradientScale);
_stylePadding = _fontAsset.boldStyle / 4.0f * gradientScale * _material.GetFloat(ShaderUtilities.ID_ScaleRatio_A);
// Clamp overall padding to Gradient Scale size.
if (_stylePadding + _padding > gradientScale)
_padding = gradientScale - _stylePadding;
}
else
_stylePadding = 0;
}
else
{
if (_material.HasProperty(ShaderUtilities.ID_GradientScale))
{
float gradientScale = _material.GetFloat(ShaderUtilities.ID_GradientScale);
_stylePadding = _fontAsset.normalStyle / 4.0f * gradientScale * _material.GetFloat(ShaderUtilities.ID_ScaleRatio_A);
// Clamp overall padding to Gradient Scale size.
if (_stylePadding + _padding > gradientScale)
_padding = gradientScale - _stylePadding;
}
else
_stylePadding = 0;
}
#endregion Handle Style Padding
}
override public void SetFormat(TextFormat format, float fontSizeScale)
{
_format = format;
float size = format.size * fontSizeScale;
if (_format.specialStyle == TextFormat.SpecialStyle.Subscript || _format.specialStyle == TextFormat.SpecialStyle.Superscript)
size *= SupScale;
_scale = size / _fontAsset.faceInfo.pointSize * _fontAsset.faceInfo.scale;
_style = FontStyles.Normal;
if (format.bold)
{
_style |= FontStyles.Bold;
_fontWeight = FontWeight.Bold;
_boldMultiplier = 1 + _fontAsset.boldSpacing * 0.01f;
}
else
{
_fontWeight = _defaultFontWeight;
_boldMultiplier = 1.0f;
}
if (format.italic)
_style |= FontStyles.Italic;
format.FillVertexColors(vertexColors);
}
override public bool GetGlyph(char ch, out float width, out float height, out float baseline)
{
_char = GetCharacterFromFontAsset(ch, _style);
if (_char != null)
{
width = _char.glyph.metrics.horizontalAdvance * _boldMultiplier * _scale;
height = _lineHeight * _scale;
baseline = _ascent * _scale;
if (_format.specialStyle == TextFormat.SpecialStyle.Subscript)
{
height /= SupScale;
baseline /= SupScale;
}
else if (_format.specialStyle == TextFormat.SpecialStyle.Superscript)
{
height = height / SupScale + baseline * SupOffset;
baseline *= (SupOffset + 1 / SupScale);
}
height = Mathf.RoundToInt(height);
baseline = Mathf.RoundToInt(baseline);
return true;
}
else
{
width = 0;
height = 0;
baseline = 0;
return false;
}
}
TMP_Character GetCharacterFromFontAsset(uint unicode, FontStyles fontStyle)
{
bool isAlternativeTypeface;
#pragma warning disable
TMP_FontAsset actualAsset;
#pragma warning restore
return TMP_FontAssetUtilities.GetCharacterFromFontAsset(unicode, _fontAsset, true, fontStyle, _fontWeight,
out isAlternativeTypeface
//,out actualAsset //old TMP version need this line
);
}
static Vector3 bottomLeft;
static Vector3 topLeft;
static Vector3 topRight;
static Vector3 bottomRight;
static Vector4 uvBottomLeft;
static Vector4 uvTopLeft;
static Vector4 uvTopRight;
static Vector4 uvBottomRight;
static Vector4 uv2BottomLeft;
static Vector4 uv2TopLeft;
static Vector4 uv2TopRight;
static Vector4 uv2BottomRight;
static Color32[] vertexColors = new Color32[4];
override public int DrawGlyph(float x, float y,
List<Vector3> vertList, List<Vector2> uvList, List<Vector2> uv2List, List<Color32> colList)
{
GlyphMetrics metrics = _char.glyph.metrics;
GlyphRect rect = _char.glyph.glyphRect;
if (_format.specialStyle == TextFormat.SpecialStyle.Subscript)
y = y - Mathf.RoundToInt(_ascent * _scale * SupOffset);
else if (_format.specialStyle == TextFormat.SpecialStyle.Superscript)
y = y + Mathf.RoundToInt(_ascent * _scale * (1 / SupScale - 1 + SupOffset));
topLeft.x = x + (metrics.horizontalBearingX - _padding - _stylePadding) * _scale;
topLeft.y = y + (metrics.horizontalBearingY + _padding) * _scale;
bottomRight.x = topLeft.x + (metrics.width + _padding * 2 + _stylePadding * 2) * _scale;
bottomRight.y = topLeft.y - (metrics.height + _padding * 2) * _scale;
topRight.x = bottomRight.x;
topRight.y = topLeft.y;
bottomLeft.x = topLeft.x;
bottomLeft.y = bottomRight.y;
#region Handle Italic & Shearing
if (((_style & FontStyles.Italic) == FontStyles.Italic))
{
// Shift Top vertices forward by half (Shear Value * height of character) and Bottom vertices back by same amount.
float shear_value = _fontAsset.italicStyle * 0.01f;
Vector3 topShear = new Vector3(shear_value * ((metrics.horizontalBearingY + _padding + _stylePadding) * _scale), 0, 0);
Vector3 bottomShear = new Vector3(shear_value * (((metrics.horizontalBearingY - metrics.height - _padding - _stylePadding)) * _scale), 0, 0);
topLeft += topShear;
bottomLeft += bottomShear;
topRight += topShear;
bottomRight += bottomShear;
}
#endregion Handle Italics & Shearing
vertList.Add(bottomLeft);
vertList.Add(topLeft);
vertList.Add(topRight);
vertList.Add(bottomRight);
float u = (rect.x - _padding - _stylePadding) / _fontAsset.atlasWidth;
float v = (rect.y - _padding - _stylePadding) / _fontAsset.atlasHeight;
float uw = (rect.width + _padding * 2 + _stylePadding * 2) / _fontAsset.atlasWidth;
float vw = (rect.height + _padding * 2 + _stylePadding * 2) / _fontAsset.atlasHeight;
uvBottomLeft = new Vector2(u, v);
uvTopLeft = new Vector2(u, v + vw);
uvTopRight = new Vector2(u + uw, v + vw);
uvBottomRight = new Vector2(u + uw, v);
float xScale = _scale * 0.01f;
if (_format.bold)
xScale *= -1;
uv2BottomLeft = new Vector2(0, xScale);
uv2TopLeft = new Vector2(511, xScale);
uv2TopRight = new Vector2(2093567, xScale);
uv2BottomRight = new Vector2(2093056, xScale);
uvList.Add(uvBottomLeft);
uvList.Add(uvTopLeft);
uvList.Add(uvTopRight);
uvList.Add(uvBottomRight);
uv2List.Add(uv2BottomLeft);
uv2List.Add(uv2TopLeft);
uv2List.Add(uv2TopRight);
uv2List.Add(uv2BottomRight);
colList.Add(vertexColors[0]);
colList.Add(vertexColors[1]);
colList.Add(vertexColors[2]);
colList.Add(vertexColors[3]);
return 4;
}
override public int DrawLine(float x, float y, float width, int fontSize, int type,
List<Vector3> vertList, List<Vector2> uvList, List<Vector2> uv2List, List<Color32> colList)
{
if (_lineChar == null)
return 0;
float thickness;
float offset;
if (type == 0)
{
thickness = _fontAsset.faceInfo.underlineThickness;
offset = _fontAsset.faceInfo.underlineOffset;
}
else
{
thickness = _fontAsset.faceInfo.strikethroughThickness;
offset = _fontAsset.faceInfo.strikethroughOffset;
}
float scale = (float)fontSize / _fontAsset.faceInfo.pointSize * _fontAsset.faceInfo.scale;
float segmentWidth = _lineChar.glyph.metrics.width / 2 * scale;
if (width < _lineChar.glyph.metrics.width * scale)
segmentWidth = width / 2f;
// UNDERLINE VERTICES FOR (3) LINE SEGMENTS
#region UNDERLINE VERTICES
thickness = thickness * scale;
if (thickness < 1)
thickness = 1;
offset = Mathf.RoundToInt(offset * scale);
// Front Part of the Underline
y += offset;
topLeft.x = x;
topLeft.y = y + _padding * scale;
bottomRight.x = x + segmentWidth;
bottomRight.y = y - thickness - _padding * scale;
topRight.x = bottomRight.x;
topRight.y = topLeft.y;
bottomLeft.x = topLeft.x;
bottomLeft.y = bottomRight.y;
vertList.Add(bottomLeft);
vertList.Add(topLeft);
vertList.Add(topRight);
vertList.Add(bottomRight);
// Middle Part of the Underline
topLeft = topRight;
bottomLeft = bottomRight;
topRight.x = x + width - segmentWidth;
bottomRight.x = topRight.x;
vertList.Add(bottomLeft);
vertList.Add(topLeft);
vertList.Add(topRight);
vertList.Add(bottomRight);
// End Part of the Underline
topLeft = topRight;
bottomLeft = bottomRight;
topRight.x = x + width;
bottomRight.x = topRight.x;
vertList.Add(bottomLeft);
vertList.Add(topLeft);
vertList.Add(topRight);
vertList.Add(bottomRight);
#endregion
// UNDERLINE UV0
#region HANDLE UV0
// Calculate UV required to setup the 3 Quads for the Underline.
Vector2 uv0 = new Vector2((_lineChar.glyph.glyphRect.x - _padding) / _fontAsset.atlasWidth, (_lineChar.glyph.glyphRect.y - _padding) / _fontAsset.atlasHeight); // bottom left
Vector2 uv1 = new Vector2(uv0.x, (_lineChar.glyph.glyphRect.y + _lineChar.glyph.glyphRect.height + _padding) / _fontAsset.atlasHeight); // top left
Vector2 uv2 = new Vector2((_lineChar.glyph.glyphRect.x - _padding + (float)_lineChar.glyph.glyphRect.width / 2) / _fontAsset.atlasWidth, uv1.y); // Mid Top Left
Vector2 uv3 = new Vector2(uv2.x, uv0.y); // Mid Bottom Left
Vector2 uv4 = new Vector2((_lineChar.glyph.glyphRect.x + _padding + (float)_lineChar.glyph.glyphRect.width / 2) / _fontAsset.atlasWidth, uv1.y); // Mid Top Right
Vector2 uv5 = new Vector2(uv4.x, uv0.y); // Mid Bottom right
Vector2 uv6 = new Vector2((_lineChar.glyph.glyphRect.x + _padding + _lineChar.glyph.glyphRect.width) / _fontAsset.atlasWidth, uv1.y); // End Part - Bottom Right
Vector2 uv7 = new Vector2(uv6.x, uv0.y); // End Part - Top Right
uvList.Add(uv0);
uvList.Add(uv1);
uvList.Add(uv2);
uvList.Add(uv3);
// Middle Part of the Underline
uvList.Add(new Vector2(uv2.x - uv2.x * 0.001f, uv0.y));
uvList.Add(new Vector2(uv2.x - uv2.x * 0.001f, uv1.y));
uvList.Add(new Vector2(uv2.x + uv2.x * 0.001f, uv1.y));
uvList.Add(new Vector2(uv2.x + uv2.x * 0.001f, uv0.y));
// Right Part of the Underline
uvList.Add(uv5);
uvList.Add(uv4);
uvList.Add(uv6);
uvList.Add(uv7);
#endregion
// UNDERLINE UV2
#region HANDLE UV2 - SDF SCALE
// UV1 contains Face / Border UV layout.
float segUv1 = segmentWidth / width;
float segUv2 = 1 - segUv1;
//Calculate the xScale or how much the UV's are getting stretched on the X axis for the middle section of the underline.
float xScale = scale * 0.01f;
uv2List.Add(PackUV(0, 0, xScale));
uv2List.Add(PackUV(0, 1, xScale));
uv2List.Add(PackUV(segUv1, 1, xScale));
uv2List.Add(PackUV(segUv1, 0, xScale));
uv2List.Add(PackUV(segUv1, 0, xScale));
uv2List.Add(PackUV(segUv1, 1, xScale));
uv2List.Add(PackUV(segUv2, 1, xScale));
uv2List.Add(PackUV(segUv2, 0, xScale));
uv2List.Add(PackUV(segUv2, 0, xScale));
uv2List.Add(PackUV(segUv2, 1, xScale));
uv2List.Add(PackUV(1, 1, xScale));
uv2List.Add(PackUV(1, 0, xScale));
#endregion
// UNDERLINE VERTEX COLORS
#region
// Alpha is the lower of the vertex color or tag color alpha used.
for (int i = 0; i < 12; i++)
colList.Add(vertexColors[0]);
#endregion
return 12;
}
Vector2 PackUV(float x, float y, float xScale)
{
double x0 = (int)(x * 511);
double y0 = (int)(y * 511);
return new Vector2((float)((x0 * 4096) + y0), xScale);
}
override public bool HasCharacter(char ch)
{
return _fontAsset.HasCharacter(ch);
}
override public int GetLineHeight(int size)
{
return Mathf.RoundToInt(_lineHeight * ((float)size / _fontAsset.faceInfo.pointSize * _fontAsset.faceInfo.scale));
}
}
}
#endif

View File

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

View File

@ -0,0 +1,16 @@
#if FAIRYGUI_TMPRO
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public partial class TextFormat
{
public float faceDilate;
public float outlineSoftness;
public float underlaySoftness;
}
}
#endif

View File

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

View File

@ -0,0 +1,14 @@
{
"name": "FairyGUI.Runtime",
"rootNamespace": "",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f4270d81837019d47b93f11421168dae
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: cc39210f7f4d03f4aa637689b9d90d75
folderAsset: yes
timeCreated: 1446459912
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: b5137d7a41873f9499f95f860a6cef17
folderAsset: yes
timeCreated: 1465913233
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,58 @@
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "FairyGUI/BlurFilter" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
Pass {
ZTest Always
ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata_t {
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
};
struct v2f {
float4 vertex : SV_POSITION;
half2 texcoord : TEXCOORD0;
half2 taps[4] : TEXCOORD1;
};
sampler2D _MainTex;
half4 _MainTex_TexelSize;
half4 _BlurOffsets;
v2f vert (appdata_t v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = v.texcoord - _BlurOffsets.xy * _MainTex_TexelSize.xy;
o.taps[0] = o.texcoord + _MainTex_TexelSize * _BlurOffsets.xy;
o.taps[1] = o.texcoord - _MainTex_TexelSize * _BlurOffsets.xy;
o.taps[2] = o.texcoord + _MainTex_TexelSize * _BlurOffsets.xy * half2(1,-1);
o.taps[3] = o.texcoord - _MainTex_TexelSize * _BlurOffsets.xy * half2(1,-1);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
half4 color = tex2D(_MainTex, i.taps[0]);
color += tex2D(_MainTex, i.taps[1]);
color += tex2D(_MainTex, i.taps[2]);
color += tex2D(_MainTex, i.taps[3]);
return color * 0.25;
}
ENDCG
}
}
Fallback off
}

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: f83d3bb1d90aaf54d8aed0783317662f
timeCreated: 1465913243
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,154 @@
// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "FairyGUI/BMFont"
{
Properties
{
_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_ColorMask ("Color Mask", Float) = 15
_BlendSrcFactor ("Blend SrcFactor", Float) = 5
_BlendDstFactor ("Blend DstFactor", Float) = 10
}
SubShader
{
LOD 100
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
}
Stencil
{
Ref [_Stencil]
Comp [_StencilComp]
Pass [_StencilOp]
ReadMask [_StencilReadMask]
WriteMask [_StencilWriteMask]
}
Cull Off
Lighting Off
ZWrite Off
Fog { Mode Off }
Blend [_BlendSrcFactor] [_BlendDstFactor]
ColorMask [_ColorMask]
Pass
{
CGPROGRAM
#pragma multi_compile NOT_GRAYED GRAYED
#pragma multi_compile NOT_CLIPPED CLIPPED SOFT_CLIPPED
#pragma vertex vert
#pragma fragment frag
#pragma exclude_renderers d3d9 opengl flash
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
fixed4 color : COLOR;
float4 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float4 texcoord : TEXCOORD0;
#ifdef CLIPPED
float2 clipPos : TEXCOORD1;
#endif
#ifdef SOFT_CLIPPED
float2 clipPos : TEXCOORD1;
#endif
};
sampler2D _MainTex;
CBUFFER_START(UnityPerMaterial)
#ifdef CLIPPED
float4 _ClipBox = float4(-2, -2, 0, 0);
#endif
#ifdef SOFT_CLIPPED
float4 _ClipBox = float4(-2, -2, 0, 0);
float4 _ClipSoftness = float4(0, 0, 0, 0);
#endif
CBUFFER_END
v2f vert (appdata_t v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = v.texcoord;
#if !defined(UNITY_COLORSPACE_GAMMA) && (UNITY_VERSION >= 550)
o.color.rgb = GammaToLinearSpace(v.color.rgb);
o.color.a = v.color.a;
#else
o.color = v.color;
#endif
#ifdef CLIPPED
o.clipPos = mul(unity_ObjectToWorld, v.vertex).xy * _ClipBox.zw + _ClipBox.xy;
#endif
#ifdef SOFT_CLIPPED
o.clipPos = mul(unity_ObjectToWorld, v.vertex).xy * _ClipBox.zw + _ClipBox.xy;
#endif
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = i.color;
fixed4 tcol = tex2D(_MainTex, i.texcoord);
col.a *= tcol[i.texcoord.z];//z stores channel
#ifdef GRAYED
fixed grey = dot(col.rgb, fixed3(0.299, 0.587, 0.114));
col.rgb = fixed3(grey, grey, grey);
#endif
#ifdef SOFT_CLIPPED
float2 factor = float2(0,0);
if(i.clipPos.x<0)
factor.x = (1.0-abs(i.clipPos.x)) * _ClipSoftness.x;
else
factor.x = (1.0-i.clipPos.x) * _ClipSoftness.z;
if(i.clipPos.y<0)
factor.y = (1.0-abs(i.clipPos.y)) * _ClipSoftness.w;
else
factor.y = (1.0-i.clipPos.y) * _ClipSoftness.y;
col.a *= clamp(min(factor.x, factor.y), 0.0, 1.0);
#endif
#ifdef CLIPPED
float2 factor = abs(i.clipPos);
col.a *= step(max(factor.x, factor.y), 1);
#endif
return col;
}
ENDCG
}
}
Fallback "FairyGUI/Text"
}

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: cd79153f88fa7334ea6c5564c053bdca
timeCreated: 1459224288
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,182 @@
// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "FairyGUI/Image"
{
Properties
{
_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_ColorMask ("Color Mask", Float) = 15
_BlendSrcFactor ("Blend SrcFactor", Float) = 5
_BlendDstFactor ("Blend DstFactor", Float) = 10
}
SubShader
{
LOD 100
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
}
Stencil
{
Ref [_Stencil]
Comp [_StencilComp]
Pass [_StencilOp]
ReadMask [_StencilReadMask]
WriteMask [_StencilWriteMask]
}
Cull Off
Lighting Off
ZWrite Off
Fog { Mode Off }
Blend [_BlendSrcFactor] [_BlendDstFactor], One One
ColorMask [_ColorMask]
Pass
{
CGPROGRAM
#pragma multi_compile NOT_COMBINED COMBINED
#pragma multi_compile NOT_GRAYED GRAYED COLOR_FILTER
#pragma multi_compile NOT_CLIPPED CLIPPED SOFT_CLIPPED ALPHA_MASK
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
fixed4 color : COLOR;
float4 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float4 texcoord : TEXCOORD0;
#ifdef CLIPPED
float2 clipPos : TEXCOORD1;
#endif
#ifdef SOFT_CLIPPED
float2 clipPos : TEXCOORD1;
#endif
};
sampler2D _MainTex;
#ifdef COMBINED
sampler2D _AlphaTex;
#endif
CBUFFER_START(UnityPerMaterial)
#ifdef CLIPPED
float4 _ClipBox = float4(-2, -2, 0, 0);
#endif
#ifdef SOFT_CLIPPED
float4 _ClipBox = float4(-2, -2, 0, 0);
float4 _ClipSoftness = float4(0, 0, 0, 0);
#endif
CBUFFER_END
#ifdef COLOR_FILTER
float4x4 _ColorMatrix;
float4 _ColorOffset;
float _ColorOption = 0;
#endif
v2f vert (appdata_t v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = v.texcoord;
#if !defined(UNITY_COLORSPACE_GAMMA) && (UNITY_VERSION >= 550)
o.color.rgb = GammaToLinearSpace(v.color.rgb);
o.color.a = v.color.a;
#else
o.color = v.color;
#endif
#ifdef CLIPPED
o.clipPos = mul(unity_ObjectToWorld, v.vertex).xy * _ClipBox.zw + _ClipBox.xy;
#endif
#ifdef SOFT_CLIPPED
o.clipPos = mul(unity_ObjectToWorld, v.vertex).xy * _ClipBox.zw + _ClipBox.xy;
#endif
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.texcoord.xy / i.texcoord.w) * i.color;
#ifdef COMBINED
col.a *= tex2D(_AlphaTex, i.texcoord.xy / i.texcoord.w).g;
#endif
#ifdef GRAYED
fixed grey = dot(col.rgb, fixed3(0.299, 0.587, 0.114));
col.rgb = fixed3(grey, grey, grey);
#endif
#ifdef SOFT_CLIPPED
float2 factor = float2(0,0);
if(i.clipPos.x<0)
factor.x = (1.0-abs(i.clipPos.x)) * _ClipSoftness.x;
else
factor.x = (1.0-i.clipPos.x) * _ClipSoftness.z;
if(i.clipPos.y<0)
factor.y = (1.0-abs(i.clipPos.y)) * _ClipSoftness.w;
else
factor.y = (1.0-i.clipPos.y) * _ClipSoftness.y;
col.a *= clamp(min(factor.x, factor.y), 0.0, 1.0);
#endif
#ifdef CLIPPED
float2 factor = abs(i.clipPos);
col.a *= step(max(factor.x, factor.y), 1);
#endif
#ifdef COLOR_FILTER
if (_ColorOption == 0)
{
fixed4 col2 = col;
col2.r = dot(col, _ColorMatrix[0]) + _ColorOffset.x;
col2.g = dot(col, _ColorMatrix[1]) + _ColorOffset.y;
col2.b = dot(col, _ColorMatrix[2]) + _ColorOffset.z;
col2.a = dot(col, _ColorMatrix[3]) + _ColorOffset.w;
col = col2;
}
else //premultiply alpha
col.rgb *= col.a;
#endif
#ifdef ALPHA_MASK
clip(col.a - 0.001);
#endif
return col;
}
ENDCG
}
}
}

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 263c97191482b3649ac7bf0810cc4f77
timeCreated: 1459224288
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,150 @@
// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "FairyGUI/Text"
{
Properties
{
_MainTex ("Alpha (A)", 2D) = "white" {}
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_ColorMask ("Color Mask", Float) = 15
_BlendSrcFactor ("Blend SrcFactor", Float) = 5
_BlendDstFactor ("Blend DstFactor", Float) = 10
}
SubShader
{
LOD 100
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
}
Stencil
{
Ref [_Stencil]
Comp [_StencilComp]
Pass [_StencilOp]
ReadMask [_StencilReadMask]
WriteMask [_StencilWriteMask]
}
Cull Off
Lighting Off
ZWrite Off
Fog { Mode Off }
Blend [_BlendSrcFactor] [_BlendDstFactor]
ColorMask [_ColorMask]
Pass
{
CGPROGRAM
#pragma multi_compile NOT_GRAYED GRAYED
#pragma multi_compile NOT_CLIPPED CLIPPED SOFT_CLIPPED
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
fixed4 color : COLOR;
float4 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float4 texcoord : TEXCOORD0;
#ifdef CLIPPED
float2 clipPos : TEXCOORD1;
#endif
#ifdef SOFT_CLIPPED
float2 clipPos : TEXCOORD1;
#endif
};
sampler2D _MainTex;
CBUFFER_START(UnityPerMaterial)
#ifdef CLIPPED
float4 _ClipBox = float4(-2, -2, 0, 0);
#endif
#ifdef SOFT_CLIPPED
float4 _ClipBox = float4(-2, -2, 0, 0);
float4 _ClipSoftness = float4(0, 0, 0, 0);
#endif
CBUFFER_END
v2f vert (appdata_t v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = v.texcoord;
#if !defined(UNITY_COLORSPACE_GAMMA) && (UNITY_VERSION >= 550)
o.color.rgb = GammaToLinearSpace(v.color.rgb);
o.color.a = v.color.a;
#else
o.color = v.color;
#endif
#ifdef CLIPPED
o.clipPos = mul(unity_ObjectToWorld, v.vertex).xy * _ClipBox.zw + _ClipBox.xy;
#endif
#ifdef SOFT_CLIPPED
o.clipPos = mul(unity_ObjectToWorld, v.vertex).xy * _ClipBox.zw + _ClipBox.xy;
#endif
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = i.color;
col.a *= tex2D(_MainTex, i.texcoord).a;
#ifdef GRAYED
fixed grey = dot(col.rgb, fixed3(0.299, 0.587, 0.114));
col.rgb = fixed3(grey, grey, grey);
#endif
#ifdef SOFT_CLIPPED
float2 factor = float2(0,0);
if(i.clipPos.x<0)
factor.x = (1.0-abs(i.clipPos.x)) * _ClipSoftness.x;
else
factor.x = (1.0-i.clipPos.x) * _ClipSoftness.z;
if(i.clipPos.y<0)
factor.y = (1.0-abs(i.clipPos.y)) * _ClipSoftness.w;
else
factor.y = (1.0-i.clipPos.y) * _ClipSoftness.y;
col.a *= clamp(min(factor.x, factor.y), 0.0, 1.0);
#endif
#ifdef CLIPPED
float2 factor = abs(i.clipPos);
col.a *= step(max(factor.x, factor.y), 1);
#endif
return col;
}
ENDCG
}
}
}

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 8526777372c6fef4f8162b3a7901dcb0
timeCreated: 1459224288
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: eed3a919a48726c46a61e180a615ef7d
folderAsset: yes
timeCreated: 1460480287
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,110 @@
using UnityEngine;
using NativeBlendMode = UnityEngine.Rendering.BlendMode;
namespace FairyGUI
{
/*BlendMode.Off, Blend Off指令的效果使Blend Off指令可以获得更高的效率
Image着色器本身就有多个关键字Shader数量便增加了这样一种模式
*/
/// <summary>
///
/// </summary>
public enum BlendMode
{
Normal,
None,
Add,
Multiply,
Screen,
Erase,
Mask,
Below,
Off,
One_OneMinusSrcAlpha,
Custom1,
Custom2,
Custom3
}
/// <summary>
///
/// </summary>
public class BlendModeUtils
{
public class BlendFactor
{
public NativeBlendMode srcFactor;
public NativeBlendMode dstFactor;
public bool pma;
public BlendFactor(NativeBlendMode srcFactor, NativeBlendMode dstFactor, bool pma = false)
{
this.srcFactor = srcFactor;
this.dstFactor = dstFactor;
this.pma = pma;
}
}
//Source指的是被计算的颜色Destination是已经在屏幕上的颜色。
//混合结果=Source * factor1 + Destination * factor2
public static BlendFactor[] Factors = new BlendFactor[] {
//Normal
new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha),
//None
new BlendFactor(NativeBlendMode.One, NativeBlendMode.One),
//Add
new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.One),
//Multiply
new BlendFactor(NativeBlendMode.DstColor, NativeBlendMode.OneMinusSrcAlpha, true),
//Screen
new BlendFactor(NativeBlendMode.One, NativeBlendMode.OneMinusSrcColor, true),
//Erase
new BlendFactor(NativeBlendMode.Zero, NativeBlendMode.OneMinusSrcAlpha),
//Mask
new BlendFactor(NativeBlendMode.Zero, NativeBlendMode.SrcAlpha),
//Below
new BlendFactor(NativeBlendMode.OneMinusDstAlpha, NativeBlendMode.DstAlpha),
//Off
new BlendFactor(NativeBlendMode.One, NativeBlendMode.Zero),
//One_OneMinusSrcAlpha
new BlendFactor(NativeBlendMode.One, NativeBlendMode.OneMinusSrcAlpha),
//Custom1
new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha),
//Custom2
new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha),
//Custom3
new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha)
};
/// <summary>
///
/// </summary>
/// <param name="mat"></param>
/// <param name="blendMode"></param>
public static void Apply(Material mat, BlendMode blendMode)
{
BlendFactor bf = Factors[(int)blendMode];
mat.SetFloat(ShaderConfig.ID_BlendSrcFactor, (float)bf.srcFactor);
mat.SetFloat(ShaderConfig.ID_BlendDstFactor, (float)bf.dstFactor);
if (bf.pma)
mat.SetFloat(ShaderConfig.ID_ColorOption, 1);
else
mat.SetFloat(ShaderConfig.ID_ColorOption, 0);
}
/// <summary>
///
/// </summary>
/// <param name="blendMode"></param>
/// <param name="srcFactor"></param>
/// <param name="dstFactor"></param>
public static void Override(BlendMode blendMode, NativeBlendMode srcFactor, NativeBlendMode dstFactor)
{
BlendFactor bf = Factors[(int)blendMode];
bf.srcFactor = srcFactor;
bf.dstFactor = dstFactor;
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: ce4df113fe8d9994c83e22680544ccdb
timeCreated: 1464679834
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,202 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class CaptureCamera : MonoBehaviour
{
/// <summary>
///
/// </summary>
[System.NonSerialized]
public Transform cachedTransform;
/// <summary>
///
/// </summary>
[System.NonSerialized]
public Camera cachedCamera;
[System.NonSerialized]
static CaptureCamera _main;
[System.NonSerialized]
static int _layer = -1;
static int _hiddenLayer = -1;
public const string Name = "Capture Camera";
public const string LayerName = "VUI";
public const string HiddenLayerName = "Hidden VUI";
void OnEnable()
{
cachedCamera = this.GetComponent<Camera>();
cachedTransform = this.gameObject.transform;
if (this.gameObject.name == Name)
_main = this;
}
/// <summary>
///
/// </summary>
public static void CheckMain()
{
if (_main != null && _main.cachedCamera != null)
return;
GameObject go = GameObject.Find(Name);
if (go != null)
{
_main = go.GetComponent<CaptureCamera>();
return;
}
GameObject cameraObject = new GameObject(Name);
Camera camera = cameraObject.AddComponent<Camera>();
camera.depth = 0;
camera.cullingMask = 1 << layer;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = Color.clear;
camera.orthographic = true;
camera.orthographicSize = 5;
camera.nearClipPlane = -30;
camera.farClipPlane = 30;
camera.enabled = false;
#if UNITY_5_4_OR_NEWER
camera.stereoTargetEye = StereoTargetEyeMask.None;
#endif
#if UNITY_5_6_OR_NEWER
camera.allowHDR = false;
camera.allowMSAA = false;
#endif
cameraObject.AddComponent<CaptureCamera>();
}
/// <summary>
///
/// </summary>
public static int layer
{
get
{
if (_layer == -1)
{
_layer = LayerMask.NameToLayer(LayerName);
if (_layer == -1)
{
_layer = 30;
Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'");
}
}
return _layer;
}
}
/// <summary>
///
/// </summary>
public static int hiddenLayer
{
get
{
if (_hiddenLayer == -1)
{
_hiddenLayer = LayerMask.NameToLayer(HiddenLayerName);
if (_hiddenLayer == -1)
{
Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'");
_hiddenLayer = 31;
}
}
return _hiddenLayer;
}
}
/// <summary>
///
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="stencilSupport"></param>
/// <returns></returns>
public static RenderTexture CreateRenderTexture(int width, int height, bool stencilSupport)
{
RenderTexture texture = new RenderTexture(width, height, stencilSupport ? 24 : 0, RenderTextureFormat.ARGB32);
texture.antiAliasing = 1;
texture.filterMode = FilterMode.Bilinear;
texture.anisoLevel = 0;
texture.useMipMap = false;
texture.wrapMode = TextureWrapMode.Clamp;
texture.hideFlags = DisplayObject.hideFlags;
return texture;
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="texture"></param>
/// <param name="contentHeight"></param>
/// <param name="offset"></param>
public static void Capture(DisplayObject target, RenderTexture texture, float contentHeight, Vector2 offset)
{
CheckMain();
Matrix4x4 matrix = target.cachedTransform.localToWorldMatrix;
float scaleX = new Vector4(matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude;
float scaleY = new Vector4(matrix.m01, matrix.m11, matrix.m21, matrix.m31).magnitude;
Vector3 forward;
forward.x = matrix.m02;
forward.y = matrix.m12;
forward.z = matrix.m22;
Vector3 upwards;
upwards.x = matrix.m01;
upwards.y = matrix.m11;
upwards.z = matrix.m21;
float halfHeight = contentHeight * 0.5f;
Camera camera = _main.cachedCamera;
camera.targetTexture = texture;
float aspect = (float)texture.width / texture.height;
camera.aspect = aspect * scaleX / scaleY;
camera.orthographicSize = halfHeight * scaleY;
_main.cachedTransform.localPosition = target.cachedTransform.TransformPoint(halfHeight * aspect - offset.x, -halfHeight + offset.y, 0);
if (forward != Vector3.zero)
_main.cachedTransform.localRotation = Quaternion.LookRotation(forward, upwards);
int oldLayer = 0;
if (target.graphics != null)
{
oldLayer = target.graphics.gameObject.layer;
target.graphics.gameObject.layer = CaptureCamera.layer;
}
if (target is Container)
{
oldLayer = ((Container)target).numChildren > 0 ? ((Container)target).GetChildAt(0).layer : CaptureCamera.hiddenLayer;
((Container)target).SetChildrenLayer(CaptureCamera.layer);
}
RenderTexture old = RenderTexture.active;
RenderTexture.active = texture;
GL.Clear(true, true, Color.clear);
camera.Render();
RenderTexture.active = old;
if (target.graphics != null)
target.graphics.gameObject.layer = oldLayer;
if (target is Container)
((Container)target).SetChildrenLayer(oldLayer);
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: d207151359c99fb448f4b3380bf41b0f
timeCreated: 1535374215
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 531f2c788ec31e7459700f6811410a6f
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 24d09ba8cf3faa74f8dcd1c86ad38588
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,393 @@
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Pool;
namespace FairyGUI
{
/// <summary>
/// GoWrapper is class for wrapping common gameobject into UI display list.
/// </summary>
public class GoWrapper : DisplayObject
{
[Obsolete("No need to manually set this flag anymore, coz it will be handled automatically.")]
public bool supportStencil;
public event Action<UpdateContext> onUpdate;
public Action<Dictionary<Material, Material>> customCloneMaterials;
public Action customRecoverMaterials;
protected GameObject _wrapTarget;
protected List<RendererInfo> _renderers;
protected Dictionary<Material, Material> _materialsBackup;
protected Canvas _canvas;
protected bool _cloneMaterial;
protected bool _shouldCloneMaterial;
protected struct RendererInfo
{
public Renderer renderer;
public Material[] materials;
public int sortingOrder;
}
// protected static List<Transform> helperTransformList = new List<Transform>();
/// <summary>
///
/// </summary>
public GoWrapper()
{
// _flags |= Flags.SkipBatching;
_renderers = new List<RendererInfo>();
_materialsBackup = new Dictionary<Material, Material>();
CreateGameObject("GoWrapper");
}
/// <summary>
///
/// </summary>
/// <param name="go">包装对象。</param>
public GoWrapper(GameObject go) : this()
{
SetWrapTarget(go, false);
}
/// <summary>
/// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。
/// 对象包含的所有材质不会被复制如果材质已经是公用的这可能影响到其他对象。如果希望自动复制改为使用SetWrapTarget(target, true)设置。
/// </summary>
public GameObject wrapTarget
{
get { return _wrapTarget; }
set { SetWrapTarget(value, false); }
}
[Obsolete("setWrapTarget is deprecated. Use SetWrapTarget instead.")]
public void setWrapTarget(GameObject target, bool cloneMaterial)
{
SetWrapTarget(target, cloneMaterial);
}
/// <summary>
/// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。
/// </summary>
/// <param name="target"></param>
/// <param name="cloneMaterial">如果true则复制材质否则直接使用sharedMaterial。</param>
public void SetWrapTarget(GameObject target, bool cloneMaterial)
{
// set Flags.SkipBatching only target not null
if (target == null) _flags &= ~Flags.SkipBatching;
else _flags |= Flags.SkipBatching;
InvalidateBatchingState();
RecoverMaterials();
_cloneMaterial = cloneMaterial;
if (_wrapTarget != null)
_wrapTarget.transform.SetParent(null, false);
_canvas = null;
_wrapTarget = target;
_shouldCloneMaterial = false;
_renderers.Clear();
if (_wrapTarget != null)
{
_wrapTarget.transform.SetParent(this.cachedTransform, false);
_canvas = _wrapTarget.GetComponent<Canvas>();
if (_canvas != null)
{
_canvas.renderMode = RenderMode.WorldSpace;
_canvas.worldCamera = StageCamera.main;
_canvas.overrideSorting = true;
RectTransform rt = _canvas.GetComponent<RectTransform>();
rt.pivot = new Vector2(0, 1);
rt.position = new Vector3(0, 0, 0);
this.SetSize(rt.rect.width, rt.rect.height);
}
else
{
CacheRenderers();
this.SetSize(0, 0);
}
SetGoLayers(this.layer);
}
}
/// <summary>
/// GoWrapper will cache all renderers of your gameobject on constructor.
/// If your gameobject change laterly, call this function to update the cache.
/// GoWrapper会在构造函数里查询你的gameobject所有的Renderer并保存。如果你的gameobject
/// 后续发生了改变调用这个函数通知GoWrapper重新查询和保存。
/// </summary>
public void CacheRenderers()
{
if (_canvas != null)
return;
RecoverMaterials();
_renderers.Clear();
var items = ListPool<Renderer>.Get();
_wrapTarget.GetComponentsInChildren(true, items);
int cnt = items.Count;
_renderers.Capacity = cnt;
for (int i = 0; i < cnt; i++)
{
Renderer r = items[i];
Material[] mats = r.sharedMaterials;
RendererInfo ri = new RendererInfo()
{
renderer = r,
materials = mats,
sortingOrder = r.sortingOrder
};
_renderers.Add(ri);
if (!_cloneMaterial && mats != null
&& ((r is SkinnedMeshRenderer) || (r is MeshRenderer)))
{
int mcnt = mats.Length;
for (int j = 0; j < mcnt; j++)
{
Material mat = mats[j];
if (mat != null && mat.renderQueue != 3000) //Set the object rendering in Transparent Queue as UI objects
mat.renderQueue = 3000;
}
}
}
ListPool<Renderer>.Release(items);
_renderers.Sort((RendererInfo c1, RendererInfo c2) => { return c1.sortingOrder - c2.sortingOrder; });
_shouldCloneMaterial = _cloneMaterial;
}
void CloneMaterials()
{
_shouldCloneMaterial = false;
int cnt = _renderers.Count;
for (int i = 0; i < cnt; i++)
{
RendererInfo ri = _renderers[i];
Material[] mats = ri.materials;
if (mats == null)
continue;
bool shouldSetRQ = (ri.renderer is SkinnedMeshRenderer) || (ri.renderer is MeshRenderer);
int mcnt = mats.Length;
for (int j = 0; j < mcnt; j++)
{
Material mat = mats[j];
if (mat == null)
continue;
//确保相同的材质不会复制两次
Material newMat;
if (!_materialsBackup.TryGetValue(mat, out newMat))
{
newMat = new Material(mat);
_materialsBackup[mat] = newMat;
}
mats[j] = newMat;
if (shouldSetRQ && mat.renderQueue != 3000) //Set the object rendering in Transparent Queue as UI objects
newMat.renderQueue = 3000;
}
if (customCloneMaterials != null)
customCloneMaterials.Invoke(_materialsBackup);
else if (ri.renderer != null)
ri.renderer.sharedMaterials = mats;
}
}
void RecoverMaterials()
{
if (_materialsBackup.Count == 0)
return;
int cnt = _renderers.Count;
for (int i = 0; i < cnt; i++)
{
RendererInfo ri = _renderers[i];
if (ri.renderer == null)
continue;
Material[] mats = ri.materials;
if (mats == null)
continue;
int mcnt = mats.Length;
for (int j = 0; j < mcnt; j++)
{
Material mat = mats[j];
foreach (KeyValuePair<Material, Material> kv in _materialsBackup)
{
if (kv.Value == mat)
mats[j] = kv.Key;
}
}
if (customRecoverMaterials != null)
customRecoverMaterials.Invoke();
else
ri.renderer.sharedMaterials = mats;
}
foreach (KeyValuePair<Material, Material> kv in _materialsBackup)
Material.DestroyImmediate(kv.Value);
_materialsBackup.Clear();
}
public override int renderingOrder
{
get { return base.renderingOrder; }
set
{
base.renderingOrder = value;
if (_canvas != null)
_canvas.sortingOrder = value;
else
{
int cnt = _renderers.Count;
for (int i = 0; i < cnt; i++)
{
RendererInfo ri = _renderers[i];
if (ri.renderer != null)
{
if (i != 0 && _renderers[i].sortingOrder != _renderers[i - 1].sortingOrder)
value = UpdateContext.current.renderingOrder++;
ri.renderer.sortingOrder = value;
}
}
}
}
}
override protected bool SetLayer(int value, bool fromParent)
{
if (base.SetLayer(value, fromParent))
{
SetGoLayers(value);
return true;
}
else
return false;
}
protected void SetGoLayers(int layer)
{
if (_wrapTarget == null)
return;
var helperTransformList = ListPool<Transform>.Get();
_wrapTarget.GetComponentsInChildren(true, helperTransformList);
int cnt = helperTransformList.Count;
for (int i = 0; i < cnt; i++)
{
helperTransformList[i].gameObject.layer = layer;
}
ListPool<Transform>.Release(helperTransformList);
// helperTransformList.Clear();
}
override public void Update(UpdateContext context)
{
if (onUpdate != null)
onUpdate(context);
if (_shouldCloneMaterial)
CloneMaterials();
ApplyClipping(context);
base.Update(context);
}
private List<Material> helperMaterials = new List<Material>();
virtual protected void ApplyClipping(UpdateContext context)
{
#if UNITY_2018_2_OR_NEWER
int cnt = _renderers.Count;
for (int i = 0; i < cnt; i++)
{
Renderer renderer = _renderers[i].renderer;
if (renderer == null)
continue;
if (customCloneMaterials != null)
helperMaterials.AddRange(_materialsBackup.Values);
else
renderer.GetSharedMaterials(helperMaterials);
int cnt2 = helperMaterials.Count;
for (int j = 0; j < cnt2; j++)
{
Material mat = helperMaterials[j];
if (mat != null)
context.ApplyClippingProperties(mat, false);
}
helperMaterials.Clear();
}
#else
int cnt = _renderers.Count;
for (int i = 0; i < cnt; i++)
{
Material[] mats = _renderers[i].materials;
if (mats == null)
continue;
int cnt2 = mats.Length;
for (int j = 0; j < cnt2; j++)
{
Material mat = mats[j];
if (mat != null)
context.ApplyClippingProperties(mat, false);
}
}
#endif
}
public override void Dispose()
{
if ((_flags & Flags.Disposed) != 0)
return;
if (_wrapTarget != null)
{
UnityEngine.Object.Destroy(_wrapTarget);
_wrapTarget = null;
if (_materialsBackup.Count > 0)
{
//如果有备份,说明材质是复制出来的,应该删除
foreach (KeyValuePair<Material, Material> kv in _materialsBackup)
Material.DestroyImmediate(kv.Value);
}
}
_renderers = null;
_materialsBackup = null;
_canvas = null;
customCloneMaterials = null;
customRecoverMaterials = null;
base.Dispose();
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 796d0bdebe7368c47adfdf04a1abdfc6
timeCreated: 1460480288
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 736ceb6630254bd42b41568b387cbcbe
folderAsset: yes
timeCreated: 1461773297
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,33 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class ColliderHitTest : IHitTest
{
/// <summary>
///
/// </summary>
public Collider collider;
/// <summary>
///
/// </summary>
/// <param name="contentRect"></param>
/// <param name="localPoint"></param>
/// <returns></returns>
virtual public bool HitTest(Rect contentRect, Vector2 localPoint)
{
RaycastHit hit;
if (!HitTestContext.GetRaycastHitFromCache(HitTestContext.camera, out hit))
return false;
if (hit.collider != collider)
return false;
return true;
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: ffed53edbd969f3439a942ca847cd43d
timeCreated: 1461773299
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,79 @@
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class HitTestContext
{
//set before hit test
public static Vector3 screenPoint;
public static Vector3 worldPoint;
public static Vector3 direction;
public static bool forTouch;
public static Camera camera;
public static int layerMask = -1;
public static float maxDistance = Mathf.Infinity;
public static Camera cachedMainCamera;
static Dictionary<Camera, RaycastHit?> raycastHits = new Dictionary<Camera, RaycastHit?>();
/// <summary>
///
/// </summary>
/// <param name="camera"></param>
/// <param name="hit"></param>
/// <returns></returns>
public static bool GetRaycastHitFromCache(Camera camera, out RaycastHit hit)
{
RaycastHit? hitRef;
if (!raycastHits.TryGetValue(camera, out hitRef))
{
Ray ray = camera.ScreenPointToRay(screenPoint);
if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
{
raycastHits[camera] = hit;
return true;
}
else
{
raycastHits[camera] = null;
return false;
}
}
else if (hitRef == null)
{
hit = new RaycastHit();
return false;
}
else
{
hit = (RaycastHit)hitRef;
return true;
}
}
/// <summary>
///
/// </summary>
/// <param name="camera"></param>
/// <param name="hit"></param>
public static void CacheRaycastHit(Camera camera, ref RaycastHit hit)
{
raycastHits[camera] = hit;
}
/// <summary>
///
/// </summary>
public static void ClearRaycastHitCache()
{
raycastHits.Clear();
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 19869d6307205b84a81aef6031ba1f33
timeCreated: 1461750571
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,27 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public enum HitTestMode
{
Default,
Raycast
}
/// <summary>
///
/// </summary>
public interface IHitTest
{
/// <summary>
///
/// </summary>
/// <param name="contentRect"></param>
/// <param name="localPoint"></param>
/// <returns></returns>
bool HitTest(Rect contentRect, Vector2 localPoint);
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 8bbadf82645501c41957c257ab020708
timeCreated: 1461853133
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,43 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class MeshColliderHitTest : ColliderHitTest
{
public Vector2 lastHit;
/// <summary>
///
/// </summary>
/// <param name="collider"></param>
public MeshColliderHitTest(MeshCollider collider)
{
this.collider = collider;
}
/// <summary>
///
/// </summary>
/// <param name="contentRect"></param>
/// <param name="localPoint"></param>
/// <returns></returns>
override public bool HitTest(Rect contentRect, Vector2 localPoint)
{
RaycastHit hit;
if (!HitTestContext.GetRaycastHitFromCache(HitTestContext.camera, out hit))
return false;
if (hit.collider != collider)
return false;
lastHit = new Vector2(hit.textureCoord.x * contentRect.width, (1 - hit.textureCoord.y) * contentRect.height);
HitTestContext.direction = Vector3.back;
HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(new Vector2(lastHit.x, Screen.height - lastHit.y));
return true;
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 6d0a2fa0c7008814795dc7f5f3bd4b19
timeCreated: 1461750571
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,82 @@
using FairyGUI.Utils;
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class PixelHitTestData
{
public int pixelWidth;
public float scale;
public byte[] pixels;
public int pixelsLength;
public int pixelsOffset;
public void Load(ByteBuffer ba)
{
ba.ReadInt();
pixelWidth = ba.ReadInt();
scale = 1.0f / ba.ReadByte();
pixels = ba.buffer;
pixelsLength = ba.ReadInt();
pixelsOffset = ba.position;
ba.Skip(pixelsLength);
}
}
/// <summary>
///
/// </summary>
public class PixelHitTest : IHitTest
{
public int offsetX;
public int offsetY;
public float sourceWidth;
public float sourceHeight;
PixelHitTestData _data;
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="offsetX"></param>
/// <param name="offsetY"></param>
public PixelHitTest(PixelHitTestData data, int offsetX, int offsetY, float sourceWidth, float sourceHeight)
{
_data = data;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.sourceWidth = sourceWidth;
this.sourceHeight = sourceHeight;
}
/// <summary>
///
/// </summary>
/// <param name="contentRect"></param>
/// <param name="localPoint"></param>
/// <returns></returns>
public bool HitTest(Rect contentRect, Vector2 localPoint)
{
if (!contentRect.Contains(localPoint))
return false;
int x = Mathf.FloorToInt((localPoint.x * sourceWidth / contentRect.width - offsetX) * _data.scale);
int y = Mathf.FloorToInt((localPoint.y * sourceHeight / contentRect.height - offsetY) * _data.scale);
if (x < 0 || y < 0 || x >= _data.pixelWidth)
return false;
int pos = y * _data.pixelWidth + x;
int pos2 = pos / 8;
int pos3 = pos % 8;
if (pos2 >= 0 && pos2 < _data.pixelsLength)
return ((_data.pixels[_data.pixelsOffset + pos2] >> pos3) & 0x1) > 0;
else
return false;
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 98cb65df7f5853c4b8e3719a28d4d81f
timeCreated: 1535374215
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,26 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class RectHitTest : IHitTest
{
/// <summary>
///
/// </summary>
public Rect rect;
/// <summary>
///
/// </summary>
/// <param name="contentRect"></param>
/// <param name="localPoint"></param>
/// <returns></returns>
public bool HitTest(Rect contentRect, Vector2 localPoint)
{
return rect.Contains(localPoint);
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 92768f03d9b8dea47b1649613c4d0de7
timeCreated: 1474896442
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,44 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class ShapeHitTest : IHitTest
{
/// <summary>
///
/// </summary>
public DisplayObject shape;
public ShapeHitTest(DisplayObject obj)
{
shape = obj;
}
/// <summary>
///
/// </summary>
/// <param name="contentRect"></param>
/// <param name="localPoint"></param>
/// <returns></returns>
public bool HitTest(Rect contentRect, Vector2 localPoint)
{
if (shape.graphics == null)
return false;
if (shape.parent != null)
{
localPoint = shape.parent.TransformPoint(localPoint, shape);
contentRect.size = shape.size;
}
IHitTest ht = shape.graphics.meshFactory as IHitTest;
if (ht == null)
return false;
return ht.HitTest(contentRect, localPoint);
}
}
}

View File

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

View File

@ -0,0 +1,436 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class Image : DisplayObject, IMeshFactory
{
protected Rect? _scale9Grid;
protected bool _scaleByTile;
protected Vector2 _textureScale;
protected int _tileGridIndice;
protected FillMesh _fillMesh;
public Image() : this(null)
{
}
/// <summary>
///
/// </summary>
/// <param name="texture"></param>
public Image(NTexture texture)
: base()
{
_flags |= Flags.TouchDisabled;
CreateGameObject("Image");
graphics = new NGraphics(gameObject);
graphics.shader = ShaderConfig.imageShader;
graphics.meshFactory = this;
_textureScale = Vector2.one;
if (texture != null)
UpdateTexture(texture);
}
/// <summary>
///
/// </summary>
public NTexture texture
{
get { return graphics.texture; }
set
{
UpdateTexture(value);
}
}
public Vector2 textureScale
{
get { return _textureScale; }
set
{
_textureScale = value;
graphics.SetMeshDirty();
}
}
/// <summary>
///
/// </summary>
public Color color
{
get
{
return graphics.color;
}
set
{
graphics.color = value;
graphics.Tint();
}
}
/// <summary>
///
/// </summary>
public FillMethod fillMethod
{
get { return _fillMesh != null ? _fillMesh.method : FillMethod.None; }
set
{
if (_fillMesh == null)
{
if (value == FillMethod.None)
return;
_fillMesh = new FillMesh();
}
if (_fillMesh.method != value)
{
_fillMesh.method = value;
graphics.SetMeshDirty();
}
}
}
/// <summary>
///
/// </summary>
public int fillOrigin
{
get { return _fillMesh != null ? _fillMesh.origin : 0; }
set
{
if (_fillMesh == null)
_fillMesh = new FillMesh();
if (_fillMesh.origin != value)
{
_fillMesh.origin = value;
graphics.SetMeshDirty();
}
}
}
/// <summary>
///
/// </summary>
public bool fillClockwise
{
get { return _fillMesh != null ? _fillMesh.clockwise : true; }
set
{
if (_fillMesh == null)
_fillMesh = new FillMesh();
if (_fillMesh.clockwise != value)
{
_fillMesh.clockwise = value;
graphics.SetMeshDirty();
}
}
}
/// <summary>
///
/// </summary>
public float fillAmount
{
get { return _fillMesh != null ? _fillMesh.amount : 0; }
set
{
if (_fillMesh == null)
_fillMesh = new FillMesh();
if (_fillMesh.amount != value)
{
_fillMesh.amount = value;
graphics.SetMeshDirty();
}
}
}
/// <summary>
///
/// </summary>
public Rect? scale9Grid
{
get { return _scale9Grid; }
set
{
if (_scale9Grid != value)
{
_scale9Grid = value;
graphics.SetMeshDirty();
}
}
}
/// <summary>
///
/// </summary>
public bool scaleByTile
{
get { return _scaleByTile; }
set
{
if (_scaleByTile != value)
{
_scaleByTile = value;
graphics.SetMeshDirty();
}
}
}
/// <summary>
///
/// </summary>
public int tileGridIndice
{
get { return _tileGridIndice; }
set
{
if (_tileGridIndice != value)
{
_tileGridIndice = value;
graphics.SetMeshDirty();
}
}
}
/// <summary>
///
/// </summary>
public void SetNativeSize()
{
if (graphics.texture != null)
SetSize(graphics.texture.width, graphics.texture.height);
else
SetSize(0, 0);
}
virtual protected void UpdateTexture(NTexture value)
{
if (value == graphics.texture)
return;
graphics.texture = value;
_textureScale = Vector2.one;
if (_contentRect.width == 0)
SetNativeSize();
InvalidateBatchingState();
}
public void OnPopulateMesh(VertexBuffer vb)
{
if (_fillMesh != null && _fillMesh.method != FillMethod.None)
{
_fillMesh.OnPopulateMesh(vb);
}
else if (_scaleByTile)
{
NTexture texture = graphics.texture;
if (texture.root == texture
&& texture.nativeTexture != null
&& texture.nativeTexture.wrapMode == TextureWrapMode.Repeat)
{
Rect uvRect = vb.uvRect;
uvRect.width *= vb.contentRect.width / texture.width * _textureScale.x;
uvRect.height *= vb.contentRect.height / texture.height * _textureScale.y;
vb.AddQuad(vb.contentRect, vb.vertexColor, uvRect);
vb.AddTriangles();
}
else
{
Rect contentRect = vb.contentRect;
contentRect.width *= _textureScale.x;
contentRect.height *= _textureScale.y;
TileFill(vb, contentRect, vb.uvRect, texture.width, texture.height);
vb.AddTriangles();
}
}
else if (_scale9Grid != null)
{
SliceFill(vb);
}
else
graphics.OnPopulateMesh(vb);
}
static int[] TRIANGLES_9_GRID = new int[] {
4,0,1,1,5,4,
5,1,2,2,6,5,
6,2,3,3,7,6,
8,4,5,5,9,8,
9,5,6,6,10,9,
10,6,7,7,11,10,
12,8,9,9,13,12,
13,9,10,10,14,13,
14,10,11,
11,15,14
};
static int[] gridTileIndice = new int[] { -1, 0, -1, 2, 4, 3, -1, 1, -1 };
static float[] gridX = new float[4];
static float[] gridY = new float[4];
static float[] gridTexX = new float[4];
static float[] gridTexY = new float[4];
public void SliceFill(VertexBuffer vb)
{
NTexture texture = graphics.texture;
Rect gridRect = (Rect)_scale9Grid;
Rect contentRect = vb.contentRect;
contentRect.width *= _textureScale.x;
contentRect.height *= _textureScale.y;
Rect uvRect = vb.uvRect;
float sourceW = texture.width;
float sourceH = texture.height;
if (graphics.flip != FlipType.None)
{
if (graphics.flip == FlipType.Horizontal || graphics.flip == FlipType.Both)
{
gridRect.x = sourceW - gridRect.xMax;
gridRect.xMax = gridRect.x + gridRect.width;
}
if (graphics.flip == FlipType.Vertical || graphics.flip == FlipType.Both)
{
gridRect.y = sourceH - gridRect.yMax;
gridRect.yMax = gridRect.y + gridRect.height;
}
}
float sx = uvRect.width / sourceW;
float sy = uvRect.height / sourceH;
float xMax = uvRect.xMax;
float yMax = uvRect.yMax;
float xMax2 = gridRect.xMax;
float yMax2 = gridRect.yMax;
gridTexX[0] = uvRect.x;
gridTexX[1] = uvRect.x + gridRect.x * sx;
gridTexX[2] = uvRect.x + xMax2 * sx;
gridTexX[3] = xMax;
gridTexY[0] = yMax;
gridTexY[1] = yMax - gridRect.y * sy;
gridTexY[2] = yMax - yMax2 * sy;
gridTexY[3] = uvRect.y;
if (contentRect.width >= (sourceW - gridRect.width))
{
gridX[1] = gridRect.x;
gridX[2] = contentRect.width - (sourceW - xMax2);
gridX[3] = contentRect.width;
}
else
{
float tmp = gridRect.x / (sourceW - xMax2);
tmp = contentRect.width * tmp / (1 + tmp);
gridX[1] = tmp;
gridX[2] = tmp;
gridX[3] = contentRect.width;
}
if (contentRect.height >= (sourceH - gridRect.height))
{
gridY[1] = gridRect.y;
gridY[2] = contentRect.height - (sourceH - yMax2);
gridY[3] = contentRect.height;
}
else
{
float tmp = gridRect.y / (sourceH - yMax2);
tmp = contentRect.height * tmp / (1 + tmp);
gridY[1] = tmp;
gridY[2] = tmp;
gridY[3] = contentRect.height;
}
if (_tileGridIndice == 0)
{
for (int cy = 0; cy < 4; cy++)
{
for (int cx = 0; cx < 4; cx++)
vb.AddVert(new Vector2(gridX[cx] / _textureScale.x, gridY[cy] / _textureScale.y), vb.vertexColor, new Vector2(gridTexX[cx], gridTexY[cy]));
}
vb.AddTriangles(TRIANGLES_9_GRID);
}
else
{
Rect drawRect;
Rect texRect;
int row, col;
int part;
for (int pi = 0; pi < 9; pi++)
{
col = pi % 3;
row = pi / 3;
part = gridTileIndice[pi];
drawRect = Rect.MinMaxRect(gridX[col], gridY[row], gridX[col + 1], gridY[row + 1]);
texRect = Rect.MinMaxRect(gridTexX[col], gridTexY[row + 1], gridTexX[col + 1], gridTexY[row]);
if (part != -1 && (_tileGridIndice & (1 << part)) != 0)
{
TileFill(vb, drawRect, texRect,
(part == 0 || part == 1 || part == 4) ? gridRect.width : drawRect.width,
(part == 2 || part == 3 || part == 4) ? gridRect.height : drawRect.height);
}
else
{
drawRect.x /= _textureScale.x;
drawRect.y /= _textureScale.y;
drawRect.width /= _textureScale.x;
drawRect.height /= _textureScale.y;
vb.AddQuad(drawRect, vb.vertexColor, texRect);
}
}
vb.AddTriangles();
}
}
void TileFill(VertexBuffer vb, Rect contentRect, Rect uvRect, float sourceW, float sourceH)
{
int hc = Mathf.CeilToInt(contentRect.width / sourceW);
int vc = Mathf.CeilToInt(contentRect.height / sourceH);
float tailWidth = contentRect.width - (hc - 1) * sourceW;
float tailHeight = contentRect.height - (vc - 1) * sourceH;
float xMax = uvRect.xMax;
float yMax = uvRect.yMax;
for (int i = 0; i < hc; i++)
{
for (int j = 0; j < vc; j++)
{
Rect uvTmp = uvRect;
if (i == hc - 1)
uvTmp.xMax = Mathf.Lerp(uvRect.x, xMax, tailWidth / sourceW);
if (j == vc - 1)
uvTmp.yMin = Mathf.Lerp(uvRect.y, yMax, 1 - tailHeight / sourceH);
Rect drawRect = new Rect(contentRect.x + i * sourceW, contentRect.y + j * sourceH,
i == (hc - 1) ? tailWidth : sourceW, j == (vc - 1) ? tailHeight : sourceH);
drawRect.x /= _textureScale.x;
drawRect.y /= _textureScale.y;
drawRect.width /= _textureScale.x;
drawRect.height /= _textureScale.y;
vb.AddQuad(drawRect, vb.vertexColor, uvTmp);
}
}
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 948ec8822e3c52942bc6e7f6265b264c
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,243 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace FairyGUI
{
[Flags]
public enum MaterialFlags
{
Clipped = 1,
SoftClipped = 2,
StencilTest = 4,
AlphaMask = 8,
Grayed = 16,
ColorFilter = 32
}
/// <summary>
/// Every texture-shader combination has a MaterialManager.
/// </summary>
public class MaterialManager
{
public event Action<Material> onCreateNewMaterial;
public bool firstMaterialInFrame;
NTexture _texture;
Shader _shader;
List<string> _addKeywords;
Dictionary<int, List<MaterialRef>> _materials;
bool _combineTexture;
class MaterialRef
{
public Material material;
public int frame;
public BlendMode blendMode;
public uint group;
}
const int internalKeywordsCount = 6;
static string[] internalKeywords = new[] { "CLIPPED", "SOFT_CLIPPED", null, "ALPHA_MASK", "GRAYED", "COLOR_FILTER" };
/// <summary>
///
/// </summary>
/// <param name="texture"></param>
/// <param name="shader"></param>
internal MaterialManager(NTexture texture, Shader shader)
{
_texture = texture;
_shader = shader;
_materials = new Dictionary<int, List<MaterialRef>>();
_combineTexture = texture.alphaTexture != null;
}
/// <summary>
///
/// </summary>
/// <param name="keywords"></param>
/// <returns></returns>
public int GetFlagsByKeywords(IList<string> keywords)
{
if (_addKeywords == null)
_addKeywords = new List<string>();
int flags = 0;
for (int i = 0; i < keywords.Count; i++)
{
string s = keywords[i];
if (string.IsNullOrEmpty(s))
continue;
int j = _addKeywords.IndexOf(s);
if (j == -1)
{
j = _addKeywords.Count;
_addKeywords.Add(s);
}
flags += (1 << (j + internalKeywordsCount));
}
return flags;
}
/// <summary>
///
/// </summary>
/// <param name="flags"></param>
/// <param name="blendMode"></param>
/// <param name="group"></param>
/// <returns></returns>
public Material GetMaterial(int flags, BlendMode blendMode, uint group)
{
if (blendMode != BlendMode.Normal && BlendModeUtils.Factors[(int)blendMode].pma)
flags |= (int)MaterialFlags.ColorFilter;
List<MaterialRef> items;
if (!_materials.TryGetValue(flags, out items))
{
items = new List<MaterialRef>();
_materials[flags] = items;
}
int frameId = Time.frameCount;
int cnt = items.Count;
MaterialRef result = null;
for (int i = 0; i < cnt; i++)
{
MaterialRef item = items[i];
if (item.group == group && item.blendMode == blendMode)
{
if (item.frame != frameId)
{
firstMaterialInFrame = true;
item.frame = frameId;
}
else
firstMaterialInFrame = false;
if (_combineTexture)
item.material.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture);
return item.material;
}
else if (result == null && (item.frame > frameId || item.frame < frameId - 1)) //collect materials if it is unused in last frame
result = item;
}
if (result == null)
{
result = new MaterialRef() { material = CreateMaterial(flags) };
items.Add(result);
}
else if (_combineTexture)
result.material.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture);
if (result.blendMode != blendMode)
{
BlendModeUtils.Apply(result.material, blendMode);
result.blendMode = blendMode;
}
result.group = group;
result.frame = frameId;
firstMaterialInFrame = true;
return result.material;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
Material CreateMaterial(int flags)
{
Material mat = new Material(_shader);
mat.mainTexture = _texture.nativeTexture;
if (_texture.alphaTexture != null)
{
mat.EnableKeyword("COMBINED");
mat.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture);
}
for (int i = 0; i < internalKeywordsCount; i++)
{
if ((flags & (1 << i)) != 0)
{
string s = internalKeywords[i];
if (s != null)
mat.EnableKeyword(s);
}
}
if (_addKeywords != null)
{
int keywordCnt = _addKeywords.Count;
for (int i = 0; i < keywordCnt; i++)
{
if ((flags & (1 << (i + internalKeywordsCount))) != 0)
mat.EnableKeyword(_addKeywords[i]);
}
}
mat.hideFlags = DisplayObject.hideFlags;
if (onCreateNewMaterial != null)
onCreateNewMaterial(mat);
return mat;
}
/// <summary>
///
/// </summary>
public void DestroyMaterials()
{
var iter = _materials.GetEnumerator();
while (iter.MoveNext())
{
List<MaterialRef> items = iter.Current.Value;
if (Application.isPlaying)
{
int cnt = items.Count;
for (int j = 0; j < cnt; j++)
Object.Destroy(items[j].material);
}
else
{
int cnt = items.Count;
for (int j = 0; j < cnt; j++)
Object.DestroyImmediate(items[j].material);
}
items.Clear();
}
iter.Dispose();
}
/// <summary>
///
/// </summary>
public void RefreshMaterials()
{
_combineTexture = _texture.alphaTexture != null;
var iter = _materials.GetEnumerator();
while (iter.MoveNext())
{
List<MaterialRef> items = iter.Current.Value;
int cnt = items.Count;
for (int j = 0; j < cnt; j++)
{
Material mat = items[j].material;
mat.mainTexture = _texture.nativeTexture;
if (_combineTexture)
{
mat.EnableKeyword("COMBINED");
mat.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture);
}
}
}
iter.Dispose();
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 7223c4628e56c1e448c70e10168f5fa1
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: fca659474d209d94fbded309f407995c
folderAsset: yes
timeCreated: 1545987172
licenseType: Store
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,75 @@
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class CompositeMesh : IMeshFactory, IHitTest
{
/// <summary>
///
/// </summary>
public readonly List<IMeshFactory> elements;
/// <summary>
/// If it is -1, means all elements are active, otherwise, only the specific element is active
/// </summary>
public int activeIndex;
public CompositeMesh()
{
elements = new List<IMeshFactory>();
activeIndex = -1;
}
public void OnPopulateMesh(VertexBuffer vb)
{
int cnt = elements.Count;
if (cnt == 1)
elements[0].OnPopulateMesh(vb);
else
{
VertexBuffer vb2 = VertexBuffer.Begin(vb);
for (int i = 0; i < cnt; i++)
{
if (activeIndex == -1 || i == activeIndex)
{
vb2.Clear();
elements[i].OnPopulateMesh(vb2);
vb.Append(vb2);
}
}
vb2.End();
}
}
public bool HitTest(Rect contentRect, Vector2 point)
{
if (!contentRect.Contains(point))
return false;
bool flag = false;
int cnt = elements.Count;
for (int i = 0; i < cnt; i++)
{
if (activeIndex == -1 || i == activeIndex)
{
IHitTest ht = elements[i] as IHitTest;
if (ht != null)
{
if (ht.HitTest(contentRect, point))
return true;
}
else
flag = true;
}
}
return flag;
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: ba3d921c1f6e95f4e9105f45fd67bda5
timeCreated: 1546159121
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,200 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class EllipseMesh : IMeshFactory, IHitTest
{
/// <summary>
///
/// </summary>
public Rect? drawRect;
/// <summary>
///
/// </summary>
public float lineWidth;
/// <summary>
///
/// </summary>
public Color32 lineColor;
/// <summary>
///
/// </summary>
public Color32? centerColor;
/// <summary>
///
/// </summary>
public Color32? fillColor;
/// <summary>
///
/// </summary>
public float startDegree;
/// <summary>
///
/// </summary>
public float endDegreee;
static int[] SECTOR_CENTER_TRIANGLES = new int[] {
0, 4, 1,
0, 3, 4,
0, 2, 3,
0, 8, 5,
0, 7, 8,
0, 6, 7,
6, 5, 2,
2, 1, 6
};
public EllipseMesh()
{
lineColor = Color.black;
startDegree = 0;
endDegreee = 360;
}
public void OnPopulateMesh(VertexBuffer vb)
{
Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect;
Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor;
float sectionStart = Mathf.Clamp(startDegree, 0, 360);
float sectionEnd = Mathf.Clamp(endDegreee, 0, 360);
bool clipped = sectionStart > 0 || sectionEnd < 360;
sectionStart = sectionStart * Mathf.Deg2Rad;
sectionEnd = sectionEnd * Mathf.Deg2Rad;
Color32 centerColor2 = centerColor == null ? color : (Color32)centerColor;
float radiusX = rect.width / 2;
float radiusY = rect.height / 2;
int sides = Mathf.CeilToInt(Mathf.PI * (radiusX + radiusY) / 4);
sides = Mathf.Clamp(sides, 40, 800);
float angleDelta = 2 * Mathf.PI / sides;
float angle = 0;
float lineAngle = 0;
if (lineWidth > 0 && clipped)
{
lineAngle = lineWidth / Mathf.Max(radiusX, radiusY);
sectionStart += lineAngle;
sectionEnd -= lineAngle;
}
int vpos = vb.currentVertCount;
float centerX = rect.x + radiusX;
float centerY = rect.y + radiusY;
vb.AddVert(new Vector3(centerX, centerY, 0), centerColor2);
for (int i = 0; i < sides; i++)
{
if (angle < sectionStart)
angle = sectionStart;
else if (angle > sectionEnd)
angle = sectionEnd;
Vector3 vec = new Vector3(Mathf.Cos(angle) * (radiusX - lineWidth) + centerX, Mathf.Sin(angle) * (radiusY - lineWidth) + centerY, 0);
vb.AddVert(vec, color);
if (lineWidth > 0)
{
vb.AddVert(vec, lineColor);
vb.AddVert(new Vector3(Mathf.Cos(angle) * radiusX + centerX, Mathf.Sin(angle) * radiusY + centerY, 0), lineColor);
}
angle += angleDelta;
}
if (lineWidth > 0)
{
int cnt = sides * 3;
for (int i = 0; i < cnt; i += 3)
{
if (i != cnt - 3)
{
vb.AddTriangle(0, i + 1, i + 4);
vb.AddTriangle(i + 5, i + 2, i + 3);
vb.AddTriangle(i + 3, i + 6, i + 5);
}
else if (!clipped)
{
vb.AddTriangle(0, i + 1, 1);
vb.AddTriangle(2, i + 2, i + 3);
vb.AddTriangle(i + 3, 3, 2);
}
else
{
vb.AddTriangle(0, i + 1, i + 1);
vb.AddTriangle(i + 2, i + 2, i + 3);
vb.AddTriangle(i + 3, i + 3, i + 2);
}
}
}
else
{
for (int i = 0; i < sides; i++)
{
if (i != sides - 1)
vb.AddTriangle(0, i + 1, i + 2);
else if (!clipped)
vb.AddTriangle(0, i + 1, 1);
else
vb.AddTriangle(0, i + 1, i + 1);
}
}
if (lineWidth > 0 && clipped)
{
//扇形内边缘的线条
vb.AddVert(new Vector3(radiusX, radiusY, 0), lineColor);
float centerRadius = lineWidth * 0.5f;
sectionStart -= lineAngle;
angle = sectionStart + lineAngle * 0.5f + Mathf.PI * 0.5f;
vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor);
angle -= Mathf.PI;
vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor);
vb.AddVert(new Vector3(Mathf.Cos(sectionStart) * radiusX + radiusX, Mathf.Sin(sectionStart) * radiusY + radiusY, 0), lineColor);
vb.AddVert(vb.GetPosition(vpos + 3), lineColor);
sectionEnd += lineAngle;
angle = sectionEnd - lineAngle * 0.5f + Mathf.PI * 0.5f;
vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor);
angle -= Mathf.PI;
vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor);
vb.AddVert(vb.GetPosition(vpos + sides * 3), lineColor);
vb.AddVert(new Vector3(Mathf.Cos(sectionEnd) * radiusX + radiusX, Mathf.Sin(sectionEnd) * radiusY + radiusY, 0), lineColor);
vb.AddTriangles(SECTOR_CENTER_TRIANGLES, sides * 3 + 1);
}
}
public bool HitTest(Rect contentRect, Vector2 point)
{
if (!contentRect.Contains(point))
return false;
float radiusX = contentRect.width * 0.5f;
float raduisY = contentRect.height * 0.5f;
float xx = point.x - radiusX - contentRect.x;
float yy = point.y - raduisY - contentRect.y;
if (Mathf.Pow(xx / radiusX, 2) + Mathf.Pow(yy / raduisY, 2) < 1)
{
if (startDegree != 0 || endDegreee != 360)
{
float deg = Mathf.Atan2(yy, xx) * Mathf.Rad2Deg;
if (deg < 0)
deg += 360;
return deg >= startDegree && deg <= endDegreee;
}
else
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 7ea96854995120948847301fb48d1675
timeCreated: 1545987173
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,400 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class FillMesh : IMeshFactory
{
/// <summary>
///
/// </summary>
public FillMethod method;
/// <summary>
///
/// </summary>
public int origin;
/// <summary>
///
/// </summary>
public float amount;
/// <summary>
///
/// </summary>
public bool clockwise;
public FillMesh()
{
clockwise = true;
amount = 1;
}
public void OnPopulateMesh(VertexBuffer vb)
{
float amount = Mathf.Clamp01(this.amount);
switch (method)
{
case FillMethod.Horizontal:
FillHorizontal(vb, vb.contentRect, origin, amount);
break;
case FillMethod.Vertical:
FillVertical(vb, vb.contentRect, origin, amount);
break;
case FillMethod.Radial90:
FillRadial90(vb, vb.contentRect, (Origin90)origin, amount, clockwise);
break;
case FillMethod.Radial180:
FillRadial180(vb, vb.contentRect, (Origin180)origin, amount, clockwise);
break;
case FillMethod.Radial360:
FillRadial360(vb, vb.contentRect, (Origin360)origin, amount, clockwise);
break;
}
}
static void FillHorizontal(VertexBuffer vb, Rect vertRect, int origin, float amount)
{
float a = vertRect.width * amount;
if ((OriginHorizontal)origin == OriginHorizontal.Right || (OriginVertical)origin == OriginVertical.Bottom)
vertRect.x += (vertRect.width - a);
vertRect.width = a;
vb.AddQuad(vertRect);
vb.AddTriangles();
}
static void FillVertical(VertexBuffer vb, Rect vertRect, int origin, float amount)
{
float a = vertRect.height * amount;
if ((OriginHorizontal)origin == OriginHorizontal.Right || (OriginVertical)origin == OriginVertical.Bottom)
vertRect.y += (vertRect.height - a);
vertRect.height = a;
vb.AddQuad(vertRect);
vb.AddTriangles();
}
//4 vertex
static void FillRadial90(VertexBuffer vb, Rect vertRect, Origin90 origin, float amount, bool clockwise)
{
bool flipX = origin == Origin90.TopRight || origin == Origin90.BottomRight;
bool flipY = origin == Origin90.BottomLeft || origin == Origin90.BottomRight;
if (flipX != flipY)
clockwise = !clockwise;
float ratio = clockwise ? amount : (1 - amount);
float tan = Mathf.Tan(Mathf.PI * 0.5f * ratio);
bool thresold = false;
if (ratio != 1)
thresold = (vertRect.height / vertRect.width - tan) > 0;
if (!clockwise)
thresold = !thresold;
float x = vertRect.x + (ratio == 0 ? float.MaxValue : (vertRect.height / tan));
float y = vertRect.y + (ratio == 1 ? float.MaxValue : (vertRect.width * tan));
float x2 = x;
float y2 = y;
if (flipX)
x2 = vertRect.width - x;
if (flipY)
y2 = vertRect.height - y;
float xMin = flipX ? (vertRect.width - vertRect.x) : vertRect.xMin;
float yMin = flipY ? (vertRect.height - vertRect.y) : vertRect.yMin;
float xMax = flipX ? -vertRect.xMin : vertRect.xMax;
float yMax = flipY ? -vertRect.yMin : vertRect.yMax;
vb.AddVert(new Vector3(xMin, yMin, 0));
if (clockwise)
vb.AddVert(new Vector3(xMax, yMin, 0));
if (y > vertRect.yMax)
{
if (thresold)
vb.AddVert(new Vector3(x2, yMax, 0));
else
vb.AddVert(new Vector3(xMax, yMax, 0));
}
else
vb.AddVert(new Vector3(xMax, y2, 0));
if (x > vertRect.xMax)
{
if (thresold)
vb.AddVert(new Vector3(xMax, y2, 0));
else
vb.AddVert(new Vector3(xMax, yMax, 0));
}
else
vb.AddVert(new Vector3(x2, yMax, 0));
if (!clockwise)
vb.AddVert(new Vector3(xMin, yMax, 0));
if (flipX == flipY)
{
vb.AddTriangle(0, 1, 2);
vb.AddTriangle(0, 2, 3);
}
else
{
vb.AddTriangle(2, 1, 0);
vb.AddTriangle(3, 2, 0);
}
}
//8 vertex
static void FillRadial180(VertexBuffer vb, Rect vertRect, Origin180 origin, float amount, bool clockwise)
{
switch (origin)
{
case Origin180.Top:
if (amount <= 0.5f)
{
vertRect.width /= 2;
if (clockwise)
vertRect.x += vertRect.width;
FillRadial90(vb, vertRect, clockwise ? Origin90.TopLeft : Origin90.TopRight, amount / 0.5f, clockwise);
Vector3 vec = vb.GetPosition(-4);
vb.AddQuad(new Rect(vec.x, vec.y, 0, 0));
vb.AddTriangles(-4);
}
else
{
vertRect.width /= 2;
if (!clockwise)
vertRect.x += vertRect.width;
FillRadial90(vb, vertRect, clockwise ? Origin90.TopRight : Origin90.TopLeft, (amount - 0.5f) / 0.5f, clockwise);
if (clockwise)
vertRect.x += vertRect.width;
else
vertRect.x -= vertRect.width;
vb.AddQuad(vertRect);
vb.AddTriangles(-4);
}
break;
case Origin180.Bottom:
if (amount <= 0.5f)
{
vertRect.width /= 2;
if (!clockwise)
vertRect.x += vertRect.width;
FillRadial90(vb, vertRect, clockwise ? Origin90.BottomRight : Origin90.BottomLeft, amount / 0.5f, clockwise);
Vector3 vec = vb.GetPosition(-4);
vb.AddQuad(new Rect(vec.x, vec.y, 0, 0));
vb.AddTriangles(-4);
}
else
{
vertRect.width /= 2;
if (clockwise)
vertRect.x += vertRect.width;
FillRadial90(vb, vertRect, clockwise ? Origin90.BottomLeft : Origin90.BottomRight, (amount - 0.5f) / 0.5f, clockwise);
if (clockwise)
vertRect.x -= vertRect.width;
else
vertRect.x += vertRect.width;
vb.AddQuad(vertRect);
vb.AddTriangles(-4);
}
break;
case Origin180.Left:
if (amount <= 0.5f)
{
vertRect.height /= 2;
if (!clockwise)
vertRect.y += vertRect.height;
FillRadial90(vb, vertRect, clockwise ? Origin90.BottomLeft : Origin90.TopLeft, amount / 0.5f, clockwise);
Vector3 vec = vb.GetPosition(-4);
vb.AddQuad(new Rect(vec.x, vec.y, 0, 0));
vb.AddTriangles(-4);
}
else
{
vertRect.height /= 2;
if (clockwise)
vertRect.y += vertRect.height;
FillRadial90(vb, vertRect, clockwise ? Origin90.TopLeft : Origin90.BottomLeft, (amount - 0.5f) / 0.5f, clockwise);
if (clockwise)
vertRect.y -= vertRect.height;
else
vertRect.y += vertRect.height;
vb.AddQuad(vertRect);
vb.AddTriangles(-4);
}
break;
case Origin180.Right:
if (amount <= 0.5f)
{
vertRect.height /= 2;
if (clockwise)
vertRect.y += vertRect.height;
FillRadial90(vb, vertRect, clockwise ? Origin90.TopRight : Origin90.BottomRight, amount / 0.5f, clockwise);
Vector3 vec = vb.GetPosition(-4);
vb.AddQuad(new Rect(vec.x, vec.y, 0, 0));
vb.AddTriangles(-4);
}
else
{
vertRect.height /= 2;
if (!clockwise)
vertRect.y += vertRect.height;
FillRadial90(vb, vertRect, clockwise ? Origin90.BottomRight : Origin90.TopRight, (amount - 0.5f) / 0.5f, clockwise);
if (clockwise)
vertRect.y += vertRect.height;
else
vertRect.y -= vertRect.height;
vb.AddQuad(vertRect);
vb.AddTriangles(-4);
}
break;
}
}
//12 vertex
static void FillRadial360(VertexBuffer vb, Rect vertRect, Origin360 origin, float amount, bool clockwise)
{
switch (origin)
{
case Origin360.Top:
if (amount < 0.5f)
{
vertRect.width /= 2;
if (clockwise)
vertRect.x += vertRect.width;
FillRadial180(vb, vertRect, clockwise ? Origin180.Left : Origin180.Right, amount / 0.5f, clockwise);
Vector3 vec = vb.GetPosition(-8);
vb.AddQuad(new Rect(vec.x, vec.y, 0, 0));
vb.AddTriangles(-4);
}
else
{
vertRect.width /= 2;
if (!clockwise)
vertRect.x += vertRect.width;
FillRadial180(vb, vertRect, clockwise ? Origin180.Right : Origin180.Left, (amount - 0.5f) / 0.5f, clockwise);
if (clockwise)
vertRect.x += vertRect.width;
else
vertRect.x -= vertRect.width;
vb.AddQuad(vertRect);
vb.AddTriangles(-4);
}
break;
case Origin360.Bottom:
if (amount < 0.5f)
{
vertRect.width /= 2;
if (!clockwise)
vertRect.x += vertRect.width;
FillRadial180(vb, vertRect, clockwise ? Origin180.Right : Origin180.Left, amount / 0.5f, clockwise);
Vector3 vec = vb.GetPosition(-8);
vb.AddQuad(new Rect(vec.x, vec.y, 0, 0));
vb.AddTriangles(-4);
}
else
{
vertRect.width /= 2;
if (clockwise)
vertRect.x += vertRect.width;
FillRadial180(vb, vertRect, clockwise ? Origin180.Left : Origin180.Right, (amount - 0.5f) / 0.5f, clockwise);
if (clockwise)
vertRect.x -= vertRect.width;
else
vertRect.x += vertRect.width;
vb.AddQuad(vertRect);
vb.AddTriangles(-4);
}
break;
case Origin360.Left:
if (amount < 0.5f)
{
vertRect.height /= 2;
if (!clockwise)
vertRect.y += vertRect.height;
FillRadial180(vb, vertRect, clockwise ? Origin180.Bottom : Origin180.Top, amount / 0.5f, clockwise);
Vector3 vec = vb.GetPosition(-8);
vb.AddQuad(new Rect(vec.x, vec.y, 0, 0));
vb.AddTriangles(-4);
}
else
{
vertRect.height /= 2;
if (clockwise)
vertRect.y += vertRect.height;
FillRadial180(vb, vertRect, clockwise ? Origin180.Top : Origin180.Bottom, (amount - 0.5f) / 0.5f, clockwise);
if (clockwise)
vertRect.y -= vertRect.height;
else
vertRect.y += vertRect.height;
vb.AddQuad(vertRect);
vb.AddTriangles(-4);
}
break;
case Origin360.Right:
if (amount < 0.5f)
{
vertRect.height /= 2;
if (clockwise)
vertRect.y += vertRect.height;
FillRadial180(vb, vertRect, clockwise ? Origin180.Top : Origin180.Bottom, amount / 0.5f, clockwise);
Vector3 vec = vb.GetPosition(-8);
vb.AddQuad(new Rect(vec.x, vec.y, 0, 0));
vb.AddTriangles(-4);
}
else
{
vertRect.height /= 2;
if (!clockwise)
vertRect.y += vertRect.height;
FillRadial180(vb, vertRect, clockwise ? Origin180.Bottom : Origin180.Top, (amount - 0.5f) / 0.5f, clockwise);
if (clockwise)
vertRect.y += vertRect.height;
else
vertRect.y -= vertRect.height;
vb.AddQuad(vertRect);
vb.AddTriangles(-4);
}
break;
}
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 8b37d56dc1840734a8fdb4971f5bc733
timeCreated: 1545987173
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,179 @@
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// Inspired by kim ki won (http://mypi.ruliweb.daum.net/mypi.htm?id=newtypekorea)
/// </summary>
public class LineMesh : IMeshFactory
{
/// <summary>
///
/// </summary>
public GPath path;
/// <summary>
///
/// </summary>
public float lineWidth;
/// <summary>
///
/// </summary>
public AnimationCurve lineWidthCurve;
/// <summary>
///
/// </summary>
public Gradient gradient;
/// <summary>
///
/// </summary>
public bool roundEdge;
/// <summary>
///
/// </summary>
public float fillStart;
/// <summary>
///
/// </summary>
public float fillEnd;
/// <summary>
///
/// </summary>
public float pointDensity;
/// <summary>
///
/// </summary>
public bool repeatFill;
static List<Vector3> points = new List<Vector3>();
static List<float> ts = new List<float>();
public LineMesh()
{
path = new GPath();
lineWidth = 2;
fillStart = 0;
fillEnd = 1;
pointDensity = 0.1f;
}
public void OnPopulateMesh(VertexBuffer vb)
{
Vector2 uvMin = vb.uvRect.position;
Vector2 uvMax = new Vector2(vb.uvRect.xMax, vb.uvRect.yMax);
float uvRatio = path.length / vb.textureSize.x;
int segCount = path.segmentCount;
float t = 0;
float lw = lineWidth;
float u;
for (int si = 0; si < segCount; si++)
{
float ratio = path.GetSegmentLength(si) / path.length;
float t0 = Mathf.Clamp(fillStart - t, 0, ratio) / ratio;
float t1 = Mathf.Clamp(fillEnd - t, 0, ratio) / ratio;
if (t0 >= t1)
{
t += ratio;
continue;
}
points.Clear();
ts.Clear();
path.GetPointsInSegment(si, t0, t1, points, ts, pointDensity);
int cnt = points.Count;
Color c0 = vb.vertexColor;
Color c1 = vb.vertexColor;
if (gradient != null)
c0 = gradient.Evaluate(t);
if (lineWidthCurve != null)
lw = lineWidthCurve.Evaluate(t);
if (roundEdge && si == 0 && t0 == 0)
DrawRoundEdge(vb, points[0], points[1], lw, c0, uvMin);
int vertCount = vb.currentVertCount;
for (int i = 1; i < cnt; i++)
{
Vector3 p0 = points[i - 1];
Vector3 p1 = points[i];
int k = vertCount + (i - 1) * 2;
float tc = t + ratio * ts[i];
Vector3 lineVector = p1 - p0;
Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1));
widthVector.Normalize();
if (i == 1)
{
if (repeatFill)
u = tc * uvRatio * uvMax.x;
else
u = Mathf.Lerp(uvMin.x, uvMax.x, t + ratio * ts[i - 1]);
vb.AddVert(p0 - widthVector * lw * 0.5f, c0, new Vector2(u, uvMax.y));
vb.AddVert(p0 + widthVector * lw * 0.5f, c0, new Vector2(u, uvMin.y));
if (si != 0) //joint
{
vb.AddTriangle(k - 2, k - 1, k + 1);
vb.AddTriangle(k - 2, k + 1, k);
}
}
if (gradient != null)
c1 = gradient.Evaluate(tc);
if (lineWidthCurve != null)
lw = lineWidthCurve.Evaluate(tc);
if (repeatFill)
u = tc * uvRatio * uvMax.x;
else
u = Mathf.Lerp(uvMin.x, uvMax.x, tc);
vb.AddVert(p1 - widthVector * lw * 0.5f, c1, new Vector2(u, uvMax.y));
vb.AddVert(p1 + widthVector * lw * 0.5f, c1, new Vector2(u, uvMin.y));
vb.AddTriangle(k, k + 1, k + 3);
vb.AddTriangle(k, k + 3, k + 2);
}
if (roundEdge && si == segCount - 1 && t1 == 1)
DrawRoundEdge(vb, points[cnt - 1], points[cnt - 2], lw, c1, uvMax);
t += ratio;
}
}
void DrawRoundEdge(VertexBuffer vb, Vector2 p0, Vector2 p1, float lw, Color32 color, Vector2 uv)
{
Vector2 widthVector = Vector3.Cross(p0 - p1, new Vector3(0, 0, 1));
widthVector.Normalize();
widthVector = widthVector * lw / 2f;
Vector2 lineVector = (p0 - p1).normalized * lw / 2f;
int sides = Mathf.CeilToInt(Mathf.PI * lw / 2);
if (sides < 6)
sides = 6;
int current = vb.currentVertCount;
float angleUnit = Mathf.PI / (sides - 1);
vb.AddVert(p0, color, uv);
vb.AddVert(p0 + widthVector, color, uv);
for (int n = 0; n < sides; n++)
{
vb.AddVert(p0 + Mathf.Cos(angleUnit * n) * widthVector + Mathf.Sin(angleUnit * n) * lineVector, color, uv);
vb.AddTriangle(current, current + 1 + n, current + 2 + n);
}
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 6d1935a924fabf74a92c72b22a042279
timeCreated: 1546519483
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,15 @@

namespace FairyGUI
{
/// <summary>
///
/// </summary>
public interface IMeshFactory
{
/// <summary>
///
/// </summary>
/// <param name="vb"></param>
void OnPopulateMesh(VertexBuffer vb);
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 274275eaa3fbbc94697cbe90a0fb52f1
timeCreated: 1545987172
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,51 @@
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class PlaneMesh : IMeshFactory
{
public int gridSize = 30;
public void OnPopulateMesh(VertexBuffer vb)
{
float w = vb.contentRect.width;
float h = vb.contentRect.height;
float xMax = vb.contentRect.xMax;
float yMax = vb.contentRect.yMax;
int hc = (int)Mathf.Min(Mathf.CeilToInt(w / gridSize), 9);
int vc = (int)Mathf.Min(Mathf.CeilToInt(h / gridSize), 9);
int eachPartX = Mathf.FloorToInt(w / hc);
int eachPartY = Mathf.FloorToInt(h / vc);
float x, y;
for (int i = 0; i <= vc; i++)
{
if (i == vc)
y = yMax;
else
y = vb.contentRect.y + i * eachPartY;
for (int j = 0; j <= hc; j++)
{
if (j == hc)
x = xMax;
else
x = vb.contentRect.x + j * eachPartX;
vb.AddVert(new Vector3(x, y, 0));
}
}
for (int i = 0; i < vc; i++)
{
int k = i * (hc + 1);
for (int j = 1; j <= hc; j++)
{
int m = k + j;
vb.AddTriangle(m - 1, m, m + hc);
vb.AddTriangle(m, m + hc + 1, m + hc);
}
}
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 121b756a7a8240c49b63fa9de560691a
timeCreated: 1547970144
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,291 @@
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class PolygonMesh : IMeshFactory, IHitTest
{
/// <summary>
/// points must be in clockwise order, and must start from bottom-left if stretchUV is set.
/// </summary>
public readonly List<Vector2> points;
/// <summary>
/// if you dont want to provide uv, leave it empty.
/// </summary>
public readonly List<Vector2> texcoords;
/// <summary>
///
/// </summary>
public float lineWidth;
/// <summary>
///
/// </summary>
public Color32 lineColor;
/// <summary>
///
/// </summary>
public Color32? fillColor;
/// <summary>
///
/// </summary>
public Color32[] colors;
/// <summary>
///
/// </summary>
public bool usePercentPositions;
static List<int> sRestIndices = new List<int>();
public PolygonMesh()
{
points = new List<Vector2>();
texcoords = new List<Vector2>();
}
/// <summary>
///
/// </summary>
/// <param name="point"></param>
public void Add(Vector2 point)
{
points.Add(point);
}
/// <summary>
///
/// </summary>
/// <param name="point"></param>
/// <param name="texcoord"></param>
public void Add(Vector2 point, Vector2 texcoord)
{
points.Add(point);
texcoords.Add(texcoord);
}
public void OnPopulateMesh(VertexBuffer vb)
{
int numVertices = points.Count;
if (numVertices < 3)
return;
int restIndexPos, numRestIndices;
Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor;
float w = vb.contentRect.width;
float h = vb.contentRect.height;
bool useTexcoords = texcoords.Count >= numVertices;
bool fullUV = true;
for (int i = 0; i < numVertices; i++)
{
Vector3 vec = new Vector3(points[i].x, points[i].y, 0);
if (usePercentPositions)
{
vec.x *= w;
vec.y *= h;
}
if (useTexcoords)
{
Vector2 uv = texcoords[i];
if (uv.x != 0 && uv.x != 1 || uv.y != 0 && uv.y != 1)
fullUV = false;
uv.x = Mathf.Lerp(vb.uvRect.x, vb.uvRect.xMax, uv.x);
uv.y = Mathf.Lerp(vb.uvRect.y, vb.uvRect.yMax, uv.y);
vb.AddVert(vec, color, uv);
}
else
vb.AddVert(vec, color);
}
if (useTexcoords && fullUV && numVertices == 4)
vb._isArbitraryQuad = true;
// Algorithm "Ear clipping method" described here:
// -> https://en.wikipedia.org/wiki/Polygon_triangulation
//
// Implementation inspired by:
// -> http://polyk.ivank.net
// -> Starling
sRestIndices.Clear();
for (int i = 0; i < numVertices; ++i)
sRestIndices.Add(i);
restIndexPos = 0;
numRestIndices = numVertices;
Vector2 a, b, c, p;
int otherIndex;
bool earFound;
int i0, i1, i2;
while (numRestIndices > 3)
{
earFound = false;
i0 = sRestIndices[restIndexPos % numRestIndices];
i1 = sRestIndices[(restIndexPos + 1) % numRestIndices];
i2 = sRestIndices[(restIndexPos + 2) % numRestIndices];
a = points[i0];
b = points[i1];
c = points[i2];
if ((a.y - b.y) * (c.x - b.x) + (b.x - a.x) * (c.y - b.y) >= 0)
{
earFound = true;
for (int i = 3; i < numRestIndices; ++i)
{
otherIndex = sRestIndices[(restIndexPos + i) % numRestIndices];
p = points[otherIndex];
if (IsPointInTriangle(ref p, ref a, ref b, ref c))
{
earFound = false;
break;
}
}
}
if (earFound)
{
vb.AddTriangle(i0, i1, i2);
sRestIndices.RemoveAt((restIndexPos + 1) % numRestIndices);
numRestIndices--;
restIndexPos = 0;
}
else
{
restIndexPos++;
if (restIndexPos == numRestIndices) break; // no more ears
}
}
vb.AddTriangle(sRestIndices[0], sRestIndices[1], sRestIndices[2]);
if (colors != null)
vb.RepeatColors(colors, 0, vb.currentVertCount);
if (lineWidth > 0)
DrawOutline(vb);
}
void DrawOutline(VertexBuffer vb)
{
int numVertices = points.Count;
int start = vb.currentVertCount - numVertices;
int k = vb.currentVertCount;
for (int i = 0; i < numVertices; i++)
{
Vector3 p0 = vb.vertices[start + i];
p0.y = -p0.y;
Vector3 p1;
if (i < numVertices - 1)
p1 = vb.vertices[start + i + 1];
else
p1 = vb.vertices[start];
p1.y = -p1.y;
Vector3 lineVector = p1 - p0;
Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1));
widthVector.Normalize();
vb.AddVert(p0 - widthVector * lineWidth * 0.5f, lineColor);
vb.AddVert(p0 + widthVector * lineWidth * 0.5f, lineColor);
vb.AddVert(p1 - widthVector * lineWidth * 0.5f, lineColor);
vb.AddVert(p1 + widthVector * lineWidth * 0.5f, lineColor);
k += 4;
vb.AddTriangle(k - 4, k - 3, k - 1);
vb.AddTriangle(k - 4, k - 1, k - 2);
//joint
if (i != 0)
{
vb.AddTriangle(k - 6, k - 5, k - 3);
vb.AddTriangle(k - 6, k - 3, k - 4);
}
if (i == numVertices - 1)
{
start += numVertices;
vb.AddTriangle(k - 2, k - 1, start + 1);
vb.AddTriangle(k - 2, start + 1, start);
}
}
}
bool IsPointInTriangle(ref Vector2 p, ref Vector2 a, ref Vector2 b, ref Vector2 c)
{
// From Starling
// This algorithm is described well in this article:
// http://www.blackpawn.com/texts/pointinpoly/default.html
float v0x = c.x - a.x;
float v0y = c.y - a.y;
float v1x = b.x - a.x;
float v1y = b.y - a.y;
float v2x = p.x - a.x;
float v2y = p.y - a.y;
float dot00 = v0x * v0x + v0y * v0y;
float dot01 = v0x * v1x + v0y * v1y;
float dot02 = v0x * v2x + v0y * v2y;
float dot11 = v1x * v1x + v1y * v1y;
float dot12 = v1x * v2x + v1y * v2y;
float invDen = 1.0f / (dot00 * dot11 - dot01 * dot01);
float u = (dot11 * dot02 - dot01 * dot12) * invDen;
float v = (dot00 * dot12 - dot01 * dot02) * invDen;
return (u >= 0) && (v >= 0) && (u + v < 1);
}
public bool HitTest(Rect contentRect, Vector2 point)
{
if (!contentRect.Contains(point))
return false;
// Algorithm & implementation thankfully taken from:
// -> http://alienryderflex.com/polygon/
// inspired by Starling
int len = points.Count;
int i;
int j = len - 1;
bool oddNodes = false;
float w = contentRect.width;
float h = contentRect.height;
for (i = 0; i < len; ++i)
{
float ix = points[i].x;
float iy = points[i].y;
float jx = points[j].x;
float jy = points[j].y;
if (usePercentPositions)
{
ix *= w;
iy *= h;
ix *= w;
iy *= h;
}
if ((iy < point.y && jy >= point.y || jy < point.y && iy >= point.y) && (ix <= point.x || jx <= point.x))
{
if (ix + (point.y - iy) / (jy - iy) * (jx - ix) < point.x)
oddNodes = !oddNodes;
}
j = i;
}
return oddNodes;
}
}
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: db020628cd79e714fbafdbaaa2cc355f
timeCreated: 1545987173
licenseType: Store
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