diff --git a/.gitignore b/.gitignore
index 23fae005..7a44f0f7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -31,3 +31,4 @@ sysinfo.txt
*.apk
*.unitypackage
.DS_Store
+/.idea/
diff --git a/.vscode/launch.json b/.vscode/launch.json
deleted file mode 100644
index 4c1111c0..00000000
--- a/.vscode/launch.json
+++ /dev/null
@@ -1,39 +0,0 @@
-{
- // Use IntelliSense to learn about possible attributes.
- // Hover to view descriptions of existing attributes.
- // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
- "version": "0.2.0",
- "configurations": [
- {
- "name": "Unity Editor",
- "type": "unity",
- "path": "/Users/guzhu/Documents/FairyGUI-unity-git/Library/EditorInstance.json",
- "request": "launch"
- },
- {
- "name": "Windows Player",
- "type": "unity",
- "request": "launch"
- },
- {
- "name": "OSX Player",
- "type": "unity",
- "request": "launch"
- },
- {
- "name": "Linux Player",
- "type": "unity",
- "request": "launch"
- },
- {
- "name": "iOS Player",
- "type": "unity",
- "request": "launch"
- },
- {
- "name": "Android Player",
- "type": "unity",
- "request": "launch"
- }
- ]
-}
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
deleted file mode 100644
index 067df49d..00000000
--- a/.vscode/settings.json
+++ /dev/null
@@ -1,57 +0,0 @@
-{
- "files.exclude":
- {
- "**/.DS_Store":true,
- "**/.git":true,
- "**/.gitmodules":true,
- "**/*.booproj":true,
- "**/*.pidb":true,
- "**/*.suo":true,
- "**/*.user":true,
- "**/*.userprefs":true,
- "**/*.unityproj":true,
- "**/*.dll":true,
- "**/*.exe":true,
- "**/*.pdf":true,
- "**/*.mid":true,
- "**/*.midi":true,
- "**/*.wav":true,
- "**/*.gif":true,
- "**/*.ico":true,
- "**/*.jpg":true,
- "**/*.jpeg":true,
- "**/*.png":true,
- "**/*.psd":true,
- "**/*.tga":true,
- "**/*.tif":true,
- "**/*.tiff":true,
- "**/*.3ds":true,
- "**/*.3DS":true,
- "**/*.fbx":true,
- "**/*.FBX":true,
- "**/*.lxo":true,
- "**/*.LXO":true,
- "**/*.ma":true,
- "**/*.MA":true,
- "**/*.obj":true,
- "**/*.OBJ":true,
- "**/*.asset":true,
- "**/*.cubemap":true,
- "**/*.flare":true,
- "**/*.mat":true,
- "**/*.meta":true,
- "**/*.prefab":true,
- "**/*.unity":true,
- "build/":true,
- "Build/":true,
- "Library/":true,
- "library/":true,
- "obj/":true,
- "Obj/":true,
- "ProjectSettings/":true,
- "temp/":true,
- "Temp/":true,
- "Extensions/":true
- },
- "csharp.referencesCodeLens.enabled": false
-}
\ No newline at end of file
diff --git a/Assets/Examples/Bag/BagMain.cs b/Assets/Examples/Bag/BagMain.cs
index 7675052b..1f4d434b 100644
--- a/Assets/Examples/Bag/BagMain.cs
+++ b/Assets/Examples/Bag/BagMain.cs
@@ -1,36 +1,36 @@
-using UnityEngine;
-using FairyGUI;
-
-///
-/// A game bag demo, demonstrated how to customize loader to load icons not in the UI package.
-///
-public class BagMain : MonoBehaviour
-{
- GComponent _mainView;
- BagWindow _bagWindow;
-
- void Awake()
- {
- //Register custom loader class
- UIObjectFactory.SetLoaderExtension(typeof(MyGLoader));
- }
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
- GRoot.inst.SetContentScaleFactor(1136, 640);
- _mainView = this.GetComponent().ui;
-
- _bagWindow = new BagWindow();
- _mainView.GetChild("bagBtn").onClick.Add(() => { _bagWindow.Show(); });
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+///
+/// A game bag demo, demonstrated how to customize loader to load icons not in the UI package.
+///
+public class BagMain : MonoBehaviour
+{
+ GComponent _mainView;
+ BagWindow _bagWindow;
+
+ void Awake()
+ {
+ //Register custom loader class
+ UIObjectFactory.SetLoaderExtension(typeof(MyGLoader));
+ }
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+ GRoot.inst.SetContentScaleFactor(1136, 640);
+ _mainView = this.GetComponent().ui;
+
+ _bagWindow = new BagWindow();
+ _mainView.GetChild("bagBtn").onClick.Add(() => { _bagWindow.Show(); });
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Bag/BagWindow.cs b/Assets/Examples/Bag/BagWindow.cs
index 2cbccfd9..6b809f6f 100644
--- a/Assets/Examples/Bag/BagWindow.cs
+++ b/Assets/Examples/Bag/BagWindow.cs
@@ -1,49 +1,49 @@
-using FairyGUI;
-using UnityEngine;
-
-public class BagWindow : Window
-{
- GList _list;
-
- public BagWindow()
- {
- }
-
- protected override void OnInit()
- {
- this.contentPane = UIPackage.CreateObject("Bag", "BagWin").asCom;
- this.Center();
- this.modal = true;
-
- _list = this.contentPane.GetChild("list").asList;
- _list.onClickItem.Add(__clickItem);
- _list.itemRenderer = RenderListItem;
- _list.numItems = 45;
- }
-
- void RenderListItem(int index, GObject obj)
- {
- GButton button = (GButton)obj;
- button.icon = "i" + UnityEngine.Random.Range(0, 10);
- button.title = "" + UnityEngine.Random.Range(0, 100);
- }
-
- override protected void DoShowAnimation()
- {
- this.SetScale(0.1f, 0.1f);
- this.SetPivot(0.5f, 0.5f);
- this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown);
- }
-
- override protected void DoHideAnimation()
- {
- this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately);
- }
-
- void __clickItem(EventContext context)
- {
- GButton item = (GButton)context.data;
- this.contentPane.GetChild("n11").asLoader.url = item.icon;
- this.contentPane.GetChild("n13").text = item.icon;
- }
-}
+using FairyGUI;
+using UnityEngine;
+
+public class BagWindow : Window
+{
+ GList _list;
+
+ public BagWindow()
+ {
+ }
+
+ protected override void OnInit()
+ {
+ this.contentPane = UIPackage.CreateObject("Bag", "BagWin").asCom;
+ this.Center();
+ this.modal = true;
+
+ _list = this.contentPane.GetChild("list").asList;
+ _list.onClickItem.Add(__clickItem);
+ _list.itemRenderer = RenderListItem;
+ _list.numItems = 45;
+ }
+
+ void RenderListItem(int index, GObject obj)
+ {
+ GButton button = (GButton)obj;
+ button.icon = "i" + UnityEngine.Random.Range(0, 10);
+ button.title = "" + UnityEngine.Random.Range(0, 100);
+ }
+
+ override protected void DoShowAnimation()
+ {
+ this.SetScale(0.1f, 0.1f);
+ this.SetPivot(0.5f, 0.5f);
+ this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown);
+ }
+
+ override protected void DoHideAnimation()
+ {
+ this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately);
+ }
+
+ void __clickItem(EventContext context)
+ {
+ GButton item = (GButton)context.data;
+ this.contentPane.GetChild("n11").asLoader.url = item.icon;
+ this.contentPane.GetChild("n13").text = item.icon;
+ }
+}
diff --git a/Assets/Examples/Bag/IconManager.cs b/Assets/Examples/Bag/IconManager.cs
index 3c8816c8..4259ebf9 100644
--- a/Assets/Examples/Bag/IconManager.cs
+++ b/Assets/Examples/Bag/IconManager.cs
@@ -1,184 +1,184 @@
-using UnityEngine;
-using System.Collections;
-using System.Collections.Generic;
-using FairyGUI;
-#if UNITY_5_4_OR_NEWER
-using UnityEngine.Networking;
-#endif
-
-public delegate void LoadCompleteCallback(NTexture texture);
-public delegate void LoadErrorCallback(string error);
-
-///
-/// Use to load icons from asset bundle, and pool them
-///
-public class IconManager : MonoBehaviour
-{
- static IconManager _instance;
- public static IconManager inst
- {
- get
- {
- if (_instance == null)
- {
- GameObject go = new GameObject("IconManager");
- DontDestroyOnLoad(go);
- _instance = go.AddComponent();
- }
- return _instance;
- }
- }
-
- public const int POOL_CHECK_TIME = 30;
- public const int MAX_POOL_SIZE = 10;
-
- List _items;
- bool _started;
- Hashtable _pool;
- string _basePath;
-
- void Awake()
- {
- _items = new List();
- _pool = new Hashtable();
- _basePath = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/";
- if (Application.platform != RuntimePlatform.Android)
- _basePath = "file:///" + _basePath;
-
- StartCoroutine(FreeIdleIcons());
- }
-
- public void LoadIcon(string url,
- LoadCompleteCallback onSuccess,
- LoadErrorCallback onFail)
- {
- LoadItem item = new LoadItem();
- item.url = url;
- item.onSuccess = onSuccess;
- item.onFail = onFail;
- _items.Add(item);
- if (!_started)
- StartCoroutine(Run());
- }
-
- IEnumerator Run()
- {
- _started = true;
-
- LoadItem item = null;
- while (true)
- {
- if (_items.Count > 0)
- {
- item = _items[0];
- _items.RemoveAt(0);
- }
- else
- break;
-
- if (_pool.ContainsKey(item.url))
- {
- //Debug.Log("hit " + item.url);
-
- NTexture texture = (NTexture)_pool[item.url];
- texture.refCount++;
-
- if (item.onSuccess != null)
- item.onSuccess(texture);
-
- continue;
- }
-
- string url = _basePath + item.url + ".ab";
-#if UNITY_2017_2_OR_NEWER
-#if UNITY_2018_1_OR_NEWER
- UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url);
-#else
- UnityWebRequest www = UnityWebRequest.GetAssetBundle(url);
-#endif
- yield return www.SendWebRequest();
-
- if (!www.isNetworkError && !www.isHttpError)
- {
- AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
-#else
- WWW www = new WWW(url);
- yield return www;
-
- if (string.IsNullOrEmpty(www.error))
- {
- AssetBundle bundle = www.assetBundle;
-#endif
-
- if (bundle == null)
- {
- Debug.LogWarning("Run Window->Build FairyGUI example Bundles first.");
- if (item.onFail != null)
- item.onFail(www.error);
- continue;
- }
-#if (UNITY_5 || UNITY_5_3_OR_NEWER)
- NTexture texture = new NTexture(bundle.LoadAllAssets()[0]);
-#else
- NTexture texture = new NTexture((Texture2D)bundle.mainAsset);
-#endif
- texture.refCount++;
- bundle.Unload(false);
-
- _pool[item.url] = texture;
-
- if (item.onSuccess != null)
- item.onSuccess(texture);
- }
- else
- {
- if (item.onFail != null)
- item.onFail(www.error);
- }
- }
-
- _started = false;
- }
-
- IEnumerator FreeIdleIcons()
- {
- yield return new WaitForSeconds(POOL_CHECK_TIME); //check the pool every 30 seconds
-
- int cnt = _pool.Count;
- if (cnt > MAX_POOL_SIZE)
- {
- ArrayList toRemove = null;
- foreach (DictionaryEntry de in _pool)
- {
- string key = (string)de.Key;
- NTexture texture = (NTexture)de.Value;
- if (texture.refCount == 0)
- {
- if (toRemove == null)
- toRemove = new ArrayList();
- toRemove.Add(key);
- texture.Dispose();
-
- //Debug.Log("free icon " + de.Key);
-
- cnt--;
- if (cnt <= 8)
- break;
- }
- }
- if (toRemove != null)
- {
- foreach (string key in toRemove)
- _pool.Remove(key);
- }
- }
- }
-
-}
-
-class LoadItem
-{
- public string url;
- public LoadCompleteCallback onSuccess;
- public LoadErrorCallback onFail;
-}
+using UnityEngine;
+using System.Collections;
+using System.Collections.Generic;
+using FairyGUI;
+#if UNITY_5_4_OR_NEWER
+using UnityEngine.Networking;
+#endif
+
+public delegate void LoadCompleteCallback(NTexture texture);
+public delegate void LoadErrorCallback(string error);
+
+///
+/// Use to load icons from asset bundle, and pool them
+///
+public class IconManager : MonoBehaviour
+{
+ static IconManager _instance;
+ public static IconManager inst
+ {
+ get
+ {
+ if (_instance == null)
+ {
+ GameObject go = new GameObject("IconManager");
+ DontDestroyOnLoad(go);
+ _instance = go.AddComponent();
+ }
+ return _instance;
+ }
+ }
+
+ public const int POOL_CHECK_TIME = 30;
+ public const int MAX_POOL_SIZE = 10;
+
+ List _items;
+ bool _started;
+ Hashtable _pool;
+ string _basePath;
+
+ void Awake()
+ {
+ _items = new List();
+ _pool = new Hashtable();
+ _basePath = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/";
+ if (Application.platform != RuntimePlatform.Android)
+ _basePath = "file:///" + _basePath;
+
+ StartCoroutine(FreeIdleIcons());
+ }
+
+ public void LoadIcon(string url,
+ LoadCompleteCallback onSuccess,
+ LoadErrorCallback onFail)
+ {
+ LoadItem item = new LoadItem();
+ item.url = url;
+ item.onSuccess = onSuccess;
+ item.onFail = onFail;
+ _items.Add(item);
+ if (!_started)
+ StartCoroutine(Run());
+ }
+
+ IEnumerator Run()
+ {
+ _started = true;
+
+ LoadItem item = null;
+ while (true)
+ {
+ if (_items.Count > 0)
+ {
+ item = _items[0];
+ _items.RemoveAt(0);
+ }
+ else
+ break;
+
+ if (_pool.ContainsKey(item.url))
+ {
+ //Debug.Log("hit " + item.url);
+
+ NTexture texture = (NTexture)_pool[item.url];
+ texture.refCount++;
+
+ if (item.onSuccess != null)
+ item.onSuccess(texture);
+
+ continue;
+ }
+
+ string url = _basePath + item.url + ".ab";
+#if UNITY_2017_2_OR_NEWER
+#if UNITY_2018_1_OR_NEWER
+ UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url);
+#else
+ UnityWebRequest www = UnityWebRequest.GetAssetBundle(url);
+#endif
+ yield return www.SendWebRequest();
+
+ if (!www.isNetworkError && !www.isHttpError)
+ {
+ AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
+#else
+ WWW www = new WWW(url);
+ yield return www;
+
+ if (string.IsNullOrEmpty(www.error))
+ {
+ AssetBundle bundle = www.assetBundle;
+#endif
+
+ if (bundle == null)
+ {
+ Debug.LogWarning("Run Window->Build FairyGUI example Bundles first.");
+ if (item.onFail != null)
+ item.onFail(www.error);
+ continue;
+ }
+#if (UNITY_5 || UNITY_5_3_OR_NEWER)
+ NTexture texture = new NTexture(bundle.LoadAllAssets()[0]);
+#else
+ NTexture texture = new NTexture((Texture2D)bundle.mainAsset);
+#endif
+ texture.refCount++;
+ bundle.Unload(false);
+
+ _pool[item.url] = texture;
+
+ if (item.onSuccess != null)
+ item.onSuccess(texture);
+ }
+ else
+ {
+ if (item.onFail != null)
+ item.onFail(www.error);
+ }
+ }
+
+ _started = false;
+ }
+
+ IEnumerator FreeIdleIcons()
+ {
+ yield return new WaitForSeconds(POOL_CHECK_TIME); //check the pool every 30 seconds
+
+ int cnt = _pool.Count;
+ if (cnt > MAX_POOL_SIZE)
+ {
+ ArrayList toRemove = null;
+ foreach (DictionaryEntry de in _pool)
+ {
+ string key = (string)de.Key;
+ NTexture texture = (NTexture)de.Value;
+ if (texture.refCount == 0)
+ {
+ if (toRemove == null)
+ toRemove = new ArrayList();
+ toRemove.Add(key);
+ texture.Dispose();
+
+ //Debug.Log("free icon " + de.Key);
+
+ cnt--;
+ if (cnt <= 8)
+ break;
+ }
+ }
+ if (toRemove != null)
+ {
+ foreach (string key in toRemove)
+ _pool.Remove(key);
+ }
+ }
+ }
+
+}
+
+class LoadItem
+{
+ public string url;
+ public LoadCompleteCallback onSuccess;
+ public LoadErrorCallback onFail;
+}
diff --git a/Assets/Examples/Bag/MyGLoader.cs b/Assets/Examples/Bag/MyGLoader.cs
index 9d4e7634..67cff271 100644
--- a/Assets/Examples/Bag/MyGLoader.cs
+++ b/Assets/Examples/Bag/MyGLoader.cs
@@ -1,33 +1,33 @@
-using UnityEngine;
-using FairyGUI;
-using System.IO;
-
-///
-/// Extend the ability of GLoader
-///
-public class MyGLoader : GLoader
-{
- protected override void LoadExternal()
- {
- IconManager.inst.LoadIcon(this.url, OnLoadSuccess, OnLoadFail);
- }
-
- protected override void FreeExternal(NTexture texture)
- {
- texture.refCount--;
- }
-
- void OnLoadSuccess(NTexture texture)
- {
- if (string.IsNullOrEmpty(this.url))
- return;
-
- this.onExternalLoadSuccess(texture);
- }
-
- void OnLoadFail(string error)
- {
- Debug.Log("load " + this.url + " failed: " + error);
- this.onExternalLoadFailed();
- }
-}
+using UnityEngine;
+using FairyGUI;
+using System.IO;
+
+///
+/// Extend the ability of GLoader
+///
+public class MyGLoader : GLoader
+{
+ protected override void LoadExternal()
+ {
+ IconManager.inst.LoadIcon(this.url, OnLoadSuccess, OnLoadFail);
+ }
+
+ protected override void FreeExternal(NTexture texture)
+ {
+ texture.refCount--;
+ }
+
+ void OnLoadSuccess(NTexture texture)
+ {
+ if (string.IsNullOrEmpty(this.url))
+ return;
+
+ this.onExternalLoadSuccess(texture);
+ }
+
+ void OnLoadFail(string error)
+ {
+ Debug.Log("load " + this.url + " failed: " + error);
+ this.onExternalLoadFailed();
+ }
+}
diff --git a/Assets/Examples/Basics/BasicsMain.cs b/Assets/Examples/Basics/BasicsMain.cs
index 3e3af636..e211ca1b 100644
--- a/Assets/Examples/Basics/BasicsMain.cs
+++ b/Assets/Examples/Basics/BasicsMain.cs
@@ -1,441 +1,441 @@
-using UnityEngine;
-using System.Collections.Generic;
-using FairyGUI;
-
-public class BasicsMain : MonoBehaviour
-{
- private GComponent _mainView;
- private GObject _backBtn;
- private GComponent _demoContainer;
- private Controller _viewController;
- private Dictionary _demoObjects;
-
- public Gradient lineGradient;
-
- void Awake()
- {
-#if (UNITY_5 || UNITY_5_3_OR_NEWER)
- //Use the font names directly
- UIConfig.defaultFont = "Microsoft YaHei";
-#else
- //Need to put a ttf file into Resources folder. Here is the file name of the ttf file.
- UIConfig.defaultFont = "afont";
-#endif
- UIPackage.AddPackage("UI/Basics");
-
- UIConfig.verticalScrollBar = "ui://Basics/ScrollBar_VT";
- UIConfig.horizontalScrollBar = "ui://Basics/ScrollBar_HZ";
- UIConfig.popupMenu = "ui://Basics/PopupMenu";
- UIConfig.buttonSound = (NAudioClip)UIPackage.GetItemAsset("Basics", "click");
- }
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _backBtn = _mainView.GetChild("btn_Back");
- _backBtn.visible = false;
- _backBtn.onClick.Add(onClickBack);
-
- _demoContainer = _mainView.GetChild("container").asCom;
- _viewController = _mainView.GetController("c1");
-
- _demoObjects = new Dictionary();
-
- int cnt = _mainView.numChildren;
- for (int i = 0; i < cnt; i++)
- {
- GObject obj = _mainView.GetChildAt(i);
- if (obj.group != null && obj.group.name == "btns")
- obj.onClick.Add(runDemo);
- }
- }
-
- private void runDemo(EventContext context)
- {
- string type = ((GObject)(context.sender)).name.Substring(4);
- GComponent obj;
- if (!_demoObjects.TryGetValue(type, out obj))
- {
- obj = UIPackage.CreateObject("Basics", "Demo_" + type).asCom;
- _demoObjects[type] = obj;
- }
-
- _demoContainer.RemoveChildren();
- _demoContainer.AddChild(obj);
- _viewController.selectedIndex = 1;
- _backBtn.visible = true;
-
- switch (type)
- {
- case "Graph":
- PlayGraph();
- break;
-
- case "Button":
- PlayButton();
- break;
-
- case "Text":
- PlayText();
- break;
-
- case "Grid":
- PlayGrid();
- break;
-
- case "Transition":
- PlayTransition();
- break;
-
- case "Window":
- PlayWindow();
- break;
-
- case "Popup":
- PlayPopup();
- break;
-
- case "Drag&Drop":
- PlayDragDrop();
- break;
-
- case "Depth":
- PlayDepth();
- break;
-
- case "ProgressBar":
- PlayProgressBar();
- break;
- }
- }
-
- private void onClickBack()
- {
- _viewController.selectedIndex = 0;
- _backBtn.visible = false;
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
-
- //-----------------------------
- private void PlayGraph()
- {
- GComponent obj = _demoObjects["Graph"];
-
- Shape shape;
-
- shape = obj.GetChild("pie").asGraph.shape;
- EllipseMesh ellipse = shape.graphics.GetMeshFactory();
- ellipse.startDegree = 30;
- ellipse.endDegreee = 300;
- shape.graphics.SetMeshDirty();
-
- shape = obj.GetChild("trapezoid").asGraph.shape;
- PolygonMesh trapezoid = shape.graphics.GetMeshFactory();
- trapezoid.usePercentPositions = true;
- trapezoid.points.Clear();
- trapezoid.points.Add(new Vector2(0f, 1f));
- trapezoid.points.Add(new Vector2(0.3f, 0));
- trapezoid.points.Add(new Vector2(0.7f, 0));
- trapezoid.points.Add(new Vector2(1f, 1f));
- trapezoid.texcoords.Clear();
- trapezoid.texcoords.AddRange(VertexBuffer.NormalizedUV);
- shape.graphics.SetMeshDirty();
- shape.graphics.texture = (NTexture)UIPackage.GetItemAsset("Basics", "change");
-
- shape = obj.GetChild("line").asGraph.shape;
- LineMesh line = shape.graphics.GetMeshFactory();
- line.lineWidthCurve = AnimationCurve.Linear(0, 25, 1, 10);
- line.roundEdge = true;
- line.gradient = lineGradient;
- line.path.Create(new GPathPoint[] {
- new GPathPoint(new Vector3(0, 120, 0)),
- new GPathPoint(new Vector3(20, 120, 0)),
- new GPathPoint(new Vector3(100, 100, 0)),
- new GPathPoint(new Vector3(180, 30, 0)),
- new GPathPoint(new Vector3(100, 0, 0)),
- new GPathPoint(new Vector3(20, 30, 0)),
- new GPathPoint(new Vector3(100, 100, 0)),
- new GPathPoint(new Vector3(180, 120, 0)),
- new GPathPoint(new Vector3(200, 120, 0)),
- });
- shape.graphics.SetMeshDirty();
- GTween.To(0, 1, 5).SetEase(EaseType.Linear).SetTarget(shape.graphics).OnUpdate((GTweener t) =>
- {
- ((NGraphics)t.target).GetMeshFactory().fillEnd = t.value.x;
- ((NGraphics)t.target).SetMeshDirty();
- });
-
- shape = obj.GetChild("line2").asGraph.shape;
- LineMesh line2 = shape.graphics.GetMeshFactory();
- line2.lineWidth = 3;
- line2.roundEdge = true;
- line2.path.Create(new GPathPoint[] {
- new GPathPoint(new Vector3(0, 120, 0), GPathPoint.CurveType.Straight),
- new GPathPoint(new Vector3(60, 30, 0), GPathPoint.CurveType.Straight),
- new GPathPoint(new Vector3(80, 90, 0), GPathPoint.CurveType.Straight),
- new GPathPoint(new Vector3(140, 30, 0), GPathPoint.CurveType.Straight),
- new GPathPoint(new Vector3(160, 90, 0), GPathPoint.CurveType.Straight),
- new GPathPoint(new Vector3(220, 30, 0), GPathPoint.CurveType.Straight)
- });
- shape.graphics.SetMeshDirty();
-
- GObject image = obj.GetChild("line3");
- LineMesh line3 = image.displayObject.graphics.GetMeshFactory();
- line3.lineWidth = 30;
- line3.roundEdge = false;
- line3.path.Create(new GPathPoint[] {
- new GPathPoint(new Vector3(0, 30, 0), new Vector3(50, -30), new Vector3(150, -50)),
- new GPathPoint(new Vector3(200, 30, 0), new Vector3(300, 130)),
- new GPathPoint(new Vector3(400, 30, 0))
- });
- image.displayObject.graphics.SetMeshDirty();
- }
-
- //-----------------------------
- private void PlayButton()
- {
- GComponent obj = _demoObjects["Button"];
- obj.GetChild("n34").onClick.Add(() => { UnityEngine.Debug.Log("click button"); });
- }
-
- //------------------------------
- private void PlayText()
- {
- GComponent obj = _demoObjects["Text"];
- obj.GetChild("n12").asRichTextField.onClickLink.Add((EventContext context) =>
- {
- GRichTextField t = context.sender as GRichTextField;
- t.text = "[img]ui://Basics/pet[/img][color=#FF0000]You click the link[/color]:" + context.data;
- });
- obj.GetChild("n25").onClick.Add(() =>
- {
- obj.GetChild("n24").text = obj.GetChild("n22").text;
- });
- }
-
- //------------------------------
- private void PlayGrid()
- {
- GComponent obj = _demoObjects["Grid"];
- GList list1 = obj.GetChild("list1").asList;
- list1.RemoveChildrenToPool();
- string[] testNames = System.Enum.GetNames(typeof(RuntimePlatform));
- Color[] testColor = new Color[] { Color.yellow, Color.red, Color.white, Color.cyan };
- int cnt = testNames.Length;
- for (int i = 0; i < cnt; i++)
- {
- GButton item = list1.AddItemFromPool().asButton;
- item.GetChild("t0").text = "" + (i + 1);
- item.GetChild("t1").text = testNames[i];
- item.GetChild("t2").asTextField.color = testColor[UnityEngine.Random.Range(0, 4)];
- item.GetChild("star").asProgress.value = (int)((float)UnityEngine.Random.Range(1, 4) / 3f * 100);
- }
-
- GList list2 = obj.GetChild("list2").asList;
- list2.RemoveChildrenToPool();
- for (int i = 0; i < cnt; i++)
- {
- GButton item = list2.AddItemFromPool().asButton;
- item.GetChild("cb").asButton.selected = false;
- item.GetChild("t1").text = testNames[i];
- item.GetChild("mc").asMovieClip.playing = i % 2 == 0;
- item.GetChild("t3").text = "" + UnityEngine.Random.Range(0, 10000);
- }
- }
-
- //------------------------------
- private void PlayTransition()
- {
- GComponent obj = _demoObjects["Transition"];
- obj.GetChild("n2").asCom.GetTransition("t0").Play(int.MaxValue, 0, null);
- obj.GetChild("n3").asCom.GetTransition("peng").Play(int.MaxValue, 0, null);
-
- obj.onAddedToStage.Add(() =>
- {
- obj.GetChild("n2").asCom.GetTransition("t0").Stop();
- obj.GetChild("n3").asCom.GetTransition("peng").Stop();
- });
- }
-
- //------------------------------
- private Window _winA;
- private Window _winB;
- private void PlayWindow()
- {
- GComponent obj = _demoObjects["Window"];
- obj.GetChild("n0").onClick.Add(() =>
- {
- if (_winA == null)
- _winA = new Window1();
- _winA.Show();
- });
-
- obj.GetChild("n1").onClick.Add(() =>
- {
- if (_winB == null)
- _winB = new Window2();
- _winB.Show();
- });
- }
-
- //------------------------------
- private PopupMenu _pm;
- private GComponent _popupCom;
- private void PlayPopup()
- {
- if (_pm == null)
- {
- _pm = new PopupMenu();
- _pm.AddItem("Item 1", __clickMenu);
- _pm.AddItem("Item 2", __clickMenu);
- _pm.AddItem("Item 3", __clickMenu);
- _pm.AddItem("Item 4", __clickMenu);
- }
-
- if (_popupCom == null)
- {
- _popupCom = UIPackage.CreateObject("Basics", "Component12").asCom;
- _popupCom.Center();
- }
- GComponent obj = _demoObjects["Popup"];
- obj.GetChild("n0").onClick.Add((EventContext context) =>
- {
- _pm.Show((GObject)context.sender, PopupDirection.Down);
- });
-
- obj.GetChild("n1").onClick.Add(() =>
- {
- GRoot.inst.ShowPopup(_popupCom);
- });
-
-
- obj.onRightClick.Add(() =>
- {
- _pm.Show();
- });
- }
-
- private void __clickMenu(EventContext context)
- {
- GObject itemObject = (GObject)context.data;
- UnityEngine.Debug.Log("click " + itemObject.text);
- }
-
- //------------------------------
- Vector2 startPos;
- private void PlayDepth()
- {
- GComponent obj = _demoObjects["Depth"];
- GComponent testContainer = obj.GetChild("n22").asCom;
- GObject fixedObj = testContainer.GetChild("n0");
- fixedObj.sortingOrder = 100;
- fixedObj.draggable = true;
-
- int numChildren = testContainer.numChildren;
- int i = 0;
- while (i < numChildren)
- {
- GObject child = testContainer.GetChildAt(i);
- if (child != fixedObj)
- {
- testContainer.RemoveChildAt(i);
- numChildren--;
- }
- else
- i++;
- }
- startPos = new Vector2(fixedObj.x, fixedObj.y);
-
- obj.GetChild("btn0").onClick.Add(() =>
- {
- GGraph graph = new GGraph();
- startPos.x += 10;
- startPos.y += 10;
- graph.xy = startPos;
- graph.DrawRect(150, 150, 1, Color.black, Color.red);
- obj.GetChild("n22").asCom.AddChild(graph);
- });
-
- obj.GetChild("btn1").onClick.Add(() =>
- {
- GGraph graph = new GGraph();
- startPos.x += 10;
- startPos.y += 10;
- graph.xy = startPos;
- graph.DrawRect(150, 150, 1, Color.black, Color.green);
- graph.sortingOrder = 200;
- obj.GetChild("n22").asCom.AddChild(graph);
- });
- }
-
- //------------------------------
- private void PlayDragDrop()
- {
- GComponent obj = _demoObjects["Drag&Drop"];
- obj.GetChild("a").draggable = true;
-
- GButton b = obj.GetChild("b").asButton;
- b.draggable = true;
- b.onDragStart.Add((EventContext context) =>
- {
- //Cancel the original dragging, and start a new one with a agent.
- context.PreventDefault();
-
- DragDropManager.inst.StartDrag(b, b.icon, b.icon, (int)context.data);
- });
-
- GButton c = obj.GetChild("c").asButton;
- c.icon = null;
- c.onDrop.Add((EventContext context) =>
- {
- c.icon = (string)context.data;
- });
-
- GObject bounds = obj.GetChild("n7");
- Rect rect = bounds.TransformRect(new Rect(0, 0, bounds.width, bounds.height), GRoot.inst);
-
- //---!!Because at this time the container is on the right side of the stage and beginning to move to left(transition), so we need to caculate the final position
- rect.x -= obj.parent.x;
- //----
-
- GButton d = obj.GetChild("d").asButton;
- d.draggable = true;
- d.dragBounds = rect;
- }
-
- //------------------------------
- private void PlayProgressBar()
- {
- GComponent obj = _demoObjects["ProgressBar"];
- Timers.inst.Add(0.001f, 0, __playProgress);
- obj.onRemovedFromStage.Add(() => { Timers.inst.Remove(__playProgress); });
- }
-
- void __playProgress(object param)
- {
- GComponent obj = _demoObjects["ProgressBar"];
- int cnt = obj.numChildren;
- for (int i = 0; i < cnt; i++)
- {
- GProgressBar child = obj.GetChildAt(i) as GProgressBar;
- if (child != null)
- {
-
- child.value += 1;
- if (child.value > child.max)
- child.value = 0;
- }
- }
- }
+using UnityEngine;
+using System.Collections.Generic;
+using FairyGUI;
+
+public class BasicsMain : MonoBehaviour
+{
+ private GComponent _mainView;
+ private GObject _backBtn;
+ private GComponent _demoContainer;
+ private Controller _viewController;
+ private Dictionary _demoObjects;
+
+ public Gradient lineGradient;
+
+ void Awake()
+ {
+#if (UNITY_5 || UNITY_5_3_OR_NEWER)
+ //Use the font names directly
+ UIConfig.defaultFont = "Microsoft YaHei";
+#else
+ //Need to put a ttf file into Resources folder. Here is the file name of the ttf file.
+ UIConfig.defaultFont = "afont";
+#endif
+ UIPackage.AddPackage("UI/Basics");
+
+ UIConfig.verticalScrollBar = "ui://Basics/ScrollBar_VT";
+ UIConfig.horizontalScrollBar = "ui://Basics/ScrollBar_HZ";
+ UIConfig.popupMenu = "ui://Basics/PopupMenu";
+ UIConfig.buttonSound = (NAudioClip)UIPackage.GetItemAsset("Basics", "click");
+ }
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _backBtn = _mainView.GetChild("btn_Back");
+ _backBtn.visible = false;
+ _backBtn.onClick.Add(onClickBack);
+
+ _demoContainer = _mainView.GetChild("container").asCom;
+ _viewController = _mainView.GetController("c1");
+
+ _demoObjects = new Dictionary();
+
+ int cnt = _mainView.numChildren;
+ for (int i = 0; i < cnt; i++)
+ {
+ GObject obj = _mainView.GetChildAt(i);
+ if (obj.group != null && obj.group.name == "btns")
+ obj.onClick.Add(runDemo);
+ }
+ }
+
+ private void runDemo(EventContext context)
+ {
+ string type = ((GObject)(context.sender)).name.Substring(4);
+ GComponent obj;
+ if (!_demoObjects.TryGetValue(type, out obj))
+ {
+ obj = UIPackage.CreateObject("Basics", "Demo_" + type).asCom;
+ _demoObjects[type] = obj;
+ }
+
+ _demoContainer.RemoveChildren();
+ _demoContainer.AddChild(obj);
+ _viewController.selectedIndex = 1;
+ _backBtn.visible = true;
+
+ switch (type)
+ {
+ case "Graph":
+ PlayGraph();
+ break;
+
+ case "Button":
+ PlayButton();
+ break;
+
+ case "Text":
+ PlayText();
+ break;
+
+ case "Grid":
+ PlayGrid();
+ break;
+
+ case "Transition":
+ PlayTransition();
+ break;
+
+ case "Window":
+ PlayWindow();
+ break;
+
+ case "Popup":
+ PlayPopup();
+ break;
+
+ case "Drag&Drop":
+ PlayDragDrop();
+ break;
+
+ case "Depth":
+ PlayDepth();
+ break;
+
+ case "ProgressBar":
+ PlayProgressBar();
+ break;
+ }
+ }
+
+ private void onClickBack()
+ {
+ _viewController.selectedIndex = 0;
+ _backBtn.visible = false;
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
+
+ //-----------------------------
+ private void PlayGraph()
+ {
+ GComponent obj = _demoObjects["Graph"];
+
+ Shape shape;
+
+ shape = obj.GetChild("pie").asGraph.shape;
+ EllipseMesh ellipse = shape.graphics.GetMeshFactory();
+ ellipse.startDegree = 30;
+ ellipse.endDegreee = 300;
+ shape.graphics.SetMeshDirty();
+
+ shape = obj.GetChild("trapezoid").asGraph.shape;
+ PolygonMesh trapezoid = shape.graphics.GetMeshFactory();
+ trapezoid.usePercentPositions = true;
+ trapezoid.points.Clear();
+ trapezoid.points.Add(new Vector2(0f, 1f));
+ trapezoid.points.Add(new Vector2(0.3f, 0));
+ trapezoid.points.Add(new Vector2(0.7f, 0));
+ trapezoid.points.Add(new Vector2(1f, 1f));
+ trapezoid.texcoords.Clear();
+ trapezoid.texcoords.AddRange(VertexBuffer.NormalizedUV);
+ shape.graphics.SetMeshDirty();
+ shape.graphics.texture = (NTexture)UIPackage.GetItemAsset("Basics", "change");
+
+ shape = obj.GetChild("line").asGraph.shape;
+ LineMesh line = shape.graphics.GetMeshFactory();
+ line.lineWidthCurve = AnimationCurve.Linear(0, 25, 1, 10);
+ line.roundEdge = true;
+ line.gradient = lineGradient;
+ line.path.Create(new GPathPoint[] {
+ new GPathPoint(new Vector3(0, 120, 0)),
+ new GPathPoint(new Vector3(20, 120, 0)),
+ new GPathPoint(new Vector3(100, 100, 0)),
+ new GPathPoint(new Vector3(180, 30, 0)),
+ new GPathPoint(new Vector3(100, 0, 0)),
+ new GPathPoint(new Vector3(20, 30, 0)),
+ new GPathPoint(new Vector3(100, 100, 0)),
+ new GPathPoint(new Vector3(180, 120, 0)),
+ new GPathPoint(new Vector3(200, 120, 0)),
+ });
+ shape.graphics.SetMeshDirty();
+ GTween.To(0, 1, 5).SetEase(EaseType.Linear).SetTarget(shape.graphics).OnUpdate((GTweener t) =>
+ {
+ ((NGraphics)t.target).GetMeshFactory().fillEnd = t.value.x;
+ ((NGraphics)t.target).SetMeshDirty();
+ });
+
+ shape = obj.GetChild("line2").asGraph.shape;
+ LineMesh line2 = shape.graphics.GetMeshFactory();
+ line2.lineWidth = 3;
+ line2.roundEdge = true;
+ line2.path.Create(new GPathPoint[] {
+ new GPathPoint(new Vector3(0, 120, 0), GPathPoint.CurveType.Straight),
+ new GPathPoint(new Vector3(60, 30, 0), GPathPoint.CurveType.Straight),
+ new GPathPoint(new Vector3(80, 90, 0), GPathPoint.CurveType.Straight),
+ new GPathPoint(new Vector3(140, 30, 0), GPathPoint.CurveType.Straight),
+ new GPathPoint(new Vector3(160, 90, 0), GPathPoint.CurveType.Straight),
+ new GPathPoint(new Vector3(220, 30, 0), GPathPoint.CurveType.Straight)
+ });
+ shape.graphics.SetMeshDirty();
+
+ GObject image = obj.GetChild("line3");
+ LineMesh line3 = image.displayObject.graphics.GetMeshFactory();
+ line3.lineWidth = 30;
+ line3.roundEdge = false;
+ line3.path.Create(new GPathPoint[] {
+ new GPathPoint(new Vector3(0, 30, 0), new Vector3(50, -30), new Vector3(150, -50)),
+ new GPathPoint(new Vector3(200, 30, 0), new Vector3(300, 130)),
+ new GPathPoint(new Vector3(400, 30, 0))
+ });
+ image.displayObject.graphics.SetMeshDirty();
+ }
+
+ //-----------------------------
+ private void PlayButton()
+ {
+ GComponent obj = _demoObjects["Button"];
+ obj.GetChild("n34").onClick.Add(() => { UnityEngine.Debug.Log("click button"); });
+ }
+
+ //------------------------------
+ private void PlayText()
+ {
+ GComponent obj = _demoObjects["Text"];
+ obj.GetChild("n12").asRichTextField.onClickLink.Add((EventContext context) =>
+ {
+ GRichTextField t = context.sender as GRichTextField;
+ t.text = "[img]ui://Basics/pet[/img][color=#FF0000]You click the link[/color]:" + context.data;
+ });
+ obj.GetChild("n25").onClick.Add(() =>
+ {
+ obj.GetChild("n24").text = obj.GetChild("n22").text;
+ });
+ }
+
+ //------------------------------
+ private void PlayGrid()
+ {
+ GComponent obj = _demoObjects["Grid"];
+ GList list1 = obj.GetChild("list1").asList;
+ list1.RemoveChildrenToPool();
+ string[] testNames = System.Enum.GetNames(typeof(RuntimePlatform));
+ Color[] testColor = new Color[] { Color.yellow, Color.red, Color.white, Color.cyan };
+ int cnt = testNames.Length;
+ for (int i = 0; i < cnt; i++)
+ {
+ GButton item = list1.AddItemFromPool().asButton;
+ item.GetChild("t0").text = "" + (i + 1);
+ item.GetChild("t1").text = testNames[i];
+ item.GetChild("t2").asTextField.color = testColor[UnityEngine.Random.Range(0, 4)];
+ item.GetChild("star").asProgress.value = (int)((float)UnityEngine.Random.Range(1, 4) / 3f * 100);
+ }
+
+ GList list2 = obj.GetChild("list2").asList;
+ list2.RemoveChildrenToPool();
+ for (int i = 0; i < cnt; i++)
+ {
+ GButton item = list2.AddItemFromPool().asButton;
+ item.GetChild("cb").asButton.selected = false;
+ item.GetChild("t1").text = testNames[i];
+ item.GetChild("mc").asMovieClip.playing = i % 2 == 0;
+ item.GetChild("t3").text = "" + UnityEngine.Random.Range(0, 10000);
+ }
+ }
+
+ //------------------------------
+ private void PlayTransition()
+ {
+ GComponent obj = _demoObjects["Transition"];
+ obj.GetChild("n2").asCom.GetTransition("t0").Play(int.MaxValue, 0, null);
+ obj.GetChild("n3").asCom.GetTransition("peng").Play(int.MaxValue, 0, null);
+
+ obj.onAddedToStage.Add(() =>
+ {
+ obj.GetChild("n2").asCom.GetTransition("t0").Stop();
+ obj.GetChild("n3").asCom.GetTransition("peng").Stop();
+ });
+ }
+
+ //------------------------------
+ private Window _winA;
+ private Window _winB;
+ private void PlayWindow()
+ {
+ GComponent obj = _demoObjects["Window"];
+ obj.GetChild("n0").onClick.Add(() =>
+ {
+ if (_winA == null)
+ _winA = new Window1();
+ _winA.Show();
+ });
+
+ obj.GetChild("n1").onClick.Add(() =>
+ {
+ if (_winB == null)
+ _winB = new Window2();
+ _winB.Show();
+ });
+ }
+
+ //------------------------------
+ private PopupMenu _pm;
+ private GComponent _popupCom;
+ private void PlayPopup()
+ {
+ if (_pm == null)
+ {
+ _pm = new PopupMenu();
+ _pm.AddItem("Item 1", __clickMenu);
+ _pm.AddItem("Item 2", __clickMenu);
+ _pm.AddItem("Item 3", __clickMenu);
+ _pm.AddItem("Item 4", __clickMenu);
+ }
+
+ if (_popupCom == null)
+ {
+ _popupCom = UIPackage.CreateObject("Basics", "Component12").asCom;
+ _popupCom.Center();
+ }
+ GComponent obj = _demoObjects["Popup"];
+ obj.GetChild("n0").onClick.Add((EventContext context) =>
+ {
+ _pm.Show((GObject)context.sender, PopupDirection.Down);
+ });
+
+ obj.GetChild("n1").onClick.Add(() =>
+ {
+ GRoot.inst.ShowPopup(_popupCom);
+ });
+
+
+ obj.onRightClick.Add(() =>
+ {
+ _pm.Show();
+ });
+ }
+
+ private void __clickMenu(EventContext context)
+ {
+ GObject itemObject = (GObject)context.data;
+ UnityEngine.Debug.Log("click " + itemObject.text);
+ }
+
+ //------------------------------
+ Vector2 startPos;
+ private void PlayDepth()
+ {
+ GComponent obj = _demoObjects["Depth"];
+ GComponent testContainer = obj.GetChild("n22").asCom;
+ GObject fixedObj = testContainer.GetChild("n0");
+ fixedObj.sortingOrder = 100;
+ fixedObj.draggable = true;
+
+ int numChildren = testContainer.numChildren;
+ int i = 0;
+ while (i < numChildren)
+ {
+ GObject child = testContainer.GetChildAt(i);
+ if (child != fixedObj)
+ {
+ testContainer.RemoveChildAt(i);
+ numChildren--;
+ }
+ else
+ i++;
+ }
+ startPos = new Vector2(fixedObj.x, fixedObj.y);
+
+ obj.GetChild("btn0").onClick.Add(() =>
+ {
+ GGraph graph = new GGraph();
+ startPos.x += 10;
+ startPos.y += 10;
+ graph.xy = startPos;
+ graph.DrawRect(150, 150, 1, Color.black, Color.red);
+ obj.GetChild("n22").asCom.AddChild(graph);
+ });
+
+ obj.GetChild("btn1").onClick.Add(() =>
+ {
+ GGraph graph = new GGraph();
+ startPos.x += 10;
+ startPos.y += 10;
+ graph.xy = startPos;
+ graph.DrawRect(150, 150, 1, Color.black, Color.green);
+ graph.sortingOrder = 200;
+ obj.GetChild("n22").asCom.AddChild(graph);
+ });
+ }
+
+ //------------------------------
+ private void PlayDragDrop()
+ {
+ GComponent obj = _demoObjects["Drag&Drop"];
+ obj.GetChild("a").draggable = true;
+
+ GButton b = obj.GetChild("b").asButton;
+ b.draggable = true;
+ b.onDragStart.Add((EventContext context) =>
+ {
+ //Cancel the original dragging, and start a new one with a agent.
+ context.PreventDefault();
+
+ DragDropManager.inst.StartDrag(b, b.icon, b.icon, (int)context.data);
+ });
+
+ GButton c = obj.GetChild("c").asButton;
+ c.icon = null;
+ c.onDrop.Add((EventContext context) =>
+ {
+ c.icon = (string)context.data;
+ });
+
+ GObject bounds = obj.GetChild("n7");
+ Rect rect = bounds.TransformRect(new Rect(0, 0, bounds.width, bounds.height), GRoot.inst);
+
+ //---!!Because at this time the container is on the right side of the stage and beginning to move to left(transition), so we need to caculate the final position
+ rect.x -= obj.parent.x;
+ //----
+
+ GButton d = obj.GetChild("d").asButton;
+ d.draggable = true;
+ d.dragBounds = rect;
+ }
+
+ //------------------------------
+ private void PlayProgressBar()
+ {
+ GComponent obj = _demoObjects["ProgressBar"];
+ Timers.inst.Add(0.001f, 0, __playProgress);
+ obj.onRemovedFromStage.Add(() => { Timers.inst.Remove(__playProgress); });
+ }
+
+ void __playProgress(object param)
+ {
+ GComponent obj = _demoObjects["ProgressBar"];
+ int cnt = obj.numChildren;
+ for (int i = 0; i < cnt; i++)
+ {
+ GProgressBar child = obj.GetChildAt(i) as GProgressBar;
+ if (child != null)
+ {
+
+ child.value += 1;
+ if (child.value > child.max)
+ child.value = 0;
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Basics/Window1.cs b/Assets/Examples/Basics/Window1.cs
index fab5de33..318878f9 100644
--- a/Assets/Examples/Basics/Window1.cs
+++ b/Assets/Examples/Basics/Window1.cs
@@ -1,29 +1,29 @@
-using System;
-using System.Collections.Generic;
-using FairyGUI;
-
-public class Window1 : Window
-{
- public Window1()
- {
- }
-
- protected override void OnInit()
- {
- this.contentPane = UIPackage.CreateObject("Basics", "WindowA").asCom;
- this.Center();
- }
-
- override protected void OnShown()
- {
- GList list = this.contentPane.GetChild("n6").asList;
- list.RemoveChildrenToPool();
-
- for (int i = 0; i < 6; i++)
- {
- GButton item = list.AddItemFromPool().asButton;
- item.title = "" + i;
- item.icon = UIPackage.GetItemURL("Basics", "r4");
- }
- }
-}
+using System;
+using System.Collections.Generic;
+using FairyGUI;
+
+public class Window1 : Window
+{
+ public Window1()
+ {
+ }
+
+ protected override void OnInit()
+ {
+ this.contentPane = UIPackage.CreateObject("Basics", "WindowA").asCom;
+ this.Center();
+ }
+
+ override protected void OnShown()
+ {
+ GList list = this.contentPane.GetChild("n6").asList;
+ list.RemoveChildrenToPool();
+
+ for (int i = 0; i < 6; i++)
+ {
+ GButton item = list.AddItemFromPool().asButton;
+ item.title = "" + i;
+ item.icon = UIPackage.GetItemURL("Basics", "r4");
+ }
+ }
+}
diff --git a/Assets/Examples/Basics/Window2.cs b/Assets/Examples/Basics/Window2.cs
index 590c4851..df1a5efa 100644
--- a/Assets/Examples/Basics/Window2.cs
+++ b/Assets/Examples/Basics/Window2.cs
@@ -1,39 +1,39 @@
-using System;
-using System.Collections.Generic;
-using FairyGUI;
-using UnityEngine;
-
-public class Window2 : Window
-{
- public Window2()
- {
- }
-
- protected override void OnInit()
- {
- this.contentPane = UIPackage.CreateObject("Basics", "WindowB").asCom;
- this.Center();
- }
-
- override protected void DoShowAnimation()
- {
- this.SetScale(0.1f, 0.1f);
- this.SetPivot(0.5f, 0.5f);
- this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown);
- }
-
- override protected void DoHideAnimation()
- {
- this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately);
- }
-
- override protected void OnShown()
- {
- contentPane.GetTransition("t1").Play();
- }
-
- override protected void OnHide()
- {
- contentPane.GetTransition("t1").Stop();
- }
-}
+using System;
+using System.Collections.Generic;
+using FairyGUI;
+using UnityEngine;
+
+public class Window2 : Window
+{
+ public Window2()
+ {
+ }
+
+ protected override void OnInit()
+ {
+ this.contentPane = UIPackage.CreateObject("Basics", "WindowB").asCom;
+ this.Center();
+ }
+
+ override protected void DoShowAnimation()
+ {
+ this.SetScale(0.1f, 0.1f);
+ this.SetPivot(0.5f, 0.5f);
+ this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown);
+ }
+
+ override protected void DoHideAnimation()
+ {
+ this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately);
+ }
+
+ override protected void OnShown()
+ {
+ contentPane.GetTransition("t1").Play();
+ }
+
+ override protected void OnHide()
+ {
+ contentPane.GetTransition("t1").Stop();
+ }
+}
diff --git a/Assets/Examples/BundleUsage/BundleUsageMain.cs b/Assets/Examples/BundleUsage/BundleUsageMain.cs
index 3b5634d2..a107bf7c 100644
--- a/Assets/Examples/BundleUsage/BundleUsageMain.cs
+++ b/Assets/Examples/BundleUsage/BundleUsageMain.cs
@@ -1,75 +1,75 @@
-using System.Collections;
-using UnityEngine;
-using FairyGUI;
-#if UNITY_5_4_OR_NEWER
-using UnityEngine.Networking;
-#endif
-
-///
-/// Demonstrated how to load UI package from assetbundle. The bundle can be build from the Window Menu->Build FairyGUI example bundles.
-///
-class BundleUsageMain : MonoBehaviour
-{
- GComponent _mainView;
-
- void Start()
- {
- Application.targetFrameRate = 60;
-
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- StartCoroutine(LoadUIPackage());
- }
-
- IEnumerator LoadUIPackage()
- {
- string url = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/bundleusage.ab";
- if (Application.platform != RuntimePlatform.Android)
- url = "file:///" + url;
-
-#if UNITY_2017_2_OR_NEWER
-#if UNITY_2018_1_OR_NEWER
- UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url);
-#else
- UnityWebRequest www = UnityWebRequest.GetAssetBundle(url);
-#endif
- yield return www.SendWebRequest();
-
- if (!www.isNetworkError && !www.isHttpError)
- {
- AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
-#else
- WWW www = new WWW(url);
- yield return www;
-
- if (string.IsNullOrEmpty(www.error))
- {
- AssetBundle bundle = www.assetBundle;
-#endif
- if (bundle == null)
- {
- Debug.LogWarning("Run Window->Build FairyGUI example Bundles first.");
- yield return 0;
- }
- UIPackage.AddPackage(bundle);
-
- _mainView = UIPackage.CreateObject("BundleUsage", "Main").asCom;
- _mainView.fairyBatching = true;
- _mainView.SetSize(GRoot.inst.width, GRoot.inst.height);
- _mainView.AddRelation(GRoot.inst, RelationType.Size);
-
- GRoot.inst.AddChild(_mainView);
- _mainView.GetTransition("t0").Play();
- }
- else
- Debug.LogError(www.error);
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
-}
+using System.Collections;
+using UnityEngine;
+using FairyGUI;
+#if UNITY_5_4_OR_NEWER
+using UnityEngine.Networking;
+#endif
+
+///
+/// Demonstrated how to load UI package from assetbundle. The bundle can be build from the Window Menu->Build FairyGUI example bundles.
+///
+class BundleUsageMain : MonoBehaviour
+{
+ GComponent _mainView;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ StartCoroutine(LoadUIPackage());
+ }
+
+ IEnumerator LoadUIPackage()
+ {
+ string url = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/bundleusage.ab";
+ if (Application.platform != RuntimePlatform.Android)
+ url = "file:///" + url;
+
+#if UNITY_2017_2_OR_NEWER
+#if UNITY_2018_1_OR_NEWER
+ UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url);
+#else
+ UnityWebRequest www = UnityWebRequest.GetAssetBundle(url);
+#endif
+ yield return www.SendWebRequest();
+
+ if (!www.isNetworkError && !www.isHttpError)
+ {
+ AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
+#else
+ WWW www = new WWW(url);
+ yield return www;
+
+ if (string.IsNullOrEmpty(www.error))
+ {
+ AssetBundle bundle = www.assetBundle;
+#endif
+ if (bundle == null)
+ {
+ Debug.LogWarning("Run Window->Build FairyGUI example Bundles first.");
+ yield return 0;
+ }
+ UIPackage.AddPackage(bundle);
+
+ _mainView = UIPackage.CreateObject("BundleUsage", "Main").asCom;
+ _mainView.fairyBatching = true;
+ _mainView.SetSize(GRoot.inst.width, GRoot.inst.height);
+ _mainView.AddRelation(GRoot.inst, RelationType.Size);
+
+ GRoot.inst.AddChild(_mainView);
+ _mainView.GetTransition("t0").Play();
+ }
+ else
+ Debug.LogError(www.error);
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
+}
diff --git a/Assets/Examples/Cooldown/CooldownMain.cs b/Assets/Examples/Cooldown/CooldownMain.cs
index 3a6102b6..b540b93d 100644
--- a/Assets/Examples/Cooldown/CooldownMain.cs
+++ b/Assets/Examples/Cooldown/CooldownMain.cs
@@ -1,57 +1,57 @@
-using UnityEngine;
-using FairyGUI;
-public class CooldownMain : MonoBehaviour
-{
- GComponent _mainView;
-
- GButton _btn0;
- GImage _mask0;
- float _time1;
-
- GButton _btn1;
- GImage _mask1;
- float _time2;
-
- void Start()
- {
- Application.targetFrameRate = 60;
-
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.gameObject.GetComponent().ui;
-
- _btn0 = _mainView.GetChild("b0").asButton;
- _btn0.icon = "Cooldown/k0";
- _time1 = 5;
- _mask0 = _btn0.GetChild("mask").asImage;
-
- _btn1 = _mainView.GetChild("b1").asButton;
- _btn1.icon = "Cooldown/k1";
- _time2 = 10;
- _mask1 = _btn1.GetChild("mask").asImage;
-
- }
-
- void Update()
- {
- _time1 -= Time.deltaTime;
- if (_time1 < 0)
- _time1 = 5;
- _mask0.fillAmount = 1 - (5 - _time1) / 5f;
-
- _time2 -= Time.deltaTime;
- if (_time2 < 0)
- _time2 = 10;
- _btn1.text = string.Empty + Mathf.RoundToInt(_time2);
- _mask1.fillAmount = 1 - (10 - _time2) / 10f;
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
-
+using UnityEngine;
+using FairyGUI;
+public class CooldownMain : MonoBehaviour
+{
+ GComponent _mainView;
+
+ GButton _btn0;
+ GImage _mask0;
+ float _time1;
+
+ GButton _btn1;
+ GImage _mask1;
+ float _time2;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.gameObject.GetComponent().ui;
+
+ _btn0 = _mainView.GetChild("b0").asButton;
+ _btn0.icon = "Cooldown/k0";
+ _time1 = 5;
+ _mask0 = _btn0.GetChild("mask").asImage;
+
+ _btn1 = _mainView.GetChild("b1").asButton;
+ _btn1.icon = "Cooldown/k1";
+ _time2 = 10;
+ _mask1 = _btn1.GetChild("mask").asImage;
+
+ }
+
+ void Update()
+ {
+ _time1 -= Time.deltaTime;
+ if (_time1 < 0)
+ _time1 = 5;
+ _mask0.fillAmount = 1 - (5 - _time1) / 5f;
+
+ _time2 -= Time.deltaTime;
+ if (_time2 < 0)
+ _time2 = 10;
+ _btn1.text = string.Empty + Mathf.RoundToInt(_time2);
+ _mask1.fillAmount = 1 - (10 - _time2) / 10f;
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
+
}
\ No newline at end of file
diff --git a/Assets/Examples/Curve/CurveMain.cs b/Assets/Examples/Curve/CurveMain.cs
index 2f736a02..0b5803b0 100644
--- a/Assets/Examples/Curve/CurveMain.cs
+++ b/Assets/Examples/Curve/CurveMain.cs
@@ -1,58 +1,58 @@
-using UnityEngine;
-using FairyGUI;
-
-public class CurveMain : MonoBehaviour
-{
- GComponent _mainView;
- GList _list;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _list = _mainView.GetChild("list").asList;
- _list.SetVirtualAndLoop();
- _list.itemRenderer = RenderListItem;
- _list.numItems = 5;
- _list.scrollPane.onScroll.Add(DoSpecialEffect);
-
- DoSpecialEffect();
- }
-
- void DoSpecialEffect()
- {
- //change the scale according to the distance to middle
- float midX = _list.scrollPane.posX + _list.viewWidth / 2;
- int cnt = _list.numChildren;
- for (int i = 0; i < cnt; i++)
- {
- GObject obj = _list.GetChildAt(i);
- float dist = Mathf.Abs(midX - obj.x - obj.width / 2);
- if (dist > obj.width) //no intersection
- obj.SetScale(1, 1);
- else
- {
- float ss = 1 + (1 - dist / obj.width) * 0.24f;
- obj.SetScale(ss, ss);
- }
- }
- }
-
- void RenderListItem(int index, GObject obj)
- {
- GButton item = (GButton)obj;
- item.SetPivot(0.5f, 0.5f);
- item.icon = UIPackage.GetItemURL("Curve", "n" + (index + 1));
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class CurveMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GList _list;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _list = _mainView.GetChild("list").asList;
+ _list.SetVirtualAndLoop();
+ _list.itemRenderer = RenderListItem;
+ _list.numItems = 5;
+ _list.scrollPane.onScroll.Add(DoSpecialEffect);
+
+ DoSpecialEffect();
+ }
+
+ void DoSpecialEffect()
+ {
+ //change the scale according to the distance to middle
+ float midX = _list.scrollPane.posX + _list.viewWidth / 2;
+ int cnt = _list.numChildren;
+ for (int i = 0; i < cnt; i++)
+ {
+ GObject obj = _list.GetChildAt(i);
+ float dist = Mathf.Abs(midX - obj.x - obj.width / 2);
+ if (dist > obj.width) //no intersection
+ obj.SetScale(1, 1);
+ else
+ {
+ float ss = 1 + (1 - dist / obj.width) * 0.24f;
+ obj.SetScale(ss, ss);
+ }
+ }
+ }
+
+ void RenderListItem(int index, GObject obj)
+ {
+ GButton item = (GButton)obj;
+ item.SetPivot(0.5f, 0.5f);
+ item.icon = UIPackage.GetItemURL("Curve", "n" + (index + 1));
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/CutScene/CutSceneMain.cs b/Assets/Examples/CutScene/CutSceneMain.cs
index a9aacab6..a1cfafd8 100644
--- a/Assets/Examples/CutScene/CutSceneMain.cs
+++ b/Assets/Examples/CutScene/CutSceneMain.cs
@@ -1,28 +1,28 @@
-using System.Collections;
-using UnityEngine;
-using FairyGUI;
-
-///
-/// Demonstrated the simple flow of a game.
-///
-public class CutSceneMain : MonoBehaviour
-{
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- UIPackage.AddPackage("UI/CutScene");
-
- LevelManager.inst.Init();
- LevelManager.inst.LoadLevel("scene1");
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using System.Collections;
+using UnityEngine;
+using FairyGUI;
+
+///
+/// Demonstrated the simple flow of a game.
+///
+public class CutSceneMain : MonoBehaviour
+{
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ UIPackage.AddPackage("UI/CutScene");
+
+ LevelManager.inst.Init();
+ LevelManager.inst.LoadLevel("scene1");
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/CutScene/LevelManager.cs b/Assets/Examples/CutScene/LevelManager.cs
index 53afda87..a08c2a13 100644
--- a/Assets/Examples/CutScene/LevelManager.cs
+++ b/Assets/Examples/CutScene/LevelManager.cs
@@ -1,82 +1,82 @@
-using System.Collections;
-using UnityEngine;
-#if UNITY_5_3_OR_NEWER
-using UnityEngine.SceneManagement;
-#endif
-using FairyGUI;
-
-public class LevelManager : MonoBehaviour
-{
- static LevelManager _instance;
- public static LevelManager inst
- {
- get
- {
- if (_instance == null)
- {
- GameObject go = new GameObject("LevelManager");
- DontDestroyOnLoad(go);
- _instance = go.AddComponent();
- }
- return _instance;
- }
- }
-
- GComponent _cutSceneView;
- GComponent _mainView;
-
- public LevelManager()
- {
- }
-
- public void Init()
- {
- _cutSceneView = UIPackage.CreateObject("CutScene", "CutScene").asCom;
- _cutSceneView.SetSize(GRoot.inst.width, GRoot.inst.height);
- _cutSceneView.AddRelation(GRoot.inst, RelationType.Size);
-
- _mainView = UIPackage.CreateObject("CutScene", "Main").asCom;
- _mainView.SetSize(GRoot.inst.width, GRoot.inst.height);
- _mainView.AddRelation(GRoot.inst, RelationType.Size);
-
- _mainView.GetChild("n0").onClick.Add(() =>
- {
- LoadLevel("scene1");
- });
-
- _mainView.GetChild("n1").onClick.Add(() =>
- {
- LoadLevel("scene2");
- });
- }
-
- public void LoadLevel(string levelName)
- {
- StartCoroutine(DoLoad(levelName));
- GRoot.inst.AddChild(_cutSceneView);
- }
-
- IEnumerator DoLoad(string sceneName)
- {
- GRoot.inst.AddChild(_cutSceneView);
- GProgressBar pb = _cutSceneView.GetChild("pb").asProgress;
- pb.value = 0;
-#if UNITY_5_3_OR_NEWER
- AsyncOperation op = SceneManager.LoadSceneAsync(sceneName);
-#else
- AsyncOperation op = Application.LoadLevelAsync(sceneName);
-#endif
- float startTime = Time.time;
- while (!op.isDone || pb.value != 100)
- {
- int value = (int)((Time.time - startTime) * 100f / 3f);
- if (value > 100)
- value = 100;
- pb.value = value;
- yield return null;
- }
-
- GRoot.inst.RemoveChild(_cutSceneView);
- GRoot.inst.AddChild(_mainView);
- }
-}
+using System.Collections;
+using UnityEngine;
+#if UNITY_5_3_OR_NEWER
+using UnityEngine.SceneManagement;
+#endif
+using FairyGUI;
+
+public class LevelManager : MonoBehaviour
+{
+ static LevelManager _instance;
+ public static LevelManager inst
+ {
+ get
+ {
+ if (_instance == null)
+ {
+ GameObject go = new GameObject("LevelManager");
+ DontDestroyOnLoad(go);
+ _instance = go.AddComponent();
+ }
+ return _instance;
+ }
+ }
+
+ GComponent _cutSceneView;
+ GComponent _mainView;
+
+ public LevelManager()
+ {
+ }
+
+ public void Init()
+ {
+ _cutSceneView = UIPackage.CreateObject("CutScene", "CutScene").asCom;
+ _cutSceneView.SetSize(GRoot.inst.width, GRoot.inst.height);
+ _cutSceneView.AddRelation(GRoot.inst, RelationType.Size);
+
+ _mainView = UIPackage.CreateObject("CutScene", "Main").asCom;
+ _mainView.SetSize(GRoot.inst.width, GRoot.inst.height);
+ _mainView.AddRelation(GRoot.inst, RelationType.Size);
+
+ _mainView.GetChild("n0").onClick.Add(() =>
+ {
+ LoadLevel("scene1");
+ });
+
+ _mainView.GetChild("n1").onClick.Add(() =>
+ {
+ LoadLevel("scene2");
+ });
+ }
+
+ public void LoadLevel(string levelName)
+ {
+ StartCoroutine(DoLoad(levelName));
+ GRoot.inst.AddChild(_cutSceneView);
+ }
+
+ IEnumerator DoLoad(string sceneName)
+ {
+ GRoot.inst.AddChild(_cutSceneView);
+ GProgressBar pb = _cutSceneView.GetChild("pb").asProgress;
+ pb.value = 0;
+#if UNITY_5_3_OR_NEWER
+ AsyncOperation op = SceneManager.LoadSceneAsync(sceneName);
+#else
+ AsyncOperation op = Application.LoadLevelAsync(sceneName);
+#endif
+ float startTime = Time.time;
+ while (!op.isDone || pb.value != 100)
+ {
+ int value = (int)((Time.time - startTime) * 100f / 3f);
+ if (value > 100)
+ value = 100;
+ pb.value = value;
+ yield return null;
+ }
+
+ GRoot.inst.RemoveChild(_cutSceneView);
+ GRoot.inst.AddChild(_mainView);
+ }
+}
diff --git a/Assets/Examples/Editor/BuildAssetBundles.cs b/Assets/Examples/Editor/BuildAssetBundles.cs
index 2cef9b1f..2a59e3c3 100644
--- a/Assets/Examples/Editor/BuildAssetBundles.cs
+++ b/Assets/Examples/Editor/BuildAssetBundles.cs
@@ -1,38 +1,38 @@
-using UnityEngine;
-using UnityEditor;
-using System.IO;
-
-public class BuildAssetBundles
-{
- [MenuItem("Window/Build FairyGUI Example Bundles")]
- public static void Builde()
- {
-#if (UNITY_5 || UNITY_5_3_OR_NEWER)
- for (int i = 0; i < 10; i++)
- {
- AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/Icons/i" + i + ".png").assetBundleName = "fairygui-examples/i" + i + ".ab";
- }
-
- AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_fui.bytes").assetBundleName = "fairygui-examples/bundleusage.ab";
- AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_atlas0.png").assetBundleName = "fairygui-examples/bundleusage.ab";
-
- BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, BuildAssetBundleOptions.None, BuildTarget.Android);
-#else
- for (int i = 0; i < 10; i++)
- {
- Object obj = AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/Icons/i"+i+".png", typeof(Object));
- BuildPipeline.BuildAssetBundle(obj, null, Path.Combine(Application.streamingAssetsPath, "fairygui-examples/i" + i + ".ab"),
- BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android);
- }
-
- Object mainAsset = AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_fui.bytes", typeof(Object));
- Object[] assets = new Object[] {
- AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_atlas0.png", typeof(Object))
- };
-
- BuildPipeline.BuildAssetBundle(mainAsset, assets, Path.Combine(Application.streamingAssetsPath, "fairygui-examples/bundleusage.ab"),
- BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android);
- AssetDatabase.Refresh();
-#endif
- }
+using UnityEngine;
+using UnityEditor;
+using System.IO;
+
+public class BuildAssetBundles
+{
+ [MenuItem("Window/Build FairyGUI Example Bundles")]
+ public static void Builde()
+ {
+#if (UNITY_5 || UNITY_5_3_OR_NEWER)
+ for (int i = 0; i < 10; i++)
+ {
+ AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/Icons/i" + i + ".png").assetBundleName = "fairygui-examples/i" + i + ".ab";
+ }
+
+ AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_fui.bytes").assetBundleName = "fairygui-examples/bundleusage.ab";
+ AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_atlas0.png").assetBundleName = "fairygui-examples/bundleusage.ab";
+
+ BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, BuildAssetBundleOptions.None, BuildTarget.Android);
+#else
+ for (int i = 0; i < 10; i++)
+ {
+ Object obj = AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/Icons/i"+i+".png", typeof(Object));
+ BuildPipeline.BuildAssetBundle(obj, null, Path.Combine(Application.streamingAssetsPath, "fairygui-examples/i" + i + ".ab"),
+ BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android);
+ }
+
+ Object mainAsset = AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_fui.bytes", typeof(Object));
+ Object[] assets = new Object[] {
+ AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_atlas0.png", typeof(Object))
+ };
+
+ BuildPipeline.BuildAssetBundle(mainAsset, assets, Path.Combine(Application.streamingAssetsPath, "fairygui-examples/bundleusage.ab"),
+ BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android);
+ AssetDatabase.Refresh();
+#endif
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/EmitNumbers/EmitComponent.cs b/Assets/Examples/EmitNumbers/EmitComponent.cs
index 0d54701a..2910a789 100644
--- a/Assets/Examples/EmitNumbers/EmitComponent.cs
+++ b/Assets/Examples/EmitNumbers/EmitComponent.cs
@@ -1,94 +1,94 @@
-using UnityEngine;
-using FairyGUI;
-
-public class EmitComponent : GComponent
-{
- GLoader _symbolLoader;
- GTextField _numberText;
- Transform _owner;
-
- const float OFFSET_ADDITION = 2.2f;
- static Vector2 JITTER_FACTOR = new Vector2(80, 80);
-
- public EmitComponent()
- {
- this.touchable = false;
-
- _symbolLoader = new GLoader();
- _symbolLoader.autoSize = true;
- AddChild(_symbolLoader);
-
- _numberText = new GTextField();
- _numberText.autoSize = AutoSizeType.Both;
-
- AddChild(_numberText);
- }
-
- public void SetHurt(Transform owner, int type, long hurt, bool critical)
- {
- _owner = owner;
-
- TextFormat tf = _numberText.textFormat;
- if (type == 0)
- tf.font = EmitManager.inst.hurtFont1;
- else
- tf.font = EmitManager.inst.hurtFont2;
- _numberText.textFormat = tf;
- _numberText.text = "-" + hurt;
-
- if (critical)
- _symbolLoader.url = EmitManager.inst.criticalSign;
- else
- _symbolLoader.url = "";
-
- UpdateLayout();
-
- this.alpha = 1;
- UpdatePosition(Vector2.zero);
- Vector2 rnd = Vector2.Scale(UnityEngine.Random.insideUnitCircle, JITTER_FACTOR);
- int toX = (int)rnd.x * 2;
- int toY = (int)rnd.y * 2;
-
- EmitManager.inst.view.AddChild(this);
- GTween.To(Vector2.zero, new Vector2(toX, toY), 1f).SetTarget(this)
- .OnUpdate((GTweener tweener) => { this.UpdatePosition(tweener.value.vec2); }).OnComplete(this.OnCompleted);
- this.TweenFade(0, 0.5f).SetDelay(0.5f);
- }
-
- void UpdateLayout()
- {
- this.SetSize(_symbolLoader.width + _numberText.width, Mathf.Max(_symbolLoader.height, _numberText.height));
- _numberText.SetXY(_symbolLoader.width > 0 ? (_symbolLoader.width + 2) : 0,
- (this.height - _numberText.height) / 2);
- _symbolLoader.y = (this.height - _symbolLoader.height) / 2;
- }
-
- void UpdatePosition(Vector2 pos)
- {
- Vector3 ownerPos = _owner.position;
- ownerPos.y += OFFSET_ADDITION;
- Vector3 screenPos = Camera.main.WorldToScreenPoint(ownerPos);
- screenPos.y = Screen.height - screenPos.y; //convert to Stage coordinates system
-
- Vector3 pt = GRoot.inst.GlobalToLocal(screenPos);
- this.SetXY(Mathf.RoundToInt(pt.x + pos.x - this.actualWidth / 2), Mathf.RoundToInt(pt.y + pos.y - this.height));
- }
-
- void OnCompleted()
- {
- _owner = null;
- EmitManager.inst.view.RemoveChild(this);
- EmitManager.inst.ReturnComponent(this);
- }
-
- public void Cancel()
- {
- _owner = null;
- if (this.parent != null)
- {
- GTween.Kill(this);
- EmitManager.inst.view.RemoveChild(this);
- }
- EmitManager.inst.ReturnComponent(this);
- }
+using UnityEngine;
+using FairyGUI;
+
+public class EmitComponent : GComponent
+{
+ GLoader _symbolLoader;
+ GTextField _numberText;
+ Transform _owner;
+
+ const float OFFSET_ADDITION = 2.2f;
+ static Vector2 JITTER_FACTOR = new Vector2(80, 80);
+
+ public EmitComponent()
+ {
+ this.touchable = false;
+
+ _symbolLoader = new GLoader();
+ _symbolLoader.autoSize = true;
+ AddChild(_symbolLoader);
+
+ _numberText = new GTextField();
+ _numberText.autoSize = AutoSizeType.Both;
+
+ AddChild(_numberText);
+ }
+
+ public void SetHurt(Transform owner, int type, long hurt, bool critical)
+ {
+ _owner = owner;
+
+ TextFormat tf = _numberText.textFormat;
+ if (type == 0)
+ tf.font = EmitManager.inst.hurtFont1;
+ else
+ tf.font = EmitManager.inst.hurtFont2;
+ _numberText.textFormat = tf;
+ _numberText.text = "-" + hurt;
+
+ if (critical)
+ _symbolLoader.url = EmitManager.inst.criticalSign;
+ else
+ _symbolLoader.url = "";
+
+ UpdateLayout();
+
+ this.alpha = 1;
+ UpdatePosition(Vector2.zero);
+ Vector2 rnd = Vector2.Scale(UnityEngine.Random.insideUnitCircle, JITTER_FACTOR);
+ int toX = (int)rnd.x * 2;
+ int toY = (int)rnd.y * 2;
+
+ EmitManager.inst.view.AddChild(this);
+ GTween.To(Vector2.zero, new Vector2(toX, toY), 1f).SetTarget(this)
+ .OnUpdate((GTweener tweener) => { this.UpdatePosition(tweener.value.vec2); }).OnComplete(this.OnCompleted);
+ this.TweenFade(0, 0.5f).SetDelay(0.5f);
+ }
+
+ void UpdateLayout()
+ {
+ this.SetSize(_symbolLoader.width + _numberText.width, Mathf.Max(_symbolLoader.height, _numberText.height));
+ _numberText.SetXY(_symbolLoader.width > 0 ? (_symbolLoader.width + 2) : 0,
+ (this.height - _numberText.height) / 2);
+ _symbolLoader.y = (this.height - _symbolLoader.height) / 2;
+ }
+
+ void UpdatePosition(Vector2 pos)
+ {
+ Vector3 ownerPos = _owner.position;
+ ownerPos.y += OFFSET_ADDITION;
+ Vector3 screenPos = Camera.main.WorldToScreenPoint(ownerPos);
+ screenPos.y = Screen.height - screenPos.y; //convert to Stage coordinates system
+
+ Vector3 pt = GRoot.inst.GlobalToLocal(screenPos);
+ this.SetXY(Mathf.RoundToInt(pt.x + pos.x - this.actualWidth / 2), Mathf.RoundToInt(pt.y + pos.y - this.height));
+ }
+
+ void OnCompleted()
+ {
+ _owner = null;
+ EmitManager.inst.view.RemoveChild(this);
+ EmitManager.inst.ReturnComponent(this);
+ }
+
+ public void Cancel()
+ {
+ _owner = null;
+ if (this.parent != null)
+ {
+ GTween.Kill(this);
+ EmitManager.inst.view.RemoveChild(this);
+ }
+ EmitManager.inst.ReturnComponent(this);
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/EmitNumbers/EmitManager.cs b/Assets/Examples/EmitNumbers/EmitManager.cs
index 19ea95e0..ef12b53e 100644
--- a/Assets/Examples/EmitNumbers/EmitManager.cs
+++ b/Assets/Examples/EmitNumbers/EmitManager.cs
@@ -1,50 +1,50 @@
-using System.Collections.Generic;
-using UnityEngine;
-using FairyGUI;
-
-public class EmitManager
-{
- static EmitManager _instance;
- public static EmitManager inst
- {
- get
- {
- if (_instance == null)
- _instance = new EmitManager();
- return _instance;
- }
- }
-
- public string hurtFont1;
- public string hurtFont2;
- public string criticalSign;
-
- public GComponent view { get; private set; }
-
- private readonly Stack _componentPool = new Stack();
-
- public EmitManager()
- {
- hurtFont1 = "ui://EmitNumbers/number1";
- hurtFont2 = "ui://EmitNumbers/number2";
- criticalSign = "ui://EmitNumbers/critical";
-
- view = new GComponent();
- GRoot.inst.AddChild(view);
- }
-
- public void Emit(Transform owner, int type, long hurt, bool critical)
- {
- EmitComponent ec;
- if (_componentPool.Count > 0)
- ec = _componentPool.Pop();
- else
- ec = new EmitComponent();
- ec.SetHurt(owner, type, hurt, critical);
- }
-
- public void ReturnComponent(EmitComponent com)
- {
- _componentPool.Push(com);
- }
+using System.Collections.Generic;
+using UnityEngine;
+using FairyGUI;
+
+public class EmitManager
+{
+ static EmitManager _instance;
+ public static EmitManager inst
+ {
+ get
+ {
+ if (_instance == null)
+ _instance = new EmitManager();
+ return _instance;
+ }
+ }
+
+ public string hurtFont1;
+ public string hurtFont2;
+ public string criticalSign;
+
+ public GComponent view { get; private set; }
+
+ private readonly Stack _componentPool = new Stack();
+
+ public EmitManager()
+ {
+ hurtFont1 = "ui://EmitNumbers/number1";
+ hurtFont2 = "ui://EmitNumbers/number2";
+ criticalSign = "ui://EmitNumbers/critical";
+
+ view = new GComponent();
+ GRoot.inst.AddChild(view);
+ }
+
+ public void Emit(Transform owner, int type, long hurt, bool critical)
+ {
+ EmitComponent ec;
+ if (_componentPool.Count > 0)
+ ec = _componentPool.Pop();
+ else
+ ec = new EmitComponent();
+ ec.SetHurt(owner, type, hurt, critical);
+ }
+
+ public void ReturnComponent(EmitComponent com)
+ {
+ _componentPool.Push(com);
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/EmitNumbers/EmitNumbersMain.cs b/Assets/Examples/EmitNumbers/EmitNumbersMain.cs
index af07bcac..f1cdcdf3 100644
--- a/Assets/Examples/EmitNumbers/EmitNumbersMain.cs
+++ b/Assets/Examples/EmitNumbers/EmitNumbersMain.cs
@@ -1,44 +1,44 @@
-using System.Collections;
-using UnityEngine;
-using FairyGUI;
-
-public class EmitNumbersMain : MonoBehaviour
-{
- Transform _npc1;
- Transform _npc2;
- bool _finished;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _npc1 = GameObject.Find("npc1").transform;
- _npc2 = GameObject.Find("npc2").transform;
-
- StartCoroutine(RunTest());
- }
-
- void OnDisable()
- {
- _finished = true;
- }
-
- IEnumerator RunTest()
- {
- while (!_finished)
- {
- EmitManager.inst.Emit(_npc1, 0, UnityEngine.Random.Range(100, 100000), UnityEngine.Random.Range(0, 10) == 5);
- EmitManager.inst.Emit(_npc2, 1, UnityEngine.Random.Range(100, 100000), UnityEngine.Random.Range(0, 10) == 5);
- yield return new WaitForSeconds(0.3f);
- }
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using System.Collections;
+using UnityEngine;
+using FairyGUI;
+
+public class EmitNumbersMain : MonoBehaviour
+{
+ Transform _npc1;
+ Transform _npc2;
+ bool _finished;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _npc1 = GameObject.Find("npc1").transform;
+ _npc2 = GameObject.Find("npc2").transform;
+
+ StartCoroutine(RunTest());
+ }
+
+ void OnDisable()
+ {
+ _finished = true;
+ }
+
+ IEnumerator RunTest()
+ {
+ while (!_finished)
+ {
+ EmitManager.inst.Emit(_npc1, 0, UnityEngine.Random.Range(100, 100000), UnityEngine.Random.Range(0, 10) == 5);
+ EmitManager.inst.Emit(_npc2, 1, UnityEngine.Random.Range(100, 100000), UnityEngine.Random.Range(0, 10) == 5);
+ yield return new WaitForSeconds(0.3f);
+ }
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Emoji/EmojiMain.cs b/Assets/Examples/Emoji/EmojiMain.cs
index b26160c5..94897138 100644
--- a/Assets/Examples/Emoji/EmojiMain.cs
+++ b/Assets/Examples/Emoji/EmojiMain.cs
@@ -1,196 +1,196 @@
-using System;
-using System.Collections.Generic;
-using UnityEngine;
-using FairyGUI;
-
-public class EmojiMain : MonoBehaviour
-{
- GComponent _mainView;
- GList _list;
- GTextInput _input1;
- GTextInput _input2;
- GComponent _emojiSelectUI1;
- GComponent _emojiSelectUI2;
-
- class Message
- {
- public string sender;
- public string senderIcon;
- public string msg;
- public bool fromMe;
- }
- List _messages;
-
- Dictionary _emojies;
-
- void Awake()
- {
- UIPackage.AddPackage("UI/Emoji");
-
- UIConfig.verticalScrollBar = "ui://Emoji/ScrollBar_VT";
- UIConfig.defaultScrollBarDisplay = ScrollBarDisplayType.Auto;
- }
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _messages = new List();
-
- _mainView = this.GetComponent().ui;
-
- _list = _mainView.GetChild("list").asList;
- _list.SetVirtual();
- _list.itemProvider = GetListItemResource;
- _list.itemRenderer = RenderListItem;
-
- _input1 = _mainView.GetChild("input1").asTextInput;
- _input1.onKeyDown.Add(__inputKeyDown1);
-
- _input2 = _mainView.GetChild("input2").asTextInput;
- _input2.onKeyDown.Add(__inputKeyDown2);
-
- //作为demo,这里只添加了部分表情素材
- _emojies = new Dictionary();
- for (uint i = 0x1f600; i < 0x1f637; i++)
- {
- string url = UIPackage.GetItemURL("Emoji", Convert.ToString(i, 16));
- if (url != null)
- _emojies.Add(i, new Emoji(url));
- }
- _input2.emojies = _emojies;
-
- _mainView.GetChild("btnSend1").onClick.Add(__clickSendBtn1);
- _mainView.GetChild("btnSend2").onClick.Add(__clickSendBtn2);
-
- _mainView.GetChild("btnEmoji1").onClick.Add(__clickEmojiBtn1);
- _mainView.GetChild("btnEmoji2").onClick.Add(__clickEmojiBtn2);
-
- _emojiSelectUI1 = UIPackage.CreateObject("Emoji", "EmojiSelectUI").asCom;
- _emojiSelectUI1.fairyBatching = true;
- _emojiSelectUI1.GetChild("list").asList.onClickItem.Add(__clickEmoji1);
-
- _emojiSelectUI2 = UIPackage.CreateObject("Emoji", "EmojiSelectUI_ios").asCom;
- _emojiSelectUI2.fairyBatching = true;
- _emojiSelectUI2.GetChild("list").asList.onClickItem.Add(__clickEmoji2);
- }
-
- void AddMsg(string sender, string senderIcon, string msg, bool fromMe)
- {
- bool isScrollBottom = _list.scrollPane.isBottomMost;
-
- Message newMessage = new Message();
- newMessage.sender = sender;
- newMessage.senderIcon = senderIcon;
- newMessage.msg = msg;
- newMessage.fromMe = fromMe;
- _messages.Add(newMessage);
-
- if (newMessage.fromMe)
- {
- if (_messages.Count == 1 || UnityEngine.Random.Range(0f, 1f) < 0.5f)
- {
- Message replyMessage = new Message();
- replyMessage.sender = "FairyGUI";
- replyMessage.senderIcon = "r1";
- replyMessage.msg = "Today is a good day. \U0001f600";
- replyMessage.fromMe = false;
- _messages.Add(replyMessage);
- }
- }
-
- if (_messages.Count > 100)
- _messages.RemoveRange(0, _messages.Count - 100);
-
- _list.numItems = _messages.Count;
-
- if (isScrollBottom)
- _list.scrollPane.ScrollBottom();
- }
-
- string GetListItemResource(int index)
- {
- Message msg = _messages[index];
- if (msg.fromMe)
- return "ui://Emoji/chatRight";
- else
- return "ui://Emoji/chatLeft";
- }
-
- void RenderListItem(int index, GObject obj)
- {
- GButton item = (GButton)obj;
- Message msg = _messages[index];
- if (!msg.fromMe)
- item.GetChild("name").text = msg.sender;
- item.icon = UIPackage.GetItemURL("Emoji", msg.senderIcon);
-
- //Recaculate the text width
- GRichTextField tf = item.GetChild("msg").asRichTextField;
- tf.emojies = _emojies;
- tf.text = EmojiParser.inst.Parse(msg.msg);
- }
-
- void __clickSendBtn1(EventContext context)
- {
- string msg = _input1.text;
- if (msg.Length == 0)
- return;
-
- AddMsg("Unity", "r0", msg, true);
- _input1.text = "";
- }
-
- void __clickSendBtn2(EventContext context)
- {
- string msg = _input2.text;
- if (msg.Length == 0)
- return;
-
- AddMsg("Unity", "r0", msg, true);
- _input2.text = "";
- }
-
- void __clickEmojiBtn1(EventContext context)
- {
- GRoot.inst.ShowPopup(_emojiSelectUI1, (GObject)context.sender, PopupDirection.Up);
- }
-
- void __clickEmojiBtn2(EventContext context)
- {
- GRoot.inst.ShowPopup(_emojiSelectUI2, (GObject)context.sender, PopupDirection.Up);
- }
-
- void __clickEmoji1(EventContext context)
- {
- GButton item = (GButton)context.data;
- _input1.ReplaceSelection("[:" + item.text + "]");
- }
-
- void __clickEmoji2(EventContext context)
- {
- GButton item = (GButton)context.data;
- _input2.ReplaceSelection(Char.ConvertFromUtf32(Convert.ToInt32(UIPackage.GetItemByURL(item.icon).name, 16)));
- }
-
- void __inputKeyDown1(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Return)
- _mainView.GetChild("btnSend1").onClick.Call();
- }
-
- void __inputKeyDown2(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Return)
- _mainView.GetChild("btnSend2").onClick.Call();
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using System;
+using System.Collections.Generic;
+using UnityEngine;
+using FairyGUI;
+
+public class EmojiMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GList _list;
+ GTextInput _input1;
+ GTextInput _input2;
+ GComponent _emojiSelectUI1;
+ GComponent _emojiSelectUI2;
+
+ class Message
+ {
+ public string sender;
+ public string senderIcon;
+ public string msg;
+ public bool fromMe;
+ }
+ List _messages;
+
+ Dictionary _emojies;
+
+ void Awake()
+ {
+ UIPackage.AddPackage("UI/Emoji");
+
+ UIConfig.verticalScrollBar = "ui://Emoji/ScrollBar_VT";
+ UIConfig.defaultScrollBarDisplay = ScrollBarDisplayType.Auto;
+ }
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _messages = new List();
+
+ _mainView = this.GetComponent().ui;
+
+ _list = _mainView.GetChild("list").asList;
+ _list.SetVirtual();
+ _list.itemProvider = GetListItemResource;
+ _list.itemRenderer = RenderListItem;
+
+ _input1 = _mainView.GetChild("input1").asTextInput;
+ _input1.onKeyDown.Add(__inputKeyDown1);
+
+ _input2 = _mainView.GetChild("input2").asTextInput;
+ _input2.onKeyDown.Add(__inputKeyDown2);
+
+ //作为demo,这里只添加了部分表情素材
+ _emojies = new Dictionary();
+ for (uint i = 0x1f600; i < 0x1f637; i++)
+ {
+ string url = UIPackage.GetItemURL("Emoji", Convert.ToString(i, 16));
+ if (url != null)
+ _emojies.Add(i, new Emoji(url));
+ }
+ _input2.emojies = _emojies;
+
+ _mainView.GetChild("btnSend1").onClick.Add(__clickSendBtn1);
+ _mainView.GetChild("btnSend2").onClick.Add(__clickSendBtn2);
+
+ _mainView.GetChild("btnEmoji1").onClick.Add(__clickEmojiBtn1);
+ _mainView.GetChild("btnEmoji2").onClick.Add(__clickEmojiBtn2);
+
+ _emojiSelectUI1 = UIPackage.CreateObject("Emoji", "EmojiSelectUI").asCom;
+ _emojiSelectUI1.fairyBatching = true;
+ _emojiSelectUI1.GetChild("list").asList.onClickItem.Add(__clickEmoji1);
+
+ _emojiSelectUI2 = UIPackage.CreateObject("Emoji", "EmojiSelectUI_ios").asCom;
+ _emojiSelectUI2.fairyBatching = true;
+ _emojiSelectUI2.GetChild("list").asList.onClickItem.Add(__clickEmoji2);
+ }
+
+ void AddMsg(string sender, string senderIcon, string msg, bool fromMe)
+ {
+ bool isScrollBottom = _list.scrollPane.isBottomMost;
+
+ Message newMessage = new Message();
+ newMessage.sender = sender;
+ newMessage.senderIcon = senderIcon;
+ newMessage.msg = msg;
+ newMessage.fromMe = fromMe;
+ _messages.Add(newMessage);
+
+ if (newMessage.fromMe)
+ {
+ if (_messages.Count == 1 || UnityEngine.Random.Range(0f, 1f) < 0.5f)
+ {
+ Message replyMessage = new Message();
+ replyMessage.sender = "FairyGUI";
+ replyMessage.senderIcon = "r1";
+ replyMessage.msg = "Today is a good day. \U0001f600";
+ replyMessage.fromMe = false;
+ _messages.Add(replyMessage);
+ }
+ }
+
+ if (_messages.Count > 100)
+ _messages.RemoveRange(0, _messages.Count - 100);
+
+ _list.numItems = _messages.Count;
+
+ if (isScrollBottom)
+ _list.scrollPane.ScrollBottom();
+ }
+
+ string GetListItemResource(int index)
+ {
+ Message msg = _messages[index];
+ if (msg.fromMe)
+ return "ui://Emoji/chatRight";
+ else
+ return "ui://Emoji/chatLeft";
+ }
+
+ void RenderListItem(int index, GObject obj)
+ {
+ GButton item = (GButton)obj;
+ Message msg = _messages[index];
+ if (!msg.fromMe)
+ item.GetChild("name").text = msg.sender;
+ item.icon = UIPackage.GetItemURL("Emoji", msg.senderIcon);
+
+ //Recaculate the text width
+ GRichTextField tf = item.GetChild("msg").asRichTextField;
+ tf.emojies = _emojies;
+ tf.text = EmojiParser.inst.Parse(msg.msg);
+ }
+
+ void __clickSendBtn1(EventContext context)
+ {
+ string msg = _input1.text;
+ if (msg.Length == 0)
+ return;
+
+ AddMsg("Unity", "r0", msg, true);
+ _input1.text = "";
+ }
+
+ void __clickSendBtn2(EventContext context)
+ {
+ string msg = _input2.text;
+ if (msg.Length == 0)
+ return;
+
+ AddMsg("Unity", "r0", msg, true);
+ _input2.text = "";
+ }
+
+ void __clickEmojiBtn1(EventContext context)
+ {
+ GRoot.inst.ShowPopup(_emojiSelectUI1, (GObject)context.sender, PopupDirection.Up);
+ }
+
+ void __clickEmojiBtn2(EventContext context)
+ {
+ GRoot.inst.ShowPopup(_emojiSelectUI2, (GObject)context.sender, PopupDirection.Up);
+ }
+
+ void __clickEmoji1(EventContext context)
+ {
+ GButton item = (GButton)context.data;
+ _input1.ReplaceSelection("[:" + item.text + "]");
+ }
+
+ void __clickEmoji2(EventContext context)
+ {
+ GButton item = (GButton)context.data;
+ _input2.ReplaceSelection(Char.ConvertFromUtf32(Convert.ToInt32(UIPackage.GetItemByURL(item.icon).name, 16)));
+ }
+
+ void __inputKeyDown1(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Return)
+ _mainView.GetChild("btnSend1").onClick.Call();
+ }
+
+ void __inputKeyDown2(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Return)
+ _mainView.GetChild("btnSend2").onClick.Call();
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Emoji/EmojiParser.cs b/Assets/Examples/Emoji/EmojiParser.cs
index 64a672e6..93a4e809 100644
--- a/Assets/Examples/Emoji/EmojiParser.cs
+++ b/Assets/Examples/Emoji/EmojiParser.cs
@@ -1,31 +1,31 @@
-using FairyGUI;
-using FairyGUI.Utils;
-
-public class EmojiParser : UBBParser
-{
- static EmojiParser _instance;
- public new static EmojiParser inst
- {
- get
- {
- if (_instance == null)
- _instance = new EmojiParser();
- return _instance;
- }
- }
-
- private static string[] TAGS = new string[]
- { "88","am","bs","bz","ch","cool","dhq","dn","fd","gz","han","hx","hxiao","hxiu" };
- public EmojiParser ()
- {
- foreach (string ss in TAGS)
- {
- this.handlers[":"+ss] = OnTag_Emoji;
- }
- }
-
- string OnTag_Emoji(string tagName, bool end, string attr)
- {
- return "
";
- }
+using FairyGUI;
+using FairyGUI.Utils;
+
+public class EmojiParser : UBBParser
+{
+ static EmojiParser _instance;
+ public new static EmojiParser inst
+ {
+ get
+ {
+ if (_instance == null)
+ _instance = new EmojiParser();
+ return _instance;
+ }
+ }
+
+ private static string[] TAGS = new string[]
+ { "88","am","bs","bz","ch","cool","dhq","dn","fd","gz","han","hx","hxiao","hxiu" };
+ public EmojiParser ()
+ {
+ foreach (string ss in TAGS)
+ {
+ this.handlers[":"+ss] = OnTag_Emoji;
+ }
+ }
+
+ string OnTag_Emoji(string tagName, bool end, string attr)
+ {
+ return "
";
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Extension/ExtensionMain.cs b/Assets/Examples/Extension/ExtensionMain.cs
index 8a5156f5..231c54b1 100644
--- a/Assets/Examples/Extension/ExtensionMain.cs
+++ b/Assets/Examples/Extension/ExtensionMain.cs
@@ -1,55 +1,55 @@
-using UnityEngine;
-using FairyGUI;
-
-public class ExtensionMain : MonoBehaviour
-{
- GComponent _mainView;
- GList _list;
-
- void Awake()
- {
- UIPackage.AddPackage("UI/Extension");
- UIObjectFactory.SetPackageItemExtension("ui://Extension/mailItem", typeof(MailItem));
-
- }
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _list = _mainView.GetChild("mailList").asList;
- for (int i = 0; i < 10; i++)
- {
- MailItem item = (MailItem)_list.AddItemFromPool();
- item.setFetched(i % 3 == 0);
- item.setRead(i % 2 == 0);
- item.setTime("5 Nov 2015 16:24:33");
- item.title = "Mail title here";
- }
-
- _list.EnsureBoundsCorrect();
- float delay = 0f;
- for (int i = 0; i < 10; i++)
- {
- MailItem item = (MailItem)_list.GetChildAt(i);
- if (_list.IsChildInView(item))
- {
- item.PlayEffect(delay);
- delay += 0.2f;
- }
- else
- break;
- }
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class ExtensionMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GList _list;
+
+ void Awake()
+ {
+ UIPackage.AddPackage("UI/Extension");
+ UIObjectFactory.SetPackageItemExtension("ui://Extension/mailItem", typeof(MailItem));
+
+ }
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _list = _mainView.GetChild("mailList").asList;
+ for (int i = 0; i < 10; i++)
+ {
+ MailItem item = (MailItem)_list.AddItemFromPool();
+ item.setFetched(i % 3 == 0);
+ item.setRead(i % 2 == 0);
+ item.setTime("5 Nov 2015 16:24:33");
+ item.title = "Mail title here";
+ }
+
+ _list.EnsureBoundsCorrect();
+ float delay = 0f;
+ for (int i = 0; i < 10; i++)
+ {
+ MailItem item = (MailItem)_list.GetChildAt(i);
+ if (_list.IsChildInView(item))
+ {
+ item.PlayEffect(delay);
+ delay += 0.2f;
+ }
+ else
+ break;
+ }
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Extension/MailItem.cs b/Assets/Examples/Extension/MailItem.cs
index dd95a6b7..a67c34c4 100644
--- a/Assets/Examples/Extension/MailItem.cs
+++ b/Assets/Examples/Extension/MailItem.cs
@@ -1,41 +1,41 @@
-using UnityEngine;
-using FairyGUI;
-
-public class MailItem : GButton
-{
- GTextField _timeText;
- Controller _readController;
- Controller _fetchController;
- Transition _trans;
-
- public override void ConstructFromXML(FairyGUI.Utils.XML cxml)
- {
- base.ConstructFromXML(cxml);
-
- _timeText = this.GetChild("timeText").asTextField;
- _readController = this.GetController("IsRead");
- _fetchController = this.GetController("c1");
- _trans = this.GetTransition("t0");
- }
-
- public void setTime(string value)
- {
- _timeText.text = value;
- }
-
- public void setRead(bool value)
- {
- _readController.selectedIndex = value ? 1 : 0;
- }
-
- public void setFetched(bool value)
- {
- _fetchController.selectedIndex = value ? 1 : 0;
- }
-
- public void PlayEffect(float delay)
- {
- this.visible = false;
- _trans.Play(1, delay, null);
- }
-}
+using UnityEngine;
+using FairyGUI;
+
+public class MailItem : GButton
+{
+ GTextField _timeText;
+ Controller _readController;
+ Controller _fetchController;
+ Transition _trans;
+
+ public override void ConstructFromXML(FairyGUI.Utils.XML cxml)
+ {
+ base.ConstructFromXML(cxml);
+
+ _timeText = this.GetChild("timeText").asTextField;
+ _readController = this.GetController("IsRead");
+ _fetchController = this.GetController("c1");
+ _trans = this.GetTransition("t0");
+ }
+
+ public void setTime(string value)
+ {
+ _timeText.text = value;
+ }
+
+ public void setRead(bool value)
+ {
+ _readController.selectedIndex = value ? 1 : 0;
+ }
+
+ public void setFetched(bool value)
+ {
+ _fetchController.selectedIndex = value ? 1 : 0;
+ }
+
+ public void PlayEffect(float delay)
+ {
+ this.visible = false;
+ _trans.Play(1, delay, null);
+ }
+}
diff --git a/Assets/Examples/Filter/FilterMain.cs b/Assets/Examples/Filter/FilterMain.cs
index 3aa27bb5..16f101a3 100644
--- a/Assets/Examples/Filter/FilterMain.cs
+++ b/Assets/Examples/Filter/FilterMain.cs
@@ -1,78 +1,78 @@
-using UnityEngine;
-using FairyGUI;
-
-public class FilterMain : MonoBehaviour
-{
- GComponent _mainView;
- GSlider _s0;
- GSlider _s1;
- GSlider _s2;
- GSlider _s3;
- GSlider _s4;
-
- void Awake()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- UIPackage.AddPackage("UI/Filter");
- }
-
- void Start()
- {
- _mainView = this.GetComponent().ui;
-
- BlurFilter blurFilter = new BlurFilter();
- blurFilter.blurSize = 2;
- _mainView.GetChild("n21").filter = blurFilter;
-
- _s0 = _mainView.GetChild("s0").asSlider;
- _s1 = _mainView.GetChild("s1").asSlider;
- _s2 = _mainView.GetChild("s2").asSlider;
- _s3 = _mainView.GetChild("s3").asSlider;
- _s4 = _mainView.GetChild("s4").asSlider;
-
- _s0.value = 100;
- _s1.value = 100;
- _s2.value = 100;
- _s3.value = 200;
- _s4.value = 20;
-
- _s0.onChanged.Add(__sliderChanged);
- _s1.onChanged.Add(__sliderChanged);
- _s2.onChanged.Add(__sliderChanged);
- _s3.onChanged.Add(__sliderChanged);
- _s4.onChanged.Add(__sliderChanged);
- }
-
- void __sliderChanged(EventContext context)
- {
- int cnt = _mainView.numChildren;
- for (int i = 0; i < cnt; i++)
- {
- GObject obj = _mainView.GetChildAt(i);
- if (obj.filter is ColorFilter)
- {
- ColorFilter filter = (ColorFilter)obj.filter;
- filter.Reset();
- filter.AdjustBrightness((float)(_s0.value - 100) / 100f);
- filter.AdjustContrast((float)(_s1.value - 100) / 100f);
- filter.AdjustSaturation((float)(_s2.value - 100) / 100f);
- filter.AdjustHue((float)(_s3.value - 100) / 100f);
- }
- else if (obj.filter is BlurFilter)
- {
- BlurFilter filter = (BlurFilter)obj.filter;
- filter.blurSize = (float)_s4.value / 100;
- }
- }
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class FilterMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GSlider _s0;
+ GSlider _s1;
+ GSlider _s2;
+ GSlider _s3;
+ GSlider _s4;
+
+ void Awake()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ UIPackage.AddPackage("UI/Filter");
+ }
+
+ void Start()
+ {
+ _mainView = this.GetComponent().ui;
+
+ BlurFilter blurFilter = new BlurFilter();
+ blurFilter.blurSize = 2;
+ _mainView.GetChild("n21").filter = blurFilter;
+
+ _s0 = _mainView.GetChild("s0").asSlider;
+ _s1 = _mainView.GetChild("s1").asSlider;
+ _s2 = _mainView.GetChild("s2").asSlider;
+ _s3 = _mainView.GetChild("s3").asSlider;
+ _s4 = _mainView.GetChild("s4").asSlider;
+
+ _s0.value = 100;
+ _s1.value = 100;
+ _s2.value = 100;
+ _s3.value = 200;
+ _s4.value = 20;
+
+ _s0.onChanged.Add(__sliderChanged);
+ _s1.onChanged.Add(__sliderChanged);
+ _s2.onChanged.Add(__sliderChanged);
+ _s3.onChanged.Add(__sliderChanged);
+ _s4.onChanged.Add(__sliderChanged);
+ }
+
+ void __sliderChanged(EventContext context)
+ {
+ int cnt = _mainView.numChildren;
+ for (int i = 0; i < cnt; i++)
+ {
+ GObject obj = _mainView.GetChildAt(i);
+ if (obj.filter is ColorFilter)
+ {
+ ColorFilter filter = (ColorFilter)obj.filter;
+ filter.Reset();
+ filter.AdjustBrightness((float)(_s0.value - 100) / 100f);
+ filter.AdjustContrast((float)(_s1.value - 100) / 100f);
+ filter.AdjustSaturation((float)(_s2.value - 100) / 100f);
+ filter.AdjustHue((float)(_s3.value - 100) / 100f);
+ }
+ else if (obj.filter is BlurFilter)
+ {
+ BlurFilter filter = (BlurFilter)obj.filter;
+ filter.blurSize = (float)_s4.value / 100;
+ }
+ }
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Gesture/GestureMain.cs b/Assets/Examples/Gesture/GestureMain.cs
index 565071db..85015b72 100644
--- a/Assets/Examples/Gesture/GestureMain.cs
+++ b/Assets/Examples/Gesture/GestureMain.cs
@@ -1,115 +1,115 @@
-using UnityEngine;
-using FairyGUI;
-
-public class GestureMain : MonoBehaviour
-{
- GComponent _mainView;
- Transform _ball;
-
- void Awake()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- UIPackage.AddPackage("UI/Gesture");
- }
-
- void Start()
- {
- _mainView = this.GetComponent().ui;
- GObject holder = _mainView.GetChild("holder");
-
- _ball = GameObject.Find("Globe").transform;
-
- SwipeGesture gesture1 = new SwipeGesture(holder);
- gesture1.onMove.Add(OnSwipeMove);
- gesture1.onEnd.Add(OnSwipeEnd);
-
- LongPressGesture gesture2 = new LongPressGesture(holder);
- gesture2.once = false;
- gesture2.onAction.Add(OnHold);
-
- PinchGesture gesture3 = new PinchGesture(holder);
- gesture3.onAction.Add(OnPinch);
-
- RotationGesture gesture4 = new RotationGesture(holder);
- gesture4.onAction.Add(OnRotate);
- }
-
- void OnSwipeMove(EventContext context)
- {
- SwipeGesture gesture = (SwipeGesture)context.sender;
- Vector3 v = new Vector3();
- if (Mathf.Abs(gesture.delta.x) > Mathf.Abs(gesture.delta.y))
- {
- v.y = -Mathf.Round(gesture.delta.x);
- if (Mathf.Abs(v.y) < 2) //消除手抖的影响
- return;
- }
- else
- {
- v.x = -Mathf.Round(gesture.delta.y);
- if (Mathf.Abs(v.x) < 2)
- return;
- }
- _ball.Rotate(v, Space.World);
- }
-
- void OnSwipeEnd(EventContext context)
- {
- SwipeGesture gesture = (SwipeGesture)context.sender;
- Vector3 v = new Vector3();
- if (Mathf.Abs(gesture.velocity.x) > Mathf.Abs(gesture.velocity.y))
- {
- v.y = -Mathf.Round(Mathf.Sign(gesture.velocity.x) * Mathf.Sqrt(Mathf.Abs(gesture.velocity.x)));
- if (Mathf.Abs(v.y) < 2)
- return;
- }
- else
- {
- v.x = -Mathf.Round(Mathf.Sign(gesture.velocity.y) * Mathf.Sqrt(Mathf.Abs(gesture.velocity.y)));
- if (Mathf.Abs(v.x) < 2)
- return;
- }
-
- GTween.To(v, Vector3.zero, 0.3f).SetTarget(_ball).OnUpdate(
- (GTweener tweener) =>
- {
- _ball.Rotate(tweener.deltaValue.vec3, Space.World);
- });
- }
-
- void OnHold(EventContext context)
- {
- GTween.Shake(_ball.transform.localPosition, 0.05f, 0.5f).SetTarget(_ball).OnUpdate(
- (GTweener tweener) =>
- {
- _ball.transform.localPosition = new Vector3(tweener.value.x, tweener.value.y, _ball.transform.localPosition.z);
- });
- }
-
- void OnPinch(EventContext context)
- {
- GTween.Kill(_ball);
-
- PinchGesture gesture = (PinchGesture)context.sender;
- float newValue = Mathf.Clamp(_ball.localScale.x + gesture.delta, 0.3f, 2);
- _ball.localScale = new Vector3(newValue, newValue, newValue);
- }
-
- void OnRotate(EventContext context)
- {
- GTween.Kill(_ball);
-
- RotationGesture gesture = (RotationGesture)context.sender;
- _ball.Rotate(Vector3.forward, -gesture.delta, Space.World);
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class GestureMain : MonoBehaviour
+{
+ GComponent _mainView;
+ Transform _ball;
+
+ void Awake()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ UIPackage.AddPackage("UI/Gesture");
+ }
+
+ void Start()
+ {
+ _mainView = this.GetComponent().ui;
+ GObject holder = _mainView.GetChild("holder");
+
+ _ball = GameObject.Find("Globe").transform;
+
+ SwipeGesture gesture1 = new SwipeGesture(holder);
+ gesture1.onMove.Add(OnSwipeMove);
+ gesture1.onEnd.Add(OnSwipeEnd);
+
+ LongPressGesture gesture2 = new LongPressGesture(holder);
+ gesture2.once = false;
+ gesture2.onAction.Add(OnHold);
+
+ PinchGesture gesture3 = new PinchGesture(holder);
+ gesture3.onAction.Add(OnPinch);
+
+ RotationGesture gesture4 = new RotationGesture(holder);
+ gesture4.onAction.Add(OnRotate);
+ }
+
+ void OnSwipeMove(EventContext context)
+ {
+ SwipeGesture gesture = (SwipeGesture)context.sender;
+ Vector3 v = new Vector3();
+ if (Mathf.Abs(gesture.delta.x) > Mathf.Abs(gesture.delta.y))
+ {
+ v.y = -Mathf.Round(gesture.delta.x);
+ if (Mathf.Abs(v.y) < 2) //消除手抖的影响
+ return;
+ }
+ else
+ {
+ v.x = -Mathf.Round(gesture.delta.y);
+ if (Mathf.Abs(v.x) < 2)
+ return;
+ }
+ _ball.Rotate(v, Space.World);
+ }
+
+ void OnSwipeEnd(EventContext context)
+ {
+ SwipeGesture gesture = (SwipeGesture)context.sender;
+ Vector3 v = new Vector3();
+ if (Mathf.Abs(gesture.velocity.x) > Mathf.Abs(gesture.velocity.y))
+ {
+ v.y = -Mathf.Round(Mathf.Sign(gesture.velocity.x) * Mathf.Sqrt(Mathf.Abs(gesture.velocity.x)));
+ if (Mathf.Abs(v.y) < 2)
+ return;
+ }
+ else
+ {
+ v.x = -Mathf.Round(Mathf.Sign(gesture.velocity.y) * Mathf.Sqrt(Mathf.Abs(gesture.velocity.y)));
+ if (Mathf.Abs(v.x) < 2)
+ return;
+ }
+
+ GTween.To(v, Vector3.zero, 0.3f).SetTarget(_ball).OnUpdate(
+ (GTweener tweener) =>
+ {
+ _ball.Rotate(tweener.deltaValue.vec3, Space.World);
+ });
+ }
+
+ void OnHold(EventContext context)
+ {
+ GTween.Shake(_ball.transform.localPosition, 0.05f, 0.5f).SetTarget(_ball).OnUpdate(
+ (GTweener tweener) =>
+ {
+ _ball.transform.localPosition = new Vector3(tweener.value.x, tweener.value.y, _ball.transform.localPosition.z);
+ });
+ }
+
+ void OnPinch(EventContext context)
+ {
+ GTween.Kill(_ball);
+
+ PinchGesture gesture = (PinchGesture)context.sender;
+ float newValue = Mathf.Clamp(_ball.localScale.x + gesture.delta, 0.3f, 2);
+ _ball.localScale = new Vector3(newValue, newValue, newValue);
+ }
+
+ void OnRotate(EventContext context)
+ {
+ GTween.Kill(_ball);
+
+ RotationGesture gesture = (RotationGesture)context.sender;
+ _ball.Rotate(Vector3.forward, -gesture.delta, Space.World);
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Guide/GuideMain.cs b/Assets/Examples/Guide/GuideMain.cs
index 140cbb6c..896236ff 100644
--- a/Assets/Examples/Guide/GuideMain.cs
+++ b/Assets/Examples/Guide/GuideMain.cs
@@ -1,44 +1,44 @@
-using UnityEngine;
-using FairyGUI;
-
-public class GuideMain : MonoBehaviour
-{
- GComponent _mainView;
- GComponent _guideLayer;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _guideLayer = UIPackage.CreateObject("Guide", "GuideLayer").asCom;
- _guideLayer.SetSize(GRoot.inst.width, GRoot.inst.height);
- _guideLayer.AddRelation(GRoot.inst, RelationType.Size);
-
- GObject bagBtn = _mainView.GetChild("bagBtn");
- bagBtn.onClick.Add(() =>
- {
- _guideLayer.RemoveFromParent();
- });
-
- _mainView.GetChild("n2").onClick.Add(() =>
- {
- GRoot.inst.AddChild(_guideLayer); //!!Before using TransformRect(or GlobalToLocal), the object must be added first
- Rect rect = bagBtn.TransformRect(new Rect(0, 0, bagBtn.width, bagBtn.height), _guideLayer);
-
- GObject window = _guideLayer.GetChild("window");
- window.size = new Vector2((int)rect.size.x, (int)rect.size.y);
- window.TweenMove(new Vector2((int)rect.position.x, (int)rect.position.y), 0.5f);
- });
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class GuideMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GComponent _guideLayer;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _guideLayer = UIPackage.CreateObject("Guide", "GuideLayer").asCom;
+ _guideLayer.SetSize(GRoot.inst.width, GRoot.inst.height);
+ _guideLayer.AddRelation(GRoot.inst, RelationType.Size);
+
+ GObject bagBtn = _mainView.GetChild("bagBtn");
+ bagBtn.onClick.Add(() =>
+ {
+ _guideLayer.RemoveFromParent();
+ });
+
+ _mainView.GetChild("n2").onClick.Add(() =>
+ {
+ GRoot.inst.AddChild(_guideLayer); //!!Before using TransformRect(or GlobalToLocal), the object must be added first
+ Rect rect = bagBtn.TransformRect(new Rect(0, 0, bagBtn.width, bagBtn.height), _guideLayer);
+
+ GObject window = _guideLayer.GetChild("window");
+ window.size = new Vector2((int)rect.size.x, (int)rect.size.y);
+ window.TweenMove(new Vector2((int)rect.position.x, (int)rect.position.y), 0.5f);
+ });
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/HeadBar/HeadBarMain.cs b/Assets/Examples/HeadBar/HeadBarMain.cs
index 69acbcba..47b1fc40 100644
--- a/Assets/Examples/HeadBar/HeadBarMain.cs
+++ b/Assets/Examples/HeadBar/HeadBarMain.cs
@@ -1,34 +1,34 @@
-using UnityEngine;
-using FairyGUI;
-
-public class HeadBarMain : MonoBehaviour
-{
- GComponent _mainView;
-
- void Start()
- {
- Application.targetFrameRate = 60;
-
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- Transform npc = GameObject.Find("npc1").transform;
- UIPanel panel = npc.Find("HeadBar").GetComponent();
- panel.ui.GetChild("name").text = "Long [color=#FFFFFF]Long[/color][img]ui://HeadBar/cool[/img] Name";
- panel.ui.GetChild("blood").asProgress.value = 75;
- panel.ui.GetChild("sign").asLoader.url = "ui://HeadBar/task";
-
- npc = GameObject.Find("npc2").transform;
- panel = npc.Find("HeadBar").GetComponent();
- panel.ui.GetChild("name").text = "Man2";
- panel.ui.GetChild("blood").asProgress.value = 25;
- panel.ui.GetChild("sign").asLoader.url = "ui://HeadBar/fighting";
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class HeadBarMain : MonoBehaviour
+{
+ GComponent _mainView;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ Transform npc = GameObject.Find("npc1").transform;
+ UIPanel panel = npc.Find("HeadBar").GetComponent();
+ panel.ui.GetChild("name").text = "Long [color=#FFFFFF]Long[/color][img]ui://HeadBar/cool[/img] Name";
+ panel.ui.GetChild("blood").asProgress.value = 75;
+ panel.ui.GetChild("sign").asLoader.url = "ui://HeadBar/task";
+
+ npc = GameObject.Find("npc2").transform;
+ panel = npc.Find("HeadBar").GetComponent();
+ panel.ui.GetChild("name").text = "Man2";
+ panel.ui.GetChild("blood").asProgress.value = 25;
+ panel.ui.GetChild("sign").asLoader.url = "ui://HeadBar/fighting";
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/HitTest/HitTestMain.cs b/Assets/Examples/HitTest/HitTestMain.cs
index 9b36c76c..c72eb113 100644
--- a/Assets/Examples/HitTest/HitTestMain.cs
+++ b/Assets/Examples/HitTest/HitTestMain.cs
@@ -1,40 +1,40 @@
-using UnityEngine;
-using FairyGUI;
-
-public class HitTestMain : MonoBehaviour
-{
- Transform cube;
-
- void Start()
- {
- Application.targetFrameRate = 60;
-
- cube = GameObject.Find("Cube").transform;
-
- Stage.inst.onTouchBegin.Add(OnTouchBegin);
- }
-
- void OnTouchBegin()
- {
- if (!Stage.isTouchOnUI)
- {
- RaycastHit hit;
- Ray ray = Camera.main.ScreenPointToRay(new Vector2(Stage.inst.touchPosition.x, Screen.height - Stage.inst.touchPosition.y));
- if (Physics.Raycast(ray, out hit))
- {
- if (hit.transform == cube)
- {
- Debug.Log("Hit the cube");
- }
- }
- }
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class HitTestMain : MonoBehaviour
+{
+ Transform cube;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+
+ cube = GameObject.Find("Cube").transform;
+
+ Stage.inst.onTouchBegin.Add(OnTouchBegin);
+ }
+
+ void OnTouchBegin()
+ {
+ if (!Stage.isTouchOnUI)
+ {
+ RaycastHit hit;
+ Ray ray = Camera.main.ScreenPointToRay(new Vector2(Stage.inst.touchPosition.x, Screen.height - Stage.inst.touchPosition.y));
+ if (Physics.Raycast(ray, out hit))
+ {
+ if (hit.transform == cube)
+ {
+ Debug.Log("Hit the cube");
+ }
+ }
+ }
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Joystick/JoystickMain.cs b/Assets/Examples/Joystick/JoystickMain.cs
index 4c03b67a..6e60f2b7 100644
--- a/Assets/Examples/Joystick/JoystickMain.cs
+++ b/Assets/Examples/Joystick/JoystickMain.cs
@@ -1,42 +1,42 @@
-using UnityEngine;
-using FairyGUI;
-
-public class JoystickMain : MonoBehaviour
-{
- GComponent _mainView;
- GTextField _text;
- JoystickModule _joystick;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _text = _mainView.GetChild("n9").asTextField;
-
- _joystick = new JoystickModule(_mainView);
- _joystick.onMove.Add(__joystickMove);
- _joystick.onEnd.Add(__joystickEnd);
- }
-
- void __joystickMove(EventContext context)
- {
- float degree = (float)context.data;
- _text.text = "" + degree;
- }
-
- void __joystickEnd()
- {
- _text.text = "";
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class JoystickMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GTextField _text;
+ JoystickModule _joystick;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _text = _mainView.GetChild("n9").asTextField;
+
+ _joystick = new JoystickModule(_mainView);
+ _joystick.onMove.Add(__joystickMove);
+ _joystick.onEnd.Add(__joystickEnd);
+ }
+
+ void __joystickMove(EventContext context)
+ {
+ float degree = (float)context.data;
+ _text.text = "" + degree;
+ }
+
+ void __joystickEnd()
+ {
+ _text.text = "";
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Joystick/JoystickModule.cs b/Assets/Examples/Joystick/JoystickModule.cs
index 2b8d1899..52e00af2 100644
--- a/Assets/Examples/Joystick/JoystickModule.cs
+++ b/Assets/Examples/Joystick/JoystickModule.cs
@@ -1,159 +1,159 @@
-using FairyGUI;
-using UnityEngine;
-
-public class JoystickModule : EventDispatcher
-{
- float _InitX;
- float _InitY;
- float _startStageX;
- float _startStageY;
- float _lastStageX;
- float _lastStageY;
- GButton _button;
- GObject _touchArea;
- GObject _thumb;
- GObject _center;
- int touchId;
- GTweener _tweener;
-
- public EventListener onMove { get; private set; }
- public EventListener onEnd { get; private set; }
-
- public int radius { get; set; }
-
- public JoystickModule(GComponent mainView)
- {
- onMove = new EventListener(this, "onMove");
- onEnd = new EventListener(this, "onEnd");
-
- _button = mainView.GetChild("joystick").asButton;
- _button.changeStateOnClick = false;
- _thumb = _button.GetChild("thumb");
- _touchArea = mainView.GetChild("joystick_touch");
- _center = mainView.GetChild("joystick_center");
-
- _InitX = _center.x + _center.width / 2;
- _InitY = _center.y + _center.height / 2;
- touchId = -1;
- radius = 150;
-
- _touchArea.onTouchBegin.Add(this.OnTouchBegin);
- _touchArea.onTouchMove.Add(this.OnTouchMove);
- _touchArea.onTouchEnd.Add(this.OnTouchEnd);
- }
-
- public void Trigger(EventContext context)
- {
- OnTouchBegin(context);
- }
-
- private void OnTouchBegin(EventContext context)
- {
- if (touchId == -1)//First touch
- {
- InputEvent evt = (InputEvent)context.data;
- touchId = evt.touchId;
-
- if (_tweener != null)
- {
- _tweener.Kill();
- _tweener = null;
- }
-
- Vector2 pt = GRoot.inst.GlobalToLocal(new Vector2(evt.x, evt.y));
- float bx = pt.x;
- float by = pt.y;
- _button.selected = true;
-
- if (bx < 0)
- bx = 0;
- else if (bx > _touchArea.width)
- bx = _touchArea.width;
-
- if (by > GRoot.inst.height)
- by = GRoot.inst.height;
- else if (by < _touchArea.y)
- by = _touchArea.y;
-
- _lastStageX = bx;
- _lastStageY = by;
- _startStageX = bx;
- _startStageY = by;
-
- _center.visible = true;
- _center.SetXY(bx - _center.width / 2, by - _center.height / 2);
- _button.SetXY(bx - _button.width / 2, by - _button.height / 2);
-
- float deltaX = bx - _InitX;
- float deltaY = by - _InitY;
- float degrees = Mathf.Atan2(deltaY, deltaX) * 180 / Mathf.PI;
- _thumb.rotation = degrees + 90;
-
- context.CaptureTouch();
- }
- }
-
- private void OnTouchEnd(EventContext context)
- {
- InputEvent inputEvt = (InputEvent)context.data;
- if (touchId != -1 && inputEvt.touchId == touchId)
- {
- touchId = -1;
- _thumb.rotation = _thumb.rotation + 180;
- _center.visible = false;
- _tweener = _button.TweenMove(new Vector2(_InitX - _button.width / 2, _InitY - _button.height / 2), 0.3f).OnComplete(() =>
- {
- _tweener = null;
- _button.selected = false;
- _thumb.rotation = 0;
- _center.visible = true;
- _center.SetXY(_InitX - _center.width / 2, _InitY - _center.height / 2);
- }
- );
-
- this.onEnd.Call();
- }
- }
-
- private void OnTouchMove(EventContext context)
- {
- InputEvent evt = (InputEvent)context.data;
- if (touchId != -1 && evt.touchId == touchId)
- {
- Vector2 pt = GRoot.inst.GlobalToLocal(new Vector2(evt.x, evt.y));
- float bx = pt.x;
- float by = pt.y;
- float moveX = bx - _lastStageX;
- float moveY = by - _lastStageY;
- _lastStageX = bx;
- _lastStageY = by;
- float buttonX = _button.x + moveX;
- float buttonY = _button.y + moveY;
-
- float offsetX = buttonX + _button.width / 2 - _startStageX;
- float offsetY = buttonY + _button.height / 2 - _startStageY;
-
- float rad = Mathf.Atan2(offsetY, offsetX);
- float degree = rad * 180 / Mathf.PI;
- _thumb.rotation = degree + 90;
-
- float maxX = radius * Mathf.Cos(rad);
- float maxY = radius * Mathf.Sin(rad);
- if (Mathf.Abs(offsetX) > Mathf.Abs(maxX))
- offsetX = maxX;
- if (Mathf.Abs(offsetY) > Mathf.Abs(maxY))
- offsetY = maxY;
-
- buttonX = _startStageX + offsetX;
- buttonY = _startStageY + offsetY;
- if (buttonX < 0)
- buttonX = 0;
- if (buttonY > GRoot.inst.height)
- buttonY = GRoot.inst.height;
-
- _button.SetXY(buttonX - _button.width / 2, buttonY - _button.height / 2);
-
- this.onMove.Call(degree);
- }
- }
+using FairyGUI;
+using UnityEngine;
+
+public class JoystickModule : EventDispatcher
+{
+ float _InitX;
+ float _InitY;
+ float _startStageX;
+ float _startStageY;
+ float _lastStageX;
+ float _lastStageY;
+ GButton _button;
+ GObject _touchArea;
+ GObject _thumb;
+ GObject _center;
+ int touchId;
+ GTweener _tweener;
+
+ public EventListener onMove { get; private set; }
+ public EventListener onEnd { get; private set; }
+
+ public int radius { get; set; }
+
+ public JoystickModule(GComponent mainView)
+ {
+ onMove = new EventListener(this, "onMove");
+ onEnd = new EventListener(this, "onEnd");
+
+ _button = mainView.GetChild("joystick").asButton;
+ _button.changeStateOnClick = false;
+ _thumb = _button.GetChild("thumb");
+ _touchArea = mainView.GetChild("joystick_touch");
+ _center = mainView.GetChild("joystick_center");
+
+ _InitX = _center.x + _center.width / 2;
+ _InitY = _center.y + _center.height / 2;
+ touchId = -1;
+ radius = 150;
+
+ _touchArea.onTouchBegin.Add(this.OnTouchBegin);
+ _touchArea.onTouchMove.Add(this.OnTouchMove);
+ _touchArea.onTouchEnd.Add(this.OnTouchEnd);
+ }
+
+ public void Trigger(EventContext context)
+ {
+ OnTouchBegin(context);
+ }
+
+ private void OnTouchBegin(EventContext context)
+ {
+ if (touchId == -1)//First touch
+ {
+ InputEvent evt = (InputEvent)context.data;
+ touchId = evt.touchId;
+
+ if (_tweener != null)
+ {
+ _tweener.Kill();
+ _tweener = null;
+ }
+
+ Vector2 pt = GRoot.inst.GlobalToLocal(new Vector2(evt.x, evt.y));
+ float bx = pt.x;
+ float by = pt.y;
+ _button.selected = true;
+
+ if (bx < 0)
+ bx = 0;
+ else if (bx > _touchArea.width)
+ bx = _touchArea.width;
+
+ if (by > GRoot.inst.height)
+ by = GRoot.inst.height;
+ else if (by < _touchArea.y)
+ by = _touchArea.y;
+
+ _lastStageX = bx;
+ _lastStageY = by;
+ _startStageX = bx;
+ _startStageY = by;
+
+ _center.visible = true;
+ _center.SetXY(bx - _center.width / 2, by - _center.height / 2);
+ _button.SetXY(bx - _button.width / 2, by - _button.height / 2);
+
+ float deltaX = bx - _InitX;
+ float deltaY = by - _InitY;
+ float degrees = Mathf.Atan2(deltaY, deltaX) * 180 / Mathf.PI;
+ _thumb.rotation = degrees + 90;
+
+ context.CaptureTouch();
+ }
+ }
+
+ private void OnTouchEnd(EventContext context)
+ {
+ InputEvent inputEvt = (InputEvent)context.data;
+ if (touchId != -1 && inputEvt.touchId == touchId)
+ {
+ touchId = -1;
+ _thumb.rotation = _thumb.rotation + 180;
+ _center.visible = false;
+ _tweener = _button.TweenMove(new Vector2(_InitX - _button.width / 2, _InitY - _button.height / 2), 0.3f).OnComplete(() =>
+ {
+ _tweener = null;
+ _button.selected = false;
+ _thumb.rotation = 0;
+ _center.visible = true;
+ _center.SetXY(_InitX - _center.width / 2, _InitY - _center.height / 2);
+ }
+ );
+
+ this.onEnd.Call();
+ }
+ }
+
+ private void OnTouchMove(EventContext context)
+ {
+ InputEvent evt = (InputEvent)context.data;
+ if (touchId != -1 && evt.touchId == touchId)
+ {
+ Vector2 pt = GRoot.inst.GlobalToLocal(new Vector2(evt.x, evt.y));
+ float bx = pt.x;
+ float by = pt.y;
+ float moveX = bx - _lastStageX;
+ float moveY = by - _lastStageY;
+ _lastStageX = bx;
+ _lastStageY = by;
+ float buttonX = _button.x + moveX;
+ float buttonY = _button.y + moveY;
+
+ float offsetX = buttonX + _button.width / 2 - _startStageX;
+ float offsetY = buttonY + _button.height / 2 - _startStageY;
+
+ float rad = Mathf.Atan2(offsetY, offsetX);
+ float degree = rad * 180 / Mathf.PI;
+ _thumb.rotation = degree + 90;
+
+ float maxX = radius * Mathf.Cos(rad);
+ float maxY = radius * Mathf.Sin(rad);
+ if (Mathf.Abs(offsetX) > Mathf.Abs(maxX))
+ offsetX = maxX;
+ if (Mathf.Abs(offsetY) > Mathf.Abs(maxY))
+ offsetY = maxY;
+
+ buttonX = _startStageX + offsetX;
+ buttonY = _startStageY + offsetY;
+ if (buttonX < 0)
+ buttonX = 0;
+ if (buttonY > GRoot.inst.height)
+ buttonY = GRoot.inst.height;
+
+ _button.SetXY(buttonX - _button.width / 2, buttonY - _button.height / 2);
+
+ this.onMove.Call(degree);
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/LoopList/LoopListMain.cs b/Assets/Examples/LoopList/LoopListMain.cs
index a9a061cb..0ae15a1d 100644
--- a/Assets/Examples/LoopList/LoopListMain.cs
+++ b/Assets/Examples/LoopList/LoopListMain.cs
@@ -1,63 +1,63 @@
-using UnityEngine;
-using FairyGUI;
-
-public class LoopListMain : MonoBehaviour
-{
- GComponent _mainView;
- GList _list;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- UIPackage.AddPackage("UI/LoopList");
-
- _mainView = this.GetComponent().ui;
-
- _list = _mainView.GetChild("list").asList;
- _list.SetVirtualAndLoop();
-
- _list.itemRenderer = RenderListItem;
- _list.numItems = 5;
- _list.scrollPane.onScroll.Add(DoSpecialEffect);
-
- DoSpecialEffect();
- }
-
- void DoSpecialEffect()
- {
- //change the scale according to the distance to middle
- float midX = _list.scrollPane.posX + _list.viewWidth / 2;
- int cnt = _list.numChildren;
- for (int i = 0; i < cnt; i++)
- {
- GObject obj = _list.GetChildAt(i);
- float dist = Mathf.Abs(midX - obj.x - obj.width / 2);
- if (dist > obj.width) //no intersection
- obj.SetScale(1, 1);
- else
- {
- float ss = 1 + (1 - dist / obj.width) * 0.24f;
- obj.SetScale(ss, ss);
- }
- }
-
- _mainView.GetChild("n3").text = "" + ((_list.GetFirstChildInView() + 1) % _list.numItems);
- }
-
- void RenderListItem(int index, GObject obj)
- {
- GButton item = (GButton)obj;
- item.SetPivot(0.5f, 0.5f);
- item.icon = UIPackage.GetItemURL("LoopList", "n" + (index + 1));
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class LoopListMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GList _list;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ UIPackage.AddPackage("UI/LoopList");
+
+ _mainView = this.GetComponent().ui;
+
+ _list = _mainView.GetChild("list").asList;
+ _list.SetVirtualAndLoop();
+
+ _list.itemRenderer = RenderListItem;
+ _list.numItems = 5;
+ _list.scrollPane.onScroll.Add(DoSpecialEffect);
+
+ DoSpecialEffect();
+ }
+
+ void DoSpecialEffect()
+ {
+ //change the scale according to the distance to middle
+ float midX = _list.scrollPane.posX + _list.viewWidth / 2;
+ int cnt = _list.numChildren;
+ for (int i = 0; i < cnt; i++)
+ {
+ GObject obj = _list.GetChildAt(i);
+ float dist = Mathf.Abs(midX - obj.x - obj.width / 2);
+ if (dist > obj.width) //no intersection
+ obj.SetScale(1, 1);
+ else
+ {
+ float ss = 1 + (1 - dist / obj.width) * 0.24f;
+ obj.SetScale(ss, ss);
+ }
+ }
+
+ _mainView.GetChild("n3").text = "" + ((_list.GetFirstChildInView() + 1) % _list.numItems);
+ }
+
+ void RenderListItem(int index, GObject obj)
+ {
+ GButton item = (GButton)obj;
+ item.SetPivot(0.5f, 0.5f);
+ item.icon = UIPackage.GetItemURL("LoopList", "n" + (index + 1));
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/ModalWaiting/ModalWaitingMain.cs b/Assets/Examples/ModalWaiting/ModalWaitingMain.cs
index b22020ef..969e55c6 100644
--- a/Assets/Examples/ModalWaiting/ModalWaitingMain.cs
+++ b/Assets/Examples/ModalWaiting/ModalWaitingMain.cs
@@ -1,47 +1,47 @@
-using System.Collections;
-using UnityEngine;
-using FairyGUI;
-
-public class ModalWaitingMain : MonoBehaviour
-{
- GComponent _mainView;
- Window4 _testWin;
-
- void Awake()
- {
- UIPackage.AddPackage("UI/ModalWaiting");
- UIConfig.globalModalWaiting = "ui://ModalWaiting/GlobalModalWaiting";
- UIConfig.windowModalWaiting = "ui://ModalWaiting/WindowModalWaiting";
- }
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _testWin = new Window4();
-
- _mainView.GetChild("n0").onClick.Add(() => { _testWin.Show(); });
-
- StartCoroutine(WaitSomeTime());
- }
-
- IEnumerator WaitSomeTime()
- {
- GRoot.inst.ShowModalWait();
-
- yield return new WaitForSeconds(3);
-
- GRoot.inst.CloseModalWait();
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using System.Collections;
+using UnityEngine;
+using FairyGUI;
+
+public class ModalWaitingMain : MonoBehaviour
+{
+ GComponent _mainView;
+ Window4 _testWin;
+
+ void Awake()
+ {
+ UIPackage.AddPackage("UI/ModalWaiting");
+ UIConfig.globalModalWaiting = "ui://ModalWaiting/GlobalModalWaiting";
+ UIConfig.windowModalWaiting = "ui://ModalWaiting/WindowModalWaiting";
+ }
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _testWin = new Window4();
+
+ _mainView.GetChild("n0").onClick.Add(() => { _testWin.Show(); });
+
+ StartCoroutine(WaitSomeTime());
+ }
+
+ IEnumerator WaitSomeTime()
+ {
+ GRoot.inst.ShowModalWait();
+
+ yield return new WaitForSeconds(3);
+
+ GRoot.inst.CloseModalWait();
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/ModalWaiting/Window4.cs b/Assets/Examples/ModalWaiting/Window4.cs
index 66db15f3..a6fad6da 100644
--- a/Assets/Examples/ModalWaiting/Window4.cs
+++ b/Assets/Examples/ModalWaiting/Window4.cs
@@ -1,20 +1,20 @@
-using FairyGUI;
-
-public class Window4 : Window
-{
- public Window4()
- {
- }
-
- protected override void OnInit()
- {
- this.contentPane = UIPackage.CreateObject("ModalWaiting", "TestWin").asCom;
- this.contentPane.GetChild("n1").onClick.Add(OnClick);
- }
-
- void OnClick()
- {
- this.ShowModalWait();
- Timers.inst.Add(3, 1, (object param) => { this.CloseModalWait(); });
- }
-}
+using FairyGUI;
+
+public class Window4 : Window
+{
+ public Window4()
+ {
+ }
+
+ protected override void OnInit()
+ {
+ this.contentPane = UIPackage.CreateObject("ModalWaiting", "TestWin").asCom;
+ this.contentPane.GetChild("n1").onClick.Add(OnClick);
+ }
+
+ void OnClick()
+ {
+ this.ShowModalWait();
+ Timers.inst.Add(3, 1, (object param) => { this.CloseModalWait(); });
+ }
+}
diff --git a/Assets/Examples/Model/ModelMain.cs b/Assets/Examples/Model/ModelMain.cs
index 63b53776..0d7382dd 100644
--- a/Assets/Examples/Model/ModelMain.cs
+++ b/Assets/Examples/Model/ModelMain.cs
@@ -1,30 +1,30 @@
-using UnityEngine;
-using FairyGUI;
-
-public class ModelMain : MonoBehaviour
-{
- GComponent _mainView;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- Object prefab = Resources.Load("Role/npc");
- GameObject go = (GameObject)Object.Instantiate(prefab);
- go.transform.localPosition = new Vector3(61, -89, 1000); //set z to far from UICamera is important!
- go.transform.localScale = new Vector3(180, 180, 180);
- go.transform.localEulerAngles = new Vector3(0, 100, 0);
- _mainView.GetChild("holder").asGraph.SetNativeObject(new GoWrapper(go));
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class ModelMain : MonoBehaviour
+{
+ GComponent _mainView;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ Object prefab = Resources.Load("Role/npc");
+ GameObject go = (GameObject)Object.Instantiate(prefab);
+ go.transform.localPosition = new Vector3(61, -89, 1000); //set z to far from UICamera is important!
+ go.transform.localScale = new Vector3(180, 180, 180);
+ go.transform.localEulerAngles = new Vector3(0, 100, 0);
+ _mainView.GetChild("holder").asGraph.SetNativeObject(new GoWrapper(go));
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Particles/CoolComponent.cs b/Assets/Examples/Particles/CoolComponent.cs
index 3cab713c..6dd1a183 100644
--- a/Assets/Examples/Particles/CoolComponent.cs
+++ b/Assets/Examples/Particles/CoolComponent.cs
@@ -1,16 +1,16 @@
-using UnityEngine;
-using FairyGUI;
-
-public class CoolComponent : GComponent
-{
- public override void ConstructFromXML(FairyGUI.Utils.XML cxml)
- {
- base.ConstructFromXML(cxml);
-
- GGraph graph = this.GetChild("effect").asGraph;
-
- Object prefab = Resources.Load("Flame");
- GameObject go = (GameObject)Object.Instantiate(prefab);
- graph.SetNativeObject(new GoWrapper(go));
- }
-}
+using UnityEngine;
+using FairyGUI;
+
+public class CoolComponent : GComponent
+{
+ public override void ConstructFromXML(FairyGUI.Utils.XML cxml)
+ {
+ base.ConstructFromXML(cxml);
+
+ GGraph graph = this.GetChild("effect").asGraph;
+
+ Object prefab = Resources.Load("Flame");
+ GameObject go = (GameObject)Object.Instantiate(prefab);
+ graph.SetNativeObject(new GoWrapper(go));
+ }
+}
diff --git a/Assets/Examples/Particles/ParticlesMain.cs b/Assets/Examples/Particles/ParticlesMain.cs
index 9d1b2364..c2db0873 100644
--- a/Assets/Examples/Particles/ParticlesMain.cs
+++ b/Assets/Examples/Particles/ParticlesMain.cs
@@ -1,37 +1,37 @@
-using UnityEngine;
-using FairyGUI;
-
-public class ParticlesMain : MonoBehaviour
-{
- GComponent _mainView;
-
- void Awake()
- {
- UIPackage.AddPackage("UI/Particles");
-
- UIObjectFactory.SetPackageItemExtension("ui://Particles/CoolComponent", typeof(CoolComponent));
- }
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- Object prefab = Resources.Load("Flame");
- GameObject go = (GameObject)Object.Instantiate(prefab);
- _mainView.GetChild("holder").asGraph.SetNativeObject(new GoWrapper(go));
-
- _mainView.GetChild("c0").draggable = true;
- _mainView.GetChild("c1").draggable = true;
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class ParticlesMain : MonoBehaviour
+{
+ GComponent _mainView;
+
+ void Awake()
+ {
+ UIPackage.AddPackage("UI/Particles");
+
+ UIObjectFactory.SetPackageItemExtension("ui://Particles/CoolComponent", typeof(CoolComponent));
+ }
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ Object prefab = Resources.Load("Flame");
+ GameObject go = (GameObject)Object.Instantiate(prefab);
+ _mainView.GetChild("holder").asGraph.SetNativeObject(new GoWrapper(go));
+
+ _mainView.GetChild("c0").draggable = true;
+ _mainView.GetChild("c1").draggable = true;
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Perspetive/PerspectiveMain.cs b/Assets/Examples/Perspetive/PerspectiveMain.cs
index 4a71a662..0357efd9 100644
--- a/Assets/Examples/Perspetive/PerspectiveMain.cs
+++ b/Assets/Examples/Perspetive/PerspectiveMain.cs
@@ -1,29 +1,29 @@
-using UnityEngine;
-using FairyGUI;
-
-public class PerspectiveMain : MonoBehaviour
-{
- GList _list;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- //GComponent g1 = GameObject.Find("UIPanel1").GetComponent().ui;
-
- GComponent g2 = GameObject.Find("UIPanel2").GetComponent().ui;
- _list = g2.GetChild("mailList").asList;
- _list.SetVirtual();
- _list.itemRenderer = (int index, GObject obj) => { obj.text = index + " Mail title here"; };
- _list.numItems = 20;
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class PerspectiveMain : MonoBehaviour
+{
+ GList _list;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ //GComponent g1 = GameObject.Find("UIPanel1").GetComponent().ui;
+
+ GComponent g2 = GameObject.Find("UIPanel2").GetComponent().ui;
+ _list = g2.GetChild("mailList").asList;
+ _list.SetVirtual();
+ _list.itemRenderer = (int index, GObject obj) => { obj.text = index + " Mail title here"; };
+ _list.numItems = 20;
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/PullToRefresh/PullToRefreshMain.cs b/Assets/Examples/PullToRefresh/PullToRefreshMain.cs
index 97cf9412..762f9177 100644
--- a/Assets/Examples/PullToRefresh/PullToRefreshMain.cs
+++ b/Assets/Examples/PullToRefresh/PullToRefreshMain.cs
@@ -1,98 +1,98 @@
-using UnityEngine;
-using FairyGUI;
-
-public class PullToRefreshMain : MonoBehaviour
-{
- GComponent _mainView;
- GList _list1;
- GList _list2;
-
- void Awake()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- UIObjectFactory.SetPackageItemExtension("ui://PullToRefresh/Header", typeof(ScrollPaneHeader));
- }
-
- void Start()
- {
- _mainView = this.GetComponent().ui;
-
- _list1 = _mainView.GetChild("list1").asList;
- _list1.itemRenderer = RenderListItem1;
- _list1.SetVirtual();
- _list1.numItems = 1;
- _list1.scrollPane.onPullDownRelease.Add(OnPullDownToRefresh);
-
- _list2 = _mainView.GetChild("list2").asList;
- _list2.itemRenderer = RenderListItem2;
- _list2.SetVirtual();
- _list2.numItems = 1;
- _list2.scrollPane.onPullUpRelease.Add(OnPullUpToRefresh);
- }
-
- void RenderListItem1(int index, GObject obj)
- {
- GButton item = obj.asButton;
- item.title = "Item " + (_list1.numItems - index - 1);
- }
-
- void RenderListItem2(int index, GObject obj)
- {
- GButton item = obj.asButton;
- item.title = "Item " + index;
- }
-
- void OnPullDownToRefresh()
- {
- ScrollPaneHeader header = (ScrollPaneHeader)_list1.scrollPane.header;
- if (header.ReadyToRefresh)
- {
- header.SetRefreshStatus(2);
- _list1.scrollPane.LockHeader(header.sourceHeight);
-
- //Simulate a async resquest
- Timers.inst.Add(2, 1, (object param) =>
- {
- _list1.numItems += 5;
-
- //Refresh completed
- header.SetRefreshStatus(3);
- _list1.scrollPane.LockHeader(35);
-
- Timers.inst.Add(2, 1, (object param2) =>
- {
- header.SetRefreshStatus(0);
- _list1.scrollPane.LockHeader(0);
- });
- });
- }
- }
-
- void OnPullUpToRefresh()
- {
- GComponent footer = (GComponent)_list2.scrollPane.footer;
-
- footer.GetController("c1").selectedIndex = 1;
- _list2.scrollPane.LockFooter(footer.sourceHeight);
-
- //Simulate a async resquest
- Timers.inst.Add(2, 1, (object param) =>
- {
- _list2.numItems += 5;
-
- //Refresh completed
- footer.GetController("c1").selectedIndex = 0;
- _list2.scrollPane.LockFooter(0);
- });
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class PullToRefreshMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GList _list1;
+ GList _list2;
+
+ void Awake()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ UIObjectFactory.SetPackageItemExtension("ui://PullToRefresh/Header", typeof(ScrollPaneHeader));
+ }
+
+ void Start()
+ {
+ _mainView = this.GetComponent().ui;
+
+ _list1 = _mainView.GetChild("list1").asList;
+ _list1.itemRenderer = RenderListItem1;
+ _list1.SetVirtual();
+ _list1.numItems = 1;
+ _list1.scrollPane.onPullDownRelease.Add(OnPullDownToRefresh);
+
+ _list2 = _mainView.GetChild("list2").asList;
+ _list2.itemRenderer = RenderListItem2;
+ _list2.SetVirtual();
+ _list2.numItems = 1;
+ _list2.scrollPane.onPullUpRelease.Add(OnPullUpToRefresh);
+ }
+
+ void RenderListItem1(int index, GObject obj)
+ {
+ GButton item = obj.asButton;
+ item.title = "Item " + (_list1.numItems - index - 1);
+ }
+
+ void RenderListItem2(int index, GObject obj)
+ {
+ GButton item = obj.asButton;
+ item.title = "Item " + index;
+ }
+
+ void OnPullDownToRefresh()
+ {
+ ScrollPaneHeader header = (ScrollPaneHeader)_list1.scrollPane.header;
+ if (header.ReadyToRefresh)
+ {
+ header.SetRefreshStatus(2);
+ _list1.scrollPane.LockHeader(header.sourceHeight);
+
+ //Simulate a async resquest
+ Timers.inst.Add(2, 1, (object param) =>
+ {
+ _list1.numItems += 5;
+
+ //Refresh completed
+ header.SetRefreshStatus(3);
+ _list1.scrollPane.LockHeader(35);
+
+ Timers.inst.Add(2, 1, (object param2) =>
+ {
+ header.SetRefreshStatus(0);
+ _list1.scrollPane.LockHeader(0);
+ });
+ });
+ }
+ }
+
+ void OnPullUpToRefresh()
+ {
+ GComponent footer = (GComponent)_list2.scrollPane.footer;
+
+ footer.GetController("c1").selectedIndex = 1;
+ _list2.scrollPane.LockFooter(footer.sourceHeight);
+
+ //Simulate a async resquest
+ Timers.inst.Add(2, 1, (object param) =>
+ {
+ _list2.numItems += 5;
+
+ //Refresh completed
+ footer.GetController("c1").selectedIndex = 0;
+ _list2.scrollPane.LockFooter(0);
+ });
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/PullToRefresh/ScrollPaneHeader.cs b/Assets/Examples/PullToRefresh/ScrollPaneHeader.cs
index 34420657..66e1d834 100644
--- a/Assets/Examples/PullToRefresh/ScrollPaneHeader.cs
+++ b/Assets/Examples/PullToRefresh/ScrollPaneHeader.cs
@@ -1,37 +1,37 @@
-using FairyGUI;
-using UnityEngine;
-
-public class ScrollPaneHeader : GComponent
-{
- Controller _c1;
-
- public override void ConstructFromXML(FairyGUI.Utils.XML xml)
- {
- base.ConstructFromXML(xml);
-
- _c1 = this.GetController("c1");
-
- this.onSizeChanged.Add(OnSizeChanged);
- }
-
- void OnSizeChanged()
- {
- if (_c1.selectedIndex == 2 || _c1.selectedIndex == 3)
- return;
-
- if (this.height > this.sourceHeight)
- _c1.selectedIndex = 1;
- else
- _c1.selectedIndex = 0;
- }
-
- public bool ReadyToRefresh
- {
- get { return _c1.selectedIndex == 1; }
- }
-
- public void SetRefreshStatus(int value)
- {
- _c1.selectedIndex = value;
- }
-}
+using FairyGUI;
+using UnityEngine;
+
+public class ScrollPaneHeader : GComponent
+{
+ Controller _c1;
+
+ public override void ConstructFromXML(FairyGUI.Utils.XML xml)
+ {
+ base.ConstructFromXML(xml);
+
+ _c1 = this.GetController("c1");
+
+ this.onSizeChanged.Add(OnSizeChanged);
+ }
+
+ void OnSizeChanged()
+ {
+ if (_c1.selectedIndex == 2 || _c1.selectedIndex == 3)
+ return;
+
+ if (this.height > this.sourceHeight)
+ _c1.selectedIndex = 1;
+ else
+ _c1.selectedIndex = 0;
+ }
+
+ public bool ReadyToRefresh
+ {
+ get { return _c1.selectedIndex == 1; }
+ }
+
+ public void SetRefreshStatus(int value)
+ {
+ _c1.selectedIndex = value;
+ }
+}
diff --git a/Assets/Examples/RenderTexture/RenderImage.cs b/Assets/Examples/RenderTexture/RenderImage.cs
index c28bab8e..5b8f035b 100644
--- a/Assets/Examples/RenderTexture/RenderImage.cs
+++ b/Assets/Examples/RenderTexture/RenderImage.cs
@@ -1,292 +1,292 @@
-using FairyGUI;
-using FairyGUI.Utils;
-using System.Collections;
-using UnityEngine;
-
-public class RenderImage
-{
- public Transform modelRoot { get; private set; }
-
- Camera _camera;
- Image _image;
- Transform _root;
- Transform _background;
- Transform _model;
- RenderTexture _renderTexture;
- int _width;
- int _height;
- bool _cacheTexture;
- float _rotating;
-
- const int RENDER_LAYER = 0;
- const int HIDDEN_LAYER = 10;
-
- public RenderImage(GGraph holder)
- {
- _width = (int)holder.width;
- _height = (int)holder.height;
- _cacheTexture = true;
-
- this._image = new Image();
- holder.SetNativeObject(this._image);
-
- Object prefab = Resources.Load("RenderTexture/RenderImageCamera");
- GameObject go = (GameObject)Object.Instantiate(prefab);
- _camera = go.GetComponent();
- _camera.transform.position = new Vector3(0, 1000, 0);
- _camera.cullingMask = 1 << RENDER_LAYER;
- _camera.enabled = false;
- Object.DontDestroyOnLoad(_camera.gameObject);
-
- this._root = new GameObject("RenderImage").transform;
- this._root.SetParent(_camera.transform, false);
- SetLayer(this._root.gameObject, HIDDEN_LAYER);
-
- this.modelRoot = new GameObject("model_root").transform;
- this.modelRoot.SetParent(this._root, false);
-
- this._background = new GameObject("background").transform;
- this._background.SetParent(this._root, false);
-
- this._image.onAddedToStage.Add(OnAddedToStage);
- this._image.onRemovedFromStage.Add(OnRemoveFromStage);
-
- if (this._image.stage != null)
- OnAddedToStage();
- else
- _camera.gameObject.SetActive(false);
- }
-
- public void Dispose()
- {
- Object.Destroy(_camera.gameObject);
- DestroyTexture();
-
- this._image.Dispose();
- this._image = null;
- }
-
- ///
- /// The rendertexture is not transparent. So if you want to the UI elements can be seen in the back of the models/particles in rendertexture,
- /// you can set a maximunm two images for background.
- /// Be careful if your image is 9 grid scaling, you must make sure the place holder is inside the middle box(dont cover from border to middle).
- ///
- ///
- public void SetBackground(GObject image)
- {
- SetBackground(image, null);
- }
-
- ///
- /// The rendertexture is not transparent. So if you want to the UI elements can be seen in the back of the models/particles in rendertexture,
- /// you can set a maximunm two images for background.
- ///
- ///
- ///
- public void SetBackground(GObject image1, GObject image2)
- {
- Image source1 = (Image)image1.displayObject;
- Image source2 = image2 != null ? (Image)image2.displayObject : null;
-
- Vector3 pos = _background.position;
- pos.z = _camera.farClipPlane;
- _background.position = pos;
-
- Vector2[] uv = new Vector2[4];
- Vector2[] uv2 = null;
-
- Rect rect = _image.TransformRect(new Rect(0, 0, this._width, this._height), source1);
- Rect uvRect = GetImageUVRect(source1, rect, uv);
-
- if (source2 != null)
- {
- rect = _image.TransformRect(new Rect(0, 0, this._width, this._height), source2);
- uv2 = new Vector2[4];
- GetImageUVRect(source2, rect, uv2);
- }
-
- Vector3[] vertices = new Vector3[4];
- for (int i = 0; i < 4; i++)
- {
- Vector2 v = uv[i];
- vertices[i] = new Vector3((v.x - uvRect.x) / uvRect.width * 2 - 1,
- (v.y - uvRect.y) / uvRect.height * 2 - 1, 0);
- }
-
- Mesh mesh = new Mesh();
- mesh.vertices = vertices;
- mesh.uv = uv;
- if (uv2 != null)
- mesh.uv2 = uv2;
- mesh.colors32 = new Color32[] { Color.white, Color.white, Color.white, Color.white };
- mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 };
-
- MeshFilter meshFilter = this._background.gameObject.GetComponent();
- if (meshFilter == null)
- meshFilter = this._background.gameObject.AddComponent();
- meshFilter.mesh = mesh;
- MeshRenderer meshRenderer = this._background.gameObject.GetComponent();
- if (meshRenderer == null)
- meshRenderer = this._background.gameObject.AddComponent();
-#if (UNITY_5 || UNITY_5_3_OR_NEWER)
- meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
-#else
- meshRenderer.castShadows = false;
-#endif
- meshRenderer.receiveShadows = false;
- Shader shader = Shader.Find("Game/FullScreen");
- Material mat = new Material(shader);
- mat.mainTexture = source1.texture.nativeTexture;
- if (source2 != null)
- mat.SetTexture("_Tex2", source2.texture.nativeTexture);
- meshRenderer.material = mat;
- }
-
- Rect GetImageUVRect(Image image, Rect localRect, Vector2[] uv)
- {
- Rect imageRect = new Rect(0, 0, image.size.x, image.size.y);
- Rect bound = ToolSet.Intersection(ref imageRect, ref localRect);
- Rect uvRect = image.texture.uvRect;
-
- if (image.scale9Grid != null)
- {
- Rect gridRect = (Rect)image.scale9Grid;
- float sourceW = image.texture.width;
- float sourceH = image.texture.height;
- uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, gridRect.xMin / sourceW),
- Mathf.Lerp(uvRect.yMin, uvRect.yMax, (sourceH - gridRect.yMax) / sourceH),
- Mathf.Lerp(uvRect.xMin, uvRect.xMax, gridRect.xMax / sourceW),
- Mathf.Lerp(uvRect.yMin, uvRect.yMax, (sourceH - gridRect.yMin) / sourceH));
-
- float vw = imageRect.width - (sourceW - gridRect.width);
- float vh = imageRect.height - (sourceH - gridRect.height);
- uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, (bound.x - gridRect.x) / vw),
- Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMax - (sourceH - gridRect.yMax)) / vh),
- Mathf.Lerp(uvRect.xMin, uvRect.xMax, (bound.xMax - gridRect.x) / vw),
- Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMin - gridRect.y) / vh));
- }
- else
- {
- uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, bound.xMin / imageRect.width),
- Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMax) / imageRect.height),
- Mathf.Lerp(uvRect.xMin, uvRect.xMax, bound.xMax / imageRect.width),
- Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMin) / imageRect.height));
- }
-
- uv[0] = uvRect.position;
- uv[1] = new Vector2(uvRect.xMin, uvRect.yMax);
- uv[2] = new Vector2(uvRect.xMax, uvRect.yMax);
- uv[3] = new Vector2(uvRect.xMax, uvRect.yMin);
-
- if (image.texture.rotated)
- ToolSet.RotateUV(uv, ref image.texture.uvRect);
-
- return uvRect;
- }
-
- public void LoadModel(string model)
- {
- this.UnloadModel();
-
- Object prefab = Resources.Load(model);
- GameObject go = ((GameObject)Object.Instantiate(prefab));
- _model = go.transform;
- _model.SetParent(this.modelRoot, false);
- }
-
- public void UnloadModel()
- {
- if (_model != null)
- {
- Object.Destroy(_model.gameObject);
- _model = null;
- }
- _rotating = 0;
- }
-
- public void StartRotate(float delta)
- {
- _rotating = delta;
- }
-
- public void StopRotate()
- {
- _rotating = 0;
- }
-
- void CreateTexture()
- {
- if (_renderTexture != null)
- return;
-
- _renderTexture = new RenderTexture(_width, _height, 24, RenderTextureFormat.ARGB32)
- {
- antiAliasing = 1,
- filterMode = FilterMode.Bilinear,
- anisoLevel = 0,
- useMipMap = false
- };
- this._image.texture = new NTexture(_renderTexture);
- this._image.blendMode = BlendMode.Off;
- }
-
- void DestroyTexture()
- {
- if (_renderTexture != null)
- {
- Object.Destroy(_renderTexture);
- _renderTexture = null;
- this._image.texture = null;
- }
- }
-
- void OnAddedToStage()
- {
- if (_renderTexture == null)
- CreateTexture();
-
- Timers.inst.AddUpdate(this.Render);
- _camera.gameObject.SetActive(true);
-
- Render();
- }
-
- void OnRemoveFromStage()
- {
- if (!_cacheTexture)
- DestroyTexture();
-
- Timers.inst.Remove(this.Render);
- _camera.gameObject.SetActive(false);
- }
-
- void Render(object param = null)
- {
- if (_rotating != 0 && this.modelRoot != null)
- {
- Vector3 localRotation = this.modelRoot.localRotation.eulerAngles;
- localRotation.y += _rotating;
- this.modelRoot.localRotation = Quaternion.Euler(localRotation);
- }
-
- SetLayer(this._root.gameObject, RENDER_LAYER);
-
- _camera.targetTexture = this._renderTexture;
- RenderTexture old = RenderTexture.active;
- RenderTexture.active = this._renderTexture;
- GL.Clear(true, true, Color.clear);
- _camera.Render();
- RenderTexture.active = old;
-
- SetLayer(this._root.gameObject, HIDDEN_LAYER);
- }
-
- void SetLayer(GameObject go, int layer)
- {
- Transform[] transforms = go.GetComponentsInChildren(true);
- foreach (Transform t in transforms)
- {
- t.gameObject.layer = layer;
- }
- }
+using FairyGUI;
+using FairyGUI.Utils;
+using System.Collections;
+using UnityEngine;
+
+public class RenderImage
+{
+ public Transform modelRoot { get; private set; }
+
+ Camera _camera;
+ Image _image;
+ Transform _root;
+ Transform _background;
+ Transform _model;
+ RenderTexture _renderTexture;
+ int _width;
+ int _height;
+ bool _cacheTexture;
+ float _rotating;
+
+ const int RENDER_LAYER = 0;
+ const int HIDDEN_LAYER = 10;
+
+ public RenderImage(GGraph holder)
+ {
+ _width = (int)holder.width;
+ _height = (int)holder.height;
+ _cacheTexture = true;
+
+ this._image = new Image();
+ holder.SetNativeObject(this._image);
+
+ Object prefab = Resources.Load("RenderTexture/RenderImageCamera");
+ GameObject go = (GameObject)Object.Instantiate(prefab);
+ _camera = go.GetComponent();
+ _camera.transform.position = new Vector3(0, 1000, 0);
+ _camera.cullingMask = 1 << RENDER_LAYER;
+ _camera.enabled = false;
+ Object.DontDestroyOnLoad(_camera.gameObject);
+
+ this._root = new GameObject("RenderImage").transform;
+ this._root.SetParent(_camera.transform, false);
+ SetLayer(this._root.gameObject, HIDDEN_LAYER);
+
+ this.modelRoot = new GameObject("model_root").transform;
+ this.modelRoot.SetParent(this._root, false);
+
+ this._background = new GameObject("background").transform;
+ this._background.SetParent(this._root, false);
+
+ this._image.onAddedToStage.Add(OnAddedToStage);
+ this._image.onRemovedFromStage.Add(OnRemoveFromStage);
+
+ if (this._image.stage != null)
+ OnAddedToStage();
+ else
+ _camera.gameObject.SetActive(false);
+ }
+
+ public void Dispose()
+ {
+ Object.Destroy(_camera.gameObject);
+ DestroyTexture();
+
+ this._image.Dispose();
+ this._image = null;
+ }
+
+ ///
+ /// The rendertexture is not transparent. So if you want to the UI elements can be seen in the back of the models/particles in rendertexture,
+ /// you can set a maximunm two images for background.
+ /// Be careful if your image is 9 grid scaling, you must make sure the place holder is inside the middle box(dont cover from border to middle).
+ ///
+ ///
+ public void SetBackground(GObject image)
+ {
+ SetBackground(image, null);
+ }
+
+ ///
+ /// The rendertexture is not transparent. So if you want to the UI elements can be seen in the back of the models/particles in rendertexture,
+ /// you can set a maximunm two images for background.
+ ///
+ ///
+ ///
+ public void SetBackground(GObject image1, GObject image2)
+ {
+ Image source1 = (Image)image1.displayObject;
+ Image source2 = image2 != null ? (Image)image2.displayObject : null;
+
+ Vector3 pos = _background.position;
+ pos.z = _camera.farClipPlane;
+ _background.position = pos;
+
+ Vector2[] uv = new Vector2[4];
+ Vector2[] uv2 = null;
+
+ Rect rect = _image.TransformRect(new Rect(0, 0, this._width, this._height), source1);
+ Rect uvRect = GetImageUVRect(source1, rect, uv);
+
+ if (source2 != null)
+ {
+ rect = _image.TransformRect(new Rect(0, 0, this._width, this._height), source2);
+ uv2 = new Vector2[4];
+ GetImageUVRect(source2, rect, uv2);
+ }
+
+ Vector3[] vertices = new Vector3[4];
+ for (int i = 0; i < 4; i++)
+ {
+ Vector2 v = uv[i];
+ vertices[i] = new Vector3((v.x - uvRect.x) / uvRect.width * 2 - 1,
+ (v.y - uvRect.y) / uvRect.height * 2 - 1, 0);
+ }
+
+ Mesh mesh = new Mesh();
+ mesh.vertices = vertices;
+ mesh.uv = uv;
+ if (uv2 != null)
+ mesh.uv2 = uv2;
+ mesh.colors32 = new Color32[] { Color.white, Color.white, Color.white, Color.white };
+ mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 };
+
+ MeshFilter meshFilter = this._background.gameObject.GetComponent();
+ if (meshFilter == null)
+ meshFilter = this._background.gameObject.AddComponent();
+ meshFilter.mesh = mesh;
+ MeshRenderer meshRenderer = this._background.gameObject.GetComponent();
+ if (meshRenderer == null)
+ meshRenderer = this._background.gameObject.AddComponent();
+#if (UNITY_5 || UNITY_5_3_OR_NEWER)
+ meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
+#else
+ meshRenderer.castShadows = false;
+#endif
+ meshRenderer.receiveShadows = false;
+ Shader shader = Shader.Find("Game/FullScreen");
+ Material mat = new Material(shader);
+ mat.mainTexture = source1.texture.nativeTexture;
+ if (source2 != null)
+ mat.SetTexture("_Tex2", source2.texture.nativeTexture);
+ meshRenderer.material = mat;
+ }
+
+ Rect GetImageUVRect(Image image, Rect localRect, Vector2[] uv)
+ {
+ Rect imageRect = new Rect(0, 0, image.size.x, image.size.y);
+ Rect bound = ToolSet.Intersection(ref imageRect, ref localRect);
+ Rect uvRect = image.texture.uvRect;
+
+ if (image.scale9Grid != null)
+ {
+ Rect gridRect = (Rect)image.scale9Grid;
+ float sourceW = image.texture.width;
+ float sourceH = image.texture.height;
+ uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, gridRect.xMin / sourceW),
+ Mathf.Lerp(uvRect.yMin, uvRect.yMax, (sourceH - gridRect.yMax) / sourceH),
+ Mathf.Lerp(uvRect.xMin, uvRect.xMax, gridRect.xMax / sourceW),
+ Mathf.Lerp(uvRect.yMin, uvRect.yMax, (sourceH - gridRect.yMin) / sourceH));
+
+ float vw = imageRect.width - (sourceW - gridRect.width);
+ float vh = imageRect.height - (sourceH - gridRect.height);
+ uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, (bound.x - gridRect.x) / vw),
+ Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMax - (sourceH - gridRect.yMax)) / vh),
+ Mathf.Lerp(uvRect.xMin, uvRect.xMax, (bound.xMax - gridRect.x) / vw),
+ Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMin - gridRect.y) / vh));
+ }
+ else
+ {
+ uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, bound.xMin / imageRect.width),
+ Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMax) / imageRect.height),
+ Mathf.Lerp(uvRect.xMin, uvRect.xMax, bound.xMax / imageRect.width),
+ Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMin) / imageRect.height));
+ }
+
+ uv[0] = uvRect.position;
+ uv[1] = new Vector2(uvRect.xMin, uvRect.yMax);
+ uv[2] = new Vector2(uvRect.xMax, uvRect.yMax);
+ uv[3] = new Vector2(uvRect.xMax, uvRect.yMin);
+
+ if (image.texture.rotated)
+ ToolSet.RotateUV(uv, ref image.texture.uvRect);
+
+ return uvRect;
+ }
+
+ public void LoadModel(string model)
+ {
+ this.UnloadModel();
+
+ Object prefab = Resources.Load(model);
+ GameObject go = ((GameObject)Object.Instantiate(prefab));
+ _model = go.transform;
+ _model.SetParent(this.modelRoot, false);
+ }
+
+ public void UnloadModel()
+ {
+ if (_model != null)
+ {
+ Object.Destroy(_model.gameObject);
+ _model = null;
+ }
+ _rotating = 0;
+ }
+
+ public void StartRotate(float delta)
+ {
+ _rotating = delta;
+ }
+
+ public void StopRotate()
+ {
+ _rotating = 0;
+ }
+
+ void CreateTexture()
+ {
+ if (_renderTexture != null)
+ return;
+
+ _renderTexture = new RenderTexture(_width, _height, 24, RenderTextureFormat.ARGB32)
+ {
+ antiAliasing = 1,
+ filterMode = FilterMode.Bilinear,
+ anisoLevel = 0,
+ useMipMap = false
+ };
+ this._image.texture = new NTexture(_renderTexture);
+ this._image.blendMode = BlendMode.Off;
+ }
+
+ void DestroyTexture()
+ {
+ if (_renderTexture != null)
+ {
+ Object.Destroy(_renderTexture);
+ _renderTexture = null;
+ this._image.texture = null;
+ }
+ }
+
+ void OnAddedToStage()
+ {
+ if (_renderTexture == null)
+ CreateTexture();
+
+ Timers.inst.AddUpdate(this.Render);
+ _camera.gameObject.SetActive(true);
+
+ Render();
+ }
+
+ void OnRemoveFromStage()
+ {
+ if (!_cacheTexture)
+ DestroyTexture();
+
+ Timers.inst.Remove(this.Render);
+ _camera.gameObject.SetActive(false);
+ }
+
+ void Render(object param = null)
+ {
+ if (_rotating != 0 && this.modelRoot != null)
+ {
+ Vector3 localRotation = this.modelRoot.localRotation.eulerAngles;
+ localRotation.y += _rotating;
+ this.modelRoot.localRotation = Quaternion.Euler(localRotation);
+ }
+
+ SetLayer(this._root.gameObject, RENDER_LAYER);
+
+ _camera.targetTexture = this._renderTexture;
+ RenderTexture old = RenderTexture.active;
+ RenderTexture.active = this._renderTexture;
+ GL.Clear(true, true, Color.clear);
+ _camera.Render();
+ RenderTexture.active = old;
+
+ SetLayer(this._root.gameObject, HIDDEN_LAYER);
+ }
+
+ void SetLayer(GameObject go, int layer)
+ {
+ Transform[] transforms = go.GetComponentsInChildren(true);
+ foreach (Transform t in transforms)
+ {
+ t.gameObject.layer = layer;
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/RenderTexture/RenderTextureMain.cs b/Assets/Examples/RenderTexture/RenderTextureMain.cs
index 2e55c4a3..fbfc24f3 100644
--- a/Assets/Examples/RenderTexture/RenderTextureMain.cs
+++ b/Assets/Examples/RenderTexture/RenderTextureMain.cs
@@ -1,28 +1,28 @@
-using UnityEngine;
-using FairyGUI;
-
-public class RenderTextureMain : MonoBehaviour
-{
- GComponent _mainView;
- Window3 _testWin;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _testWin = new Window3();
-
- _mainView.GetChild("n2").onClick.Add(() => { _testWin.Show(); });
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class RenderTextureMain : MonoBehaviour
+{
+ GComponent _mainView;
+ Window3 _testWin;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _testWin = new Window3();
+
+ _mainView.GetChild("n2").onClick.Add(() => { _testWin.Show(); });
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/RenderTexture/Window3.cs b/Assets/Examples/RenderTexture/Window3.cs
index d2ec1548..9180c2a2 100644
--- a/Assets/Examples/RenderTexture/Window3.cs
+++ b/Assets/Examples/RenderTexture/Window3.cs
@@ -1,52 +1,52 @@
-using System;
-using System.Collections.Generic;
-using FairyGUI;
-using UnityEngine;
-
-public class Window3 : Window
-{
- RenderImage _renderImage;
-
- public Window3()
- {
- }
-
- protected override void OnInit()
- {
- this.contentPane = UIPackage.CreateObject("RenderTexture", "TestWin").asCom;
- this.SetXY(200, 50);
-
- _renderImage = new RenderImage(contentPane.GetChild("holder").asGraph);
- //RenderImage是不透明的,可以设置最多两张图片作为背景图
- _renderImage.SetBackground(contentPane.GetChild("frame").asCom.GetChild("n0"), contentPane.GetChild("n20"));
-
- contentPane.GetChild("btnLeft").onTouchBegin.Add(__clickLeft);
- contentPane.GetChild("btnRight").onTouchBegin.Add(__clickRight);
- }
-
- override protected void OnShown()
- {
- _renderImage.LoadModel("Role/npc");
- _renderImage.modelRoot.localPosition = new Vector3(0, -1.0f, 5f);
- _renderImage.modelRoot.localScale = new Vector3(1, 1, 1);
- _renderImage.modelRoot.localRotation = Quaternion.Euler(0, 120, 0);
- }
-
- void __clickLeft()
- {
- _renderImage.StartRotate(-2);
- Stage.inst.onTouchEnd.Add(__touchEnd);
- }
-
- void __clickRight()
- {
- _renderImage.StartRotate(2);
- Stage.inst.onTouchEnd.Add(__touchEnd);
- }
-
- void __touchEnd()
- {
- _renderImage.StopRotate();
- Stage.inst.onTouchEnd.Remove(__touchEnd);
- }
-}
+using System;
+using System.Collections.Generic;
+using FairyGUI;
+using UnityEngine;
+
+public class Window3 : Window
+{
+ RenderImage _renderImage;
+
+ public Window3()
+ {
+ }
+
+ protected override void OnInit()
+ {
+ this.contentPane = UIPackage.CreateObject("RenderTexture", "TestWin").asCom;
+ this.SetXY(200, 50);
+
+ _renderImage = new RenderImage(contentPane.GetChild("holder").asGraph);
+ //RenderImage是不透明的,可以设置最多两张图片作为背景图
+ _renderImage.SetBackground(contentPane.GetChild("frame").asCom.GetChild("n0"), contentPane.GetChild("n20"));
+
+ contentPane.GetChild("btnLeft").onTouchBegin.Add(__clickLeft);
+ contentPane.GetChild("btnRight").onTouchBegin.Add(__clickRight);
+ }
+
+ override protected void OnShown()
+ {
+ _renderImage.LoadModel("Role/npc");
+ _renderImage.modelRoot.localPosition = new Vector3(0, -1.0f, 5f);
+ _renderImage.modelRoot.localScale = new Vector3(1, 1, 1);
+ _renderImage.modelRoot.localRotation = Quaternion.Euler(0, 120, 0);
+ }
+
+ void __clickLeft()
+ {
+ _renderImage.StartRotate(-2);
+ Stage.inst.onTouchEnd.Add(__touchEnd);
+ }
+
+ void __clickRight()
+ {
+ _renderImage.StartRotate(2);
+ Stage.inst.onTouchEnd.Add(__touchEnd);
+ }
+
+ void __touchEnd()
+ {
+ _renderImage.StopRotate();
+ Stage.inst.onTouchEnd.Remove(__touchEnd);
+ }
+}
diff --git a/Assets/Examples/ScrollPane/ScrollPaneMain.cs b/Assets/Examples/ScrollPane/ScrollPaneMain.cs
index 22daf45f..ee947d93 100644
--- a/Assets/Examples/ScrollPane/ScrollPaneMain.cs
+++ b/Assets/Examples/ScrollPane/ScrollPaneMain.cs
@@ -1,113 +1,113 @@
-using UnityEngine;
-using FairyGUI;
-
-public class ScrollPaneMain : MonoBehaviour
-{
- GComponent _mainView;
- GList _list;
-
- void Awake()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
- }
-
- void Start()
- {
- _mainView = this.GetComponent().ui;
-
- _list = _mainView.GetChild("list").asList;
- _list.itemRenderer = RenderListItem;
- _list.SetVirtual();
- _list.numItems = 1000;
- _list.onTouchBegin.Add(OnClickList);
-
- _mainView.GetChild("box").asCom.onDrop.Add(OnDrop);
-
- LongPressGesture gesture = new LongPressGesture(_list);
- gesture.once = true;
- gesture.trigger = 1f;
- gesture.onAction.Add(OnLongPress);
- }
-
- void RenderListItem(int index, GObject obj)
- {
- GButton item = obj.asButton;
- item.title = "Item " + index;
- item.scrollPane.posX = 0; //reset scroll pos
-
- //Be carefull, RenderListItem is calling repeatedly, dont call 'Add' here!
- //请注意,RenderListItem是重复调用的,不要使用Add增加侦听!
- item.GetChild("b0").onClick.Set(OnClickStick);
- item.GetChild("b1").onClick.Set(OnClickDelete);
- }
-
- void OnClickList(EventContext context)
- {
- //find out if there is an item in edit status
- //查找是否有项目处于编辑状态
- int cnt = _list.numChildren;
- for (int i = 0; i < cnt; i++)
- {
- GButton item = _list.GetChildAt(i).asButton;
- if (item.scrollPane.posX != 0)
- {
- //Check if clicked on the button
- if (item.GetChild("b0").asButton.IsAncestorOf(GRoot.inst.touchTarget)
- || item.GetChild("b1").asButton.IsAncestorOf(GRoot.inst.touchTarget))
- {
- return;
- }
- item.scrollPane.SetPosX(0, true);
- //avoid scroll pane default behavior
- //取消滚动面板可能发生的拉动。
- item.scrollPane.CancelDragging();
- _list.scrollPane.CancelDragging();
- break;
- }
- }
- }
-
- void OnLongPress(EventContext context)
- {
- //find out which item is under finger
- //逐层往上知道查到点击了那个item
- GObject obj = GRoot.inst.touchTarget;
- GObject p = obj.parent;
- while (p != null)
- {
- if (p == _list)
- break;
-
- p = p.parent;
- }
-
- if (p == null)
- return;
- Debug.Log(obj.text);
- DragDropManager.inst.StartDrag(obj, obj.icon, obj.text);
- }
-
- void OnDrop(EventContext context)
- {
- _mainView.GetChild("txt").text = "Drop " + (string)context.data;
- }
-
- void OnClickStick(EventContext context)
- {
- _mainView.GetChild("txt").text = "Stick " + (((GObject)context.sender).parent).text;
- }
-
- void OnClickDelete(EventContext context)
- {
- _mainView.GetChild("txt").text = "Delete " + (((GObject)context.sender).parent).text;
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class ScrollPaneMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GList _list;
+
+ void Awake()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+ }
+
+ void Start()
+ {
+ _mainView = this.GetComponent().ui;
+
+ _list = _mainView.GetChild("list").asList;
+ _list.itemRenderer = RenderListItem;
+ _list.SetVirtual();
+ _list.numItems = 1000;
+ _list.onTouchBegin.Add(OnClickList);
+
+ _mainView.GetChild("box").asCom.onDrop.Add(OnDrop);
+
+ LongPressGesture gesture = new LongPressGesture(_list);
+ gesture.once = true;
+ gesture.trigger = 1f;
+ gesture.onAction.Add(OnLongPress);
+ }
+
+ void RenderListItem(int index, GObject obj)
+ {
+ GButton item = obj.asButton;
+ item.title = "Item " + index;
+ item.scrollPane.posX = 0; //reset scroll pos
+
+ //Be carefull, RenderListItem is calling repeatedly, dont call 'Add' here!
+ //请注意,RenderListItem是重复调用的,不要使用Add增加侦听!
+ item.GetChild("b0").onClick.Set(OnClickStick);
+ item.GetChild("b1").onClick.Set(OnClickDelete);
+ }
+
+ void OnClickList(EventContext context)
+ {
+ //find out if there is an item in edit status
+ //查找是否有项目处于编辑状态
+ int cnt = _list.numChildren;
+ for (int i = 0; i < cnt; i++)
+ {
+ GButton item = _list.GetChildAt(i).asButton;
+ if (item.scrollPane.posX != 0)
+ {
+ //Check if clicked on the button
+ if (item.GetChild("b0").asButton.IsAncestorOf(GRoot.inst.touchTarget)
+ || item.GetChild("b1").asButton.IsAncestorOf(GRoot.inst.touchTarget))
+ {
+ return;
+ }
+ item.scrollPane.SetPosX(0, true);
+ //avoid scroll pane default behavior
+ //取消滚动面板可能发生的拉动。
+ item.scrollPane.CancelDragging();
+ _list.scrollPane.CancelDragging();
+ break;
+ }
+ }
+ }
+
+ void OnLongPress(EventContext context)
+ {
+ //find out which item is under finger
+ //逐层往上知道查到点击了那个item
+ GObject obj = GRoot.inst.touchTarget;
+ GObject p = obj.parent;
+ while (p != null)
+ {
+ if (p == _list)
+ break;
+
+ p = p.parent;
+ }
+
+ if (p == null)
+ return;
+ Debug.Log(obj.text);
+ DragDropManager.inst.StartDrag(obj, obj.icon, obj.text);
+ }
+
+ void OnDrop(EventContext context)
+ {
+ _mainView.GetChild("txt").text = "Drop " + (string)context.data;
+ }
+
+ void OnClickStick(EventContext context)
+ {
+ _mainView.GetChild("txt").text = "Stick " + (((GObject)context.sender).parent).text;
+ }
+
+ void OnClickDelete(EventContext context)
+ {
+ _mainView.GetChild("txt").text = "Delete " + (((GObject)context.sender).parent).text;
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/Transition/TransitionMain.cs b/Assets/Examples/Transition/TransitionMain.cs
index 468c6383..cd4fdf39 100644
--- a/Assets/Examples/Transition/TransitionMain.cs
+++ b/Assets/Examples/Transition/TransitionMain.cs
@@ -1,105 +1,105 @@
-using UnityEngine;
-using FairyGUI;
-
-public class TransitionMain : MonoBehaviour
-{
- GComponent _mainView;
- GGroup _btnGroup;
- GComponent _g1;
- GComponent _g2;
- GComponent _g3;
- GComponent _g4;
- GComponent _g5;
- GComponent _g6;
-
- float _startValue;
- float _endValue;
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _btnGroup = _mainView.GetChild("g0").asGroup;
-
- _g1 = UIPackage.CreateObject("Transition", "BOSS").asCom;
- _g2 = UIPackage.CreateObject("Transition", "BOSS_SKILL").asCom;
- _g3 = UIPackage.CreateObject("Transition", "TRAP").asCom;
-
- _g4 = UIPackage.CreateObject("Transition", "GoodHit").asCom;
- _g5 = UIPackage.CreateObject("Transition", "PowerUp").asCom;
- _g5.GetTransition("t0").SetHook("play_num_now", __playNum);
-
- _g6 = UIPackage.CreateObject("Transition", "PathDemo").asCom;
-
- _mainView.GetChild("btn0").onClick.Add(() => { __play(_g1); });
- _mainView.GetChild("btn1").onClick.Add(() => { __play(_g2); });
- _mainView.GetChild("btn2").onClick.Add(() => { __play(_g3); });
- _mainView.GetChild("btn3").onClick.Add(__play4);
- _mainView.GetChild("btn4").onClick.Add(__play5);
- _mainView.GetChild("btn5").onClick.Add(() => { __play(_g6); });
- }
-
- void __play(GComponent target)
- {
- _btnGroup.visible = false;
- GRoot.inst.AddChild(target);
- Transition t = target.GetTransition("t0");
-
- t.Play(() =>
- {
- _btnGroup.visible = true;
- GRoot.inst.RemoveChild(target);
- });
- }
-
- void __play4()
- {
- _btnGroup.visible = false;
- _g4.x = GRoot.inst.width - _g4.width - 20;
- _g4.y = 100;
- GRoot.inst.AddChild(_g4);
- Transition t = _g4.GetTransition("t0");
- t.Play(3, 0, () =>
- {
- _btnGroup.visible = true;
- GRoot.inst.RemoveChild(_g4);
- });
- }
-
- void __play5()
- {
- _btnGroup.visible = false;
- _g5.x = 20;
- _g5.y = GRoot.inst.height - _g5.height - 100;
- GRoot.inst.AddChild(_g5);
- Transition t = _g5.GetTransition("t0");
- _startValue = 10000;
- int add = UnityEngine.Random.Range(1000, 3000);
- _endValue = _startValue + add;
- _g5.GetChild("value").text = "" + _startValue;
- _g5.GetChild("add_value").text = "" + add;
- t.Play(() =>
- {
- _btnGroup.visible = true;
- GRoot.inst.RemoveChild(_g5);
- });
- }
-
- void __playNum()
- {
- GTween.To(_startValue, _endValue, 0.3f).SetEase(EaseType.Linear)
- .OnUpdate((GTweener tweener) => { _g5.GetChild("value").text = "" + Mathf.Floor(tweener.value.x); });
-
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class TransitionMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GGroup _btnGroup;
+ GComponent _g1;
+ GComponent _g2;
+ GComponent _g3;
+ GComponent _g4;
+ GComponent _g5;
+ GComponent _g6;
+
+ float _startValue;
+ float _endValue;
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _btnGroup = _mainView.GetChild("g0").asGroup;
+
+ _g1 = UIPackage.CreateObject("Transition", "BOSS").asCom;
+ _g2 = UIPackage.CreateObject("Transition", "BOSS_SKILL").asCom;
+ _g3 = UIPackage.CreateObject("Transition", "TRAP").asCom;
+
+ _g4 = UIPackage.CreateObject("Transition", "GoodHit").asCom;
+ _g5 = UIPackage.CreateObject("Transition", "PowerUp").asCom;
+ _g5.GetTransition("t0").SetHook("play_num_now", __playNum);
+
+ _g6 = UIPackage.CreateObject("Transition", "PathDemo").asCom;
+
+ _mainView.GetChild("btn0").onClick.Add(() => { __play(_g1); });
+ _mainView.GetChild("btn1").onClick.Add(() => { __play(_g2); });
+ _mainView.GetChild("btn2").onClick.Add(() => { __play(_g3); });
+ _mainView.GetChild("btn3").onClick.Add(__play4);
+ _mainView.GetChild("btn4").onClick.Add(__play5);
+ _mainView.GetChild("btn5").onClick.Add(() => { __play(_g6); });
+ }
+
+ void __play(GComponent target)
+ {
+ _btnGroup.visible = false;
+ GRoot.inst.AddChild(target);
+ Transition t = target.GetTransition("t0");
+
+ t.Play(() =>
+ {
+ _btnGroup.visible = true;
+ GRoot.inst.RemoveChild(target);
+ });
+ }
+
+ void __play4()
+ {
+ _btnGroup.visible = false;
+ _g4.x = GRoot.inst.width - _g4.width - 20;
+ _g4.y = 100;
+ GRoot.inst.AddChild(_g4);
+ Transition t = _g4.GetTransition("t0");
+ t.Play(3, 0, () =>
+ {
+ _btnGroup.visible = true;
+ GRoot.inst.RemoveChild(_g4);
+ });
+ }
+
+ void __play5()
+ {
+ _btnGroup.visible = false;
+ _g5.x = 20;
+ _g5.y = GRoot.inst.height - _g5.height - 100;
+ GRoot.inst.AddChild(_g5);
+ Transition t = _g5.GetTransition("t0");
+ _startValue = 10000;
+ int add = UnityEngine.Random.Range(1000, 3000);
+ _endValue = _startValue + add;
+ _g5.GetChild("value").text = "" + _startValue;
+ _g5.GetChild("add_value").text = "" + add;
+ t.Play(() =>
+ {
+ _btnGroup.visible = true;
+ GRoot.inst.RemoveChild(_g5);
+ });
+ }
+
+ void __playNum()
+ {
+ GTween.To(_startValue, _endValue, 0.3f).SetEase(EaseType.Linear)
+ .OnUpdate((GTweener tweener) => { _g5.GetChild("value").text = "" + Mathf.Floor(tweener.value.x); });
+
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/TreeView/TreeViewMain.cs b/Assets/Examples/TreeView/TreeViewMain.cs
index 819552ad..02959d9e 100644
--- a/Assets/Examples/TreeView/TreeViewMain.cs
+++ b/Assets/Examples/TreeView/TreeViewMain.cs
@@ -1,92 +1,92 @@
-using UnityEngine;
-using FairyGUI;
-
-public class TreeViewMain : MonoBehaviour
-{
- GComponent _mainView;
- GTree _tree1;
- GTree _tree2;
- string _fileURL;
-
- void Awake()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
- }
-
- void Start()
- {
- _mainView = this.GetComponent().ui;
-
- _fileURL = "ui://TreeView/file";
-
- _tree1 = _mainView.GetChild("tree").asTree;
- _tree1.onClickItem.Add(__clickNode);
- _tree2 = _mainView.GetChild("tree2").asTree;
- _tree2.onClickItem.Add(__clickNode);
- _tree2.treeNodeRender = RenderTreeNode;
-
- GTreeNode topNode = new GTreeNode(true);
- topNode.data = "I'm a top node";
- _tree2.rootNode.AddChild(topNode);
- for (int i = 0; i < 5; i++)
- {
- GTreeNode node = new GTreeNode(false);
- node.data = "Hello " + i;
- topNode.AddChild(node);
- }
-
- GTreeNode aFolderNode = new GTreeNode(true);
- aFolderNode.data = "A folder node";
- topNode.AddChild(aFolderNode);
- for (int i = 0; i < 5; i++)
- {
- GTreeNode node = new GTreeNode(false);
- node.data = "Good " + i;
- aFolderNode.AddChild(node);
- }
-
- for (int i = 0; i < 3; i++)
- {
- GTreeNode node = new GTreeNode(false);
- node.data = "World " + i;
- topNode.AddChild(node);
- }
-
- GTreeNode anotherTopNode = new GTreeNode(false);
- anotherTopNode.data = new string[] { "I'm a top node too", "ui://TreeView/heart" };
- _tree2.rootNode.AddChild(anotherTopNode);
- }
-
- void RenderTreeNode(GTreeNode node, GComponent obj)
- {
- if (node.isFolder)
- {
- obj.text = (string)node.data;
- }
- else if (node.data is string[])
- {
- obj.icon = ((string[])node.data)[1];
- obj.text = ((string[])node.data)[0];
- }
- else
- {
- obj.icon = _fileURL;
- obj.text = (string)node.data;
- }
- }
-
- void __clickNode(EventContext context)
- {
- GTreeNode node = ((GObject)context.data).treeNode;
- Debug.Log(node.text);
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class TreeViewMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GTree _tree1;
+ GTree _tree2;
+ string _fileURL;
+
+ void Awake()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+ }
+
+ void Start()
+ {
+ _mainView = this.GetComponent().ui;
+
+ _fileURL = "ui://TreeView/file";
+
+ _tree1 = _mainView.GetChild("tree").asTree;
+ _tree1.onClickItem.Add(__clickNode);
+ _tree2 = _mainView.GetChild("tree2").asTree;
+ _tree2.onClickItem.Add(__clickNode);
+ _tree2.treeNodeRender = RenderTreeNode;
+
+ GTreeNode topNode = new GTreeNode(true);
+ topNode.data = "I'm a top node";
+ _tree2.rootNode.AddChild(topNode);
+ for (int i = 0; i < 5; i++)
+ {
+ GTreeNode node = new GTreeNode(false);
+ node.data = "Hello " + i;
+ topNode.AddChild(node);
+ }
+
+ GTreeNode aFolderNode = new GTreeNode(true);
+ aFolderNode.data = "A folder node";
+ topNode.AddChild(aFolderNode);
+ for (int i = 0; i < 5; i++)
+ {
+ GTreeNode node = new GTreeNode(false);
+ node.data = "Good " + i;
+ aFolderNode.AddChild(node);
+ }
+
+ for (int i = 0; i < 3; i++)
+ {
+ GTreeNode node = new GTreeNode(false);
+ node.data = "World " + i;
+ topNode.AddChild(node);
+ }
+
+ GTreeNode anotherTopNode = new GTreeNode(false);
+ anotherTopNode.data = new string[] { "I'm a top node too", "ui://TreeView/heart" };
+ _tree2.rootNode.AddChild(anotherTopNode);
+ }
+
+ void RenderTreeNode(GTreeNode node, GComponent obj)
+ {
+ if (node.isFolder)
+ {
+ obj.text = (string)node.data;
+ }
+ else if (node.data is string[])
+ {
+ obj.icon = ((string[])node.data)[1];
+ obj.text = ((string[])node.data)[0];
+ }
+ else
+ {
+ obj.icon = _fileURL;
+ obj.text = (string)node.data;
+ }
+ }
+
+ void __clickNode(EventContext context)
+ {
+ GTreeNode node = ((GObject)context.data).treeNode;
+ Debug.Log(node.text);
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/TurnCard/Card.cs b/Assets/Examples/TurnCard/Card.cs
index 4a094fdb..508a20bf 100644
--- a/Assets/Examples/TurnCard/Card.cs
+++ b/Assets/Examples/TurnCard/Card.cs
@@ -1,73 +1,73 @@
-using FairyGUI;
-
-public class Card : GButton
-{
- GObject _back;
- GObject _front;
-
- public override void ConstructFromXML(FairyGUI.Utils.XML xml)
- {
- base.ConstructFromXML(xml);
-
- _back = GetChild("n0");
- _front = GetChild("icon");
- _front.visible = false;
- }
-
- public bool opened
- {
- get
- {
- return _front.visible;
- }
-
- set
- {
- GTween.Kill(this);
-
- _front.visible = value;
- _back.visible = !value;
- }
- }
-
- public void SetPerspective()
- {
- _front.displayObject.perspective = true;
- _back.displayObject.perspective = true;
- }
-
- public void Turn()
- {
- if (GTween.IsTweening(this))
- return;
-
- bool toOpen = !_front.visible;
- GTween.To(0, 180, 0.8f).SetTarget(this).SetEase(EaseType.QuadOut).OnUpdate(TurnInTween).SetUserData(toOpen);
- }
-
- void TurnInTween(GTweener tweener)
- {
- bool toOpen = (bool)tweener.userData;
- float v = tweener.value.x;
- if (toOpen)
- {
- _back.rotationY = v;
- _front.rotationY = -180 + v;
- if (v > 90)
- {
- _front.visible = true;
- _back.visible = false;
- }
- }
- else
- {
- _back.rotationY = -180 + v;
- _front.rotationY = v;
- if (v > 90)
- {
- _front.visible = false;
- _back.visible = true;
- }
- }
- }
+using FairyGUI;
+
+public class Card : GButton
+{
+ GObject _back;
+ GObject _front;
+
+ public override void ConstructFromXML(FairyGUI.Utils.XML xml)
+ {
+ base.ConstructFromXML(xml);
+
+ _back = GetChild("n0");
+ _front = GetChild("icon");
+ _front.visible = false;
+ }
+
+ public bool opened
+ {
+ get
+ {
+ return _front.visible;
+ }
+
+ set
+ {
+ GTween.Kill(this);
+
+ _front.visible = value;
+ _back.visible = !value;
+ }
+ }
+
+ public void SetPerspective()
+ {
+ _front.displayObject.perspective = true;
+ _back.displayObject.perspective = true;
+ }
+
+ public void Turn()
+ {
+ if (GTween.IsTweening(this))
+ return;
+
+ bool toOpen = !_front.visible;
+ GTween.To(0, 180, 0.8f).SetTarget(this).SetEase(EaseType.QuadOut).OnUpdate(TurnInTween).SetUserData(toOpen);
+ }
+
+ void TurnInTween(GTweener tweener)
+ {
+ bool toOpen = (bool)tweener.userData;
+ float v = tweener.value.x;
+ if (toOpen)
+ {
+ _back.rotationY = v;
+ _front.rotationY = -180 + v;
+ if (v > 90)
+ {
+ _front.visible = true;
+ _back.visible = false;
+ }
+ }
+ else
+ {
+ _back.rotationY = -180 + v;
+ _front.rotationY = v;
+ if (v > 90)
+ {
+ _front.visible = false;
+ _back.visible = true;
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/TurnCard/TurnCardMain.cs b/Assets/Examples/TurnCard/TurnCardMain.cs
index 550cfa9a..6cba9217 100644
--- a/Assets/Examples/TurnCard/TurnCardMain.cs
+++ b/Assets/Examples/TurnCard/TurnCardMain.cs
@@ -1,45 +1,45 @@
-using UnityEngine;
-using FairyGUI;
-
-public class TurnCardMain : MonoBehaviour
-{
- GComponent _mainView;
- Card _c0;
- Card _c1;
-
- void Awake()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- UIPackage.AddPackage("UI/TurnCard");
- UIObjectFactory.SetPackageItemExtension("ui://TurnCard/CardComponent", typeof(Card));
- }
-
- void Start()
- {
- _mainView = this.GetComponent().ui;
-
- _c0 = (Card)_mainView.GetChild("c0");
-
- _c1 = (Card)_mainView.GetChild("c1");
- _c1.SetPerspective();
-
- _c0.onClick.Add(__clickCard);
- _c1.onClick.Add(__clickCard);
- }
-
- void __clickCard(EventContext context)
- {
- Card card = (Card)context.sender;
- card.Turn();
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class TurnCardMain : MonoBehaviour
+{
+ GComponent _mainView;
+ Card _c0;
+ Card _c1;
+
+ void Awake()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ UIPackage.AddPackage("UI/TurnCard");
+ UIObjectFactory.SetPackageItemExtension("ui://TurnCard/CardComponent", typeof(Card));
+ }
+
+ void Start()
+ {
+ _mainView = this.GetComponent().ui;
+
+ _c0 = (Card)_mainView.GetChild("c0");
+
+ _c1 = (Card)_mainView.GetChild("c1");
+ _c1.SetPerspective();
+
+ _c0.onClick.Add(__clickCard);
+ _c1.onClick.Add(__clickCard);
+ }
+
+ void __clickCard(EventContext context)
+ {
+ Card card = (Card)context.sender;
+ card.Turn();
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/TurnPage/BookPage.cs b/Assets/Examples/TurnPage/BookPage.cs
index f96dde44..f975e840 100644
--- a/Assets/Examples/TurnPage/BookPage.cs
+++ b/Assets/Examples/TurnPage/BookPage.cs
@@ -1,46 +1,46 @@
-using UnityEngine;
-using FairyGUI;
-
-class BookPage : GComponent
-{
- Controller _style;
- GoWrapper _modelWrapper;
- GObject _pageNumber;
-
- public override void ConstructFromXML(FairyGUI.Utils.XML xml)
- {
- base.ConstructFromXML(xml);
-
- _style = GetController("style");
-
- _pageNumber = GetChild("pn");
-
- _modelWrapper = new GoWrapper();
- GetChild("model").asGraph.SetNativeObject(_modelWrapper);
- }
-
- public void render(int pageIndex)
- {
- _pageNumber.text = (pageIndex + 1).ToString();
-
- if (pageIndex == 0)
- _style.selectedIndex = 0; //pic page
- else if (pageIndex == 2)
- {
- if (_modelWrapper.wrapTarget == null)
- {
- Object prefab = Resources.Load("Role/npc3");
- GameObject go = (GameObject)Object.Instantiate(prefab);
- go.transform.localPosition = new Vector3(0, 0, 1000);
- go.transform.localScale = new Vector3(120, 120, 120);
- go.transform.localEulerAngles = new Vector3(0, 100, 0);
-
- _modelWrapper.SetWrapTarget(go, true);
- }
-
- _style.selectedIndex = 2; //show a model
- }
- else
- _style.selectedIndex = 1; //empty page
- }
-}
+using UnityEngine;
+using FairyGUI;
+
+class BookPage : GComponent
+{
+ Controller _style;
+ GoWrapper _modelWrapper;
+ GObject _pageNumber;
+
+ public override void ConstructFromXML(FairyGUI.Utils.XML xml)
+ {
+ base.ConstructFromXML(xml);
+
+ _style = GetController("style");
+
+ _pageNumber = GetChild("pn");
+
+ _modelWrapper = new GoWrapper();
+ GetChild("model").asGraph.SetNativeObject(_modelWrapper);
+ }
+
+ public void render(int pageIndex)
+ {
+ _pageNumber.text = (pageIndex + 1).ToString();
+
+ if (pageIndex == 0)
+ _style.selectedIndex = 0; //pic page
+ else if (pageIndex == 2)
+ {
+ if (_modelWrapper.wrapTarget == null)
+ {
+ Object prefab = Resources.Load("Role/npc3");
+ GameObject go = (GameObject)Object.Instantiate(prefab);
+ go.transform.localPosition = new Vector3(0, 0, 1000);
+ go.transform.localScale = new Vector3(120, 120, 120);
+ go.transform.localEulerAngles = new Vector3(0, 100, 0);
+
+ _modelWrapper.SetWrapTarget(go, true);
+ }
+
+ _style.selectedIndex = 2; //show a model
+ }
+ else
+ _style.selectedIndex = 1; //empty page
+ }
+}
diff --git a/Assets/Examples/TurnPage/FairyBook.cs b/Assets/Examples/TurnPage/FairyBook.cs
index 6b47225c..7bb6348a 100644
--- a/Assets/Examples/TurnPage/FairyBook.cs
+++ b/Assets/Examples/TurnPage/FairyBook.cs
@@ -1,1225 +1,1225 @@
-using System;
-using FairyGUI;
-using FairyGUI.Utils;
-using UnityEngine;
-
-///
-/// Achieving the effect of turning over books. Use virtual mechanism to support unlimited pages. Support covers.
-///
-public class FairyBook : GComponent
-{
- ///
- ///
- ///
- ///
- ///
- public delegate void PageRenderer(int index, GComponent page);
-
- ///
- ///
- ///
- public PageRenderer pageRenderer;
-
- ///
- ///
- ///
- public static float EffectDuration = 0.5f;
-
- ///
- ///
- ///
- public enum Paper
- {
- Soft,
- Hard
- }
-
- public enum CoverType
- {
- Front,
- Back
- }
-
- enum CoverStatus
- {
- Hidden,
- ShowingFront,
- ShowingBack
- }
-
- enum CoverTurningOp
- {
- None,
- ShowFront,
- HideFront,
- ShowBack,
- HideBack
- }
-
- enum Corner
- {
- INVALID,
- TL,
- BL,
- TR,
- BR
- }
-
- GComponent _pagesContainer;
- string _pageResource;
- int _pageWidth;
- int _pageHeight;
-
- int _pageCount;
- int _currentPage;
- Paper _paper;
-
- int _turningTarget;
- float _turningAmount;
- CoverTurningOp _coverTurningOp;
- GPath _turningPath;
-
- GComponent[] _objects;
- GGraph _mask1;
- GGraph _mask2;
- GObject _softShadow;
- int[] _objectIndice;
- int[] _objectNewIndice;
-
- Corner _draggingCorner;
- Vector2 _dragPoint;
- float _touchDownTime;
-
- GComponent _frontCover;
- GComponent _backCover;
- Vector2 _frontCoverPos;
- Vector2 _backCoverPos;
- CoverStatus _coverStatus;
-
- EventListener _onTurnComplete;
-
- public override void ConstructFromXML(XML xml)
- {
- base.ConstructFromXML(xml);
-
- _pagesContainer = GetChild("pages").asCom;
- if (_pagesContainer == null)
- {
- Debug.LogError("Not a valid book resource");
- return;
- }
-
- GComponent obj1 = _pagesContainer.GetChild("left").asCom;
- GComponent obj2 = _pagesContainer.GetChild("right").asCom;
- if (obj1 == null || obj2 == null || obj1.resourceURL != obj2.resourceURL
- || obj1.width != obj2.width || obj2.x != obj1.x + obj1.width)
- {
- Debug.LogError("Not a valid book resource");
- return;
- }
-
- obj1.displayObject.home = this.displayObject.cachedTransform;
- obj2.displayObject.home = this.displayObject.cachedTransform;
- _pagesContainer.RemoveChild(obj1);
- _pagesContainer.RemoveChild(obj2);
-
- _frontCover = GetChild("frontCover") as GComponent;
- if (_frontCover != null)
- _frontCoverPos = _frontCover.position;
- _backCover = GetChild("backCover") as GComponent;
- if (_backCover != null)
- _backCoverPos = _backCover.position;
-
- _objects = new GComponent[4] { obj1, obj2, null, null };
- _objectIndice = new int[4] { -1, -1, -1, -1 };
- _objectNewIndice = new int[4];
- _turningTarget = -1;
- _currentPage = -1;
-
- _pageWidth = (int)obj1.width;
- _pageHeight = (int)obj1.height;
- _pageResource = obj1.resourceURL;
-
- _mask1 = new GGraph();
- _mask1.displayObject.home = this.displayObject.cachedTransform;
- _mask1.SetSize(_pageWidth, _pageHeight);
-
- _mask2 = new GGraph();
- _mask2.displayObject.home = this.displayObject.cachedTransform;
- _mask2.SetSize(_pageWidth, _pageHeight);
-
- SetupHotspot(GetChild("hotspot_tl"), Corner.TL);
- SetupHotspot(GetChild("hotspot_bl"), Corner.BL);
- SetupHotspot(GetChild("hotspot_tr"), Corner.TR);
- SetupHotspot(GetChild("hotspot_br"), Corner.BR);
- }
-
- public override void Dispose()
- {
- for (int i = 0; i < 4; i++)
- {
- if (_objects[i] != null)
- _objects[i].Dispose();
-
- }
- _mask1.Dispose();
- _mask2.Dispose();
- if (_softShadow != null)
- _softShadow.Dispose();
-
- base.Dispose();
- }
-
- ///
- ///
- ///
- public EventListener onTurnComplete
- {
- get { return _onTurnComplete ?? (_onTurnComplete = new EventListener(this, "onTurnComplete")); }
- }
-
- ///
- ///
- ///
- ///
- public void SetSoftShadowResource(string res)
- {
- _softShadow = UIPackage.CreateObjectFromURL(res);
- _softShadow.height = Mathf.Sqrt(Mathf.Pow(_pageWidth, 2) + Mathf.Pow(_pageHeight, 2)) + 60;
- _softShadow.displayObject.home = this.displayObject.cachedTransform;
- _softShadow.sortingOrder = int.MaxValue;
- }
-
- ///
- ///
- ///
- public Paper pageSoftness
- {
- get { return _paper; }
- set { _paper = value; }
- }
-
- ///
- ///
- ///
- public int pageCount
- {
- get { return _pageCount; }
- set
- {
- if (_pageCount % 2 != 0)
- throw new System.Exception("Page count must be even!");
-
- _pageCount = value;
- }
- }
-
- ///
- ///
- ///
- public int currentPage
- {
- get { return _currentPage; }
- set
- {
- if (value < 0 || value > _pageCount - 1)
- throw new Exception("Page index out of bounds: " + value);
-
- if (_currentPage != value)
- {
- GTween.Kill(this, true);
-
- _currentPage = value;
- _coverStatus = CoverStatus.Hidden;
-
- RenderPages();
- }
- }
- }
-
- ///
- ///
- ///
- ///
- public void TurnTo(int pageIndex)
- {
- if (pageIndex < 0 || pageIndex > _pageCount - 1)
- throw new Exception("Page index out of bounds: " + pageIndex);
-
- GTween.Kill(this, true);
-
- if (_coverStatus == CoverStatus.ShowingFront)
- {
- _coverTurningOp = CoverTurningOp.HideFront;
- _draggingCorner = Corner.BR;
- }
- else if (_coverStatus == CoverStatus.ShowingBack)
- {
- _coverTurningOp = CoverTurningOp.HideBack;
- _draggingCorner = Corner.BL;
- }
-
- int tt1 = _currentPage;
- if (_currentPage % 2 == 0)
- tt1--;
- int tt2 = pageIndex;
- if (pageIndex % 2 == 0)
- tt2--;
- if (tt1 == tt2)
- {
- _currentPage = pageIndex;
- _turningTarget = -1;
- }
- else
- {
- _turningTarget = pageIndex;
- if (_turningTarget < _currentPage)
- _draggingCorner = Corner.BL;
- else
- _draggingCorner = Corner.BR;
- }
-
- if (_draggingCorner == Corner.INVALID)
- return;
-
- StartTween();
- }
-
- ///
- ///
- ///
- public void TurnNext()
- {
- GTween.Kill(this, true);
-
- if (isCoverShowing(CoverType.Front))
- TurnTo(0);
- else if (_currentPage == _pageCount - 1)
- ShowCover(CoverType.Back, true);
- else if (_currentPage % 2 == 0)
- TurnTo(_currentPage + 1);
- else
- TurnTo(_currentPage + 2);
- }
-
- ///
- ///
- ///
- public void TurnPrevious()
- {
- GTween.Kill(this, true);
-
- if (isCoverShowing(CoverType.Back))
- TurnTo(_pageCount - 1);
- else if (_currentPage == 0)
- ShowCover(CoverType.Front, true);
- else if (_currentPage % 2 == 0)
- TurnTo(_currentPage - 2);
- else
- TurnTo(_currentPage - 1);
- }
-
- ///
- ///
- ///
- ///
- ///
- public void ShowCover(CoverType cover, bool turnEffect)
- {
- GTween.Kill(this, true);
-
- if (_frontCover == null)
- return;
-
- if (turnEffect)
- {
- if (cover == CoverType.Front)
- {
- if (_coverStatus == CoverStatus.ShowingFront)
- return;
-
- _coverTurningOp = CoverTurningOp.ShowFront;
- _draggingCorner = Corner.BL;
- _currentPage = 0;
- }
- else
- {
- if (_coverStatus == CoverStatus.ShowingBack)
- return;
-
- _coverTurningOp = CoverTurningOp.ShowBack;
- _draggingCorner = Corner.BR;
- _currentPage = _pageCount - 1;
- }
-
- StartTween();
- }
- else
- {
- if (cover == CoverType.Front)
- {
- _currentPage = 0;
- _coverStatus = CoverStatus.ShowingFront;
- }
- else
- {
- _currentPage = _pageCount - 1;
- _coverStatus = CoverStatus.ShowingBack;
- }
- RenderPages();
- }
- }
-
- ///
- ///
- ///
- ///
- ///
- public bool isCoverShowing(CoverType cover)
- {
- return cover == CoverType.Front ? (_coverStatus == CoverStatus.ShowingFront) : (_coverStatus == CoverStatus.ShowingBack);
- }
-
- void StartTween()
- {
- _turningAmount = 0;
- RenderPages();
- Vector2 source = GetCornerPosition(_draggingCorner, _coverTurningOp != CoverTurningOp.None);
- Vector2 target;
- if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL)
- target = GetCornerPosition(_draggingCorner + 2, _coverTurningOp != CoverTurningOp.None);
- else
- target = GetCornerPosition(_draggingCorner - 2, _coverTurningOp != CoverTurningOp.None);
-
- if (_turningPath == null)
- _turningPath = new GPath();
- Vector2 mid = new Vector2(source.x + (target.x - source.x) / 2, target.y - 50);
- _turningPath.Create(new GPathPoint(source), new GPathPoint(mid), new GPathPoint(target));
- GTween.To(source, target, EffectDuration).SetUserData(true).SetTarget(this)
- .SetPath(_turningPath)
- .OnUpdate(OnTurnUpdate).OnComplete(OnTurnComplete);
- }
-
- void OnTurnUpdate(GTweener tweener)
- {
- _dragPoint = tweener.value.vec2;
- _turningAmount = _dragPoint.x / (_coverTurningOp != CoverTurningOp.None ? _frontCover.width * 2 : _pageWidth * 2);
- if (_draggingCorner == Corner.TR || _draggingCorner == Corner.BR)
- _turningAmount = 1 - _turningAmount;
- PlayTurnEffect();
- }
-
- void OnTurnComplete(GTweener tweener)
- {
- bool suc = (bool)tweener.userData;
- _draggingCorner = Corner.INVALID;
- if (suc && _turningTarget != -1)
- _currentPage = _turningTarget;
- if (suc && _coverTurningOp != CoverTurningOp.None)
- {
- if (_coverTurningOp == CoverTurningOp.ShowFront)
- _coverStatus = CoverStatus.ShowingFront;
- else if (_coverTurningOp == CoverTurningOp.ShowBack)
- _coverStatus = CoverStatus.ShowingBack;
- else
- _coverStatus = CoverStatus.Hidden;
- }
- _coverTurningOp = CoverTurningOp.None;
- _turningTarget = -1;
-
- RenderPages();
-
- DispatchEvent("onTurnComplete");
- }
-
- void PlayTurnEffect()
- {
- if (_coverTurningOp != CoverTurningOp.None)
- PlayCoverEffect();
-
- if (_turningTarget != -1)
- {
- if (_paper == Paper.Hard)
- PlayHardEffect();
- else
- PlaySoftEffect();
- }
- }
-
- void PlayCoverEffect()
- {
- float amount = Mathf.Clamp01(_turningAmount);
- float ratio;
- bool isLeft;
- GComponent turningObj = (_coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideFront) ? _frontCover : _backCover;
- PolygonMesh mesh = GetHardMesh(turningObj);
-
- if (amount < 0.5f)
- {
- ratio = 1 - amount * 2;
- isLeft = _coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideBack;
- }
- else
- {
- ratio = (amount - 0.5f) * 2;
- isLeft = _coverTurningOp == CoverTurningOp.HideFront || _coverTurningOp == CoverTurningOp.ShowBack;
- }
-
- if (turningObj == _frontCover)
- SetCoverStatus(turningObj, CoverType.Front, !isLeft);
- else
- SetCoverStatus(turningObj, CoverType.Back, isLeft);
-
- mesh.points.Clear();
- mesh.texcoords.Clear();
- if (isLeft)
- {
- float topOffset = 1f / 8 * (1 - ratio);
- float xOffset = 1 - ratio;
- mesh.Add(new Vector2(xOffset, 1 + topOffset));
- mesh.Add(new Vector2(xOffset, -topOffset));
- mesh.Add(new Vector2(1, 0));
- mesh.Add(new Vector2(1, 1));
- }
- else
- {
- float topOffset = 1f / 8 * (1 - ratio);
- mesh.Add(new Vector2(0, 1));
- mesh.Add(new Vector2(0, 0));
- mesh.Add(new Vector2(ratio, -topOffset));
- mesh.Add(new Vector2(ratio, 1 + topOffset));
- }
-
- mesh.texcoords.AddRange(VertexBuffer.NormalizedUV);
- }
-
- void PlayHardEffect()
- {
- float amount = Mathf.Clamp01(_turningAmount);
- float ratio;
- bool isLeft;
- GComponent turningObj;
- PolygonMesh mesh;
- if (amount < 0.5f)
- {
- ratio = 1 - amount * 2;
- isLeft = _turningTarget < _currentPage;
-
- turningObj = _objects[2];
- mesh = GetHardMesh(turningObj);
- GetHardMesh(_objects[3]).points.Clear();
- }
- else
- {
- ratio = (amount - 0.5f) * 2;
- isLeft = _turningTarget > _currentPage;
-
- turningObj = _objects[3];
- mesh = GetHardMesh(turningObj);
- GetHardMesh(_objects[2]).points.Clear();
- }
-
- mesh.points.Clear();
- mesh.texcoords.Clear();
- if (isLeft)
- {
- turningObj.x = 0;
-
- float topOffset = 1f / 8 * (1 - ratio);
- float xOffset = 1 - ratio;
- mesh.Add(new Vector2(xOffset, 1 + topOffset));
- mesh.Add(new Vector2(xOffset, -topOffset));
- mesh.Add(new Vector2(1, 0));
- mesh.Add(new Vector2(1, 1));
- }
- else
- {
- turningObj.x = _pageWidth;
-
- float topOffset = 1f / 8 * (1 - ratio);
- mesh.Add(new Vector2(0, 1));
- mesh.Add(new Vector2(0, 0));
- mesh.Add(new Vector2(ratio, -topOffset));
- mesh.Add(new Vector2(ratio, 1 + topOffset));
- }
-
- mesh.texcoords.AddRange(VertexBuffer.NormalizedUV);
- }
-
- void FlipPoint(ref Vector2 pt, float w, float h)
- {
- switch (_draggingCorner)
- {
- case Corner.TL:
- pt.x = w - pt.x;
- pt.y = h - pt.y;
- break;
- case Corner.BL:
- pt.x = w - pt.x;
- break;
- case Corner.TR:
- pt.y = h - pt.y;
- break;
- }
- }
-
- void PlaySoftEffect()
- {
- GComponent turningObj1 = _objects[2];
- GComponent turningObj2 = _objects[3];
- PolygonMesh mesh1 = GetSoftMesh(turningObj1);
- PolygonMesh mesh2 = GetSoftMesh(turningObj2);
-
- /**
- * a
- * / \
- * f(0,0)------/ b--g(w,0)
- * | / / |
- * | / / |
- * | c / |
- * | \ / |
- * | \ / |
- * e(0,h)-----d--------h(w,h)
- */
- Vector2 pa, pb, pc, pd, pe, pf, pg, ph;
- float k, angle;
- bool threePoints = false;
-
- pc = _dragPoint;
- pe = new Vector2(0, _pageHeight);
- pf = Vector2.zero;
- pg = new Vector2(_pageWidth, 0);
- ph = new Vector2(_pageWidth, _pageHeight);
-
- FlipPoint(ref pc, _pageWidth * 2, _pageHeight);
- pc.x -= _pageWidth;
- if (pc.x >= _pageWidth)
- return;
-
- k = (ph.y - pc.y) / (ph.x - pc.x);
- float k2 = 1 + Mathf.Pow(k, 2);
- float min;
- min = ph.x - _pageWidth * 2 / k2;
- if (pc.x < min)
- {
- pc.x = min;
- if (pc.x >= _pageWidth)
- return;
- pc.y = ph.y - k * (ph.x - pc.x);
- }
-
- min = ph.x - (_pageWidth + _pageHeight * k) * 2 / k2;
- if (pc.x < min)
- {
- pc.x = min;
- if (pc.x >= _pageWidth)
- return;
- pc.y = ph.y - k * (ph.x - pc.x);
- }
-
- angle = Mathf.Atan(k) * Mathf.Rad2Deg;
- pd = new Vector2(_pageWidth - k2 * (ph.x - pc.x) / 2, _pageHeight);
- pb = new Vector2(pd.x + _pageHeight * k, 0);
- pa = new Vector2();
-
- if (pb.x > _pageWidth)
- {
- pb.x = _pageWidth;
- pa = new Vector2(_pageWidth, _pageHeight - (_pageWidth - pd.x) / k);
- threePoints = true;
- }
-
- FlipPoint(ref pa, _pageWidth, _pageHeight);
- FlipPoint(ref pb, _pageWidth, _pageHeight);
- FlipPoint(ref pd, _pageWidth, _pageHeight);
- FlipPoint(ref pc, _pageWidth, _pageHeight);
- if (_draggingCorner == Corner.BL || _draggingCorner == Corner.TL)
- angle = -angle;
-
- switch (_draggingCorner)
- {
- case Corner.BR:
- {
- turningObj1.SetPivot(0, 0, true);
- turningObj1.position = new Vector2(_pageWidth, 0);
-
- turningObj2.SetPivot(0, 1, true);
- turningObj2.position = new Vector2(_pageWidth + pc.x, pc.y);
- turningObj2.rotation = 2 * angle;
-
- if (_softShadow != null)
- {
- _softShadow.SetPivot(1, (_softShadow.height - 30) / _softShadow.height, true);
- _softShadow.position = new Vector2(Vector2.Distance(pc, pd), _pageHeight);
- _softShadow.rotation = -angle;
- if (_softShadow.x > _pageWidth - 20)
- _softShadow.alpha = (_pageWidth - _softShadow.x) / 20;
- else
- _softShadow.alpha = 1;
- }
-
- mesh1.points.Clear();
- mesh1.Add(pe);
- mesh1.Add(pf);
- mesh1.Add(pb);
- if (threePoints)
- mesh1.Add(pa);
- mesh1.Add(pd);
-
- mesh2.points.Clear();
- mesh2.Add(new Vector2(Vector2.Distance(pc, pd), _pageHeight));
- mesh2.Add(new Vector2(0, _pageHeight));
- if (threePoints)
- mesh2.Add(new Vector2(0, _pageHeight - Vector2.Distance(pc, pa)));
- else
- {
- mesh2.Add(new Vector2(0, 0));
- mesh2.Add(new Vector2(Vector2.Distance(pg, pb), 0));
- }
- break;
- }
- case Corner.TR:
- {
- turningObj1.SetPivot(0, 0, true);
- turningObj1.position = new Vector2(_pageWidth, 0);
-
- turningObj2.SetPivot(0, 0, true);
- turningObj2.position = new Vector2(_pageWidth + pc.x, pc.y);
- turningObj2.rotation = -2 * angle;
-
- if (_softShadow != null)
- {
- _softShadow.SetPivot(1, 30 / _softShadow.height, true);
- _softShadow.position = new Vector2(Vector2.Distance(pc, pd), 0);
- _softShadow.rotation = angle;
- if (_softShadow.x > _pageWidth - 20)
- _softShadow.alpha = (_pageWidth - _softShadow.x) / 20;
- else
- _softShadow.alpha = 1;
- }
-
- mesh1.points.Clear();
- mesh1.Add(pe);
- mesh1.Add(pf);
- mesh1.Add(pd);
- if (threePoints)
- mesh1.Add(pa);
- mesh1.Add(pb);
-
- mesh2.points.Clear();
- if (threePoints)
- mesh2.Add(new Vector2(0, Vector2.Distance(pc, pa)));
- else
- {
- mesh2.Add(new Vector2(Vector2.Distance(pb, ph), _pageHeight));
- mesh2.Add(new Vector2(0, _pageHeight));
- }
- mesh2.Add(new Vector2(0, 0));
- mesh2.Add(new Vector2(Vector2.Distance(pc, pd), 0));
- break;
- }
- case Corner.BL:
- {
- turningObj1.SetPivot(0, 0, true);
- turningObj1.position = Vector2.zero;
-
- turningObj2.SetPivot(1, 1, true);
- turningObj2.position = pc;
- turningObj2.rotation = 2 * angle;
-
- if (_softShadow != null)
- {
- _softShadow.SetPivot(1, 30 / _softShadow.height, true);
- _softShadow.position = new Vector2(_pageWidth - Vector2.Distance(pc, pd), _pageHeight);
- _softShadow.rotation = 180 - angle;
- if (_softShadow.x < 20)
- _softShadow.alpha = (_softShadow.x - 20) / 20;
- else
- _softShadow.alpha = 1;
- }
-
- mesh1.points.Clear();
- mesh1.Add(pb);
- mesh1.Add(pg);
- mesh1.Add(ph);
- mesh1.Add(pd);
- if (threePoints)
- mesh1.Add(pa);
-
- mesh2.points.Clear();
- if (!threePoints)
- {
- mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pf, pb), 0));
- mesh2.Add(new Vector2(_pageWidth, 0));
- }
- else
- mesh2.Add(new Vector2(_pageWidth, _pageHeight - Vector2.Distance(pc, pa)));
- mesh2.Add(new Vector2(_pageWidth, _pageHeight));
- mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pc, pd), _pageHeight));
- break;
- }
- case Corner.TL:
- {
- turningObj1.SetPivot(0, 0, true);
- turningObj1.position = Vector2.zero;
-
- turningObj2.SetPivot(1, 0, true);
- turningObj2.position = pc;
- turningObj2.rotation = -2 * angle;
-
- if (_softShadow != null)
- {
- _softShadow.SetPivot(1, (_softShadow.height - 30) / _softShadow.height, true);
- _softShadow.position = new Vector2(_pageWidth - Vector2.Distance(pc, pd), 0);
- _softShadow.rotation = 180 + angle;
- if (_softShadow.x < 20)
- _softShadow.alpha = (_softShadow.x - 20) / 20;
- else
- _softShadow.alpha = 1;
- }
-
- mesh1.points.Clear();
- mesh1.Add(pd);
- mesh1.Add(pg);
- mesh1.Add(ph);
- mesh1.Add(pb);
- if (threePoints)
- mesh1.Add(pa);
-
- mesh2.points.Clear();
- mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pc, pd), 0));
- mesh2.Add(new Vector2(_pageWidth, 0));
- if (threePoints)
- mesh2.Add(new Vector2(_pageWidth, Vector2.Distance(pc, pa)));
- else
- {
- mesh2.Add(new Vector2(_pageWidth, _pageHeight));
- mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pe, pb), _pageHeight));
- }
- break;
- }
- }
- }
-
- void RenderPages()
- {
- RenderCovers();
-
- if (_softShadow != null)
- _softShadow.RemoveFromParent();
-
- int curPage = _currentPage;
- if (curPage % 2 == 0)
- curPage--;
-
- int leftPage, rightPage, turningPageBack, turningPageFront;
- leftPage = curPage;
- rightPage = leftPage < _pageCount - 1 ? (leftPage + 1) : -1;
-
- if (_turningTarget != -1)
- {
- int tt = _turningTarget;
- if (tt % 2 == 0)
- tt = tt - 1;
-
- if (tt == curPage)
- {
- _currentPage = _turningTarget;
- turningPageBack = turningPageFront = -1;
- }
- else if (tt > leftPage)
- {
- turningPageFront = tt;
- turningPageBack = rightPage;
- rightPage = tt < _pageCount - 1 ? (tt + 1) : -1;
- }
- else
- {
- turningPageFront = tt > 0 ? (tt + 1) : 0;
- turningPageBack = leftPage;
- leftPage = tt > 0 ? tt : -1;
- }
- }
- else
- {
- turningPageBack = turningPageFront = -1;
- }
-
- _objectNewIndice[0] = leftPage;
- _objectNewIndice[1] = rightPage;
- _objectNewIndice[2] = turningPageBack;
- _objectNewIndice[3] = turningPageFront;
-
- for (int i = 0; i < 4; i++)
- {
- int pageIndex = _objectNewIndice[i];
- if (pageIndex != -1)
- {
- for (int j = 0; j < 4; j++)
- {
- int pageIndex2 = _objectIndice[j];
- if (pageIndex2 == pageIndex)
- {
- if (j != i)
- {
- _objectIndice[j] = _objectIndice[i];
- _objectIndice[i] = pageIndex;
-
- GComponent tmp = _objects[j];
- _objects[j] = _objects[i];
- _objects[i] = tmp;
- }
- break;
- }
- }
- }
- }
-
- for (int i = 0; i < 4; i++)
- {
- GComponent obj = _objects[i];
- int oldIndex = _objectIndice[i];
- int index = _objectNewIndice[i];
- _objectIndice[i] = index;
- if (index == -1)
- {
- if (obj != null)
- obj.RemoveFromParent();
- }
- else if (oldIndex != index)
- {
- if (obj == null)
- {
- obj = UIPackage.CreateObjectFromURL(_pageResource).asCom;
- obj.displayObject.home = this.displayObject.cachedTransform;
- _objects[i] = obj;
- }
-
- _pagesContainer.AddChild(obj);
- pageRenderer(index, obj);
- }
- else
- {
- if (obj.parent == null)
- {
- _pagesContainer.AddChild(obj);
- pageRenderer(index, obj);
- }
- else
- _pagesContainer.AddChild(obj);
- }
-
- if (obj != null && obj.parent != null)
- {
- Controller c1 = obj.GetController("side");
- if (c1 != null)
- {
- if (index == 0)
- c1.selectedPage = "first";
- else if (index == _pageCount - 1)
- c1.selectedPage = "last";
- else
- c1.selectedPage = (index % 2 == 0) ? "right" : "left";
- }
-
- if (i == 0 || i == 1)
- SetPageNormal(obj, i == 0);
- else if (_paper == Paper.Soft)
- SetPageSoft(obj, i == 2);
- else
- SetPageHard(obj, i == 2);
- }
- }
- }
-
- void RenderCovers()
- {
- if (_frontCover != null)
- {
- if (_coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideFront)
- {
- SetPageHard(_frontCover, true);
- SetCoverStatus(_frontCover, CoverType.Front, _coverTurningOp == CoverTurningOp.HideFront);
- }
- else
- {
- if (_frontCover.displayObject.cacheAsBitmap)
- SetCoverNormal(_frontCover, CoverType.Front);
-
- SetCoverStatus(_frontCover, CoverType.Front, _coverStatus == CoverStatus.ShowingFront);
- }
- }
-
- if (_backCover != null)
- {
- if (_coverTurningOp == CoverTurningOp.ShowBack || _coverTurningOp == CoverTurningOp.HideBack)
- {
- SetPageHard(_backCover, true);
- SetCoverStatus(_backCover, CoverType.Back, _coverTurningOp == CoverTurningOp.HideBack);
- }
- else
- {
- if (_backCover.displayObject.cacheAsBitmap)
- SetCoverNormal(_backCover, CoverType.Back);
-
- SetCoverStatus(_backCover, CoverType.Back, _coverStatus == CoverStatus.ShowingBack);
- }
- }
- }
-
- void SetupHotspot(GObject obj, Corner corner)
- {
- if (obj == null)
- return;
-
- obj.data = corner;
-
- obj.onTouchBegin.Add(__touchBegin);
- obj.onTouchMove.Add(__touchMove);
- obj.onTouchEnd.Add(__touchEnd);
- }
-
- void SetPageHard(GComponent obj, bool front)
- {
- obj.touchable = false;
- obj.displayObject.cacheAsBitmap = true;
- if (obj.mask != null)
- {
- obj.mask.RemoveFromParent();
- obj.mask = null;
- }
-
- PolygonMesh mesh = obj.displayObject.paintingGraphics.GetMeshFactory();
- mesh.usePercentPositions = true;
- mesh.points.Clear();
- mesh.texcoords.Clear();
- obj.displayObject.paintingGraphics.SetMeshDirty();
-
- if (front)
- {
- mesh.points.AddRange(VertexBuffer.NormalizedPosition);
- mesh.texcoords.AddRange(VertexBuffer.NormalizedUV);
- }
- }
-
- void SetPageSoft(GComponent obj, bool front)
- {
- obj.touchable = false;
- obj.displayObject.cacheAsBitmap = false;
- DisplayObject mask = front ? _mask1.displayObject : _mask2.displayObject;
- obj.mask = mask;
-
- PolygonMesh mesh = mask.graphics.GetMeshFactory();
- mesh.usePercentPositions = false;
- mesh.points.Clear();
- mesh.texcoords.Clear();
- mask.graphics.SetMeshDirty();
-
- if (front)
- {
- mesh.Add(new Vector2(0, _pageHeight));
- mesh.Add(Vector2.zero);
- mesh.Add(new Vector2(_pageWidth, 0));
- mesh.Add(new Vector2(_pageWidth, _pageHeight));
- }
- else if (_softShadow != null)
- obj.AddChild(_softShadow);
- }
-
- void SetPageNormal(GComponent obj, bool left)
- {
- obj.displayObject.cacheAsBitmap = false;
- obj.touchable = true;
- obj.SetPivot(0, 0, true);
- if (left)
- obj.SetXY(0, 0);
- else
- obj.SetXY(_pageWidth, 0);
- obj.rotation = 0;
- if (obj.mask != null)
- {
- obj.mask.RemoveFromParent();
- obj.mask = null;
- }
- }
-
- void SetCoverStatus(GComponent obj, CoverType coverType, bool show)
- {
- Controller c = obj.GetController("side");
- if (show)
- {
- if (c.selectedIndex != 0)
- {
- obj.position = coverType == CoverType.Front ? _backCoverPos : _frontCoverPos;
- obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer) + 1);
- c.selectedIndex = 0; //front
-
- if (obj.displayObject.cacheAsBitmap)
- obj.displayObject.cacheAsBitmap = true; //refresh
- }
- }
- else
- {
- if (c.selectedIndex != 1)
- {
- obj.position = coverType == CoverType.Front ? _frontCoverPos : _backCoverPos;
- obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer));
- c.selectedIndex = 1; //back
-
- if (obj.displayObject.cacheAsBitmap)
- obj.displayObject.cacheAsBitmap = true; //refresh
- }
- }
- }
-
- void SetCoverNormal(GComponent obj, CoverType coverType)
- {
- obj.position = coverType == CoverType.Front ? _frontCoverPos : _backCoverPos;
- obj.displayObject.cacheAsBitmap = false;
- obj.touchable = true;
- obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer));
- obj.GetController("side").selectedIndex = 1; //back
- }
-
- PolygonMesh GetHardMesh(GComponent obj)
- {
- obj.displayObject.paintingGraphics.SetMeshDirty();
- return obj.displayObject.paintingGraphics.GetMeshFactory();
- }
-
- PolygonMesh GetSoftMesh(GComponent obj)
- {
- obj.mask.graphics.SetMeshDirty();
- return obj.mask.graphics.GetMeshFactory();
- }
-
- void UpdateDragPosition(Vector2 pos)
- {
- if (_coverTurningOp != CoverTurningOp.None)
- {
- _dragPoint = GlobalToLocal(pos) - _frontCoverPos;
- _turningAmount = _dragPoint.x / (2 * _frontCover.width);
- }
- else
- {
- _dragPoint = _pagesContainer.GlobalToLocal(pos);
- _turningAmount = _dragPoint.x / (2 * _pageWidth);
- }
-
- if (_draggingCorner == Corner.TR || _draggingCorner == Corner.BR)
- _turningAmount = 1 - _turningAmount;
- }
-
- Vector2 GetCornerPosition(Corner corner, bool isCover)
- {
- float w = isCover ? _frontCover.width : _pageWidth;
- float h = isCover ? _frontCover.height : _pageHeight;
- Vector2 pt;
- switch (corner)
- {
- case Corner.BL:
- pt = new Vector2(0, h);
- break;
-
- case Corner.TR:
- pt = new Vector2(w * 2, 0);
- break;
-
- case Corner.BR:
- pt = new Vector2(w * 2, h);
- break;
-
- default:
- pt = Vector2.zero;
- break;
- }
-
- return pt;
- }
-
- void __touchBegin(EventContext context)
- {
- GTween.Kill(this, true);
-
- _draggingCorner = (Corner)((GObject)context.sender).data;
- if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL)
- {
- if (_coverStatus == CoverStatus.ShowingBack)
- {
- _coverTurningOp = CoverTurningOp.HideBack;
- }
- else if (_objectNewIndice[0] == -1)
- {
- if (_frontCover != null && _coverStatus != CoverStatus.ShowingFront)
- _coverTurningOp = CoverTurningOp.ShowFront;
- else
- _draggingCorner = Corner.INVALID;
- }
- else
- {
- _turningTarget = _objectNewIndice[0] - 2;
- if (_turningTarget < 0)
- _turningTarget = 0;
- }
- }
- else
- {
- if (_coverStatus == CoverStatus.ShowingFront)
- {
- _coverTurningOp = CoverTurningOp.HideFront;
- }
- else if (_objectNewIndice[1] == -1)
- {
- if (_backCover != null && _coverStatus != CoverStatus.ShowingBack)
- _coverTurningOp = CoverTurningOp.ShowBack;
- else
- _draggingCorner = Corner.INVALID;
- }
- else
- {
- _turningTarget = _objectNewIndice[1] + 1;
- }
- }
-
- if (_draggingCorner != Corner.INVALID)
- {
- _touchDownTime = Time.unscaledTime;
- UpdateDragPosition(context.inputEvent.position);
- RenderPages();
- PlayTurnEffect();
-
- context.CaptureTouch();
- }
- }
-
- void __touchMove(EventContext context)
- {
- if (_draggingCorner != Corner.INVALID)
- {
- UpdateDragPosition(context.inputEvent.position);
- PlayTurnEffect();
- }
- }
-
- void __touchEnd(EventContext context)
- {
- if (_draggingCorner != Corner.INVALID)
- {
- bool suc = _turningAmount > 0.4f || (Time.unscaledTime - _touchDownTime < 0.35f);
- Vector2 target;
- if (suc)
- {
- if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL)
- target = GetCornerPosition(_draggingCorner + 2, _coverTurningOp != CoverTurningOp.None);
- else
- target = GetCornerPosition(_draggingCorner - 2, _coverTurningOp != CoverTurningOp.None);
- }
- else
- target = GetCornerPosition(_draggingCorner, _coverTurningOp != CoverTurningOp.None);
-
- float duration = Mathf.Max(EffectDuration * 0.5f, Mathf.Abs(target.x - _dragPoint.x) / (_pageWidth * 2) * EffectDuration);
- GTween.To(_dragPoint, target, duration).SetTarget(this).SetUserData(suc)
- .OnUpdate(OnTurnUpdate).OnComplete(OnTurnComplete);
- }
- }
+using System;
+using FairyGUI;
+using FairyGUI.Utils;
+using UnityEngine;
+
+///
+/// Achieving the effect of turning over books. Use virtual mechanism to support unlimited pages. Support covers.
+///
+public class FairyBook : GComponent
+{
+ ///
+ ///
+ ///
+ ///
+ ///
+ public delegate void PageRenderer(int index, GComponent page);
+
+ ///
+ ///
+ ///
+ public PageRenderer pageRenderer;
+
+ ///
+ ///
+ ///
+ public static float EffectDuration = 0.5f;
+
+ ///
+ ///
+ ///
+ public enum Paper
+ {
+ Soft,
+ Hard
+ }
+
+ public enum CoverType
+ {
+ Front,
+ Back
+ }
+
+ enum CoverStatus
+ {
+ Hidden,
+ ShowingFront,
+ ShowingBack
+ }
+
+ enum CoverTurningOp
+ {
+ None,
+ ShowFront,
+ HideFront,
+ ShowBack,
+ HideBack
+ }
+
+ enum Corner
+ {
+ INVALID,
+ TL,
+ BL,
+ TR,
+ BR
+ }
+
+ GComponent _pagesContainer;
+ string _pageResource;
+ int _pageWidth;
+ int _pageHeight;
+
+ int _pageCount;
+ int _currentPage;
+ Paper _paper;
+
+ int _turningTarget;
+ float _turningAmount;
+ CoverTurningOp _coverTurningOp;
+ GPath _turningPath;
+
+ GComponent[] _objects;
+ GGraph _mask1;
+ GGraph _mask2;
+ GObject _softShadow;
+ int[] _objectIndice;
+ int[] _objectNewIndice;
+
+ Corner _draggingCorner;
+ Vector2 _dragPoint;
+ float _touchDownTime;
+
+ GComponent _frontCover;
+ GComponent _backCover;
+ Vector2 _frontCoverPos;
+ Vector2 _backCoverPos;
+ CoverStatus _coverStatus;
+
+ EventListener _onTurnComplete;
+
+ public override void ConstructFromXML(XML xml)
+ {
+ base.ConstructFromXML(xml);
+
+ _pagesContainer = GetChild("pages").asCom;
+ if (_pagesContainer == null)
+ {
+ Debug.LogError("Not a valid book resource");
+ return;
+ }
+
+ GComponent obj1 = _pagesContainer.GetChild("left").asCom;
+ GComponent obj2 = _pagesContainer.GetChild("right").asCom;
+ if (obj1 == null || obj2 == null || obj1.resourceURL != obj2.resourceURL
+ || obj1.width != obj2.width || obj2.x != obj1.x + obj1.width)
+ {
+ Debug.LogError("Not a valid book resource");
+ return;
+ }
+
+ obj1.displayObject.home = this.displayObject.cachedTransform;
+ obj2.displayObject.home = this.displayObject.cachedTransform;
+ _pagesContainer.RemoveChild(obj1);
+ _pagesContainer.RemoveChild(obj2);
+
+ _frontCover = GetChild("frontCover") as GComponent;
+ if (_frontCover != null)
+ _frontCoverPos = _frontCover.position;
+ _backCover = GetChild("backCover") as GComponent;
+ if (_backCover != null)
+ _backCoverPos = _backCover.position;
+
+ _objects = new GComponent[4] { obj1, obj2, null, null };
+ _objectIndice = new int[4] { -1, -1, -1, -1 };
+ _objectNewIndice = new int[4];
+ _turningTarget = -1;
+ _currentPage = -1;
+
+ _pageWidth = (int)obj1.width;
+ _pageHeight = (int)obj1.height;
+ _pageResource = obj1.resourceURL;
+
+ _mask1 = new GGraph();
+ _mask1.displayObject.home = this.displayObject.cachedTransform;
+ _mask1.SetSize(_pageWidth, _pageHeight);
+
+ _mask2 = new GGraph();
+ _mask2.displayObject.home = this.displayObject.cachedTransform;
+ _mask2.SetSize(_pageWidth, _pageHeight);
+
+ SetupHotspot(GetChild("hotspot_tl"), Corner.TL);
+ SetupHotspot(GetChild("hotspot_bl"), Corner.BL);
+ SetupHotspot(GetChild("hotspot_tr"), Corner.TR);
+ SetupHotspot(GetChild("hotspot_br"), Corner.BR);
+ }
+
+ public override void Dispose()
+ {
+ for (int i = 0; i < 4; i++)
+ {
+ if (_objects[i] != null)
+ _objects[i].Dispose();
+
+ }
+ _mask1.Dispose();
+ _mask2.Dispose();
+ if (_softShadow != null)
+ _softShadow.Dispose();
+
+ base.Dispose();
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onTurnComplete
+ {
+ get { return _onTurnComplete ?? (_onTurnComplete = new EventListener(this, "onTurnComplete")); }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public void SetSoftShadowResource(string res)
+ {
+ _softShadow = UIPackage.CreateObjectFromURL(res);
+ _softShadow.height = Mathf.Sqrt(Mathf.Pow(_pageWidth, 2) + Mathf.Pow(_pageHeight, 2)) + 60;
+ _softShadow.displayObject.home = this.displayObject.cachedTransform;
+ _softShadow.sortingOrder = int.MaxValue;
+ }
+
+ ///
+ ///
+ ///
+ public Paper pageSoftness
+ {
+ get { return _paper; }
+ set { _paper = value; }
+ }
+
+ ///
+ ///
+ ///
+ public int pageCount
+ {
+ get { return _pageCount; }
+ set
+ {
+ if (_pageCount % 2 != 0)
+ throw new System.Exception("Page count must be even!");
+
+ _pageCount = value;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public int currentPage
+ {
+ get { return _currentPage; }
+ set
+ {
+ if (value < 0 || value > _pageCount - 1)
+ throw new Exception("Page index out of bounds: " + value);
+
+ if (_currentPage != value)
+ {
+ GTween.Kill(this, true);
+
+ _currentPage = value;
+ _coverStatus = CoverStatus.Hidden;
+
+ RenderPages();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public void TurnTo(int pageIndex)
+ {
+ if (pageIndex < 0 || pageIndex > _pageCount - 1)
+ throw new Exception("Page index out of bounds: " + pageIndex);
+
+ GTween.Kill(this, true);
+
+ if (_coverStatus == CoverStatus.ShowingFront)
+ {
+ _coverTurningOp = CoverTurningOp.HideFront;
+ _draggingCorner = Corner.BR;
+ }
+ else if (_coverStatus == CoverStatus.ShowingBack)
+ {
+ _coverTurningOp = CoverTurningOp.HideBack;
+ _draggingCorner = Corner.BL;
+ }
+
+ int tt1 = _currentPage;
+ if (_currentPage % 2 == 0)
+ tt1--;
+ int tt2 = pageIndex;
+ if (pageIndex % 2 == 0)
+ tt2--;
+ if (tt1 == tt2)
+ {
+ _currentPage = pageIndex;
+ _turningTarget = -1;
+ }
+ else
+ {
+ _turningTarget = pageIndex;
+ if (_turningTarget < _currentPage)
+ _draggingCorner = Corner.BL;
+ else
+ _draggingCorner = Corner.BR;
+ }
+
+ if (_draggingCorner == Corner.INVALID)
+ return;
+
+ StartTween();
+ }
+
+ ///
+ ///
+ ///
+ public void TurnNext()
+ {
+ GTween.Kill(this, true);
+
+ if (isCoverShowing(CoverType.Front))
+ TurnTo(0);
+ else if (_currentPage == _pageCount - 1)
+ ShowCover(CoverType.Back, true);
+ else if (_currentPage % 2 == 0)
+ TurnTo(_currentPage + 1);
+ else
+ TurnTo(_currentPage + 2);
+ }
+
+ ///
+ ///
+ ///
+ public void TurnPrevious()
+ {
+ GTween.Kill(this, true);
+
+ if (isCoverShowing(CoverType.Back))
+ TurnTo(_pageCount - 1);
+ else if (_currentPage == 0)
+ ShowCover(CoverType.Front, true);
+ else if (_currentPage % 2 == 0)
+ TurnTo(_currentPage - 2);
+ else
+ TurnTo(_currentPage - 1);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void ShowCover(CoverType cover, bool turnEffect)
+ {
+ GTween.Kill(this, true);
+
+ if (_frontCover == null)
+ return;
+
+ if (turnEffect)
+ {
+ if (cover == CoverType.Front)
+ {
+ if (_coverStatus == CoverStatus.ShowingFront)
+ return;
+
+ _coverTurningOp = CoverTurningOp.ShowFront;
+ _draggingCorner = Corner.BL;
+ _currentPage = 0;
+ }
+ else
+ {
+ if (_coverStatus == CoverStatus.ShowingBack)
+ return;
+
+ _coverTurningOp = CoverTurningOp.ShowBack;
+ _draggingCorner = Corner.BR;
+ _currentPage = _pageCount - 1;
+ }
+
+ StartTween();
+ }
+ else
+ {
+ if (cover == CoverType.Front)
+ {
+ _currentPage = 0;
+ _coverStatus = CoverStatus.ShowingFront;
+ }
+ else
+ {
+ _currentPage = _pageCount - 1;
+ _coverStatus = CoverStatus.ShowingBack;
+ }
+ RenderPages();
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public bool isCoverShowing(CoverType cover)
+ {
+ return cover == CoverType.Front ? (_coverStatus == CoverStatus.ShowingFront) : (_coverStatus == CoverStatus.ShowingBack);
+ }
+
+ void StartTween()
+ {
+ _turningAmount = 0;
+ RenderPages();
+ Vector2 source = GetCornerPosition(_draggingCorner, _coverTurningOp != CoverTurningOp.None);
+ Vector2 target;
+ if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL)
+ target = GetCornerPosition(_draggingCorner + 2, _coverTurningOp != CoverTurningOp.None);
+ else
+ target = GetCornerPosition(_draggingCorner - 2, _coverTurningOp != CoverTurningOp.None);
+
+ if (_turningPath == null)
+ _turningPath = new GPath();
+ Vector2 mid = new Vector2(source.x + (target.x - source.x) / 2, target.y - 50);
+ _turningPath.Create(new GPathPoint(source), new GPathPoint(mid), new GPathPoint(target));
+ GTween.To(source, target, EffectDuration).SetUserData(true).SetTarget(this)
+ .SetPath(_turningPath)
+ .OnUpdate(OnTurnUpdate).OnComplete(OnTurnComplete);
+ }
+
+ void OnTurnUpdate(GTweener tweener)
+ {
+ _dragPoint = tweener.value.vec2;
+ _turningAmount = _dragPoint.x / (_coverTurningOp != CoverTurningOp.None ? _frontCover.width * 2 : _pageWidth * 2);
+ if (_draggingCorner == Corner.TR || _draggingCorner == Corner.BR)
+ _turningAmount = 1 - _turningAmount;
+ PlayTurnEffect();
+ }
+
+ void OnTurnComplete(GTweener tweener)
+ {
+ bool suc = (bool)tweener.userData;
+ _draggingCorner = Corner.INVALID;
+ if (suc && _turningTarget != -1)
+ _currentPage = _turningTarget;
+ if (suc && _coverTurningOp != CoverTurningOp.None)
+ {
+ if (_coverTurningOp == CoverTurningOp.ShowFront)
+ _coverStatus = CoverStatus.ShowingFront;
+ else if (_coverTurningOp == CoverTurningOp.ShowBack)
+ _coverStatus = CoverStatus.ShowingBack;
+ else
+ _coverStatus = CoverStatus.Hidden;
+ }
+ _coverTurningOp = CoverTurningOp.None;
+ _turningTarget = -1;
+
+ RenderPages();
+
+ DispatchEvent("onTurnComplete");
+ }
+
+ void PlayTurnEffect()
+ {
+ if (_coverTurningOp != CoverTurningOp.None)
+ PlayCoverEffect();
+
+ if (_turningTarget != -1)
+ {
+ if (_paper == Paper.Hard)
+ PlayHardEffect();
+ else
+ PlaySoftEffect();
+ }
+ }
+
+ void PlayCoverEffect()
+ {
+ float amount = Mathf.Clamp01(_turningAmount);
+ float ratio;
+ bool isLeft;
+ GComponent turningObj = (_coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideFront) ? _frontCover : _backCover;
+ PolygonMesh mesh = GetHardMesh(turningObj);
+
+ if (amount < 0.5f)
+ {
+ ratio = 1 - amount * 2;
+ isLeft = _coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideBack;
+ }
+ else
+ {
+ ratio = (amount - 0.5f) * 2;
+ isLeft = _coverTurningOp == CoverTurningOp.HideFront || _coverTurningOp == CoverTurningOp.ShowBack;
+ }
+
+ if (turningObj == _frontCover)
+ SetCoverStatus(turningObj, CoverType.Front, !isLeft);
+ else
+ SetCoverStatus(turningObj, CoverType.Back, isLeft);
+
+ mesh.points.Clear();
+ mesh.texcoords.Clear();
+ if (isLeft)
+ {
+ float topOffset = 1f / 8 * (1 - ratio);
+ float xOffset = 1 - ratio;
+ mesh.Add(new Vector2(xOffset, 1 + topOffset));
+ mesh.Add(new Vector2(xOffset, -topOffset));
+ mesh.Add(new Vector2(1, 0));
+ mesh.Add(new Vector2(1, 1));
+ }
+ else
+ {
+ float topOffset = 1f / 8 * (1 - ratio);
+ mesh.Add(new Vector2(0, 1));
+ mesh.Add(new Vector2(0, 0));
+ mesh.Add(new Vector2(ratio, -topOffset));
+ mesh.Add(new Vector2(ratio, 1 + topOffset));
+ }
+
+ mesh.texcoords.AddRange(VertexBuffer.NormalizedUV);
+ }
+
+ void PlayHardEffect()
+ {
+ float amount = Mathf.Clamp01(_turningAmount);
+ float ratio;
+ bool isLeft;
+ GComponent turningObj;
+ PolygonMesh mesh;
+ if (amount < 0.5f)
+ {
+ ratio = 1 - amount * 2;
+ isLeft = _turningTarget < _currentPage;
+
+ turningObj = _objects[2];
+ mesh = GetHardMesh(turningObj);
+ GetHardMesh(_objects[3]).points.Clear();
+ }
+ else
+ {
+ ratio = (amount - 0.5f) * 2;
+ isLeft = _turningTarget > _currentPage;
+
+ turningObj = _objects[3];
+ mesh = GetHardMesh(turningObj);
+ GetHardMesh(_objects[2]).points.Clear();
+ }
+
+ mesh.points.Clear();
+ mesh.texcoords.Clear();
+ if (isLeft)
+ {
+ turningObj.x = 0;
+
+ float topOffset = 1f / 8 * (1 - ratio);
+ float xOffset = 1 - ratio;
+ mesh.Add(new Vector2(xOffset, 1 + topOffset));
+ mesh.Add(new Vector2(xOffset, -topOffset));
+ mesh.Add(new Vector2(1, 0));
+ mesh.Add(new Vector2(1, 1));
+ }
+ else
+ {
+ turningObj.x = _pageWidth;
+
+ float topOffset = 1f / 8 * (1 - ratio);
+ mesh.Add(new Vector2(0, 1));
+ mesh.Add(new Vector2(0, 0));
+ mesh.Add(new Vector2(ratio, -topOffset));
+ mesh.Add(new Vector2(ratio, 1 + topOffset));
+ }
+
+ mesh.texcoords.AddRange(VertexBuffer.NormalizedUV);
+ }
+
+ void FlipPoint(ref Vector2 pt, float w, float h)
+ {
+ switch (_draggingCorner)
+ {
+ case Corner.TL:
+ pt.x = w - pt.x;
+ pt.y = h - pt.y;
+ break;
+ case Corner.BL:
+ pt.x = w - pt.x;
+ break;
+ case Corner.TR:
+ pt.y = h - pt.y;
+ break;
+ }
+ }
+
+ void PlaySoftEffect()
+ {
+ GComponent turningObj1 = _objects[2];
+ GComponent turningObj2 = _objects[3];
+ PolygonMesh mesh1 = GetSoftMesh(turningObj1);
+ PolygonMesh mesh2 = GetSoftMesh(turningObj2);
+
+ /**
+ * a
+ * / \
+ * f(0,0)------/ b--g(w,0)
+ * | / / |
+ * | / / |
+ * | c / |
+ * | \ / |
+ * | \ / |
+ * e(0,h)-----d--------h(w,h)
+ */
+ Vector2 pa, pb, pc, pd, pe, pf, pg, ph;
+ float k, angle;
+ bool threePoints = false;
+
+ pc = _dragPoint;
+ pe = new Vector2(0, _pageHeight);
+ pf = Vector2.zero;
+ pg = new Vector2(_pageWidth, 0);
+ ph = new Vector2(_pageWidth, _pageHeight);
+
+ FlipPoint(ref pc, _pageWidth * 2, _pageHeight);
+ pc.x -= _pageWidth;
+ if (pc.x >= _pageWidth)
+ return;
+
+ k = (ph.y - pc.y) / (ph.x - pc.x);
+ float k2 = 1 + Mathf.Pow(k, 2);
+ float min;
+ min = ph.x - _pageWidth * 2 / k2;
+ if (pc.x < min)
+ {
+ pc.x = min;
+ if (pc.x >= _pageWidth)
+ return;
+ pc.y = ph.y - k * (ph.x - pc.x);
+ }
+
+ min = ph.x - (_pageWidth + _pageHeight * k) * 2 / k2;
+ if (pc.x < min)
+ {
+ pc.x = min;
+ if (pc.x >= _pageWidth)
+ return;
+ pc.y = ph.y - k * (ph.x - pc.x);
+ }
+
+ angle = Mathf.Atan(k) * Mathf.Rad2Deg;
+ pd = new Vector2(_pageWidth - k2 * (ph.x - pc.x) / 2, _pageHeight);
+ pb = new Vector2(pd.x + _pageHeight * k, 0);
+ pa = new Vector2();
+
+ if (pb.x > _pageWidth)
+ {
+ pb.x = _pageWidth;
+ pa = new Vector2(_pageWidth, _pageHeight - (_pageWidth - pd.x) / k);
+ threePoints = true;
+ }
+
+ FlipPoint(ref pa, _pageWidth, _pageHeight);
+ FlipPoint(ref pb, _pageWidth, _pageHeight);
+ FlipPoint(ref pd, _pageWidth, _pageHeight);
+ FlipPoint(ref pc, _pageWidth, _pageHeight);
+ if (_draggingCorner == Corner.BL || _draggingCorner == Corner.TL)
+ angle = -angle;
+
+ switch (_draggingCorner)
+ {
+ case Corner.BR:
+ {
+ turningObj1.SetPivot(0, 0, true);
+ turningObj1.position = new Vector2(_pageWidth, 0);
+
+ turningObj2.SetPivot(0, 1, true);
+ turningObj2.position = new Vector2(_pageWidth + pc.x, pc.y);
+ turningObj2.rotation = 2 * angle;
+
+ if (_softShadow != null)
+ {
+ _softShadow.SetPivot(1, (_softShadow.height - 30) / _softShadow.height, true);
+ _softShadow.position = new Vector2(Vector2.Distance(pc, pd), _pageHeight);
+ _softShadow.rotation = -angle;
+ if (_softShadow.x > _pageWidth - 20)
+ _softShadow.alpha = (_pageWidth - _softShadow.x) / 20;
+ else
+ _softShadow.alpha = 1;
+ }
+
+ mesh1.points.Clear();
+ mesh1.Add(pe);
+ mesh1.Add(pf);
+ mesh1.Add(pb);
+ if (threePoints)
+ mesh1.Add(pa);
+ mesh1.Add(pd);
+
+ mesh2.points.Clear();
+ mesh2.Add(new Vector2(Vector2.Distance(pc, pd), _pageHeight));
+ mesh2.Add(new Vector2(0, _pageHeight));
+ if (threePoints)
+ mesh2.Add(new Vector2(0, _pageHeight - Vector2.Distance(pc, pa)));
+ else
+ {
+ mesh2.Add(new Vector2(0, 0));
+ mesh2.Add(new Vector2(Vector2.Distance(pg, pb), 0));
+ }
+ break;
+ }
+ case Corner.TR:
+ {
+ turningObj1.SetPivot(0, 0, true);
+ turningObj1.position = new Vector2(_pageWidth, 0);
+
+ turningObj2.SetPivot(0, 0, true);
+ turningObj2.position = new Vector2(_pageWidth + pc.x, pc.y);
+ turningObj2.rotation = -2 * angle;
+
+ if (_softShadow != null)
+ {
+ _softShadow.SetPivot(1, 30 / _softShadow.height, true);
+ _softShadow.position = new Vector2(Vector2.Distance(pc, pd), 0);
+ _softShadow.rotation = angle;
+ if (_softShadow.x > _pageWidth - 20)
+ _softShadow.alpha = (_pageWidth - _softShadow.x) / 20;
+ else
+ _softShadow.alpha = 1;
+ }
+
+ mesh1.points.Clear();
+ mesh1.Add(pe);
+ mesh1.Add(pf);
+ mesh1.Add(pd);
+ if (threePoints)
+ mesh1.Add(pa);
+ mesh1.Add(pb);
+
+ mesh2.points.Clear();
+ if (threePoints)
+ mesh2.Add(new Vector2(0, Vector2.Distance(pc, pa)));
+ else
+ {
+ mesh2.Add(new Vector2(Vector2.Distance(pb, ph), _pageHeight));
+ mesh2.Add(new Vector2(0, _pageHeight));
+ }
+ mesh2.Add(new Vector2(0, 0));
+ mesh2.Add(new Vector2(Vector2.Distance(pc, pd), 0));
+ break;
+ }
+ case Corner.BL:
+ {
+ turningObj1.SetPivot(0, 0, true);
+ turningObj1.position = Vector2.zero;
+
+ turningObj2.SetPivot(1, 1, true);
+ turningObj2.position = pc;
+ turningObj2.rotation = 2 * angle;
+
+ if (_softShadow != null)
+ {
+ _softShadow.SetPivot(1, 30 / _softShadow.height, true);
+ _softShadow.position = new Vector2(_pageWidth - Vector2.Distance(pc, pd), _pageHeight);
+ _softShadow.rotation = 180 - angle;
+ if (_softShadow.x < 20)
+ _softShadow.alpha = (_softShadow.x - 20) / 20;
+ else
+ _softShadow.alpha = 1;
+ }
+
+ mesh1.points.Clear();
+ mesh1.Add(pb);
+ mesh1.Add(pg);
+ mesh1.Add(ph);
+ mesh1.Add(pd);
+ if (threePoints)
+ mesh1.Add(pa);
+
+ mesh2.points.Clear();
+ if (!threePoints)
+ {
+ mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pf, pb), 0));
+ mesh2.Add(new Vector2(_pageWidth, 0));
+ }
+ else
+ mesh2.Add(new Vector2(_pageWidth, _pageHeight - Vector2.Distance(pc, pa)));
+ mesh2.Add(new Vector2(_pageWidth, _pageHeight));
+ mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pc, pd), _pageHeight));
+ break;
+ }
+ case Corner.TL:
+ {
+ turningObj1.SetPivot(0, 0, true);
+ turningObj1.position = Vector2.zero;
+
+ turningObj2.SetPivot(1, 0, true);
+ turningObj2.position = pc;
+ turningObj2.rotation = -2 * angle;
+
+ if (_softShadow != null)
+ {
+ _softShadow.SetPivot(1, (_softShadow.height - 30) / _softShadow.height, true);
+ _softShadow.position = new Vector2(_pageWidth - Vector2.Distance(pc, pd), 0);
+ _softShadow.rotation = 180 + angle;
+ if (_softShadow.x < 20)
+ _softShadow.alpha = (_softShadow.x - 20) / 20;
+ else
+ _softShadow.alpha = 1;
+ }
+
+ mesh1.points.Clear();
+ mesh1.Add(pd);
+ mesh1.Add(pg);
+ mesh1.Add(ph);
+ mesh1.Add(pb);
+ if (threePoints)
+ mesh1.Add(pa);
+
+ mesh2.points.Clear();
+ mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pc, pd), 0));
+ mesh2.Add(new Vector2(_pageWidth, 0));
+ if (threePoints)
+ mesh2.Add(new Vector2(_pageWidth, Vector2.Distance(pc, pa)));
+ else
+ {
+ mesh2.Add(new Vector2(_pageWidth, _pageHeight));
+ mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pe, pb), _pageHeight));
+ }
+ break;
+ }
+ }
+ }
+
+ void RenderPages()
+ {
+ RenderCovers();
+
+ if (_softShadow != null)
+ _softShadow.RemoveFromParent();
+
+ int curPage = _currentPage;
+ if (curPage % 2 == 0)
+ curPage--;
+
+ int leftPage, rightPage, turningPageBack, turningPageFront;
+ leftPage = curPage;
+ rightPage = leftPage < _pageCount - 1 ? (leftPage + 1) : -1;
+
+ if (_turningTarget != -1)
+ {
+ int tt = _turningTarget;
+ if (tt % 2 == 0)
+ tt = tt - 1;
+
+ if (tt == curPage)
+ {
+ _currentPage = _turningTarget;
+ turningPageBack = turningPageFront = -1;
+ }
+ else if (tt > leftPage)
+ {
+ turningPageFront = tt;
+ turningPageBack = rightPage;
+ rightPage = tt < _pageCount - 1 ? (tt + 1) : -1;
+ }
+ else
+ {
+ turningPageFront = tt > 0 ? (tt + 1) : 0;
+ turningPageBack = leftPage;
+ leftPage = tt > 0 ? tt : -1;
+ }
+ }
+ else
+ {
+ turningPageBack = turningPageFront = -1;
+ }
+
+ _objectNewIndice[0] = leftPage;
+ _objectNewIndice[1] = rightPage;
+ _objectNewIndice[2] = turningPageBack;
+ _objectNewIndice[3] = turningPageFront;
+
+ for (int i = 0; i < 4; i++)
+ {
+ int pageIndex = _objectNewIndice[i];
+ if (pageIndex != -1)
+ {
+ for (int j = 0; j < 4; j++)
+ {
+ int pageIndex2 = _objectIndice[j];
+ if (pageIndex2 == pageIndex)
+ {
+ if (j != i)
+ {
+ _objectIndice[j] = _objectIndice[i];
+ _objectIndice[i] = pageIndex;
+
+ GComponent tmp = _objects[j];
+ _objects[j] = _objects[i];
+ _objects[i] = tmp;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ for (int i = 0; i < 4; i++)
+ {
+ GComponent obj = _objects[i];
+ int oldIndex = _objectIndice[i];
+ int index = _objectNewIndice[i];
+ _objectIndice[i] = index;
+ if (index == -1)
+ {
+ if (obj != null)
+ obj.RemoveFromParent();
+ }
+ else if (oldIndex != index)
+ {
+ if (obj == null)
+ {
+ obj = UIPackage.CreateObjectFromURL(_pageResource).asCom;
+ obj.displayObject.home = this.displayObject.cachedTransform;
+ _objects[i] = obj;
+ }
+
+ _pagesContainer.AddChild(obj);
+ pageRenderer(index, obj);
+ }
+ else
+ {
+ if (obj.parent == null)
+ {
+ _pagesContainer.AddChild(obj);
+ pageRenderer(index, obj);
+ }
+ else
+ _pagesContainer.AddChild(obj);
+ }
+
+ if (obj != null && obj.parent != null)
+ {
+ Controller c1 = obj.GetController("side");
+ if (c1 != null)
+ {
+ if (index == 0)
+ c1.selectedPage = "first";
+ else if (index == _pageCount - 1)
+ c1.selectedPage = "last";
+ else
+ c1.selectedPage = (index % 2 == 0) ? "right" : "left";
+ }
+
+ if (i == 0 || i == 1)
+ SetPageNormal(obj, i == 0);
+ else if (_paper == Paper.Soft)
+ SetPageSoft(obj, i == 2);
+ else
+ SetPageHard(obj, i == 2);
+ }
+ }
+ }
+
+ void RenderCovers()
+ {
+ if (_frontCover != null)
+ {
+ if (_coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideFront)
+ {
+ SetPageHard(_frontCover, true);
+ SetCoverStatus(_frontCover, CoverType.Front, _coverTurningOp == CoverTurningOp.HideFront);
+ }
+ else
+ {
+ if (_frontCover.displayObject.cacheAsBitmap)
+ SetCoverNormal(_frontCover, CoverType.Front);
+
+ SetCoverStatus(_frontCover, CoverType.Front, _coverStatus == CoverStatus.ShowingFront);
+ }
+ }
+
+ if (_backCover != null)
+ {
+ if (_coverTurningOp == CoverTurningOp.ShowBack || _coverTurningOp == CoverTurningOp.HideBack)
+ {
+ SetPageHard(_backCover, true);
+ SetCoverStatus(_backCover, CoverType.Back, _coverTurningOp == CoverTurningOp.HideBack);
+ }
+ else
+ {
+ if (_backCover.displayObject.cacheAsBitmap)
+ SetCoverNormal(_backCover, CoverType.Back);
+
+ SetCoverStatus(_backCover, CoverType.Back, _coverStatus == CoverStatus.ShowingBack);
+ }
+ }
+ }
+
+ void SetupHotspot(GObject obj, Corner corner)
+ {
+ if (obj == null)
+ return;
+
+ obj.data = corner;
+
+ obj.onTouchBegin.Add(__touchBegin);
+ obj.onTouchMove.Add(__touchMove);
+ obj.onTouchEnd.Add(__touchEnd);
+ }
+
+ void SetPageHard(GComponent obj, bool front)
+ {
+ obj.touchable = false;
+ obj.displayObject.cacheAsBitmap = true;
+ if (obj.mask != null)
+ {
+ obj.mask.RemoveFromParent();
+ obj.mask = null;
+ }
+
+ PolygonMesh mesh = obj.displayObject.paintingGraphics.GetMeshFactory();
+ mesh.usePercentPositions = true;
+ mesh.points.Clear();
+ mesh.texcoords.Clear();
+ obj.displayObject.paintingGraphics.SetMeshDirty();
+
+ if (front)
+ {
+ mesh.points.AddRange(VertexBuffer.NormalizedPosition);
+ mesh.texcoords.AddRange(VertexBuffer.NormalizedUV);
+ }
+ }
+
+ void SetPageSoft(GComponent obj, bool front)
+ {
+ obj.touchable = false;
+ obj.displayObject.cacheAsBitmap = false;
+ DisplayObject mask = front ? _mask1.displayObject : _mask2.displayObject;
+ obj.mask = mask;
+
+ PolygonMesh mesh = mask.graphics.GetMeshFactory();
+ mesh.usePercentPositions = false;
+ mesh.points.Clear();
+ mesh.texcoords.Clear();
+ mask.graphics.SetMeshDirty();
+
+ if (front)
+ {
+ mesh.Add(new Vector2(0, _pageHeight));
+ mesh.Add(Vector2.zero);
+ mesh.Add(new Vector2(_pageWidth, 0));
+ mesh.Add(new Vector2(_pageWidth, _pageHeight));
+ }
+ else if (_softShadow != null)
+ obj.AddChild(_softShadow);
+ }
+
+ void SetPageNormal(GComponent obj, bool left)
+ {
+ obj.displayObject.cacheAsBitmap = false;
+ obj.touchable = true;
+ obj.SetPivot(0, 0, true);
+ if (left)
+ obj.SetXY(0, 0);
+ else
+ obj.SetXY(_pageWidth, 0);
+ obj.rotation = 0;
+ if (obj.mask != null)
+ {
+ obj.mask.RemoveFromParent();
+ obj.mask = null;
+ }
+ }
+
+ void SetCoverStatus(GComponent obj, CoverType coverType, bool show)
+ {
+ Controller c = obj.GetController("side");
+ if (show)
+ {
+ if (c.selectedIndex != 0)
+ {
+ obj.position = coverType == CoverType.Front ? _backCoverPos : _frontCoverPos;
+ obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer) + 1);
+ c.selectedIndex = 0; //front
+
+ if (obj.displayObject.cacheAsBitmap)
+ obj.displayObject.cacheAsBitmap = true; //refresh
+ }
+ }
+ else
+ {
+ if (c.selectedIndex != 1)
+ {
+ obj.position = coverType == CoverType.Front ? _frontCoverPos : _backCoverPos;
+ obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer));
+ c.selectedIndex = 1; //back
+
+ if (obj.displayObject.cacheAsBitmap)
+ obj.displayObject.cacheAsBitmap = true; //refresh
+ }
+ }
+ }
+
+ void SetCoverNormal(GComponent obj, CoverType coverType)
+ {
+ obj.position = coverType == CoverType.Front ? _frontCoverPos : _backCoverPos;
+ obj.displayObject.cacheAsBitmap = false;
+ obj.touchable = true;
+ obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer));
+ obj.GetController("side").selectedIndex = 1; //back
+ }
+
+ PolygonMesh GetHardMesh(GComponent obj)
+ {
+ obj.displayObject.paintingGraphics.SetMeshDirty();
+ return obj.displayObject.paintingGraphics.GetMeshFactory();
+ }
+
+ PolygonMesh GetSoftMesh(GComponent obj)
+ {
+ obj.mask.graphics.SetMeshDirty();
+ return obj.mask.graphics.GetMeshFactory();
+ }
+
+ void UpdateDragPosition(Vector2 pos)
+ {
+ if (_coverTurningOp != CoverTurningOp.None)
+ {
+ _dragPoint = GlobalToLocal(pos) - _frontCoverPos;
+ _turningAmount = _dragPoint.x / (2 * _frontCover.width);
+ }
+ else
+ {
+ _dragPoint = _pagesContainer.GlobalToLocal(pos);
+ _turningAmount = _dragPoint.x / (2 * _pageWidth);
+ }
+
+ if (_draggingCorner == Corner.TR || _draggingCorner == Corner.BR)
+ _turningAmount = 1 - _turningAmount;
+ }
+
+ Vector2 GetCornerPosition(Corner corner, bool isCover)
+ {
+ float w = isCover ? _frontCover.width : _pageWidth;
+ float h = isCover ? _frontCover.height : _pageHeight;
+ Vector2 pt;
+ switch (corner)
+ {
+ case Corner.BL:
+ pt = new Vector2(0, h);
+ break;
+
+ case Corner.TR:
+ pt = new Vector2(w * 2, 0);
+ break;
+
+ case Corner.BR:
+ pt = new Vector2(w * 2, h);
+ break;
+
+ default:
+ pt = Vector2.zero;
+ break;
+ }
+
+ return pt;
+ }
+
+ void __touchBegin(EventContext context)
+ {
+ GTween.Kill(this, true);
+
+ _draggingCorner = (Corner)((GObject)context.sender).data;
+ if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL)
+ {
+ if (_coverStatus == CoverStatus.ShowingBack)
+ {
+ _coverTurningOp = CoverTurningOp.HideBack;
+ }
+ else if (_objectNewIndice[0] == -1)
+ {
+ if (_frontCover != null && _coverStatus != CoverStatus.ShowingFront)
+ _coverTurningOp = CoverTurningOp.ShowFront;
+ else
+ _draggingCorner = Corner.INVALID;
+ }
+ else
+ {
+ _turningTarget = _objectNewIndice[0] - 2;
+ if (_turningTarget < 0)
+ _turningTarget = 0;
+ }
+ }
+ else
+ {
+ if (_coverStatus == CoverStatus.ShowingFront)
+ {
+ _coverTurningOp = CoverTurningOp.HideFront;
+ }
+ else if (_objectNewIndice[1] == -1)
+ {
+ if (_backCover != null && _coverStatus != CoverStatus.ShowingBack)
+ _coverTurningOp = CoverTurningOp.ShowBack;
+ else
+ _draggingCorner = Corner.INVALID;
+ }
+ else
+ {
+ _turningTarget = _objectNewIndice[1] + 1;
+ }
+ }
+
+ if (_draggingCorner != Corner.INVALID)
+ {
+ _touchDownTime = Time.unscaledTime;
+ UpdateDragPosition(context.inputEvent.position);
+ RenderPages();
+ PlayTurnEffect();
+
+ context.CaptureTouch();
+ }
+ }
+
+ void __touchMove(EventContext context)
+ {
+ if (_draggingCorner != Corner.INVALID)
+ {
+ UpdateDragPosition(context.inputEvent.position);
+ PlayTurnEffect();
+ }
+ }
+
+ void __touchEnd(EventContext context)
+ {
+ if (_draggingCorner != Corner.INVALID)
+ {
+ bool suc = _turningAmount > 0.4f || (Time.unscaledTime - _touchDownTime < 0.35f);
+ Vector2 target;
+ if (suc)
+ {
+ if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL)
+ target = GetCornerPosition(_draggingCorner + 2, _coverTurningOp != CoverTurningOp.None);
+ else
+ target = GetCornerPosition(_draggingCorner - 2, _coverTurningOp != CoverTurningOp.None);
+ }
+ else
+ target = GetCornerPosition(_draggingCorner, _coverTurningOp != CoverTurningOp.None);
+
+ float duration = Mathf.Max(EffectDuration * 0.5f, Mathf.Abs(target.x - _dragPoint.x) / (_pageWidth * 2) * EffectDuration);
+ GTween.To(_dragPoint, target, duration).SetTarget(this).SetUserData(suc)
+ .OnUpdate(OnTurnUpdate).OnComplete(OnTurnComplete);
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/TurnPage/TurnPageMain.cs b/Assets/Examples/TurnPage/TurnPageMain.cs
index e696899b..cb67767a 100644
--- a/Assets/Examples/TurnPage/TurnPageMain.cs
+++ b/Assets/Examples/TurnPage/TurnPageMain.cs
@@ -1,78 +1,78 @@
-using UnityEngine;
-using FairyGUI;
-
-public class TurnPageMain : MonoBehaviour
-{
- GComponent _mainView;
- FairyBook _book;
- GSlider _slider;
-
- void Awake()
- {
- UIPackage.AddPackage("UI/TurnPage");
- UIObjectFactory.SetPackageItemExtension("ui://TurnPage/Book", typeof(FairyBook));
- UIObjectFactory.SetPackageItemExtension("ui://TurnPage/Page", typeof(BookPage));
- }
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
-
- _book = (FairyBook)_mainView.GetChild("book");
- _book.SetSoftShadowResource("ui://TurnPage/shadow_soft");
- _book.pageRenderer = RenderPage;
- _book.pageCount = 20;
- _book.currentPage = 0;
- _book.ShowCover(FairyBook.CoverType.Front, false);
- _book.onTurnComplete.Add(OnTurnComplete);
-
- GearBase.disableAllTweenEffect = true;
- _mainView.GetController("bookPos").selectedIndex = 1;
- GearBase.disableAllTweenEffect = false;
-
- _mainView.GetChild("btnNext").onClick.Add(() =>
- {
- _book.TurnNext();
- });
- _mainView.GetChild("btnPrev").onClick.Add(() =>
- {
- _book.TurnPrevious();
- });
-
- _slider = _mainView.GetChild("pageSlide").asSlider;
- _slider.max = _book.pageCount - 1;
- _slider.value = 0;
- _slider.onGripTouchEnd.Add(() =>
- {
- _book.TurnTo((int)_slider.value);
- });
- }
-
- void OnTurnComplete()
- {
- _slider.value = _book.currentPage;
-
- if (_book.isCoverShowing(FairyBook.CoverType.Front))
- _mainView.GetController("bookPos").selectedIndex = 1;
- else if (_book.isCoverShowing(FairyBook.CoverType.Back))
- _mainView.GetController("bookPos").selectedIndex = 2;
- else
- _mainView.GetController("bookPos").selectedIndex = 0;
- }
-
- void RenderPage(int index, GComponent page)
- {
- ((BookPage)page).render(index);
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class TurnPageMain : MonoBehaviour
+{
+ GComponent _mainView;
+ FairyBook _book;
+ GSlider _slider;
+
+ void Awake()
+ {
+ UIPackage.AddPackage("UI/TurnPage");
+ UIObjectFactory.SetPackageItemExtension("ui://TurnPage/Book", typeof(FairyBook));
+ UIObjectFactory.SetPackageItemExtension("ui://TurnPage/Page", typeof(BookPage));
+ }
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+
+ _book = (FairyBook)_mainView.GetChild("book");
+ _book.SetSoftShadowResource("ui://TurnPage/shadow_soft");
+ _book.pageRenderer = RenderPage;
+ _book.pageCount = 20;
+ _book.currentPage = 0;
+ _book.ShowCover(FairyBook.CoverType.Front, false);
+ _book.onTurnComplete.Add(OnTurnComplete);
+
+ GearBase.disableAllTweenEffect = true;
+ _mainView.GetController("bookPos").selectedIndex = 1;
+ GearBase.disableAllTweenEffect = false;
+
+ _mainView.GetChild("btnNext").onClick.Add(() =>
+ {
+ _book.TurnNext();
+ });
+ _mainView.GetChild("btnPrev").onClick.Add(() =>
+ {
+ _book.TurnPrevious();
+ });
+
+ _slider = _mainView.GetChild("pageSlide").asSlider;
+ _slider.max = _book.pageCount - 1;
+ _slider.value = 0;
+ _slider.onGripTouchEnd.Add(() =>
+ {
+ _book.TurnTo((int)_slider.value);
+ });
+ }
+
+ void OnTurnComplete()
+ {
+ _slider.value = _book.currentPage;
+
+ if (_book.isCoverShowing(FairyBook.CoverType.Front))
+ _mainView.GetController("bookPos").selectedIndex = 1;
+ else if (_book.isCoverShowing(FairyBook.CoverType.Back))
+ _mainView.GetController("bookPos").selectedIndex = 2;
+ else
+ _mainView.GetController("bookPos").selectedIndex = 0;
+ }
+
+ void RenderPage(int index, GComponent page)
+ {
+ ((BookPage)page).render(index);
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/TypingEffect/TypingEffectMain.cs b/Assets/Examples/TypingEffect/TypingEffectMain.cs
index e7f49d55..5bdd34b7 100644
--- a/Assets/Examples/TypingEffect/TypingEffectMain.cs
+++ b/Assets/Examples/TypingEffect/TypingEffectMain.cs
@@ -1,44 +1,44 @@
-using UnityEngine;
-using FairyGUI;
-
-public class TypingEffectMain : MonoBehaviour
-{
- GComponent _mainView;
- TypingEffect _te1;
- TypingEffect _te2;
-
- void Awake()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
- }
-
- void Start()
- {
- _mainView = this.GetComponent().ui;
-
- _te1 = new TypingEffect(_mainView.GetChild("n2").asTextField);
- _te1.Start();
- Timers.inst.StartCoroutine(_te1.Print(0.050f));
-
- _te2 = new TypingEffect(_mainView.GetChild("n3").asTextField);
- _te2.Start();
- Timers.inst.Add(0.050f, 0, PrintText);
- }
-
- void PrintText(object param)
- {
- if (!_te2.Print())
- {
- Timers.inst.Remove(PrintText);
- }
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class TypingEffectMain : MonoBehaviour
+{
+ GComponent _mainView;
+ TypingEffect _te1;
+ TypingEffect _te2;
+
+ void Awake()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+ }
+
+ void Start()
+ {
+ _mainView = this.GetComponent().ui;
+
+ _te1 = new TypingEffect(_mainView.GetChild("n2").asTextField);
+ _te1.Start();
+ Timers.inst.StartCoroutine(_te1.Print(0.050f));
+
+ _te2 = new TypingEffect(_mainView.GetChild("n3").asTextField);
+ _te2.Start();
+ Timers.inst.Add(0.050f, 0, PrintText);
+ }
+
+ void PrintText(object param)
+ {
+ if (!_te2.Print())
+ {
+ Timers.inst.Remove(PrintText);
+ }
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Examples/VirtualList/VirtualListMain.cs b/Assets/Examples/VirtualList/VirtualListMain.cs
index e7f578a3..17ab325d 100644
--- a/Assets/Examples/VirtualList/VirtualListMain.cs
+++ b/Assets/Examples/VirtualList/VirtualListMain.cs
@@ -1,48 +1,48 @@
-using UnityEngine;
-using FairyGUI;
-
-public class VirtualListMain : MonoBehaviour
-{
- GComponent _mainView;
- GList _list;
-
- void Awake()
- {
- UIPackage.AddPackage("UI/VirtualList");
- UIObjectFactory.SetPackageItemExtension("ui://VirtualList/mailItem", typeof(MailItem));
- }
-
- void Start()
- {
- Application.targetFrameRate = 60;
- Stage.inst.onKeyDown.Add(OnKeyDown);
-
- _mainView = this.GetComponent().ui;
- _mainView.GetChild("n6").onClick.Add(() => { _list.AddSelection(500, true); });
- _mainView.GetChild("n7").onClick.Add(() => { _list.scrollPane.ScrollTop(); });
- _mainView.GetChild("n8").onClick.Add(() => { _list.scrollPane.ScrollBottom(); });
-
- _list = _mainView.GetChild("mailList").asList;
- _list.SetVirtual();
-
- _list.itemRenderer = RenderListItem;
- _list.numItems = 1000;
- }
-
- void RenderListItem(int index, GObject obj)
- {
- MailItem item = (MailItem)obj;
- item.setFetched(index % 3 == 0);
- item.setRead(index % 2 == 0);
- item.setTime("5 Nov 2015 16:24:33");
- item.title = index + " Mail title here";
- }
-
- void OnKeyDown(EventContext context)
- {
- if (context.inputEvent.keyCode == KeyCode.Escape)
- {
- Application.Quit();
- }
- }
+using UnityEngine;
+using FairyGUI;
+
+public class VirtualListMain : MonoBehaviour
+{
+ GComponent _mainView;
+ GList _list;
+
+ void Awake()
+ {
+ UIPackage.AddPackage("UI/VirtualList");
+ UIObjectFactory.SetPackageItemExtension("ui://VirtualList/mailItem", typeof(MailItem));
+ }
+
+ void Start()
+ {
+ Application.targetFrameRate = 60;
+ Stage.inst.onKeyDown.Add(OnKeyDown);
+
+ _mainView = this.GetComponent().ui;
+ _mainView.GetChild("n6").onClick.Add(() => { _list.AddSelection(500, true); });
+ _mainView.GetChild("n7").onClick.Add(() => { _list.scrollPane.ScrollTop(); });
+ _mainView.GetChild("n8").onClick.Add(() => { _list.scrollPane.ScrollBottom(); });
+
+ _list = _mainView.GetChild("mailList").asList;
+ _list.SetVirtual();
+
+ _list.itemRenderer = RenderListItem;
+ _list.numItems = 1000;
+ }
+
+ void RenderListItem(int index, GObject obj)
+ {
+ MailItem item = (MailItem)obj;
+ item.setFetched(index % 3 == 0);
+ item.setRead(index % 2 == 0);
+ item.setTime("5 Nov 2015 16:24:33");
+ item.title = index + " Mail title here";
+ }
+
+ void OnKeyDown(EventContext context)
+ {
+ if (context.inputEvent.keyCode == KeyCode.Escape)
+ {
+ Application.Quit();
+ }
+ }
}
\ No newline at end of file
diff --git a/Assets/Plugins.meta b/Assets/Plugins.meta
new file mode 100644
index 00000000..9a0a3f28
--- /dev/null
+++ b/Assets/Plugins.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: aa7ce4582c101d74991bd03b2c83ddf7
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Plugins/FairyGUI.meta b/Assets/Plugins/FairyGUI.meta
new file mode 100644
index 00000000..30e71501
--- /dev/null
+++ b/Assets/Plugins/FairyGUI.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 28cfe268e20887f4ab63d5c388e88ace
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/Editor.meta b/Assets/Plugins/FairyGUI/Editor.meta
similarity index 100%
rename from Assets/Scripts/Editor.meta
rename to Assets/Plugins/FairyGUI/Editor.meta
diff --git a/Assets/Scripts/Editor/DisplayObjectEditor.cs b/Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs
similarity index 97%
rename from Assets/Scripts/Editor/DisplayObjectEditor.cs
rename to Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs
index f0a87a1f..a307e67d 100644
--- a/Assets/Scripts/Editor/DisplayObjectEditor.cs
+++ b/Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs
@@ -1,126 +1,126 @@
-using UnityEngine;
-using UnityEditor;
-using FairyGUI;
-
-namespace FairyGUIEditor
-{
- ///
- ///
- ///
- [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;
- }
- }
- }
-}
+using UnityEngine;
+using UnityEditor;
+using FairyGUI;
+
+namespace FairyGUIEditor
+{
+ ///
+ ///
+ ///
+ [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;
+ }
+ }
+ }
+}
diff --git a/Assets/Scripts/Editor/DisplayObjectEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs.meta
similarity index 100%
rename from Assets/Scripts/Editor/DisplayObjectEditor.cs.meta
rename to Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs.meta
diff --git a/Assets/Scripts/Editor/EditorToolSet.cs b/Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs
similarity index 96%
rename from Assets/Scripts/Editor/EditorToolSet.cs
rename to Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs
index 9910fe82..b736ef6e 100644
--- a/Assets/Scripts/Editor/EditorToolSet.cs
+++ b/Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs
@@ -1,135 +1,135 @@
-using System.Collections.Generic;
-using UnityEngine;
-using UnityEditor;
-using FairyGUI;
-
-namespace FairyGUIEditor
-{
- ///
- ///
- ///
- 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();
- 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 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);
- }
- }
-
-}
+using System.Collections.Generic;
+using UnityEngine;
+using UnityEditor;
+using FairyGUI;
+
+namespace FairyGUIEditor
+{
+ ///
+ ///
+ ///
+ 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();
+ 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 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);
+ }
+ }
+
+}
diff --git a/Assets/Scripts/Editor/EditorToolSet.cs.meta b/Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs.meta
similarity index 100%
rename from Assets/Scripts/Editor/EditorToolSet.cs.meta
rename to Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs.meta
diff --git a/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef b/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef
new file mode 100644
index 00000000..6d7246a3
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef
@@ -0,0 +1,18 @@
+{
+ "name": "FairyGUI.Editor",
+ "rootNamespace": "",
+ "references": [
+ "GUID:b12c828e10494534a9050867cfc5ed0c"
+ ],
+ "includePlatforms": [
+ "Editor"
+ ],
+ "excludePlatforms": [],
+ "allowUnsafeCode": true,
+ "overrideReferences": false,
+ "precompiledReferences": [],
+ "autoReferenced": true,
+ "defineConstraints": [],
+ "versionDefines": [],
+ "noEngineReferences": false
+}
\ No newline at end of file
diff --git a/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef.meta b/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef.meta
new file mode 100644
index 00000000..b333f151
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 9b0d782762190cc46bfb2dd2ab152107
+AssemblyDefinitionImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/Editor/PackagesWindow.cs b/Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs
similarity index 97%
rename from Assets/Scripts/Editor/PackagesWindow.cs
rename to Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs
index 227478a6..0fb36663 100644
--- a/Assets/Scripts/Editor/PackagesWindow.cs
+++ b/Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs
@@ -1,201 +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
-{
- ///
- ///
- ///
- 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 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 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
- }
- }
-}
+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
+{
+ ///
+ ///
+ ///
+ 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 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 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
+ }
+ }
+}
diff --git a/Assets/Scripts/Editor/PackagesWindow.cs.meta b/Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs.meta
similarity index 100%
rename from Assets/Scripts/Editor/PackagesWindow.cs.meta
rename to Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs.meta
diff --git a/Assets/Scripts/Editor/StageCameraEditor.cs b/Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs
similarity index 95%
rename from Assets/Scripts/Editor/StageCameraEditor.cs
rename to Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs
index 58dba48f..0e7bba90 100644
--- a/Assets/Scripts/Editor/StageCameraEditor.cs
+++ b/Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs
@@ -1,29 +1,29 @@
-using UnityEditor;
-using FairyGUI;
-
-namespace FairyGUIEditor
-{
- ///
- ///
- ///
- [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();
- }
- }
-}
+using UnityEditor;
+using FairyGUI;
+
+namespace FairyGUIEditor
+{
+ ///
+ ///
+ ///
+ [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();
+ }
+ }
+}
diff --git a/Assets/Scripts/Editor/StageCameraEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs.meta
similarity index 100%
rename from Assets/Scripts/Editor/StageCameraEditor.cs.meta
rename to Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs.meta
diff --git a/Assets/Scripts/Editor/UIConfigEditor.cs b/Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs
similarity index 97%
rename from Assets/Scripts/Editor/UIConfigEditor.cs
rename to Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs
index 279ddb48..dc6a828e 100644
--- a/Assets/Scripts/Editor/UIConfigEditor.cs
+++ b/Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs
@@ -1,226 +1,226 @@
-using UnityEngine;
-using UnityEditor;
-using FairyGUI;
-
-namespace FairyGUIEditor
-{
- ///
- ///
- ///
- [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();
- }
- }
-}
+using UnityEngine;
+using UnityEditor;
+using FairyGUI;
+
+namespace FairyGUIEditor
+{
+ ///
+ ///
+ ///
+ [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();
+ }
+ }
+}
diff --git a/Assets/Scripts/Editor/UIConfigEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs.meta
similarity index 100%
rename from Assets/Scripts/Editor/UIConfigEditor.cs.meta
rename to Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs.meta
diff --git a/Assets/Scripts/Editor/UIContentScalerEditor.cs b/Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs
similarity index 97%
rename from Assets/Scripts/Editor/UIContentScalerEditor.cs
rename to Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs
index c04277d0..f874c985 100644
--- a/Assets/Scripts/Editor/UIContentScalerEditor.cs
+++ b/Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs
@@ -1,64 +1,64 @@
-using UnityEditor;
-using FairyGUI;
-
-namespace FairyGUIEditor
-{
- ///
- ///
- ///
- [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();
- }
- }
-}
+using UnityEditor;
+using FairyGUI;
+
+namespace FairyGUIEditor
+{
+ ///
+ ///
+ ///
+ [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();
+ }
+ }
+}
diff --git a/Assets/Scripts/Editor/UIContentScalerEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs.meta
similarity index 100%
rename from Assets/Scripts/Editor/UIContentScalerEditor.cs.meta
rename to Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs.meta
diff --git a/Assets/Scripts/Editor/UIPainterEditor.cs b/Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs
similarity index 97%
rename from Assets/Scripts/Editor/UIPainterEditor.cs
rename to Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs
index 4de1c544..1f71214e 100644
--- a/Assets/Scripts/Editor/UIPainterEditor.cs
+++ b/Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs
@@ -1,96 +1,96 @@
-using UnityEngine;
-#if UNITY_5_3_OR_NEWER
-using UnityEditor.SceneManagement;
-#endif
-using UnityEditor;
-using FairyGUI;
-
-namespace FairyGUIEditor
-{
- ///
- ///
- ///
- [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(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(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);
- }
- }
- }
- }
-}
+using UnityEngine;
+#if UNITY_5_3_OR_NEWER
+using UnityEditor.SceneManagement;
+#endif
+using UnityEditor;
+using FairyGUI;
+
+namespace FairyGUIEditor
+{
+ ///
+ ///
+ ///
+ [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(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(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);
+ }
+ }
+ }
+ }
+}
diff --git a/Assets/Scripts/Editor/UIPainterEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs.meta
similarity index 100%
rename from Assets/Scripts/Editor/UIPainterEditor.cs.meta
rename to Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs.meta
diff --git a/Assets/Scripts/Editor/UIPanelEditor.cs b/Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs
similarity index 95%
rename from Assets/Scripts/Editor/UIPanelEditor.cs
rename to Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs
index f563f0a8..572b38ce 100644
--- a/Assets/Scripts/Editor/UIPanelEditor.cs
+++ b/Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs
@@ -1,163 +1,163 @@
-using UnityEngine;
-#if UNITY_5_3_OR_NEWER
-using UnityEditor.SceneManagement;
-#endif
-using UnityEditor;
-
-namespace FairyGUIEditor
-{
- ///
- ///
- ///
- [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(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(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
- Vector3 newPos = Handles.FreeMoveHandle(pos, Quaternion.identity, 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);
- }
- }
- }
-}
+using UnityEngine;
+#if UNITY_5_3_OR_NEWER
+using UnityEditor.SceneManagement;
+#endif
+using UnityEditor;
+
+namespace FairyGUIEditor
+{
+ ///
+ ///
+ ///
+ [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(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(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_638029390776941523 = Quaternion.identity; Vector3 newPos = Handles.FreeMoveHandle(pos,Quaternion.identity, 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);
+ }
+ }
+ }
+}
diff --git a/Assets/Scripts/Editor/UIPanelEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs.meta
similarity index 100%
rename from Assets/Scripts/Editor/UIPanelEditor.cs.meta
rename to Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs.meta
diff --git a/Assets/Plugins/FairyGUI/Resources.meta b/Assets/Plugins/FairyGUI/Resources.meta
new file mode 100644
index 00000000..6e4dc8c9
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Resources.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 66d9312cafc49bf4cad1ccdbb5b6668b
+folderAsset: yes
+timeCreated: 1446459912
+licenseType: Pro
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Plugins/FairyGUI/Resources/BillingMode.json b/Assets/Plugins/FairyGUI/Resources/BillingMode.json
new file mode 100644
index 00000000..6f4bfb71
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Resources/BillingMode.json
@@ -0,0 +1 @@
+{"androidStore":"GooglePlay"}
\ No newline at end of file
diff --git a/Assets/Plugins/FairyGUI/Resources/BillingMode.json.meta b/Assets/Plugins/FairyGUI/Resources/BillingMode.json.meta
new file mode 100644
index 00000000..4a7a6a29
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Resources/BillingMode.json.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 6c5d8b4692a92924cbfe1f97aa2e166b
+TextScriptImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Resources/Shaders.meta b/Assets/Plugins/FairyGUI/Resources/Shaders.meta
similarity index 100%
rename from Assets/Resources/Shaders.meta
rename to Assets/Plugins/FairyGUI/Resources/Shaders.meta
diff --git a/Assets/Resources/Shaders/AddOn.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/AddOn.meta
similarity index 100%
rename from Assets/Resources/Shaders/AddOn.meta
rename to Assets/Plugins/FairyGUI/Resources/Shaders/AddOn.meta
diff --git a/Assets/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader b/Assets/Plugins/FairyGUI/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader
similarity index 100%
rename from Assets/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader
rename to Assets/Plugins/FairyGUI/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader
diff --git a/Assets/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader.meta
similarity index 100%
rename from Assets/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader.meta
rename to Assets/Plugins/FairyGUI/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader.meta
diff --git a/Assets/Resources/Shaders/FairyGUI-BMFont.shader b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-BMFont.shader
similarity index 100%
rename from Assets/Resources/Shaders/FairyGUI-BMFont.shader
rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-BMFont.shader
diff --git a/Assets/Resources/Shaders/FairyGUI-BMFont.shader.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-BMFont.shader.meta
similarity index 100%
rename from Assets/Resources/Shaders/FairyGUI-BMFont.shader.meta
rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-BMFont.shader.meta
diff --git a/Assets/Resources/Shaders/FairyGUI-Image.shader b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Image.shader
similarity index 100%
rename from Assets/Resources/Shaders/FairyGUI-Image.shader
rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Image.shader
diff --git a/Assets/Resources/Shaders/FairyGUI-Image.shader.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Image.shader.meta
similarity index 100%
rename from Assets/Resources/Shaders/FairyGUI-Image.shader.meta
rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Image.shader.meta
diff --git a/Assets/Resources/Shaders/FairyGUI-Text.shader b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Text.shader
similarity index 100%
rename from Assets/Resources/Shaders/FairyGUI-Text.shader
rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Text.shader
diff --git a/Assets/Resources/Shaders/FairyGUI-Text.shader.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Text.shader.meta
similarity index 100%
rename from Assets/Resources/Shaders/FairyGUI-Text.shader.meta
rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Text.shader.meta
diff --git a/Assets/Plugins/FairyGUI/Runtime.meta b/Assets/Plugins/FairyGUI/Runtime.meta
new file mode 100644
index 00000000..7dbef7f5
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Runtime.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: b27cb0bddae3bd247b20a4aa2792119a
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Plugins/FairyGUI/Runtime/Empty.cs b/Assets/Plugins/FairyGUI/Runtime/Empty.cs
new file mode 100644
index 00000000..e69de29b
diff --git a/Assets/Plugins/FairyGUI/Runtime/Empty.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Empty.cs.meta
new file mode 100644
index 00000000..54d69221
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Runtime/Empty.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f6ce87023a0c1ad41801e927f247abba
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Extensions.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions.meta
similarity index 100%
rename from Assets/Extensions.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions.meta
diff --git a/Assets/Extensions/DragonBones.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones.meta
similarity index 100%
rename from Assets/Extensions/DragonBones.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones.meta
diff --git a/Assets/Extensions/DragonBones/DragonBonesLoader.cs b/Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones/DragonBonesLoader.cs
similarity index 100%
rename from Assets/Extensions/DragonBones/DragonBonesLoader.cs
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones/DragonBonesLoader.cs
diff --git a/Assets/Extensions/DragonBones/DragonBonesLoader.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones/DragonBonesLoader.cs.meta
similarity index 100%
rename from Assets/Extensions/DragonBones/DragonBonesLoader.cs.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones/DragonBonesLoader.cs.meta
diff --git a/Assets/Extensions/Spine.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/Spine.meta
similarity index 100%
rename from Assets/Extensions/Spine.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/Spine.meta
diff --git a/Assets/Extensions/Spine/SpineLoader.cs b/Assets/Plugins/FairyGUI/Runtime/Extensions/Spine/SpineLoader.cs
similarity index 100%
rename from Assets/Extensions/Spine/SpineLoader.cs
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/Spine/SpineLoader.cs
diff --git a/Assets/Extensions/Spine/SpineLoader.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/Spine/SpineLoader.cs.meta
similarity index 100%
rename from Assets/Extensions/Spine/SpineLoader.cs.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/Spine/SpineLoader.cs.meta
diff --git a/Assets/Extensions/TextMeshPro.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro.meta
similarity index 100%
rename from Assets/Extensions/TextMeshPro.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro.meta
diff --git a/Assets/Extensions/TextMeshPro/Shaders.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders.meta
similarity index 100%
rename from Assets/Extensions/TextMeshPro/Shaders.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders.meta
diff --git a/Assets/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader
old mode 100755
new mode 100644
similarity index 100%
rename from Assets/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader
diff --git a/Assets/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader.meta
similarity index 100%
rename from Assets/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader.meta
diff --git a/Assets/Extensions/TextMeshPro/TMPFont.cs b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPFont.cs
similarity index 100%
rename from Assets/Extensions/TextMeshPro/TMPFont.cs
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPFont.cs
diff --git a/Assets/Extensions/TextMeshPro/TMPFont.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPFont.cs.meta
similarity index 100%
rename from Assets/Extensions/TextMeshPro/TMPFont.cs.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPFont.cs.meta
diff --git a/Assets/Extensions/TextMeshPro/TMPTextFormat.cs b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPTextFormat.cs
similarity index 100%
rename from Assets/Extensions/TextMeshPro/TMPTextFormat.cs
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPTextFormat.cs
diff --git a/Assets/Extensions/TextMeshPro/TMPTextFormat.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPTextFormat.cs.meta
similarity index 100%
rename from Assets/Extensions/TextMeshPro/TMPTextFormat.cs.meta
rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPTextFormat.cs.meta
diff --git a/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef b/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef
new file mode 100644
index 00000000..4c3114a7
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef
@@ -0,0 +1,3 @@
+{
+ "name": "FairyGUI"
+}
diff --git a/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef.meta b/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef.meta
new file mode 100644
index 00000000..b9ec0a58
--- /dev/null
+++ b/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: b12c828e10494534a9050867cfc5ed0c
+AssemblyDefinitionImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts.meta
similarity index 100%
rename from Assets/Scripts.meta
rename to Assets/Plugins/FairyGUI/Runtime/Scripts.meta
diff --git a/Assets/Scripts/Core.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core.meta
similarity index 100%
rename from Assets/Scripts/Core.meta
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core.meta
diff --git a/Assets/Scripts/Core/BlendMode.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs
similarity index 97%
rename from Assets/Scripts/Core/BlendMode.cs
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs
index 9bc414ee..dd725ea5 100644
--- a/Assets/Scripts/Core/BlendMode.cs
+++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs
@@ -1,110 +1,110 @@
-using UnityEngine;
-using NativeBlendMode = UnityEngine.Rendering.BlendMode;
-
-namespace FairyGUI
-{
- /*关于BlendMode.Off, 这种模式相当于Blend Off指令的效果。当然,在着色器里使用Blend Off指令可以获得更高的效率,
- 但因为Image着色器本身就有多个关键字,复制一个这样的着色器代价太大,所有为了节省Shader数量便增加了这样一种模式,也是可以接受的。
- */
-
- ///
- ///
- ///
- public enum BlendMode
- {
- Normal,
- None,
- Add,
- Multiply,
- Screen,
- Erase,
- Mask,
- Below,
- Off,
- One_OneMinusSrcAlpha,
- Custom1,
- Custom2,
- Custom3
- }
-
- ///
- ///
- ///
- 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)
- };
-
- ///
- ///
- ///
- ///
- ///
- 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);
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public static void Override(BlendMode blendMode, NativeBlendMode srcFactor, NativeBlendMode dstFactor)
- {
- BlendFactor bf = Factors[(int)blendMode];
- bf.srcFactor = srcFactor;
- bf.dstFactor = dstFactor;
- }
- }
-}
+using UnityEngine;
+using NativeBlendMode = UnityEngine.Rendering.BlendMode;
+
+namespace FairyGUI
+{
+ /*关于BlendMode.Off, 这种模式相当于Blend Off指令的效果。当然,在着色器里使用Blend Off指令可以获得更高的效率,
+ 但因为Image着色器本身就有多个关键字,复制一个这样的着色器代价太大,所有为了节省Shader数量便增加了这样一种模式,也是可以接受的。
+ */
+
+ ///
+ ///
+ ///
+ public enum BlendMode
+ {
+ Normal,
+ None,
+ Add,
+ Multiply,
+ Screen,
+ Erase,
+ Mask,
+ Below,
+ Off,
+ One_OneMinusSrcAlpha,
+ Custom1,
+ Custom2,
+ Custom3
+ }
+
+ ///
+ ///
+ ///
+ 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)
+ };
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static void Override(BlendMode blendMode, NativeBlendMode srcFactor, NativeBlendMode dstFactor)
+ {
+ BlendFactor bf = Factors[(int)blendMode];
+ bf.srcFactor = srcFactor;
+ bf.dstFactor = dstFactor;
+ }
+ }
+}
diff --git a/Assets/Scripts/Core/BlendMode.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs.meta
similarity index 100%
rename from Assets/Scripts/Core/BlendMode.cs.meta
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs.meta
diff --git a/Assets/Scripts/Core/CaptureCamera.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs
similarity index 97%
rename from Assets/Scripts/Core/CaptureCamera.cs
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs
index 8a91f827..cd550477 100644
--- a/Assets/Scripts/Core/CaptureCamera.cs
+++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs
@@ -1,202 +1,202 @@
-using UnityEngine;
-
-namespace FairyGUI
-{
- ///
- ///
- ///
- public class CaptureCamera : MonoBehaviour
- {
- ///
- ///
- ///
- [System.NonSerialized]
- public Transform cachedTransform;
- ///
- ///
- ///
- [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();
- cachedTransform = this.gameObject.transform;
-
- if (this.gameObject.name == Name)
- _main = this;
- }
-
- ///
- ///
- ///
- public static void CheckMain()
- {
- if (_main != null && _main.cachedCamera != null)
- return;
-
- GameObject go = GameObject.Find(Name);
- if (go != null)
- {
- _main = go.GetComponent();
- return;
- }
-
- GameObject cameraObject = new GameObject(Name);
- Camera camera = cameraObject.AddComponent();
- 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();
- }
-
- ///
- ///
- ///
- 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;
- }
- }
-
- ///
- ///
- ///
- 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;
- }
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- 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;
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- 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);
- }
- }
-}
+using UnityEngine;
+
+namespace FairyGUI
+{
+ ///
+ ///
+ ///
+ public class CaptureCamera : MonoBehaviour
+ {
+ ///
+ ///
+ ///
+ [System.NonSerialized]
+ public Transform cachedTransform;
+ ///
+ ///
+ ///
+ [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();
+ cachedTransform = this.gameObject.transform;
+
+ if (this.gameObject.name == Name)
+ _main = this;
+ }
+
+ ///
+ ///
+ ///
+ public static void CheckMain()
+ {
+ if (_main != null && _main.cachedCamera != null)
+ return;
+
+ GameObject go = GameObject.Find(Name);
+ if (go != null)
+ {
+ _main = go.GetComponent();
+ return;
+ }
+
+ GameObject cameraObject = new GameObject(Name);
+ Camera camera = cameraObject.AddComponent();
+ 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();
+ }
+
+ ///
+ ///
+ ///
+ 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;
+ }
+ }
+
+ ///
+ ///
+ ///
+ 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;
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
+}
diff --git a/Assets/Scripts/Core/CaptureCamera.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs.meta
similarity index 100%
rename from Assets/Scripts/Core/CaptureCamera.cs.meta
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs.meta
diff --git a/Assets/Scripts/Core/Container.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs
similarity index 96%
rename from Assets/Scripts/Core/Container.cs
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs
index 15417c15..61d6f4c1 100644
--- a/Assets/Scripts/Core/Container.cs
+++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs
@@ -1,1124 +1,1124 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using UnityEngine;
-
-namespace FairyGUI
-{
- ///
- ///
- ///
- public class Container : DisplayObject
- {
- ///
- ///
- ///
- public RenderMode renderMode;
-
- ///
- ///
- ///
- public Camera renderCamera;
-
- ///
- ///
- ///
- public bool opaque;
-
- ///
- ///
- ///
- public Vector4? clipSoftness;
-
- ///
- ///
- ///
- public IHitTest hitArea;
-
- ///
- ///
- ///
- public bool touchChildren;
-
- ///
- ///
- ///
- public event Action onUpdate;
-
- ///
- ///
- ///
- public bool reversedMask;
-
- List _children;
- DisplayObject _mask;
- Rect? _clipRect;
- List _descendants;
-
- internal int _panelOrder;
- internal DisplayObject _lastFocus;
-
- ///
- ///
- ///
- public Container()
- : base()
- {
- CreateGameObject("Container");
- Init();
- }
-
- ///
- ///
- ///
- ///
- public Container(string gameObjectName)
- : base()
- {
- CreateGameObject(gameObjectName);
- Init();
- }
-
- ///
- ///
- ///
- ///
- public Container(GameObject attachTarget)
- : base()
- {
- SetGameObject(attachTarget);
- Init();
- }
-
- void Init()
- {
- _children = new List();
- touchChildren = true;
- }
-
- ///
- ///
- ///
- public int numChildren
- {
- get { return _children.Count; }
- }
-
- ///
- ///
- ///
- ///
- ///
- public DisplayObject AddChild(DisplayObject child)
- {
- AddChildAt(child, _children.Count);
- return child;
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public DisplayObject AddChildAt(DisplayObject child, int index)
- {
- int count = _children.Count;
- if (index >= 0 && index <= count)
- {
- if (child.parent == this)
- {
- SetChildIndex(child, index);
- }
- else
- {
- child.RemoveFromParent();
- if (index == count)
- _children.Add(child);
- else
- _children.Insert(index, child);
- child.InternalSetParent(this);
-
- if (stage != null)
- {
- if (child is Container)
- child.BroadcastEvent("onAddedToStage", null);
- else
- child.DispatchEvent("onAddedToStage", null);
- }
-
- InvalidateBatchingState(true);
- }
- return child;
- }
- else
- {
- throw new Exception("Invalid child index");
- }
- }
-
- ///
- ///
- ///
- ///
- ///
- public bool Contains(DisplayObject child)
- {
- return _children.Contains(child);
- }
-
- ///
- ///
- ///
- ///
- ///
- public DisplayObject GetChildAt(int index)
- {
- return _children[index];
- }
-
- ///
- ///
- ///
- ///
- ///
- public DisplayObject GetChild(string name)
- {
- int cnt = _children.Count;
- for (int i = 0; i < cnt; ++i)
- {
- if (_children[i].name == name)
- return _children[i];
- }
-
- return null;
- }
-
- ///
- ///
- ///
- ///
- public DisplayObject[] GetChildren()
- {
- return _children.ToArray();
- }
-
- ///
- ///
- ///
- ///
- ///
- public int GetChildIndex(DisplayObject child)
- {
- return _children.IndexOf(child);
- }
-
- ///
- ///
- ///
- ///
- ///
- public DisplayObject RemoveChild(DisplayObject child)
- {
- return RemoveChild(child, false);
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public DisplayObject RemoveChild(DisplayObject child, bool dispose)
- {
- if (child.parent != this)
- throw new Exception("obj is not a child");
-
- int i = _children.IndexOf(child);
- if (i >= 0)
- return RemoveChildAt(i, dispose);
- else
- return null;
- }
-
- ///
- ///
- ///
- ///
- ///
- public DisplayObject RemoveChildAt(int index)
- {
- return RemoveChildAt(index, false);
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public DisplayObject RemoveChildAt(int index, bool dispose)
- {
- if (index >= 0 && index < _children.Count)
- {
- DisplayObject child = _children[index];
-
- if (stage != null && (child._flags & Flags.Disposed) == 0)
- {
- if (child is Container)
- {
- child.BroadcastEvent("onRemovedFromStage", null);
- if (child == Stage.inst.focus || ((Container)child).IsAncestorOf(Stage.inst.focus))
- Stage.inst._OnFocusRemoving(this);
- }
- else
- {
- child.DispatchEvent("onRemovedFromStage", null);
- if (child == Stage.inst.focus)
- Stage.inst._OnFocusRemoving(this);
- }
- }
- _children.Remove(child);
- InvalidateBatchingState(true);
- if (!dispose)
- child.InternalSetParent(null);
- else
- child.Dispose();
-
- return child;
- }
- else
- throw new Exception("Invalid child index");
- }
-
- ///
- ///
- ///
- public void RemoveChildren()
- {
- RemoveChildren(0, int.MaxValue, false);
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public void RemoveChildren(int beginIndex, int endIndex, bool dispose)
- {
- if (endIndex < 0 || endIndex >= numChildren)
- endIndex = numChildren - 1;
-
- for (int i = beginIndex; i <= endIndex; ++i)
- RemoveChildAt(beginIndex, dispose);
- }
-
- ///
- ///
- ///
- ///
- ///
- public void SetChildIndex(DisplayObject child, int index)
- {
- int oldIndex = _children.IndexOf(child);
- if (oldIndex == index) return;
- if (oldIndex == -1) throw new ArgumentException("Not a child of this container");
- _children.RemoveAt(oldIndex);
- if (index >= _children.Count)
- _children.Add(child);
- else
- _children.Insert(index, child);
- InvalidateBatchingState(true);
- }
-
- ///
- ///
- ///
- ///
- ///
- public void SwapChildren(DisplayObject child1, DisplayObject child2)
- {
- int index1 = _children.IndexOf(child1);
- int index2 = _children.IndexOf(child2);
- if (index1 == -1 || index2 == -1)
- throw new Exception("Not a child of this container");
- SwapChildrenAt(index1, index2);
- }
-
- ///
- ///
- ///
- ///
- ///
- public void SwapChildrenAt(int index1, int index2)
- {
- DisplayObject obj1 = _children[index1];
- DisplayObject obj2 = _children[index2];
- _children[index1] = obj2;
- _children[index2] = obj1;
- InvalidateBatchingState(true);
- }
-
- ///
- ///
- ///
- ///
- ///
- public void ChangeChildrenOrder(IList indice, IList objs)
- {
- int cnt = objs.Count;
- for (int i = 0; i < cnt; i++)
- {
- DisplayObject obj = objs[i];
- if (obj.parent != this)
- throw new Exception("Not a child of this container");
-
- _children[indice[i]] = obj;
- }
- InvalidateBatchingState(true);
- }
-
- ///
- ///
- ///
- ///
- public IEnumerator GetDescendants(bool backward)
- {
- return new DescendantsEnumerator(this, backward);
- }
-
- ///
- ///
- ///
- public Rect? clipRect
- {
- get { return _clipRect; }
- set
- {
- if (_clipRect != value)
- {
- _clipRect = value;
- UpdateBatchingFlags();
- }
- }
- }
-
- ///
- ///
- ///
- public DisplayObject mask
- {
- get { return _mask; }
- set
- {
- if (_mask != value)
- {
- _mask = value;
- UpdateBatchingFlags();
- }
- }
- }
-
- ///
- ///
- ///
- public void CreateGraphics()
- {
- if (graphics == null)
- {
- graphics = new NGraphics(this.gameObject);
- graphics.texture = NTexture.Empty;
- }
- }
-
- public override Rect GetBounds(DisplayObject targetSpace)
- {
- if (_clipRect != null)
- return TransformRect((Rect)_clipRect, targetSpace);
-
- int count = _children.Count;
-
- Rect rect;
- if (count == 0)
- {
- Vector2 v = TransformPoint(Vector2.zero, targetSpace);
- rect = Rect.MinMaxRect(v.x, v.y, 0, 0);
- }
- else if (count == 1)
- {
- rect = _children[0].GetBounds(targetSpace);
- }
- else
- {
- float minX = float.MaxValue, maxX = float.MinValue;
- float minY = float.MaxValue, maxY = float.MinValue;
-
- for (int i = 0; i < count; ++i)
- {
- rect = _children[i].GetBounds(targetSpace);
- minX = minX < rect.xMin ? minX : rect.xMin;
- maxX = maxX > rect.xMax ? maxX : rect.xMax;
- minY = minY < rect.yMin ? minY : rect.yMin;
- maxY = maxY > rect.yMax ? maxY : rect.yMax;
- }
-
- rect = Rect.MinMaxRect(minX, minY, maxX, maxY);
- }
-
- return rect;
- }
-
- ///
- ///
- ///
- ///
- public Camera GetRenderCamera()
- {
- if (renderMode == RenderMode.ScreenSpaceOverlay)
- return StageCamera.main;
- else
- {
- Camera cam = this.renderCamera;
- if (cam == null)
- {
- if (HitTestContext.cachedMainCamera != null)
- cam = HitTestContext.cachedMainCamera;
- else
- {
- cam = Camera.main;
- if (cam == null)
- cam = StageCamera.main;
- }
- }
- return cam;
- }
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public DisplayObject HitTest(Vector2 stagePoint, bool forTouch)
- {
- if (StageCamera.main == null)
- {
- if (this is Stage)
- return this;
- else
- return null;
- }
-
- HitTestContext.screenPoint = new Vector3(stagePoint.x, Screen.height - stagePoint.y, 0);
- if (Display.displays.Length > 1)
- {
- Vector3 p = Display.RelativeMouseAt(HitTestContext.screenPoint);
- if (p != Vector3.zero)
- HitTestContext.screenPoint = p;
- }
- HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(HitTestContext.screenPoint);
- HitTestContext.direction = Vector3.back;
- HitTestContext.forTouch = forTouch;
- HitTestContext.camera = StageCamera.main;
-
- DisplayObject ret = HitTest();
- if (ret != null)
- return ret;
- else if (this is Stage)
- return this;
- else
- return null;
- }
-
- override protected DisplayObject HitTest()
- {
- if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy)
- return null;
-
- if (this.cachedTransform.localScale.x == 0 || this.cachedTransform.localScale.y == 0)
- return null;
-
- Camera savedCamera = HitTestContext.camera;
- Vector3 savedWorldPoint = HitTestContext.worldPoint;
- Vector3 savedDirection = HitTestContext.direction;
- DisplayObject target;
-
- if (renderMode != RenderMode.ScreenSpaceOverlay || (_flags & Flags.UserGameObject) != 0)
- {
- Camera cam = GetRenderCamera();
- if (cam.targetDisplay != HitTestContext.screenPoint.z)
- return null;
-
- HitTestContext.camera = cam;
- if (renderMode == RenderMode.WorldSpace)
- {
- Vector3 screenPoint = HitTestContext.camera.WorldToScreenPoint(this.cachedTransform.position); //only for query z value
- screenPoint.x = HitTestContext.screenPoint.x;
- screenPoint.y = HitTestContext.screenPoint.y;
-
- //获得本地z轴在世界坐标的方向
- HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(screenPoint);
- Ray ray = HitTestContext.camera.ScreenPointToRay(screenPoint);
- HitTestContext.direction = Vector3.zero - ray.direction;
- }
- else if (renderMode == RenderMode.ScreenSpaceCamera)
- {
- HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(HitTestContext.screenPoint);
- }
- }
- else
- {
- if (HitTestContext.camera.targetDisplay != HitTestContext.screenPoint.z && !(this is Stage))
- return null;
- }
-
- target = HitTest_Container();
-
- HitTestContext.camera = savedCamera;
- HitTestContext.worldPoint = savedWorldPoint;
- HitTestContext.direction = savedDirection;
-
- return target;
- }
-
- DisplayObject HitTest_Container()
- {
- Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction);
- if (_vertexMatrix != null)
- HitTestContext.worldPoint = this.cachedTransform.TransformPoint(new Vector2(localPoint.x, -localPoint.y));
-
- if (hitArea != null)
- {
- if (!hitArea.HitTest(_contentRect, localPoint))
- return null;
-
- if (hitArea is MeshColliderHitTest)
- localPoint = ((MeshColliderHitTest)hitArea).lastHit;
- }
- else
- {
- if (_clipRect != null && !((Rect)_clipRect).Contains(localPoint))
- return null;
- }
-
- if (_mask != null)
- {
- DisplayObject tmp = _mask.InternalHitTestMask();
- if (!reversedMask && tmp == null || reversedMask && tmp != null)
- return null;
- }
-
- DisplayObject target = null;
- if (touchChildren)
- {
- int count = _children.Count;
- for (int i = count - 1; i >= 0; --i) // front to back!
- {
- DisplayObject child = _children[i];
- if ((child._flags & Flags.GameObjectDisposed) != 0)
- {
- child.DisplayDisposedWarning();
- continue;
- }
-
- if (child == _mask || (child._flags & Flags.TouchDisabled) != 0)
- continue;
-
- target = child.InternalHitTest();
- if (target != null)
- break;
- }
- }
-
- if (target == null && opaque && (hitArea != null || _contentRect.Contains(localPoint)))
- target = this;
-
- return target;
- }
-
- ///
- ///
- ///
- ///
- ///
- public bool IsAncestorOf(DisplayObject obj)
- {
- if (obj == null)
- return false;
-
- Container p = obj.parent;
- while (p != null)
- {
- if (p == this)
- return true;
-
- p = p.parent;
- }
- return false;
- }
-
- ///
- ///
- ///
- public bool fairyBatching
- {
- get { return (_flags & Flags.FairyBatching) != 0; }
- set
- {
- bool oldValue = (_flags & Flags.FairyBatching) != 0;
- if (oldValue != value)
- {
- if (value)
- _flags |= Flags.FairyBatching;
- else
- _flags &= ~Flags.FairyBatching;
- UpdateBatchingFlags();
- }
- }
- }
-
- internal void UpdateBatchingFlags()
- {
- bool oldValue = (_flags & Flags.BatchingRoot) != 0;
- bool newValue = (_flags & Flags.FairyBatching) != 0 || _clipRect != null || _mask != null || _paintingMode > 0;
- if (newValue)
- _flags |= Flags.BatchingRoot;
- else
- _flags &= ~Flags.BatchingRoot;
- if (oldValue != newValue)
- {
- if (newValue)
- _flags |= Flags.BatchingRequested;
- else if (_descendants != null)
- _descendants.Clear();
-
- InvalidateBatchingState();
- }
- }
-
- ///
- ///
- ///
- ///
- public void InvalidateBatchingState(bool childrenChanged)
- {
- if (childrenChanged && (_flags & Flags.BatchingRoot) != 0)
- _flags |= Flags.BatchingRequested;
- else
- {
- Container p = this.parent;
- while (p != null)
- {
- if ((p._flags & Flags.BatchingRoot) != 0)
- {
- p._flags |= Flags.BatchingRequested;
- break;
- }
-
- p = p.parent;
- }
- }
- }
-
- ///
- ///
- ///
- ///
- public void SetChildrenLayer(int value)
- {
- int cnt = _children.Count;
- for (int i = 0; i < cnt; i++)
- {
- DisplayObject child = _children[i];
- child._SetLayerDirect(value);
- if ((child is Container) && child._paintingMode == 0)
- ((Container)child).SetChildrenLayer(value);
- }
- }
-
- override public void Update(UpdateContext context)
- {
- if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy)
- return;
-
- base.Update(context);
-
- if (_paintingMode != 0)
- {
- if ((_flags & Flags.CacheAsBitmap) != 0 && _paintingInfo.flag == 2)
- {
- if (onUpdate != null)
- onUpdate();
- return;
- }
-
- context.EnterPaintingMode();
- }
-
- if (_mask != null)
- {
- context.EnterClipping(this.id, reversedMask);
- if (_mask.graphics != null)
- _mask.graphics._PreUpdateMask(context, _mask.id);
- }
- else if (_clipRect != null)
- context.EnterClipping(this.id, this.TransformRect((Rect)_clipRect, null), clipSoftness);
-
- float savedAlpha = context.alpha;
- context.alpha *= this.alpha;
- bool savedGrayed = context.grayed;
- context.grayed = context.grayed || this.grayed;
-
- if ((_flags & Flags.FairyBatching) != 0)
- context.batchingDepth++;
-
- if (context.batchingDepth > 0)
- {
- int cnt = _children.Count;
- for (int i = 0; i < cnt; i++)
- {
- DisplayObject child = _children[i];
- if ((child._flags & Flags.GameObjectDisposed) != 0)
- {
- child.DisplayDisposedWarning();
- continue;
- }
-
- if (child.visible)
- child.Update(context);
- }
- }
- else
- {
- if (_mask != null)
- _mask.renderingOrder = context.renderingOrder++;
-
- int cnt = _children.Count;
- for (int i = 0; i < cnt; i++)
- {
- DisplayObject child = _children[i];
- if ((child._flags & Flags.GameObjectDisposed) != 0)
- {
- child.DisplayDisposedWarning();
- continue;
- }
-
- if (child.visible)
- {
- if (!(child.graphics != null && child.graphics._maskFlag == 1)) //if not a mask
- child.renderingOrder = context.renderingOrder++;
-
- child.Update(context);
- }
- }
-
- if (_mask != null)
- {
- if (_mask.graphics != null)
- _mask.graphics._SetStencilEraserOrder(context.renderingOrder++);
- }
- }
-
- if ((_flags & Flags.FairyBatching) != 0)
- {
- if (context.batchingDepth == 1)
- SetRenderingOrder(context);
- context.batchingDepth--;
- }
-
- context.alpha = savedAlpha;
- context.grayed = savedGrayed;
-
- if (_clipRect != null || _mask != null)
- context.LeaveClipping();
-
- if (_paintingMode != 0)
- {
- context.LeavePaintingMode();
- UpdateContext.OnEnd += _paintingInfo.captureDelegate;
- }
-
- if (onUpdate != null)
- onUpdate();
- }
-
- private void SetRenderingOrder(UpdateContext context)
- {
- if ((_flags & Flags.BatchingRequested) != 0)
- DoFairyBatching();
-
- if (_mask != null)
- _mask.renderingOrder = context.renderingOrder++;
-
- int cnt = _descendants.Count;
- for (int i = 0; i < cnt; i++)
- {
- DisplayObject child = _descendants[i];
- if (!(child.graphics != null && child.graphics._maskFlag == 1))
- child.renderingOrder = context.renderingOrder++;
-
- if ((child._flags & Flags.BatchingRoot) != 0)
- ((Container)child).SetRenderingOrder(context);
- }
-
- if (_mask != null)
- {
- if (_mask.graphics != null)
- _mask.graphics._SetStencilEraserOrder(context.renderingOrder++);
- }
- }
-
- private void DoFairyBatching()
- {
- _flags &= ~Flags.BatchingRequested;
-
- if (_descendants == null)
- _descendants = new List();
- else
- _descendants.Clear();
- CollectChildren(this, false);
-
- int cnt = _descendants.Count;
-
- int i, j, k, m;
- object curMat, testMat, lastMat;
- DisplayObject current, test;
- float[] bound;
- for (i = 0; i < cnt; i++)
- {
- current = _descendants[i];
- bound = current._batchingBounds;
- curMat = current.material;
- if (curMat == null || (current._flags & Flags.SkipBatching) != 0)
- continue;
-
- k = -1;
- lastMat = null;
- m = i;
- for (j = i - 1; j >= 0; j--)
- {
- test = _descendants[j];
- if ((test._flags & Flags.SkipBatching) != 0)
- break;
-
- testMat = test.material;
- if (testMat != null)
- {
- if (lastMat != testMat)
- {
- lastMat = testMat;
- m = j + 1;
- }
-
- if (curMat == testMat)
- k = m;
- }
-
- if ((bound[0] > test._batchingBounds[0] ? bound[0] : test._batchingBounds[0])
- <= (bound[2] < test._batchingBounds[2] ? bound[2] : test._batchingBounds[2])
- && (bound[1] > test._batchingBounds[1] ? bound[1] : test._batchingBounds[1])
- <= (bound[3] < test._batchingBounds[3] ? bound[3] : test._batchingBounds[3]))
- {
- if (k == -1)
- k = m;
- break;
- }
- }
- if (k != -1 && i != k)
- {
- _descendants.RemoveAt(i);
- _descendants.Insert(k, current);
- }
- }
-
- //Debug.Log("DoFairyBatching " + cnt + "," + this.cachedTransform.GetInstanceID());
- }
-
- private void CollectChildren(Container initiator, bool outlineChanged)
- {
- int count = _children.Count;
- for (int i = 0; i < count; i++)
- {
- DisplayObject child = _children[i];
- if (!child.visible)
- continue;
-
- if (child._batchingBounds == null)
- child._batchingBounds = new float[4];
-
- if (child is Container)
- {
- Container container = (Container)child;
- if ((container._flags & Flags.BatchingRoot) != 0)
- {
- initiator._descendants.Add(container);
- if (outlineChanged || (container._flags & Flags.OutlineChanged) != 0)
- {
- Rect rect = container.GetBounds(initiator);
- container._batchingBounds[0] = rect.xMin;
- container._batchingBounds[1] = rect.yMin;
- container._batchingBounds[2] = rect.xMax;
- container._batchingBounds[3] = rect.yMax;
- }
- if ((container._flags & Flags.BatchingRequested) != 0)
- container.DoFairyBatching();
- }
- else
- container.CollectChildren(initiator, outlineChanged || (container._flags & Flags.OutlineChanged) != 0);
- }
- else if (child != initiator._mask)
- {
- if (outlineChanged || (child._flags & Flags.OutlineChanged) != 0)
- {
- Rect rect = child.GetBounds(initiator);
- child._batchingBounds[0] = rect.xMin;
- child._batchingBounds[1] = rect.yMin;
- child._batchingBounds[2] = rect.xMax;
- child._batchingBounds[3] = rect.yMax;
- }
- initiator._descendants.Add(child);
- }
-
- child._flags &= ~Flags.OutlineChanged;
- }
- }
-
- public override void Dispose()
- {
- if ((_flags & Flags.Disposed) != 0)
- return;
-
- base.Dispose(); //Destroy GameObject tree first, avoid destroying each seperately;
-
- int numChildren = _children.Count;
- for (int i = numChildren - 1; i >= 0; --i)
- {
- DisplayObject obj = _children[i];
- obj.InternalSetParent(null); //Avoid RemoveParent call
- obj.Dispose();
- }
- }
-
- ///
- /// If true, when the container is focused, tab navigation is lock inside it.
- ///
- public bool tabStopChildren
- {
- get { return (_flags & Flags.TabStopChildren) != 0; }
- set
- {
- if (value)
- _flags |= Flags.TabStopChildren;
- else
- _flags &= ~Flags.TabStopChildren;
- }
- }
-
- struct DescendantsEnumerator : IEnumerator
- {
- Container _root;
- Container _com;
- DisplayObject _current;
- int _index;
- bool _forward;
-
- public DescendantsEnumerator(Container root, bool backward)
- {
- _root = root;
- _com = _root;
- _current = null;
- _forward = !backward;
- if (_forward)
- _index = 0;
- else
- _index = _com._children.Count - 1;
- }
-
- public DisplayObject Current
- {
- get { return _current; }
- }
-
- object IEnumerator.Current
- {
- get { return _current; }
- }
-
- public bool MoveNext()
- {
- if (_forward)
- {
- if (_index >= _com._children.Count)
- {
- if (_com == _root)
- {
- _current = null;
- return false;
- }
-
- _current = _com;
- _com = _com.parent;
- _index = _com.GetChildIndex(_current) + 1;
- return true;
- }
- else
- {
- DisplayObject obj = _com._children[_index];
- if (obj is Container)
- {
- _com = (Container)obj;
- _index = 0;
- return MoveNext();
- }
- _index++;
- _current = obj;
- return true;
- }
- }
- else
- {
- if (_index < 0)
- {
- if (_com == _root)
- {
- _current = null;
- return false;
- }
-
- _current = _com;
- _com = _com.parent;
- _index = _com.GetChildIndex(_current) - 1;
- return true;
- }
- else
- {
- DisplayObject obj = _com._children[_index];
- if (obj is Container)
- {
- _com = (Container)obj;
- _index = _com._children.Count - 1;
- return MoveNext();
- }
- _index--;
- _current = obj;
- return true;
- }
- }
- }
-
- public void Reset()
- {
- _com = _root;
- _current = null;
- _index = 0;
- }
-
- public void Dispose()
- {
- }
- }
- }
-}
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using UnityEngine;
+
+namespace FairyGUI
+{
+ ///
+ ///
+ ///
+ public class Container : DisplayObject
+ {
+ ///
+ ///
+ ///
+ public RenderMode renderMode;
+
+ ///
+ ///
+ ///
+ public Camera renderCamera;
+
+ ///
+ ///
+ ///
+ public bool opaque;
+
+ ///
+ ///
+ ///
+ public Vector4? clipSoftness;
+
+ ///
+ ///
+ ///
+ public IHitTest hitArea;
+
+ ///
+ ///
+ ///
+ public bool touchChildren;
+
+ ///
+ ///
+ ///
+ public event Action onUpdate;
+
+ ///
+ ///
+ ///
+ public bool reversedMask;
+
+ List _children;
+ DisplayObject _mask;
+ Rect? _clipRect;
+ List _descendants;
+
+ internal int _panelOrder;
+ internal DisplayObject _lastFocus;
+
+ ///
+ ///
+ ///
+ public Container()
+ : base()
+ {
+ CreateGameObject("Container");
+ Init();
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public Container(string gameObjectName)
+ : base()
+ {
+ CreateGameObject(gameObjectName);
+ Init();
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public Container(GameObject attachTarget)
+ : base()
+ {
+ SetGameObject(attachTarget);
+ Init();
+ }
+
+ void Init()
+ {
+ _children = new List();
+ touchChildren = true;
+ }
+
+ ///
+ ///
+ ///
+ public int numChildren
+ {
+ get { return _children.Count; }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject AddChild(DisplayObject child)
+ {
+ AddChildAt(child, _children.Count);
+ return child;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject AddChildAt(DisplayObject child, int index)
+ {
+ int count = _children.Count;
+ if (index >= 0 && index <= count)
+ {
+ if (child.parent == this)
+ {
+ SetChildIndex(child, index);
+ }
+ else
+ {
+ child.RemoveFromParent();
+ if (index == count)
+ _children.Add(child);
+ else
+ _children.Insert(index, child);
+ child.InternalSetParent(this);
+
+ if (stage != null)
+ {
+ if (child is Container)
+ child.BroadcastEvent("onAddedToStage", null);
+ else
+ child.DispatchEvent("onAddedToStage", null);
+ }
+
+ InvalidateBatchingState(true);
+ }
+ return child;
+ }
+ else
+ {
+ throw new Exception("Invalid child index");
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public bool Contains(DisplayObject child)
+ {
+ return _children.Contains(child);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject GetChildAt(int index)
+ {
+ return _children[index];
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject GetChild(string name)
+ {
+ int cnt = _children.Count;
+ for (int i = 0; i < cnt; ++i)
+ {
+ if (_children[i].name == name)
+ return _children[i];
+ }
+
+ return null;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject[] GetChildren()
+ {
+ return _children.ToArray();
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public int GetChildIndex(DisplayObject child)
+ {
+ return _children.IndexOf(child);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject RemoveChild(DisplayObject child)
+ {
+ return RemoveChild(child, false);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject RemoveChild(DisplayObject child, bool dispose)
+ {
+ if (child.parent != this)
+ throw new Exception("obj is not a child");
+
+ int i = _children.IndexOf(child);
+ if (i >= 0)
+ return RemoveChildAt(i, dispose);
+ else
+ return null;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject RemoveChildAt(int index)
+ {
+ return RemoveChildAt(index, false);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject RemoveChildAt(int index, bool dispose)
+ {
+ if (index >= 0 && index < _children.Count)
+ {
+ DisplayObject child = _children[index];
+
+ if (stage != null && (child._flags & Flags.Disposed) == 0)
+ {
+ if (child is Container)
+ {
+ child.BroadcastEvent("onRemovedFromStage", null);
+ if (child == Stage.inst.focus || ((Container)child).IsAncestorOf(Stage.inst.focus))
+ Stage.inst._OnFocusRemoving(this);
+ }
+ else
+ {
+ child.DispatchEvent("onRemovedFromStage", null);
+ if (child == Stage.inst.focus)
+ Stage.inst._OnFocusRemoving(this);
+ }
+ }
+ _children.Remove(child);
+ InvalidateBatchingState(true);
+ if (!dispose)
+ child.InternalSetParent(null);
+ else
+ child.Dispose();
+
+ return child;
+ }
+ else
+ throw new Exception("Invalid child index");
+ }
+
+ ///
+ ///
+ ///
+ public void RemoveChildren()
+ {
+ RemoveChildren(0, int.MaxValue, false);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void RemoveChildren(int beginIndex, int endIndex, bool dispose)
+ {
+ if (endIndex < 0 || endIndex >= numChildren)
+ endIndex = numChildren - 1;
+
+ for (int i = beginIndex; i <= endIndex; ++i)
+ RemoveChildAt(beginIndex, dispose);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void SetChildIndex(DisplayObject child, int index)
+ {
+ int oldIndex = _children.IndexOf(child);
+ if (oldIndex == index) return;
+ if (oldIndex == -1) throw new ArgumentException("Not a child of this container");
+ _children.RemoveAt(oldIndex);
+ if (index >= _children.Count)
+ _children.Add(child);
+ else
+ _children.Insert(index, child);
+ InvalidateBatchingState(true);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void SwapChildren(DisplayObject child1, DisplayObject child2)
+ {
+ int index1 = _children.IndexOf(child1);
+ int index2 = _children.IndexOf(child2);
+ if (index1 == -1 || index2 == -1)
+ throw new Exception("Not a child of this container");
+ SwapChildrenAt(index1, index2);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void SwapChildrenAt(int index1, int index2)
+ {
+ DisplayObject obj1 = _children[index1];
+ DisplayObject obj2 = _children[index2];
+ _children[index1] = obj2;
+ _children[index2] = obj1;
+ InvalidateBatchingState(true);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void ChangeChildrenOrder(IList indice, IList objs)
+ {
+ int cnt = objs.Count;
+ for (int i = 0; i < cnt; i++)
+ {
+ DisplayObject obj = objs[i];
+ if (obj.parent != this)
+ throw new Exception("Not a child of this container");
+
+ _children[indice[i]] = obj;
+ }
+ InvalidateBatchingState(true);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public IEnumerator GetDescendants(bool backward)
+ {
+ return new DescendantsEnumerator(this, backward);
+ }
+
+ ///
+ ///
+ ///
+ public Rect? clipRect
+ {
+ get { return _clipRect; }
+ set
+ {
+ if (_clipRect != value)
+ {
+ _clipRect = value;
+ UpdateBatchingFlags();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public DisplayObject mask
+ {
+ get { return _mask; }
+ set
+ {
+ if (_mask != value)
+ {
+ _mask = value;
+ UpdateBatchingFlags();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public void CreateGraphics()
+ {
+ if (graphics == null)
+ {
+ graphics = new NGraphics(this.gameObject);
+ graphics.texture = NTexture.Empty;
+ }
+ }
+
+ public override Rect GetBounds(DisplayObject targetSpace)
+ {
+ if (_clipRect != null)
+ return TransformRect((Rect)_clipRect, targetSpace);
+
+ int count = _children.Count;
+
+ Rect rect;
+ if (count == 0)
+ {
+ Vector2 v = TransformPoint(Vector2.zero, targetSpace);
+ rect = Rect.MinMaxRect(v.x, v.y, 0, 0);
+ }
+ else if (count == 1)
+ {
+ rect = _children[0].GetBounds(targetSpace);
+ }
+ else
+ {
+ float minX = float.MaxValue, maxX = float.MinValue;
+ float minY = float.MaxValue, maxY = float.MinValue;
+
+ for (int i = 0; i < count; ++i)
+ {
+ rect = _children[i].GetBounds(targetSpace);
+ minX = minX < rect.xMin ? minX : rect.xMin;
+ maxX = maxX > rect.xMax ? maxX : rect.xMax;
+ minY = minY < rect.yMin ? minY : rect.yMin;
+ maxY = maxY > rect.yMax ? maxY : rect.yMax;
+ }
+
+ rect = Rect.MinMaxRect(minX, minY, maxX, maxY);
+ }
+
+ return rect;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public Camera GetRenderCamera()
+ {
+ if (renderMode == RenderMode.ScreenSpaceOverlay)
+ return StageCamera.main;
+ else
+ {
+ Camera cam = this.renderCamera;
+ if (cam == null)
+ {
+ if (HitTestContext.cachedMainCamera != null)
+ cam = HitTestContext.cachedMainCamera;
+ else
+ {
+ cam = Camera.main;
+ if (cam == null)
+ cam = StageCamera.main;
+ }
+ }
+ return cam;
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public DisplayObject HitTest(Vector2 stagePoint, bool forTouch)
+ {
+ if (StageCamera.main == null)
+ {
+ if (this is Stage)
+ return this;
+ else
+ return null;
+ }
+
+ HitTestContext.screenPoint = new Vector3(stagePoint.x, Screen.height - stagePoint.y, 0);
+ if (Display.displays.Length > 1)
+ {
+ Vector3 p = Display.RelativeMouseAt(HitTestContext.screenPoint);
+ if (p != Vector3.zero)
+ HitTestContext.screenPoint = p;
+ }
+ HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(HitTestContext.screenPoint);
+ HitTestContext.direction = Vector3.back;
+ HitTestContext.forTouch = forTouch;
+ HitTestContext.camera = StageCamera.main;
+
+ DisplayObject ret = HitTest();
+ if (ret != null)
+ return ret;
+ else if (this is Stage)
+ return this;
+ else
+ return null;
+ }
+
+ override protected DisplayObject HitTest()
+ {
+ if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy)
+ return null;
+
+ if (this.cachedTransform.localScale.x == 0 || this.cachedTransform.localScale.y == 0)
+ return null;
+
+ Camera savedCamera = HitTestContext.camera;
+ Vector3 savedWorldPoint = HitTestContext.worldPoint;
+ Vector3 savedDirection = HitTestContext.direction;
+ DisplayObject target;
+
+ if (renderMode != RenderMode.ScreenSpaceOverlay || (_flags & Flags.UserGameObject) != 0)
+ {
+ Camera cam = GetRenderCamera();
+ if (cam.targetDisplay != HitTestContext.screenPoint.z)
+ return null;
+
+ HitTestContext.camera = cam;
+ if (renderMode == RenderMode.WorldSpace)
+ {
+ Vector3 screenPoint = HitTestContext.camera.WorldToScreenPoint(this.cachedTransform.position); //only for query z value
+ screenPoint.x = HitTestContext.screenPoint.x;
+ screenPoint.y = HitTestContext.screenPoint.y;
+
+ //获得本地z轴在世界坐标的方向
+ HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(screenPoint);
+ Ray ray = HitTestContext.camera.ScreenPointToRay(screenPoint);
+ HitTestContext.direction = Vector3.zero - ray.direction;
+ }
+ else if (renderMode == RenderMode.ScreenSpaceCamera)
+ {
+ HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(HitTestContext.screenPoint);
+ }
+ }
+ else
+ {
+ if (HitTestContext.camera.targetDisplay != HitTestContext.screenPoint.z && !(this is Stage))
+ return null;
+ }
+
+ target = HitTest_Container();
+
+ HitTestContext.camera = savedCamera;
+ HitTestContext.worldPoint = savedWorldPoint;
+ HitTestContext.direction = savedDirection;
+
+ return target;
+ }
+
+ DisplayObject HitTest_Container()
+ {
+ Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction);
+ if (_vertexMatrix != null)
+ HitTestContext.worldPoint = this.cachedTransform.TransformPoint(new Vector2(localPoint.x, -localPoint.y));
+
+ if (hitArea != null)
+ {
+ if (!hitArea.HitTest(_contentRect, localPoint))
+ return null;
+
+ if (hitArea is MeshColliderHitTest)
+ localPoint = ((MeshColliderHitTest)hitArea).lastHit;
+ }
+ else
+ {
+ if (_clipRect != null && !((Rect)_clipRect).Contains(localPoint))
+ return null;
+ }
+
+ if (_mask != null)
+ {
+ DisplayObject tmp = _mask.InternalHitTestMask();
+ if (!reversedMask && tmp == null || reversedMask && tmp != null)
+ return null;
+ }
+
+ DisplayObject target = null;
+ if (touchChildren)
+ {
+ int count = _children.Count;
+ for (int i = count - 1; i >= 0; --i) // front to back!
+ {
+ DisplayObject child = _children[i];
+ if ((child._flags & Flags.GameObjectDisposed) != 0)
+ {
+ child.DisplayDisposedWarning();
+ continue;
+ }
+
+ if (child == _mask || (child._flags & Flags.TouchDisabled) != 0)
+ continue;
+
+ target = child.InternalHitTest();
+ if (target != null)
+ break;
+ }
+ }
+
+ if (target == null && opaque && (hitArea != null || _contentRect.Contains(localPoint)))
+ target = this;
+
+ return target;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public bool IsAncestorOf(DisplayObject obj)
+ {
+ if (obj == null)
+ return false;
+
+ Container p = obj.parent;
+ while (p != null)
+ {
+ if (p == this)
+ return true;
+
+ p = p.parent;
+ }
+ return false;
+ }
+
+ ///
+ ///
+ ///
+ public bool fairyBatching
+ {
+ get { return (_flags & Flags.FairyBatching) != 0; }
+ set
+ {
+ bool oldValue = (_flags & Flags.FairyBatching) != 0;
+ if (oldValue != value)
+ {
+ if (value)
+ _flags |= Flags.FairyBatching;
+ else
+ _flags &= ~Flags.FairyBatching;
+ UpdateBatchingFlags();
+ }
+ }
+ }
+
+ internal void UpdateBatchingFlags()
+ {
+ bool oldValue = (_flags & Flags.BatchingRoot) != 0;
+ bool newValue = (_flags & Flags.FairyBatching) != 0 || _clipRect != null || _mask != null || _paintingMode > 0;
+ if (newValue)
+ _flags |= Flags.BatchingRoot;
+ else
+ _flags &= ~Flags.BatchingRoot;
+ if (oldValue != newValue)
+ {
+ if (newValue)
+ _flags |= Flags.BatchingRequested;
+ else if (_descendants != null)
+ _descendants.Clear();
+
+ InvalidateBatchingState();
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public void InvalidateBatchingState(bool childrenChanged)
+ {
+ if (childrenChanged && (_flags & Flags.BatchingRoot) != 0)
+ _flags |= Flags.BatchingRequested;
+ else
+ {
+ Container p = this.parent;
+ while (p != null)
+ {
+ if ((p._flags & Flags.BatchingRoot) != 0)
+ {
+ p._flags |= Flags.BatchingRequested;
+ break;
+ }
+
+ p = p.parent;
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public void SetChildrenLayer(int value)
+ {
+ int cnt = _children.Count;
+ for (int i = 0; i < cnt; i++)
+ {
+ DisplayObject child = _children[i];
+ child._SetLayerDirect(value);
+ if ((child is Container) && child._paintingMode == 0)
+ ((Container)child).SetChildrenLayer(value);
+ }
+ }
+
+ override public void Update(UpdateContext context)
+ {
+ if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy)
+ return;
+
+ base.Update(context);
+
+ if (_paintingMode != 0)
+ {
+ if ((_flags & Flags.CacheAsBitmap) != 0 && _paintingInfo.flag == 2)
+ {
+ if (onUpdate != null)
+ onUpdate();
+ return;
+ }
+
+ context.EnterPaintingMode();
+ }
+
+ if (_mask != null)
+ {
+ context.EnterClipping(this.id, reversedMask);
+ if (_mask.graphics != null)
+ _mask.graphics._PreUpdateMask(context, _mask.id);
+ }
+ else if (_clipRect != null)
+ context.EnterClipping(this.id, this.TransformRect((Rect)_clipRect, null), clipSoftness);
+
+ float savedAlpha = context.alpha;
+ context.alpha *= this.alpha;
+ bool savedGrayed = context.grayed;
+ context.grayed = context.grayed || this.grayed;
+
+ if ((_flags & Flags.FairyBatching) != 0)
+ context.batchingDepth++;
+
+ if (context.batchingDepth > 0)
+ {
+ int cnt = _children.Count;
+ for (int i = 0; i < cnt; i++)
+ {
+ DisplayObject child = _children[i];
+ if ((child._flags & Flags.GameObjectDisposed) != 0)
+ {
+ child.DisplayDisposedWarning();
+ continue;
+ }
+
+ if (child.visible)
+ child.Update(context);
+ }
+ }
+ else
+ {
+ if (_mask != null)
+ _mask.renderingOrder = context.renderingOrder++;
+
+ int cnt = _children.Count;
+ for (int i = 0; i < cnt; i++)
+ {
+ DisplayObject child = _children[i];
+ if ((child._flags & Flags.GameObjectDisposed) != 0)
+ {
+ child.DisplayDisposedWarning();
+ continue;
+ }
+
+ if (child.visible)
+ {
+ if (!(child.graphics != null && child.graphics._maskFlag == 1)) //if not a mask
+ child.renderingOrder = context.renderingOrder++;
+
+ child.Update(context);
+ }
+ }
+
+ if (_mask != null)
+ {
+ if (_mask.graphics != null)
+ _mask.graphics._SetStencilEraserOrder(context.renderingOrder++);
+ }
+ }
+
+ if ((_flags & Flags.FairyBatching) != 0)
+ {
+ if (context.batchingDepth == 1)
+ SetRenderingOrder(context);
+ context.batchingDepth--;
+ }
+
+ context.alpha = savedAlpha;
+ context.grayed = savedGrayed;
+
+ if (_clipRect != null || _mask != null)
+ context.LeaveClipping();
+
+ if (_paintingMode != 0)
+ {
+ context.LeavePaintingMode();
+ UpdateContext.OnEnd += _paintingInfo.captureDelegate;
+ }
+
+ if (onUpdate != null)
+ onUpdate();
+ }
+
+ private void SetRenderingOrder(UpdateContext context)
+ {
+ if ((_flags & Flags.BatchingRequested) != 0)
+ DoFairyBatching();
+
+ if (_mask != null)
+ _mask.renderingOrder = context.renderingOrder++;
+
+ int cnt = _descendants.Count;
+ for (int i = 0; i < cnt; i++)
+ {
+ DisplayObject child = _descendants[i];
+ if (!(child.graphics != null && child.graphics._maskFlag == 1))
+ child.renderingOrder = context.renderingOrder++;
+
+ if ((child._flags & Flags.BatchingRoot) != 0)
+ ((Container)child).SetRenderingOrder(context);
+ }
+
+ if (_mask != null)
+ {
+ if (_mask.graphics != null)
+ _mask.graphics._SetStencilEraserOrder(context.renderingOrder++);
+ }
+ }
+
+ private void DoFairyBatching()
+ {
+ _flags &= ~Flags.BatchingRequested;
+
+ if (_descendants == null)
+ _descendants = new List();
+ else
+ _descendants.Clear();
+ CollectChildren(this, false);
+
+ int cnt = _descendants.Count;
+
+ int i, j, k, m;
+ object curMat, testMat, lastMat;
+ DisplayObject current, test;
+ float[] bound;
+ for (i = 0; i < cnt; i++)
+ {
+ current = _descendants[i];
+ bound = current._batchingBounds;
+ curMat = current.material;
+ if (curMat == null || (current._flags & Flags.SkipBatching) != 0)
+ continue;
+
+ k = -1;
+ lastMat = null;
+ m = i;
+ for (j = i - 1; j >= 0; j--)
+ {
+ test = _descendants[j];
+ if ((test._flags & Flags.SkipBatching) != 0)
+ break;
+
+ testMat = test.material;
+ if (testMat != null)
+ {
+ if (lastMat != testMat)
+ {
+ lastMat = testMat;
+ m = j + 1;
+ }
+
+ if (curMat == testMat)
+ k = m;
+ }
+
+ if ((bound[0] > test._batchingBounds[0] ? bound[0] : test._batchingBounds[0])
+ <= (bound[2] < test._batchingBounds[2] ? bound[2] : test._batchingBounds[2])
+ && (bound[1] > test._batchingBounds[1] ? bound[1] : test._batchingBounds[1])
+ <= (bound[3] < test._batchingBounds[3] ? bound[3] : test._batchingBounds[3]))
+ {
+ if (k == -1)
+ k = m;
+ break;
+ }
+ }
+ if (k != -1 && i != k)
+ {
+ _descendants.RemoveAt(i);
+ _descendants.Insert(k, current);
+ }
+ }
+
+ //Debug.Log("DoFairyBatching " + cnt + "," + this.cachedTransform.GetInstanceID());
+ }
+
+ private void CollectChildren(Container initiator, bool outlineChanged)
+ {
+ int count = _children.Count;
+ for (int i = 0; i < count; i++)
+ {
+ DisplayObject child = _children[i];
+ if (!child.visible)
+ continue;
+
+ if (child._batchingBounds == null)
+ child._batchingBounds = new float[4];
+
+ if (child is Container)
+ {
+ Container container = (Container)child;
+ if ((container._flags & Flags.BatchingRoot) != 0)
+ {
+ initiator._descendants.Add(container);
+ if (outlineChanged || (container._flags & Flags.OutlineChanged) != 0)
+ {
+ Rect rect = container.GetBounds(initiator);
+ container._batchingBounds[0] = rect.xMin;
+ container._batchingBounds[1] = rect.yMin;
+ container._batchingBounds[2] = rect.xMax;
+ container._batchingBounds[3] = rect.yMax;
+ }
+ if ((container._flags & Flags.BatchingRequested) != 0)
+ container.DoFairyBatching();
+ }
+ else
+ container.CollectChildren(initiator, outlineChanged || (container._flags & Flags.OutlineChanged) != 0);
+ }
+ else if (child != initiator._mask)
+ {
+ if (outlineChanged || (child._flags & Flags.OutlineChanged) != 0)
+ {
+ Rect rect = child.GetBounds(initiator);
+ child._batchingBounds[0] = rect.xMin;
+ child._batchingBounds[1] = rect.yMin;
+ child._batchingBounds[2] = rect.xMax;
+ child._batchingBounds[3] = rect.yMax;
+ }
+ initiator._descendants.Add(child);
+ }
+
+ child._flags &= ~Flags.OutlineChanged;
+ }
+ }
+
+ public override void Dispose()
+ {
+ if ((_flags & Flags.Disposed) != 0)
+ return;
+
+ base.Dispose(); //Destroy GameObject tree first, avoid destroying each seperately;
+
+ int numChildren = _children.Count;
+ for (int i = numChildren - 1; i >= 0; --i)
+ {
+ DisplayObject obj = _children[i];
+ obj.InternalSetParent(null); //Avoid RemoveParent call
+ obj.Dispose();
+ }
+ }
+
+ ///
+ /// If true, when the container is focused, tab navigation is lock inside it.
+ ///
+ public bool tabStopChildren
+ {
+ get { return (_flags & Flags.TabStopChildren) != 0; }
+ set
+ {
+ if (value)
+ _flags |= Flags.TabStopChildren;
+ else
+ _flags &= ~Flags.TabStopChildren;
+ }
+ }
+
+ struct DescendantsEnumerator : IEnumerator
+ {
+ Container _root;
+ Container _com;
+ DisplayObject _current;
+ int _index;
+ bool _forward;
+
+ public DescendantsEnumerator(Container root, bool backward)
+ {
+ _root = root;
+ _com = _root;
+ _current = null;
+ _forward = !backward;
+ if (_forward)
+ _index = 0;
+ else
+ _index = _com._children.Count - 1;
+ }
+
+ public DisplayObject Current
+ {
+ get { return _current; }
+ }
+
+ object IEnumerator.Current
+ {
+ get { return _current; }
+ }
+
+ public bool MoveNext()
+ {
+ if (_forward)
+ {
+ if (_index >= _com._children.Count)
+ {
+ if (_com == _root)
+ {
+ _current = null;
+ return false;
+ }
+
+ _current = _com;
+ _com = _com.parent;
+ _index = _com.GetChildIndex(_current) + 1;
+ return true;
+ }
+ else
+ {
+ DisplayObject obj = _com._children[_index];
+ if (obj is Container)
+ {
+ _com = (Container)obj;
+ _index = 0;
+ return MoveNext();
+ }
+ _index++;
+ _current = obj;
+ return true;
+ }
+ }
+ else
+ {
+ if (_index < 0)
+ {
+ if (_com == _root)
+ {
+ _current = null;
+ return false;
+ }
+
+ _current = _com;
+ _com = _com.parent;
+ _index = _com.GetChildIndex(_current) - 1;
+ return true;
+ }
+ else
+ {
+ DisplayObject obj = _com._children[_index];
+ if (obj is Container)
+ {
+ _com = (Container)obj;
+ _index = _com._children.Count - 1;
+ return MoveNext();
+ }
+ _index--;
+ _current = obj;
+ return true;
+ }
+ }
+ }
+
+ public void Reset()
+ {
+ _com = _root;
+ _current = null;
+ _index = 0;
+ }
+
+ public void Dispose()
+ {
+ }
+ }
+ }
+}
diff --git a/Assets/Scripts/Core/Container.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs.meta
similarity index 100%
rename from Assets/Scripts/Core/Container.cs.meta
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs.meta
diff --git a/Assets/Scripts/Core/DisplayObject.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs
similarity index 96%
rename from Assets/Scripts/Core/DisplayObject.cs
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs
index 11c79c62..5909a65b 100644
--- a/Assets/Scripts/Core/DisplayObject.cs
+++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs
@@ -1,1878 +1,1878 @@
-using System;
-using System.Text;
-using UnityEngine;
-using FairyGUI.Utils;
-
-namespace FairyGUI
-{
- ///
- ///
- ///
- public class DisplayObject : EventDispatcher
- {
- ///
- ///
- ///
- public string name;
-
- ///
- ///
- ///
- public Container parent { get; private set; }
-
- ///
- ///
- ///
- public GameObject gameObject { get; protected set; }
-
- ///
- ///
- ///
- public Transform cachedTransform { get; protected set; }
-
- ///
- ///
- ///
- public NGraphics graphics { get; protected set; }
-
- ///
- ///
- ///
- public NGraphics paintingGraphics { get; protected set; }
-
- ///
- ///
- ///
- public event Action onPaint;
-
- ///
- ///
- ///
- public GObject gOwner;
-
- ///
- ///
- ///
- public uint id;
-
- bool _visible;
- bool _touchable;
- Vector2 _pivot;
- Vector3 _pivotOffset;
- Vector3 _rotation; //由于万向锁,单独旋转一个轴是会影响到其他轴的,所以这里需要单独保存
- Vector2 _skew;
- int _renderingOrder;
- float _alpha;
- bool _grayed;
- BlendMode _blendMode;
- IFilter _filter;
- Transform _home;
- string _cursor;
- bool _perspective;
- int _focalLength;
- Vector3 _pixelPerfectAdjustment;
- int _checkPixelPerfect;
-
- EventListener _onClick;
- EventListener _onRightClick;
- EventListener _onTouchBegin;
- EventListener _onTouchMove;
- EventListener _onTouchEnd;
- EventListener _onRollOver;
- EventListener _onRollOut;
- EventListener _onMouseWheel;
- EventListener _onAddedToStage;
- EventListener _onRemovedFromStage;
- EventListener _onKeyDown;
- EventListener _onClickLink;
- EventListener _onFocusIn;
- EventListener _onFocusOut;
-
- protected internal int _paintingMode; //1-滤镜,2-blendMode,4-transformMatrix, 8-cacheAsBitmap
- protected internal PaintingInfo _paintingInfo;
- protected Rect _contentRect;
- protected NGraphics.VertexMatrix _vertexMatrix;
- protected internal Flags _flags;
- protected internal float[] _batchingBounds;
-
- internal static uint _gInstanceCounter;
-
- internal static HideFlags hideFlags = HideFlags.None;
-
- public DisplayObject()
- {
- id = _gInstanceCounter++;
-
- _alpha = 1;
- _visible = true;
- _touchable = true;
- _blendMode = BlendMode.Normal;
- _focalLength = 2000;
- _flags |= Flags.OutlineChanged;
- if (UIConfig.makePixelPerfect)
- _flags |= Flags.PixelPerfect;
- }
-
- ///
- ///
- ///
- public EventListener onClick
- {
- get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); }
- }
-
- ///
- ///
- ///
- public EventListener onRightClick
- {
- get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); }
- }
-
- ///
- ///
- ///
- public EventListener onTouchBegin
- {
- get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); }
- }
-
- ///
- ///
- ///
- public EventListener onTouchMove
- {
- get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); }
- }
-
- ///
- ///
- ///
- public EventListener onTouchEnd
- {
- get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); }
- }
-
- ///
- ///
- ///
- public EventListener onRollOver
- {
- get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); }
- }
-
- ///
- ///
- ///
- public EventListener onRollOut
- {
- get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); }
- }
-
- ///
- ///
- ///
- public EventListener onMouseWheel
- {
- get { return _onMouseWheel ?? (_onMouseWheel = new EventListener(this, "onMouseWheel")); }
- }
-
- ///
- ///
- ///
- public EventListener onAddedToStage
- {
- get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); }
- }
-
- ///
- ///
- ///
- public EventListener onRemovedFromStage
- {
- get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); }
- }
-
- ///
- ///
- ///
- public EventListener onKeyDown
- {
- get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); }
- }
-
- ///
- ///
- ///
- public EventListener onClickLink
- {
- get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); }
- }
-
- ///
- ///
- ///
- public EventListener onFocusIn
- {
- get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); }
- }
-
- ///
- ///
- ///
- public EventListener onFocusOut
- {
- get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); }
-
- }
-
- protected void CreateGameObject(string gameObjectName)
- {
- gameObject = new GameObject(gameObjectName);
- cachedTransform = gameObject.transform;
- if (Application.isPlaying)
- {
- UnityEngine.Object.DontDestroyOnLoad(gameObject);
-
- DisplayObjectInfo info = gameObject.AddComponent();
- info.displayObject = this;
- }
- gameObject.hideFlags = DisplayObject.hideFlags;
- gameObject.SetActive(false);
- }
-
- protected void SetGameObject(GameObject gameObject)
- {
- this.gameObject = gameObject;
- this.cachedTransform = gameObject.transform;
- _rotation = cachedTransform.localEulerAngles;
-
- _flags |= Flags.UserGameObject;
- }
-
- protected void DestroyGameObject()
- {
- if ((_flags & Flags.UserGameObject) == 0 && gameObject != null)
- {
- if (Application.isPlaying)
- GameObject.Destroy(gameObject);
- else
- GameObject.DestroyImmediate(gameObject);
- gameObject = null;
- cachedTransform = null;
- }
- }
-
- ///
- ///
- ///
- public float alpha
- {
- get { return _alpha; }
- set { _alpha = value; }
- }
-
- ///
- ///
- ///
- public bool grayed
- {
- get { return _grayed; }
- set { _grayed = value; }
- }
-
- ///
- ///
- ///
- public bool visible
- {
- get { return _visible; }
- set
- {
- if (_visible != value)
- {
- _visible = value;
- _flags |= Flags.OutlineChanged;
- if (parent != null && _visible)
- {
- gameObject.SetActive(true);
- InvalidateBatchingState();
- if (this is Container)
- ((Container)this).InvalidateBatchingState(true);
- }
- else
- gameObject.SetActive(false);
- }
- }
- }
-
- ///
- ///
- ///
- public float x
- {
- get { return cachedTransform.localPosition.x; }
- set
- {
- SetPosition(value, -cachedTransform.localPosition.y, cachedTransform.localPosition.z);
- }
- }
-
- ///
- ///
- ///
- public float y
- {
- get { return -cachedTransform.localPosition.y; }
- set
- {
- SetPosition(cachedTransform.localPosition.x, value, cachedTransform.localPosition.z);
- }
- }
-
- ///
- ///
- ///
- public float z
- {
- get { return cachedTransform.localPosition.z; }
- set
- {
- SetPosition(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, value);
- }
- }
-
- ///
- ///
- ///
- public Vector2 xy
- {
- get { return new Vector2(this.x, this.y); }
- set { SetPosition(value.x, value.y, cachedTransform.localPosition.z); }
- }
-
- ///
- ///
- ///
- public Vector3 position
- {
- get { return new Vector3(this.x, this.y, this.z); }
- set { SetPosition(value.x, value.y, value.z); }
- }
-
- ///
- ///
- ///
- ///
- ///
- public void SetXY(float xv, float yv)
- {
- SetPosition(xv, yv, cachedTransform.localPosition.z);
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public void SetPosition(float xv, float yv, float zv)
- {
- Vector3 v = new Vector3();
- v.x = xv;
- v.y = -yv;
- v.z = zv;
- if (v != cachedTransform.localPosition)
- {
- cachedTransform.localPosition = v;
- _flags |= Flags.OutlineChanged;
- if ((_flags & Flags.PixelPerfect) != 0)
- {
- //总在下一帧再完成PixelPerfect,这样当物体在连续运动时,不会因为PixelPerfect而发生抖动。
- _checkPixelPerfect = Time.frameCount;
- _pixelPerfectAdjustment = Vector3.zero;
- }
- }
- }
-
- ///
- /// If the object position is align by pixel
- ///
- public bool pixelPerfect
- {
- get { return (_flags & Flags.PixelPerfect) != 0; }
- set
- {
- if (value)
- _flags |= Flags.PixelPerfect;
- else
- _flags &= ~Flags.PixelPerfect;
- }
- }
-
- ///
- ///
- ///
- public float width
- {
- get
- {
- EnsureSizeCorrect();
- return _contentRect.width;
- }
- set
- {
- if (!Mathf.Approximately(value, _contentRect.width))
- {
- _contentRect.width = value;
- _flags |= Flags.WidthChanged;
- _flags &= ~Flags.HeightChanged;
- OnSizeChanged();
- }
- }
- }
-
- ///
- ///
- ///
- public float height
- {
- get
- {
- EnsureSizeCorrect();
- return _contentRect.height;
- }
- set
- {
- if (!Mathf.Approximately(value, _contentRect.height))
- {
- _contentRect.height = value;
- _flags &= ~Flags.WidthChanged;
- _flags |= Flags.HeightChanged;
- OnSizeChanged();
- }
- }
- }
-
- ///
- ///
- ///
- public Vector2 size
- {
- get
- {
- EnsureSizeCorrect();
- return _contentRect.size;
- }
- set
- {
- SetSize(value.x, value.y);
- }
- }
-
- ///
- ///
- ///
- ///
- ///
- public void SetSize(float wv, float hv)
- {
- if (!Mathf.Approximately(wv, _contentRect.width))
- _flags |= Flags.WidthChanged;
- else
- _flags &= ~Flags.WidthChanged;
- if (!Mathf.Approximately(hv, _contentRect.height))
- _flags |= Flags.HeightChanged;
- else
- _flags &= ~Flags.HeightChanged;
-
- if ((_flags & Flags.WidthChanged) != 0 || (_flags & Flags.HeightChanged) != 0)
- {
- _contentRect.width = wv;
- _contentRect.height = hv;
- OnSizeChanged();
- }
- }
-
- virtual public void EnsureSizeCorrect()
- {
- }
-
- virtual protected void OnSizeChanged()
- {
- ApplyPivot();
-
- if (_paintingInfo != null)
- _paintingInfo.flag = 1;
- if (graphics != null)
- graphics.contentRect = _contentRect;
- _flags |= Flags.OutlineChanged;
- }
-
- ///
- ///
- ///
- public float scaleX
- {
- get { return cachedTransform.localScale.x; }
- set
- {
- Vector3 v = cachedTransform.localScale;
- v.x = v.z = ValidateScale(value);
- cachedTransform.localScale = v;
- _flags |= Flags.OutlineChanged;
- ApplyPivot();
- }
- }
-
- ///
- ///
- ///
- public float scaleY
- {
- get { return cachedTransform.localScale.y; }
- set
- {
- Vector3 v = cachedTransform.localScale;
- v.y = ValidateScale(value);
- cachedTransform.localScale = v;
- _flags |= Flags.OutlineChanged;
- ApplyPivot();
- }
- }
-
- ///
- ///
- ///
- ///
- ///
- public void SetScale(float xv, float yv)
- {
- Vector3 v = new Vector3();
- v.x = v.z = ValidateScale(xv);
- v.y = ValidateScale(yv);
- cachedTransform.localScale = v;
- _flags |= Flags.OutlineChanged;
- ApplyPivot();
- }
-
- ///
- /// 在scale过小情况(极端情况=0),当使用Transform的坐标变换时,变换到世界,再从世界变换到本地,会由于精度问题造成结果错误。
- /// 这种错误会导致Batching错误,因为Batching会使用缓存的outline。
- /// 这里限制一下scale的最小值作为当前解决方案。
- /// 这个方案并不完美,因为限制了本地scale值并不能保证对世界scale不会过小。
- ///
- ///
- ///
- private float ValidateScale(float value)
- {
- if (value >= 0 && value < 0.001f)
- value = 0.001f;
- else if (value < 0 && value > -0.001f)
- value = -0.001f;
- return value;
- }
-
- ///
- ///
- ///
- public Vector2 scale
- {
- get { return cachedTransform.localScale; }
- set
- {
- SetScale(value.x, value.y);
- }
- }
-
- ///
- ///
- ///
- public float rotation
- {
- get
- {
- //和Unity默认的旋转方向相反
- return -_rotation.z;
- }
- set
- {
- _rotation.z = -value;
- _flags |= Flags.OutlineChanged;
- if (_perspective)
- UpdateTransformMatrix();
- else
- {
- cachedTransform.localEulerAngles = _rotation;
- ApplyPivot();
- }
- }
- }
-
- ///
- ///
- ///
- public float rotationX
- {
- get
- {
- return _rotation.x;
- }
- set
- {
- _rotation.x = value;
- _flags |= Flags.OutlineChanged;
- if (_perspective)
- UpdateTransformMatrix();
- else
- {
- cachedTransform.localEulerAngles = _rotation;
- ApplyPivot();
- }
- }
- }
-
- ///
- ///
- ///
- public float rotationY
- {
- get
- {
- return _rotation.y;
- }
- set
- {
- _rotation.y = value;
- _flags |= Flags.OutlineChanged;
- if (_perspective)
- UpdateTransformMatrix();
- else
- {
- cachedTransform.localEulerAngles = _rotation;
- ApplyPivot();
- }
- }
- }
-
- ///
- ///
- ///
- public Vector2 skew
- {
- get { return _skew; }
- set
- {
- _skew = value;
- _flags |= Flags.OutlineChanged;
-
- if (!Application.isPlaying) //编辑期间不支持!!
- return;
-
- UpdateTransformMatrix();
- }
- }
-
- ///
- /// 当对象处于ScreenSpace,也就是使用正交相机渲染时,对象虽然可以绕X轴或者Y轴旋转,但没有透视效果。设置perspective,可以模拟出透视效果。
- ///
- public bool perspective
- {
- get
- {
- return _perspective;
- }
- set
- {
- if (_perspective != value)
- {
- _perspective = value;
- if (_perspective)//屏蔽Unity自身的旋转变换
- cachedTransform.localEulerAngles = Vector3.zero;
- else
- cachedTransform.localEulerAngles = _rotation;
-
- ApplyPivot();
- UpdateTransformMatrix();
- }
- }
- }
-
- ///
- ///
- ///
- public int focalLength
- {
- get { return _focalLength; }
- set
- {
- if (value <= 0)
- value = 1;
-
- _focalLength = value;
- if (_vertexMatrix != null)
- UpdateTransformMatrix();
- }
- }
-
- void UpdateTransformMatrix()
- {
- Matrix4x4 matrix = Matrix4x4.identity;
- if (_skew.x != 0 || _skew.y != 0)
- ToolSet.SkewMatrix(ref matrix, _skew.x, _skew.y);
- if (_perspective)
- matrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(_rotation), Vector3.one);
- if (matrix.isIdentity)
- _vertexMatrix = null;
- else if (_vertexMatrix == null)
- _vertexMatrix = new NGraphics.VertexMatrix();
-
- //组件的transformMatrix是通过paintingMode实现的,因为全部通过矩阵变换的话,和unity自身的变换混杂在一起,无力理清。
- if (_vertexMatrix != null)
- {
- _vertexMatrix.matrix = matrix;
- _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength);
-
- if (graphics == null)
- EnterPaintingMode(4, null);
- }
- else
- {
- if (graphics == null)
- LeavePaintingMode(4);
- }
-
- if (_paintingMode > 0)
- {
- paintingGraphics.vertexMatrix = _vertexMatrix;
- _paintingInfo.flag = 1;
- }
- else if (graphics != null)
- graphics.vertexMatrix = _vertexMatrix;
-
- _flags |= Flags.OutlineChanged;
- }
-
- ///
- ///
- ///
- public Vector2 pivot
- {
- get { return _pivot; }
- set
- {
- Vector3 deltaPivot = new Vector2((value.x - _pivot.x) * _contentRect.width, (_pivot.y - value.y) * _contentRect.height);
- Vector3 oldOffset = _pivotOffset;
-
- _pivot = value;
- UpdatePivotOffset();
- Vector3 v = cachedTransform.localPosition;
- v += oldOffset - _pivotOffset + deltaPivot;
- cachedTransform.localPosition = v;
- _flags |= Flags.OutlineChanged;
- }
- }
-
- void UpdatePivotOffset()
- {
- float px = _pivot.x * _contentRect.width;
- float py = _pivot.y * _contentRect.height;
-
- //注意这里不用处理skew,因为在顶点变换里有对pivot的处理
- Matrix4x4 matrix = Matrix4x4.TRS(Vector3.zero, cachedTransform.localRotation, cachedTransform.localScale);
- _pivotOffset = matrix.MultiplyPoint(new Vector3(px, -py, 0));
-
- if (_vertexMatrix != null)
- _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength);
- }
-
- void ApplyPivot()
- {
- if (_pivot.x != 0 || _pivot.y != 0)
- {
- Vector3 oldOffset = _pivotOffset;
-
- UpdatePivotOffset();
- Vector3 v = cachedTransform.localPosition;
-
- if ((_flags & Flags.PixelPerfect) != 0)
- {
- v -= _pixelPerfectAdjustment;
- _checkPixelPerfect = Time.frameCount;
- _pixelPerfectAdjustment = Vector3.zero;
- }
-
- v += oldOffset - _pivotOffset;
- cachedTransform.localPosition = v;
- _flags |= Flags.OutlineChanged;
- }
- }
-
- ///
- /// This is the pivot position
- ///
- public Vector3 location
- {
- get
- {
- Vector3 pos = this.position;
- pos.x += _pivotOffset.x;
- pos.y -= _pivotOffset.y;
- pos.z += _pivotOffset.z;
- return pos;
- }
-
- set
- {
- this.SetPosition(value.x - _pivotOffset.x, value.y + _pivotOffset.y, value.z - _pivotOffset.z);
- }
- }
-
- ///
- ///
- ///
- virtual public Material material
- {
- get
- {
- if (graphics != null)
- return graphics.material;
- else
- return null;
- }
- set
- {
- if (graphics != null)
- graphics.material = value;
- }
- }
-
- ///
- ///
- ///
- virtual public string shader
- {
- get
- {
- if (graphics != null)
- return graphics.shader;
- else
- return null;
- }
- set
- {
- if (graphics != null)
- graphics.shader = value;
- }
- }
-
- ///
- ///
- ///
- virtual public int renderingOrder
- {
- get
- {
- return _renderingOrder;
- }
- set
- {
- if ((_flags & Flags.GameObjectDisposed) != 0)
- {
- DisplayDisposedWarning();
- return;
- }
-
- _renderingOrder = value;
- if (graphics != null)
- graphics.sortingOrder = value;
- if (_paintingMode > 0)
- paintingGraphics.sortingOrder = value;
- }
- }
-
- ///
- ///
- ///
- public int layer
- {
- get
- {
- if (_paintingMode > 0)
- return paintingGraphics.gameObject.layer;
- else
- return gameObject.layer;
- }
- set
- {
- SetLayer(value, false);
- }
- }
-
- ///
- /// If the object can be focused?
- ///
- public bool focusable
- {
- get { return (_flags & Flags.NotFocusable) == 0; }
- set
- {
- if (value)
- _flags &= ~Flags.NotFocusable;
- else
- _flags |= Flags.NotFocusable;
- }
- }
-
- ///
- /// If the object can be navigated by TAB?
- ///
- public bool tabStop
- {
- get { return (_flags & Flags.TabStop) != 0; }
- set
- {
- if (value)
- _flags |= Flags.TabStop;
- else
- _flags &= ~Flags.TabStop;
- }
- }
-
- ///
- /// If the object focused?
- ///
- public bool focused
- {
- get
- {
- return Stage.inst.focus == this || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.focus);
- }
- }
-
- internal bool _AcceptTab()
- {
- if (_touchable && _visible
- && ((_flags & Flags.TabStop) != 0 || (_flags & Flags.TabStopChildren) != 0)
- && (_flags & Flags.NotFocusable) == 0)
- {
- Stage.inst.SetFocus(this, true);
- return true;
- }
- else
- return false;
- }
-
- ///
- ///
- ///
- ///
- public string cursor
- {
- get { return _cursor; }
- set
- {
- _cursor = value;
- if (Application.isPlaying
- && (this == Stage.inst.touchTarget || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.touchTarget)))
- {
- Stage.inst._ChangeCursor(_cursor);
- }
- }
- }
-
- ///
- ///
- ///
- public bool isDisposed
- {
- get { return (_flags & Flags.Disposed) != 0 || gameObject == null; }
- }
-
- internal void InternalSetParent(Container value)
- {
- if (parent != value)
- {
- if (value == null && (parent._flags & Flags.Disposed) != 0)
- parent = value;
- else
- {
- parent = value;
- UpdateHierarchy();
- }
- _flags |= Flags.OutlineChanged;
- }
- }
-
- ///
- ///
- ///
- public Container topmost
- {
- get
- {
- DisplayObject currentObject = this;
- while (currentObject.parent != null)
- currentObject = currentObject.parent;
- return currentObject as Container;
- }
- }
-
- ///
- ///
- ///
- public Stage stage
- {
- get
- {
- return topmost as Stage;
- }
- }
-
- ///
- ///
- ///
- public Container worldSpaceContainer
- {
- get
- {
- Container wsc = null;
- DisplayObject currentObject = this;
- while (currentObject.parent != null)
- {
- if ((currentObject is Container) && ((Container)currentObject).renderMode == RenderMode.WorldSpace)
- {
- wsc = (Container)currentObject;
- break;
- }
- currentObject = currentObject.parent;
- }
-
- return wsc;
- }
- }
-
- ///
- ///
- ///
- public bool touchable
- {
- get { return _touchable; }
- set
- {
- if (_touchable != value)
- {
- _touchable = value;
- if (this is Container)
- {
- ColliderHitTest hitArea = ((Container)this).hitArea as ColliderHitTest;
- if (hitArea != null)
- hitArea.collider.enabled = value;
- }
- }
- }
- }
-
- ///
- ///
- ///
- ///
- public bool touchDisabled
- {
- get { return (_flags & Flags.TouchDisabled) != 0; }
- }
-
- ///
- /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。
- /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。
- ///
- public void EnterPaintingMode()
- {
- EnterPaintingMode(16384, null, 1);
- }
-
- ///
- /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。
- /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。
- /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。
- ///
- /// 请求者id
- /// 纹理四周的留空。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。
- public void EnterPaintingMode(int requestorId, Margin? extend)
- {
- EnterPaintingMode(requestorId, extend, 1);
- }
-
- ///
- /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。
- /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。
- /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。
- ///
- /// 请求者id
- /// 扩展纹理。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。
- /// 附加一个缩放系数
- public void EnterPaintingMode(int requestorId, Margin? extend, float scale)
- {
- bool first = _paintingMode == 0;
- _paintingMode |= requestorId;
- if (first)
- {
- if (_paintingInfo == null)
- {
- _paintingInfo = new PaintingInfo()
- {
- captureDelegate = Capture,
- scale = 1
- };
- }
-
- if (paintingGraphics == null)
- {
- if (graphics == null)
- paintingGraphics = new NGraphics(this.gameObject);
- else
- {
- GameObject go = new GameObject(this.gameObject.name + " (Painter)");
- go.layer = this.gameObject.layer;
- go.transform.SetParent(cachedTransform, false);
- go.hideFlags = DisplayObject.hideFlags;
- paintingGraphics = new NGraphics(go);
- }
- }
- else
- paintingGraphics.enabled = true;
- paintingGraphics.vertexMatrix = null;
-
- if (this is Container)
- {
- ((Container)this).SetChildrenLayer(CaptureCamera.hiddenLayer);
- ((Container)this).UpdateBatchingFlags();
- }
- else
- this.InvalidateBatchingState();
-
- if (graphics != null)
- this.gameObject.layer = CaptureCamera.hiddenLayer;
- }
- if (extend != null)
- _paintingInfo.extend = (Margin)extend;
- _paintingInfo.scale = scale;
- _paintingInfo.flag = 1;
- }
-
- ///
- /// 离开绘画模式
- ///
- ///
- public void LeavePaintingMode(int requestorId)
- {
- if (_paintingMode == 0 || (_flags & Flags.Disposed) != 0)
- return;
-
- _paintingMode ^= requestorId;
- if (_paintingMode == 0)
- {
- paintingGraphics.enabled = false;
-
- if (this is Container)
- {
- ((Container)this).SetChildrenLayer(this.layer);
- ((Container)this).UpdateBatchingFlags();
- }
- else
- this.InvalidateBatchingState();
-
- if (graphics != null)
- this.gameObject.layer = paintingGraphics.gameObject.layer;
- }
- }
-
- ///
- ///
- ///
- public bool paintingMode
- {
- get { return _paintingMode > 0; }
- }
-
- ///
- /// 将整个显示对象(如果是容器,则容器包含的整个显示列表)静态化,所有内容被缓冲到一张纹理上。
- /// DC将保持为1。CPU消耗将降到最低。但对象的任何变化不会更新。
- /// 当cacheAsBitmap已经为true时,再次调用cacheAsBitmap=true将会刷新对象一次。
- ///
- public bool cacheAsBitmap
- {
- get { return (_flags & Flags.CacheAsBitmap) != 0; }
- set
- {
- if (value)
- {
- _flags |= Flags.CacheAsBitmap;
- EnterPaintingMode(8, null, UIContentScaler.scaleFactor);
- }
- else
- {
- _flags &= ~Flags.CacheAsBitmap;
- LeavePaintingMode(8);
- }
- }
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public Texture2D GetScreenShot(Margin? extend, float scale)
- {
- EnterPaintingMode(8, null, scale);
- UpdatePainting();
- Capture();
-
- Texture2D output;
- if (paintingGraphics.texture == null)
- output = new Texture2D(1, 1, TextureFormat.RGBA32, false, true);
- else
- {
- RenderTexture rt = (RenderTexture)paintingGraphics.texture.nativeTexture;
- output = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false, true);
- RenderTexture old = RenderTexture.active;
- RenderTexture.active = rt;
- output.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
- output.Apply();
- RenderTexture.active = old;
- }
-
- LeavePaintingMode(8);
-
- return output;
- }
-
- ///
- ///
- ///
- public IFilter filter
- {
- get
- {
- return _filter;
- }
-
- set
- {
- if (!Application.isPlaying) //编辑期间不支持!!
- return;
-
- if (value == _filter)
- return;
-
- if (_filter != null)
- _filter.Dispose();
-
- if (value != null && value.target != null)
- value.target.filter = null;
-
- _filter = value;
- if (_filter != null)
- _filter.target = this;
- }
- }
-
- ///
- ///
- ///
- public BlendMode blendMode
- {
- get { return _blendMode; }
- set
- {
- _blendMode = value;
- InvalidateBatchingState();
-
- if (graphics == null)
- {
- if (_blendMode != BlendMode.Normal)
- {
- if (!Application.isPlaying) //Not supported in edit mode!
- return;
-
- EnterPaintingMode(2, null);
- paintingGraphics.blendMode = _blendMode;
- }
- else
- LeavePaintingMode(2);
- }
- else
- graphics.blendMode = _blendMode;
- }
- }
-
- ///
- ///
- ///
- ///
- ///
- virtual public Rect GetBounds(DisplayObject targetSpace)
- {
- EnsureSizeCorrect();
-
- if (targetSpace == this) // optimization
- {
- return _contentRect;
- }
- else if (targetSpace == parent && _rotation.z == 0)
- {
- return new Rect(cachedTransform.localPosition.x, -cachedTransform.localPosition.y,
- _contentRect.width * cachedTransform.localScale.x, _contentRect.height * cachedTransform.localScale.y);
- }
- else
- return TransformRect(_contentRect, targetSpace);
- }
-
- internal DisplayObject InternalHitTest()
- {
- if (_visible && (!HitTestContext.forTouch || _touchable))
- return HitTest();
- else
- return null;
- }
-
- internal DisplayObject InternalHitTestMask()
- {
- if (_visible)
- return HitTest();
- else
- return null;
- }
-
- virtual protected DisplayObject HitTest()
- {
- Rect rect = GetBounds(this);
- if (rect.width == 0 || rect.height == 0)
- return null;
-
- Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction);
- if (rect.Contains(localPoint))
- return this;
- else
- return null;
- }
-
- ///
- /// 将舞台坐标转换为本地坐标
- ///
- ///
- ///
- public Vector2 GlobalToLocal(Vector2 point)
- {
- Container wsc = this.worldSpaceContainer;
-
- if (wsc != null)//I am in a world space
- {
- Camera cam = wsc.GetRenderCamera();
- Vector3 worldPoint;
- Vector3 direction;
- Vector3 screenPoint = new Vector3();
- screenPoint.x = point.x;
- screenPoint.y = Screen.height - point.y;
-
- if (wsc.hitArea is MeshColliderHitTest)
- {
- Ray ray = cam.ScreenPointToRay(screenPoint);
- RaycastHit hit;
- if (((MeshColliderHitTest)wsc.hitArea).collider.Raycast(ray, out hit, 100))
- {
- point = new Vector2(hit.textureCoord.x * _contentRect.width, (1 - hit.textureCoord.y) * _contentRect.height);
- worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0);
- direction = Vector3.back;
- }
- else //当射线没有击中模型时,无法确定本地坐标
- return new Vector2(float.NaN, float.NaN);
- }
- else
- {
- screenPoint.z = cam.WorldToScreenPoint(this.cachedTransform.position).z;
- worldPoint = cam.ScreenToWorldPoint(screenPoint);
- Ray ray = cam.ScreenPointToRay(screenPoint);
- direction = Vector3.zero - ray.direction;
- }
-
- return this.WorldToLocal(worldPoint, direction);
- }
- else //I am in stage space
- {
- Vector3 worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0);
- return this.WorldToLocal(worldPoint, Vector3.back);
- }
- }
-
- ///
- /// 将本地坐标转换为舞台坐标
- ///
- ///
- ///
- public Vector2 LocalToGlobal(Vector2 point)
- {
- Container wsc = this.worldSpaceContainer;
-
- Vector3 worldPoint = this.cachedTransform.TransformPoint(point.x, -point.y, 0);
- if (wsc != null)
- {
- if (wsc.hitArea is MeshColliderHitTest) //Not supported for UIPainter, use TransfromPoint instead.
- return new Vector2(float.NaN, float.NaN);
-
- Vector3 screePoint = wsc.GetRenderCamera().WorldToScreenPoint(worldPoint);
- return new Vector2(screePoint.x, Stage.inst.size.y - screePoint.y);
- }
- else
- {
- point = Stage.inst.cachedTransform.InverseTransformPoint(worldPoint);
- point.y = -point.y;
- return point;
- }
- }
-
- ///
- /// 转换世界坐标点到等效的本地xy平面的点。等效的意思是他们在屏幕方向看到的位置一样。
- /// 返回的点是在对象的本地坐标空间,且z=0
- ///
- ///
- ///
- ///
- public Vector3 WorldToLocal(Vector3 worldPoint, Vector3 direction)
- {
- Vector3 localPoint = this.cachedTransform.InverseTransformPoint(worldPoint);
- if (localPoint.z != 0) //如果对象绕x轴或y轴旋转过,或者对象是在透视相机,那么z值可能不为0,
- {
- //将世界坐标的摄影机方向在本地空间上投射,求出与xy平面的交点
- direction = this.cachedTransform.InverseTransformDirection(direction);
- float distOnLine = Vector3.Dot(Vector3.zero - localPoint, Vector3.forward) / Vector3.Dot(direction, Vector3.forward);
- if (float.IsInfinity(distOnLine))
- return Vector2.zero;
-
- localPoint = localPoint + direction * distOnLine;
- }
- else if (_vertexMatrix != null)
- {
- Vector3 center = _vertexMatrix.cameraPos;
- center.z = 0;
- center -= _vertexMatrix.matrix.MultiplyPoint(center);
-
- Matrix4x4 mm = _vertexMatrix.matrix.inverse;
-
- localPoint -= center;
- localPoint = mm.MultiplyPoint(localPoint);
-
- Vector3 camPos = mm.MultiplyPoint(_vertexMatrix.cameraPos);
- Vector3 vec = localPoint - camPos;
- float lambda = -camPos.z / vec.z;
- localPoint = camPos + lambda * vec;
- localPoint.z = 0;
- }
- localPoint.y = -localPoint.y;
-
- return localPoint;
- }
-
- ///
- ///
- ///
- ///
- ///
- public Vector3 LocalToWorld(Vector3 localPoint)
- {
- localPoint.y = -localPoint.y;
- if (_vertexMatrix != null)
- {
- Vector3 center = _vertexMatrix.cameraPos;
- center.z = 0;
- center -= _vertexMatrix.matrix.MultiplyPoint(center);
-
- localPoint = _vertexMatrix.matrix.MultiplyPoint(localPoint);
- localPoint += center;
-
- Vector3 camPos = _vertexMatrix.cameraPos;
- Vector3 vec = localPoint - camPos;
- float lambda = -camPos.z / vec.z;
- localPoint = camPos + lambda * vec;
- localPoint.z = 0;
- }
-
- return this.cachedTransform.TransformPoint(localPoint);
- }
-
- ///
- ///
- ///
- ///
- /// null if to world space
- ///
- public Vector2 TransformPoint(Vector2 point, DisplayObject targetSpace)
- {
- if (targetSpace == this)
- return point;
-
- point = LocalToWorld(point);
- if (targetSpace != null)
- point = targetSpace.WorldToLocal(point, Vector3.back);
-
- return point;
- }
-
- ///
- ///
- ///
- ///
- /// null if to world space
- ///
- public Rect TransformRect(Rect rect, DisplayObject targetSpace)
- {
- if (targetSpace == this)
- return rect;
-
- if (targetSpace == parent && _rotation.z == 0) // optimization
- {
- Vector3 vec = cachedTransform.localScale;
- return new Rect((this.x + rect.x) * vec.x, (this.y + rect.y) * vec.y,
- rect.width * vec.x, rect.height * vec.y);
- }
- else
- {
- Vector4 vec4 = new Vector4(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue);
-
- TransformRectPoint(rect.xMin, rect.yMin, targetSpace, ref vec4);
- TransformRectPoint(rect.xMax, rect.yMin, targetSpace, ref vec4);
- TransformRectPoint(rect.xMin, rect.yMax, targetSpace, ref vec4);
- TransformRectPoint(rect.xMax, rect.yMax, targetSpace, ref vec4);
-
- return Rect.MinMaxRect(vec4.x, vec4.y, vec4.z, vec4.w);
- }
- }
-
- protected void TransformRectPoint(float px, float py, DisplayObject targetSpace, ref Vector4 vec4)
- {
- Vector2 v = TransformPoint(new Vector2(px, py), targetSpace);
-
- if (vec4.x > v.x) vec4.x = v.x;
- if (vec4.z < v.x) vec4.z = v.x;
- if (vec4.y > v.y) vec4.y = v.y;
- if (vec4.w < v.y) vec4.w = v.y;
- }
-
- ///
- ///
- ///
- public void RemoveFromParent()
- {
- if (parent != null)
- parent.RemoveChild(this);
- }
-
- ///
- ///
- ///
- public void InvalidateBatchingState()
- {
- if (parent != null)
- parent.InvalidateBatchingState(true);
- }
-
- virtual public void Update(UpdateContext context)
- {
- if (_checkPixelPerfect != 0)
- {
- if (_rotation == Vector3.zero)
- {
- Vector3 v = cachedTransform.localPosition;
- v.x = Mathf.Round(v.x);
- v.y = Mathf.Round(v.y);
- _pixelPerfectAdjustment = v - cachedTransform.localPosition;
- if (_pixelPerfectAdjustment != Vector3.zero)
- cachedTransform.localPosition = v;
- }
- _checkPixelPerfect = 0;
- }
-
- if (graphics != null)
- graphics.Update(context, context.alpha * _alpha, context.grayed | _grayed);
-
- if (_paintingMode != 0)
- {
- UpdatePainting();
-
- //如果是容器,Capture要等到Container.Update的最后执行,因为容器中可能也有需要Capture的内容,要等他们完成后再进行容器的Capture。
- if (!(this is Container))
- {
- if ((_flags & Flags.CacheAsBitmap) == 0 || _paintingInfo.flag != 2)
- UpdateContext.OnEnd += _paintingInfo.captureDelegate;
- }
-
- paintingGraphics.Update(context, 1, false);
- }
-
- if (_filter != null)
- _filter.Update();
-
- Stats.ObjectCount++;
- }
-
- void UpdatePainting()
- {
- NTexture paintingTexture = paintingGraphics.texture;
- if (paintingTexture != null && paintingTexture.disposed) //Texture可能已被Stage.MonitorTexture销毁
- {
- paintingTexture = null;
- _paintingInfo.flag = 1;
- }
-
- if (_paintingInfo.flag == 1)
- {
- _paintingInfo.flag = 0;
-
- //从优化考虑,决定使用绘画模式的容器都需要明确指定大小,而不是自动计算包围。这在UI使用上并没有问题,因为组件总是有固定大小的
- Margin extend = _paintingInfo.extend;
- paintingGraphics.contentRect = new Rect(-extend.left, -extend.top, _contentRect.width + extend.left + extend.right, _contentRect.height + extend.top + extend.bottom);
- int textureWidth = Mathf.RoundToInt(paintingGraphics.contentRect.width * _paintingInfo.scale);
- int textureHeight = Mathf.RoundToInt(paintingGraphics.contentRect.height * _paintingInfo.scale);
- if (paintingTexture == null || paintingTexture.width != textureWidth || paintingTexture.height != textureHeight)
- {
- if (paintingTexture != null)
- paintingTexture.Dispose();
- if (textureWidth > 0 && textureHeight > 0)
- {
- paintingTexture = new NTexture(CaptureCamera.CreateRenderTexture(textureWidth, textureHeight, UIConfig.depthSupportForPaintingMode));
- Stage.inst.MonitorTexture(paintingTexture);
- }
- else
- paintingTexture = null;
- paintingGraphics.texture = paintingTexture;
- }
- }
-
- if (paintingTexture != null)
- paintingTexture.lastActive = Time.time;
- }
-
- void Capture()
- {
- if (paintingGraphics.texture == null)
- return;
-
- Vector2 offset = new Vector2(_paintingInfo.extend.left, _paintingInfo.extend.top);
- CaptureCamera.Capture(this, (RenderTexture)paintingGraphics.texture.nativeTexture, paintingGraphics.contentRect.height, offset);
-
- _paintingInfo.flag = 2; //2表示已完成一次Capture
- if (onPaint != null)
- onPaint();
- }
-
- ///
- /// 为对象设置一个默认的父Transform。当对象不在显示列表里时,它的GameObject挂到哪里。
- ///
- public Transform home
- {
- get { return _home; }
- set
- {
- _home = value;
- if (value != null && cachedTransform.parent == null)
- cachedTransform.SetParent(value, false);
- }
- }
-
- void UpdateHierarchy()
- {
- if ((_flags & Flags.GameObjectDisposed) != 0)
- return;
-
- if ((_flags & Flags.UserGameObject) != 0)
- {
- //we dont change transform parent of this object
- if (gameObject != null)
- {
- if (parent != null && visible)
- gameObject.SetActive(true);
- else
- gameObject.SetActive(false);
- }
- }
- else if (parent != null)
- {
- cachedTransform.SetParent(parent.cachedTransform, false);
-
- if (_visible)
- gameObject.SetActive(true);
-
- int layerValue = parent.gameObject.layer;
- if (parent._paintingMode != 0)
- layerValue = CaptureCamera.hiddenLayer;
- SetLayer(layerValue, true);
- }
- else if ((_flags & Flags.Disposed) == 0 && this.gameObject != null && !StageEngine.beingQuit)
- {
- if (Application.isPlaying)
- {
- if (gOwner == null || gOwner.parent == null)//如果gOwner还有parent的话,说明只是暂时的隐藏
- {
- cachedTransform.SetParent(_home, false);
- if (_home == null)
- UnityEngine.Object.DontDestroyOnLoad(this.gameObject);
- }
- }
-
- gameObject.SetActive(false);
- }
- }
-
- virtual protected bool SetLayer(int value, bool fromParent)
- {
- if ((_flags & Flags.LayerSet) != 0) //setted
- {
- if (fromParent)
- return false;
- }
- else if ((_flags & Flags.LayerFromParent) != 0) //inherit from parent
- {
- if (!fromParent)
- _flags |= Flags.LayerSet;
- }
- else
- {
- if (fromParent)
- _flags |= Flags.LayerFromParent;
- else
- _flags |= Flags.LayerSet;
- }
-
- if (_paintingMode > 0)
- paintingGraphics.gameObject.layer = value;
- else if (gameObject.layer != value)
- {
- gameObject.layer = value;
- if ((this is Container))
- {
- int cnt = ((Container)this).numChildren;
- for (int i = 0; i < cnt; i++)
- {
- DisplayObject child = ((Container)this).GetChildAt(i);
- child.SetLayer(value, true);
- }
- }
- }
-
- return true;
- }
-
- internal void _SetLayerDirect(int value)
- {
- if (_paintingMode > 0)
- paintingGraphics.gameObject.layer = value;
- else
- gameObject.layer = value;
- }
-
- virtual public void Dispose()
- {
- if ((_flags & Flags.Disposed) != 0)
- return;
-
- _flags |= Flags.Disposed;
- RemoveFromParent();
- RemoveEventListeners();
- if (graphics != null)
- graphics.Dispose();
- if (_filter != null)
- _filter.Dispose();
- if (paintingGraphics != null)
- {
- if (paintingGraphics.texture != null)
- paintingGraphics.texture.Dispose();
-
- paintingGraphics.Dispose();
- if (paintingGraphics.gameObject != this.gameObject)
- {
- if (Application.isPlaying)
- UnityEngine.Object.Destroy(paintingGraphics.gameObject);
- else
- UnityEngine.Object.DestroyImmediate(paintingGraphics.gameObject);
- }
- }
- DestroyGameObject();
- }
-
- internal void DisplayDisposedWarning()
- {
- if ((_flags & Flags.DisposedWarning) == 0)
- {
- _flags |= Flags.DisposedWarning;
-
- StringBuilder sb = new StringBuilder();
- sb.Append("DisplayObject is still in use but GameObject was disposed. (");
- if (gOwner != null)
- {
- sb.Append("type=").Append(gOwner.GetType().Name).Append(", x=").Append(gOwner.x).Append(", y=").Append(gOwner.y).Append(", name=").Append(gOwner.name);
- if (gOwner.packageItem != null)
- sb.Append(", res=" + gOwner.packageItem.name);
- }
- else
- {
- sb.Append("id=").Append(id).Append(", type=").Append(this.GetType().Name).Append(", name=").Append(name);
- }
- sb.Append(")");
- Debug.LogError(sb.ToString());
- }
- }
-
- protected internal class PaintingInfo
- {
- public Action captureDelegate; //缓存这个delegate,可以防止Capture状态下每帧104B的GC
- public Margin extend;
- public float scale;
- public int flag;
- }
-
- [Flags]
- protected internal enum Flags
- {
- Disposed = 1,
- UserGameObject = 2,
- TouchDisabled = 4,
- OutlineChanged = 8,
- UpdatingSize = 0x10,
- WidthChanged = 0x20,
- HeightChanged = 0x40,
- PixelPerfect = 0x80,
- LayerSet = 0x100,
- LayerFromParent = 0x200,
- NotFocusable = 0x400,
- TabStop = 0x800,
- TabStopChildren = 0x1000,
- FairyBatching = 0x2000,
- BatchingRequested = 0x4000,
- BatchingRoot = 0x8000,
- SkipBatching = 0x10000,
- CacheAsBitmap = 0x20000,
- GameObjectDisposed = 0x40000,
- DisposedWarning = 0x80000
- }
- }
-
- ///
- ///
- ///
- public class DisplayObjectInfo : MonoBehaviour
- {
- ///
- ///
- /// ///
- [System.NonSerialized]
- public DisplayObject displayObject;
-
- private void OnDestroy()
- {
- if (displayObject != null)
- displayObject._flags |= DisplayObject.Flags.GameObjectDisposed;
- }
- }
-}
+using System;
+using System.Text;
+using UnityEngine;
+using FairyGUI.Utils;
+
+namespace FairyGUI
+{
+ ///
+ ///
+ ///
+ public class DisplayObject : EventDispatcher
+ {
+ ///
+ ///
+ ///
+ public string name;
+
+ ///
+ ///
+ ///
+ public Container parent { get; private set; }
+
+ ///
+ ///
+ ///
+ public GameObject gameObject { get; protected set; }
+
+ ///
+ ///
+ ///
+ public Transform cachedTransform { get; protected set; }
+
+ ///
+ ///
+ ///
+ public NGraphics graphics { get; protected set; }
+
+ ///
+ ///
+ ///
+ public NGraphics paintingGraphics { get; protected set; }
+
+ ///
+ ///
+ ///
+ public event Action onPaint;
+
+ ///
+ ///
+ ///
+ public GObject gOwner;
+
+ ///
+ ///
+ ///
+ public uint id;
+
+ bool _visible;
+ bool _touchable;
+ Vector2 _pivot;
+ Vector3 _pivotOffset;
+ Vector3 _rotation; //由于万向锁,单独旋转一个轴是会影响到其他轴的,所以这里需要单独保存
+ Vector2 _skew;
+ int _renderingOrder;
+ float _alpha;
+ bool _grayed;
+ BlendMode _blendMode;
+ IFilter _filter;
+ Transform _home;
+ string _cursor;
+ bool _perspective;
+ int _focalLength;
+ Vector3 _pixelPerfectAdjustment;
+ int _checkPixelPerfect;
+
+ EventListener _onClick;
+ EventListener _onRightClick;
+ EventListener _onTouchBegin;
+ EventListener _onTouchMove;
+ EventListener _onTouchEnd;
+ EventListener _onRollOver;
+ EventListener _onRollOut;
+ EventListener _onMouseWheel;
+ EventListener _onAddedToStage;
+ EventListener _onRemovedFromStage;
+ EventListener _onKeyDown;
+ EventListener _onClickLink;
+ EventListener _onFocusIn;
+ EventListener _onFocusOut;
+
+ protected internal int _paintingMode; //1-滤镜,2-blendMode,4-transformMatrix, 8-cacheAsBitmap
+ protected internal PaintingInfo _paintingInfo;
+ protected Rect _contentRect;
+ protected NGraphics.VertexMatrix _vertexMatrix;
+ protected internal Flags _flags;
+ protected internal float[] _batchingBounds;
+
+ internal static uint _gInstanceCounter;
+
+ internal static HideFlags hideFlags = HideFlags.None;
+
+ public DisplayObject()
+ {
+ id = _gInstanceCounter++;
+
+ _alpha = 1;
+ _visible = true;
+ _touchable = true;
+ _blendMode = BlendMode.Normal;
+ _focalLength = 2000;
+ _flags |= Flags.OutlineChanged;
+ if (UIConfig.makePixelPerfect)
+ _flags |= Flags.PixelPerfect;
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onClick
+ {
+ get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onRightClick
+ {
+ get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onTouchBegin
+ {
+ get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onTouchMove
+ {
+ get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onTouchEnd
+ {
+ get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onRollOver
+ {
+ get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onRollOut
+ {
+ get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onMouseWheel
+ {
+ get { return _onMouseWheel ?? (_onMouseWheel = new EventListener(this, "onMouseWheel")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onAddedToStage
+ {
+ get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onRemovedFromStage
+ {
+ get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onKeyDown
+ {
+ get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onClickLink
+ {
+ get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onFocusIn
+ {
+ get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); }
+ }
+
+ ///
+ ///
+ ///
+ public EventListener onFocusOut
+ {
+ get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); }
+
+ }
+
+ protected void CreateGameObject(string gameObjectName)
+ {
+ gameObject = new GameObject(gameObjectName);
+ cachedTransform = gameObject.transform;
+ if (Application.isPlaying)
+ {
+ UnityEngine.Object.DontDestroyOnLoad(gameObject);
+
+ DisplayObjectInfo info = gameObject.AddComponent();
+ info.displayObject = this;
+ }
+ gameObject.hideFlags = DisplayObject.hideFlags;
+ gameObject.SetActive(false);
+ }
+
+ protected void SetGameObject(GameObject gameObject)
+ {
+ this.gameObject = gameObject;
+ this.cachedTransform = gameObject.transform;
+ _rotation = cachedTransform.localEulerAngles;
+
+ _flags |= Flags.UserGameObject;
+ }
+
+ protected void DestroyGameObject()
+ {
+ if ((_flags & Flags.UserGameObject) == 0 && gameObject != null)
+ {
+ if (Application.isPlaying)
+ GameObject.Destroy(gameObject);
+ else
+ GameObject.DestroyImmediate(gameObject);
+ gameObject = null;
+ cachedTransform = null;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float alpha
+ {
+ get { return _alpha; }
+ set { _alpha = value; }
+ }
+
+ ///
+ ///
+ ///
+ public bool grayed
+ {
+ get { return _grayed; }
+ set { _grayed = value; }
+ }
+
+ ///
+ ///
+ ///
+ public bool visible
+ {
+ get { return _visible; }
+ set
+ {
+ if (_visible != value)
+ {
+ _visible = value;
+ _flags |= Flags.OutlineChanged;
+ if (parent != null && _visible)
+ {
+ gameObject.SetActive(true);
+ InvalidateBatchingState();
+ if (this is Container)
+ ((Container)this).InvalidateBatchingState(true);
+ }
+ else
+ gameObject.SetActive(false);
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float x
+ {
+ get { return cachedTransform.localPosition.x; }
+ set
+ {
+ SetPosition(value, -cachedTransform.localPosition.y, cachedTransform.localPosition.z);
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float y
+ {
+ get { return -cachedTransform.localPosition.y; }
+ set
+ {
+ SetPosition(cachedTransform.localPosition.x, value, cachedTransform.localPosition.z);
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float z
+ {
+ get { return cachedTransform.localPosition.z; }
+ set
+ {
+ SetPosition(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, value);
+ }
+ }
+
+ ///
+ ///
+ ///
+ public Vector2 xy
+ {
+ get { return new Vector2(this.x, this.y); }
+ set { SetPosition(value.x, value.y, cachedTransform.localPosition.z); }
+ }
+
+ ///
+ ///
+ ///
+ public Vector3 position
+ {
+ get { return new Vector3(this.x, this.y, this.z); }
+ set { SetPosition(value.x, value.y, value.z); }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void SetXY(float xv, float yv)
+ {
+ SetPosition(xv, yv, cachedTransform.localPosition.z);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void SetPosition(float xv, float yv, float zv)
+ {
+ Vector3 v = new Vector3();
+ v.x = xv;
+ v.y = -yv;
+ v.z = zv;
+ if (v != cachedTransform.localPosition)
+ {
+ cachedTransform.localPosition = v;
+ _flags |= Flags.OutlineChanged;
+ if ((_flags & Flags.PixelPerfect) != 0)
+ {
+ //总在下一帧再完成PixelPerfect,这样当物体在连续运动时,不会因为PixelPerfect而发生抖动。
+ _checkPixelPerfect = Time.frameCount;
+ _pixelPerfectAdjustment = Vector3.zero;
+ }
+ }
+ }
+
+ ///
+ /// If the object position is align by pixel
+ ///
+ public bool pixelPerfect
+ {
+ get { return (_flags & Flags.PixelPerfect) != 0; }
+ set
+ {
+ if (value)
+ _flags |= Flags.PixelPerfect;
+ else
+ _flags &= ~Flags.PixelPerfect;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float width
+ {
+ get
+ {
+ EnsureSizeCorrect();
+ return _contentRect.width;
+ }
+ set
+ {
+ if (!Mathf.Approximately(value, _contentRect.width))
+ {
+ _contentRect.width = value;
+ _flags |= Flags.WidthChanged;
+ _flags &= ~Flags.HeightChanged;
+ OnSizeChanged();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float height
+ {
+ get
+ {
+ EnsureSizeCorrect();
+ return _contentRect.height;
+ }
+ set
+ {
+ if (!Mathf.Approximately(value, _contentRect.height))
+ {
+ _contentRect.height = value;
+ _flags &= ~Flags.WidthChanged;
+ _flags |= Flags.HeightChanged;
+ OnSizeChanged();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public Vector2 size
+ {
+ get
+ {
+ EnsureSizeCorrect();
+ return _contentRect.size;
+ }
+ set
+ {
+ SetSize(value.x, value.y);
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void SetSize(float wv, float hv)
+ {
+ if (!Mathf.Approximately(wv, _contentRect.width))
+ _flags |= Flags.WidthChanged;
+ else
+ _flags &= ~Flags.WidthChanged;
+ if (!Mathf.Approximately(hv, _contentRect.height))
+ _flags |= Flags.HeightChanged;
+ else
+ _flags &= ~Flags.HeightChanged;
+
+ if ((_flags & Flags.WidthChanged) != 0 || (_flags & Flags.HeightChanged) != 0)
+ {
+ _contentRect.width = wv;
+ _contentRect.height = hv;
+ OnSizeChanged();
+ }
+ }
+
+ virtual public void EnsureSizeCorrect()
+ {
+ }
+
+ virtual protected void OnSizeChanged()
+ {
+ ApplyPivot();
+
+ if (_paintingInfo != null)
+ _paintingInfo.flag = 1;
+ if (graphics != null)
+ graphics.contentRect = _contentRect;
+ _flags |= Flags.OutlineChanged;
+ }
+
+ ///
+ ///
+ ///
+ public float scaleX
+ {
+ get { return cachedTransform.localScale.x; }
+ set
+ {
+ Vector3 v = cachedTransform.localScale;
+ v.x = v.z = ValidateScale(value);
+ cachedTransform.localScale = v;
+ _flags |= Flags.OutlineChanged;
+ ApplyPivot();
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float scaleY
+ {
+ get { return cachedTransform.localScale.y; }
+ set
+ {
+ Vector3 v = cachedTransform.localScale;
+ v.y = ValidateScale(value);
+ cachedTransform.localScale = v;
+ _flags |= Flags.OutlineChanged;
+ ApplyPivot();
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public void SetScale(float xv, float yv)
+ {
+ Vector3 v = new Vector3();
+ v.x = v.z = ValidateScale(xv);
+ v.y = ValidateScale(yv);
+ cachedTransform.localScale = v;
+ _flags |= Flags.OutlineChanged;
+ ApplyPivot();
+ }
+
+ ///
+ /// 在scale过小情况(极端情况=0),当使用Transform的坐标变换时,变换到世界,再从世界变换到本地,会由于精度问题造成结果错误。
+ /// 这种错误会导致Batching错误,因为Batching会使用缓存的outline。
+ /// 这里限制一下scale的最小值作为当前解决方案。
+ /// 这个方案并不完美,因为限制了本地scale值并不能保证对世界scale不会过小。
+ ///
+ ///
+ ///
+ private float ValidateScale(float value)
+ {
+ if (value >= 0 && value < 0.001f)
+ value = 0.001f;
+ else if (value < 0 && value > -0.001f)
+ value = -0.001f;
+ return value;
+ }
+
+ ///
+ ///
+ ///
+ public Vector2 scale
+ {
+ get { return cachedTransform.localScale; }
+ set
+ {
+ SetScale(value.x, value.y);
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float rotation
+ {
+ get
+ {
+ //和Unity默认的旋转方向相反
+ return -_rotation.z;
+ }
+ set
+ {
+ _rotation.z = -value;
+ _flags |= Flags.OutlineChanged;
+ if (_perspective)
+ UpdateTransformMatrix();
+ else
+ {
+ cachedTransform.localEulerAngles = _rotation;
+ ApplyPivot();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float rotationX
+ {
+ get
+ {
+ return _rotation.x;
+ }
+ set
+ {
+ _rotation.x = value;
+ _flags |= Flags.OutlineChanged;
+ if (_perspective)
+ UpdateTransformMatrix();
+ else
+ {
+ cachedTransform.localEulerAngles = _rotation;
+ ApplyPivot();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public float rotationY
+ {
+ get
+ {
+ return _rotation.y;
+ }
+ set
+ {
+ _rotation.y = value;
+ _flags |= Flags.OutlineChanged;
+ if (_perspective)
+ UpdateTransformMatrix();
+ else
+ {
+ cachedTransform.localEulerAngles = _rotation;
+ ApplyPivot();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public Vector2 skew
+ {
+ get { return _skew; }
+ set
+ {
+ _skew = value;
+ _flags |= Flags.OutlineChanged;
+
+ if (!Application.isPlaying) //编辑期间不支持!!
+ return;
+
+ UpdateTransformMatrix();
+ }
+ }
+
+ ///
+ /// 当对象处于ScreenSpace,也就是使用正交相机渲染时,对象虽然可以绕X轴或者Y轴旋转,但没有透视效果。设置perspective,可以模拟出透视效果。
+ ///
+ public bool perspective
+ {
+ get
+ {
+ return _perspective;
+ }
+ set
+ {
+ if (_perspective != value)
+ {
+ _perspective = value;
+ if (_perspective)//屏蔽Unity自身的旋转变换
+ cachedTransform.localEulerAngles = Vector3.zero;
+ else
+ cachedTransform.localEulerAngles = _rotation;
+
+ ApplyPivot();
+ UpdateTransformMatrix();
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public int focalLength
+ {
+ get { return _focalLength; }
+ set
+ {
+ if (value <= 0)
+ value = 1;
+
+ _focalLength = value;
+ if (_vertexMatrix != null)
+ UpdateTransformMatrix();
+ }
+ }
+
+ void UpdateTransformMatrix()
+ {
+ Matrix4x4 matrix = Matrix4x4.identity;
+ if (_skew.x != 0 || _skew.y != 0)
+ ToolSet.SkewMatrix(ref matrix, _skew.x, _skew.y);
+ if (_perspective)
+ matrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(_rotation), Vector3.one);
+ if (matrix.isIdentity)
+ _vertexMatrix = null;
+ else if (_vertexMatrix == null)
+ _vertexMatrix = new NGraphics.VertexMatrix();
+
+ //组件的transformMatrix是通过paintingMode实现的,因为全部通过矩阵变换的话,和unity自身的变换混杂在一起,无力理清。
+ if (_vertexMatrix != null)
+ {
+ _vertexMatrix.matrix = matrix;
+ _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength);
+
+ if (graphics == null)
+ EnterPaintingMode(4, null);
+ }
+ else
+ {
+ if (graphics == null)
+ LeavePaintingMode(4);
+ }
+
+ if (_paintingMode > 0)
+ {
+ paintingGraphics.vertexMatrix = _vertexMatrix;
+ _paintingInfo.flag = 1;
+ }
+ else if (graphics != null)
+ graphics.vertexMatrix = _vertexMatrix;
+
+ _flags |= Flags.OutlineChanged;
+ }
+
+ ///
+ ///
+ ///
+ public Vector2 pivot
+ {
+ get { return _pivot; }
+ set
+ {
+ Vector3 deltaPivot = new Vector2((value.x - _pivot.x) * _contentRect.width, (_pivot.y - value.y) * _contentRect.height);
+ Vector3 oldOffset = _pivotOffset;
+
+ _pivot = value;
+ UpdatePivotOffset();
+ Vector3 v = cachedTransform.localPosition;
+ v += oldOffset - _pivotOffset + deltaPivot;
+ cachedTransform.localPosition = v;
+ _flags |= Flags.OutlineChanged;
+ }
+ }
+
+ void UpdatePivotOffset()
+ {
+ float px = _pivot.x * _contentRect.width;
+ float py = _pivot.y * _contentRect.height;
+
+ //注意这里不用处理skew,因为在顶点变换里有对pivot的处理
+ Matrix4x4 matrix = Matrix4x4.TRS(Vector3.zero, cachedTransform.localRotation, cachedTransform.localScale);
+ _pivotOffset = matrix.MultiplyPoint(new Vector3(px, -py, 0));
+
+ if (_vertexMatrix != null)
+ _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength);
+ }
+
+ void ApplyPivot()
+ {
+ if (_pivot.x != 0 || _pivot.y != 0)
+ {
+ Vector3 oldOffset = _pivotOffset;
+
+ UpdatePivotOffset();
+ Vector3 v = cachedTransform.localPosition;
+
+ if ((_flags & Flags.PixelPerfect) != 0)
+ {
+ v -= _pixelPerfectAdjustment;
+ _checkPixelPerfect = Time.frameCount;
+ _pixelPerfectAdjustment = Vector3.zero;
+ }
+
+ v += oldOffset - _pivotOffset;
+ cachedTransform.localPosition = v;
+ _flags |= Flags.OutlineChanged;
+ }
+ }
+
+ ///
+ /// This is the pivot position
+ ///
+ public Vector3 location
+ {
+ get
+ {
+ Vector3 pos = this.position;
+ pos.x += _pivotOffset.x;
+ pos.y -= _pivotOffset.y;
+ pos.z += _pivotOffset.z;
+ return pos;
+ }
+
+ set
+ {
+ this.SetPosition(value.x - _pivotOffset.x, value.y + _pivotOffset.y, value.z - _pivotOffset.z);
+ }
+ }
+
+ ///
+ ///
+ ///
+ virtual public Material material
+ {
+ get
+ {
+ if (graphics != null)
+ return graphics.material;
+ else
+ return null;
+ }
+ set
+ {
+ if (graphics != null)
+ graphics.material = value;
+ }
+ }
+
+ ///
+ ///
+ ///
+ virtual public string shader
+ {
+ get
+ {
+ if (graphics != null)
+ return graphics.shader;
+ else
+ return null;
+ }
+ set
+ {
+ if (graphics != null)
+ graphics.shader = value;
+ }
+ }
+
+ ///
+ ///
+ ///
+ virtual public int renderingOrder
+ {
+ get
+ {
+ return _renderingOrder;
+ }
+ set
+ {
+ if ((_flags & Flags.GameObjectDisposed) != 0)
+ {
+ DisplayDisposedWarning();
+ return;
+ }
+
+ _renderingOrder = value;
+ if (graphics != null)
+ graphics.sortingOrder = value;
+ if (_paintingMode > 0)
+ paintingGraphics.sortingOrder = value;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public int layer
+ {
+ get
+ {
+ if (_paintingMode > 0)
+ return paintingGraphics.gameObject.layer;
+ else
+ return gameObject.layer;
+ }
+ set
+ {
+ SetLayer(value, false);
+ }
+ }
+
+ ///
+ /// If the object can be focused?
+ ///
+ public bool focusable
+ {
+ get { return (_flags & Flags.NotFocusable) == 0; }
+ set
+ {
+ if (value)
+ _flags &= ~Flags.NotFocusable;
+ else
+ _flags |= Flags.NotFocusable;
+ }
+ }
+
+ ///
+ /// If the object can be navigated by TAB?
+ ///
+ public bool tabStop
+ {
+ get { return (_flags & Flags.TabStop) != 0; }
+ set
+ {
+ if (value)
+ _flags |= Flags.TabStop;
+ else
+ _flags &= ~Flags.TabStop;
+ }
+ }
+
+ ///
+ /// If the object focused?
+ ///
+ public bool focused
+ {
+ get
+ {
+ return Stage.inst.focus == this || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.focus);
+ }
+ }
+
+ internal bool _AcceptTab()
+ {
+ if (_touchable && _visible
+ && ((_flags & Flags.TabStop) != 0 || (_flags & Flags.TabStopChildren) != 0)
+ && (_flags & Flags.NotFocusable) == 0)
+ {
+ Stage.inst.SetFocus(this, true);
+ return true;
+ }
+ else
+ return false;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public string cursor
+ {
+ get { return _cursor; }
+ set
+ {
+ _cursor = value;
+ if (Application.isPlaying
+ && (this == Stage.inst.touchTarget || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.touchTarget)))
+ {
+ Stage.inst._ChangeCursor(_cursor);
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ public bool isDisposed
+ {
+ get { return (_flags & Flags.Disposed) != 0 || gameObject == null; }
+ }
+
+ internal void InternalSetParent(Container value)
+ {
+ if (parent != value)
+ {
+ if (value == null && (parent._flags & Flags.Disposed) != 0)
+ parent = value;
+ else
+ {
+ parent = value;
+ UpdateHierarchy();
+ }
+ _flags |= Flags.OutlineChanged;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public Container topmost
+ {
+ get
+ {
+ DisplayObject currentObject = this;
+ while (currentObject.parent != null)
+ currentObject = currentObject.parent;
+ return currentObject as Container;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public Stage stage
+ {
+ get
+ {
+ return topmost as Stage;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public Container worldSpaceContainer
+ {
+ get
+ {
+ Container wsc = null;
+ DisplayObject currentObject = this;
+ while (currentObject.parent != null)
+ {
+ if ((currentObject is Container) && ((Container)currentObject).renderMode == RenderMode.WorldSpace)
+ {
+ wsc = (Container)currentObject;
+ break;
+ }
+ currentObject = currentObject.parent;
+ }
+
+ return wsc;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public bool touchable
+ {
+ get { return _touchable; }
+ set
+ {
+ if (_touchable != value)
+ {
+ _touchable = value;
+ if (this is Container)
+ {
+ ColliderHitTest hitArea = ((Container)this).hitArea as ColliderHitTest;
+ if (hitArea != null)
+ hitArea.collider.enabled = value;
+ }
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public bool touchDisabled
+ {
+ get { return (_flags & Flags.TouchDisabled) != 0; }
+ }
+
+ ///
+ /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。
+ /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。
+ ///
+ public void EnterPaintingMode()
+ {
+ EnterPaintingMode(16384, null, 1);
+ }
+
+ ///
+ /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。
+ /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。
+ /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。
+ ///
+ /// 请求者id
+ /// 纹理四周的留空。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。
+ public void EnterPaintingMode(int requestorId, Margin? extend)
+ {
+ EnterPaintingMode(requestorId, extend, 1);
+ }
+
+ ///
+ /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。
+ /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。
+ /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。
+ ///
+ /// 请求者id
+ /// 扩展纹理。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。
+ /// 附加一个缩放系数
+ public void EnterPaintingMode(int requestorId, Margin? extend, float scale)
+ {
+ bool first = _paintingMode == 0;
+ _paintingMode |= requestorId;
+ if (first)
+ {
+ if (_paintingInfo == null)
+ {
+ _paintingInfo = new PaintingInfo()
+ {
+ captureDelegate = Capture,
+ scale = 1
+ };
+ }
+
+ if (paintingGraphics == null)
+ {
+ if (graphics == null)
+ paintingGraphics = new NGraphics(this.gameObject);
+ else
+ {
+ GameObject go = new GameObject(this.gameObject.name + " (Painter)");
+ go.layer = this.gameObject.layer;
+ go.transform.SetParent(cachedTransform, false);
+ go.hideFlags = DisplayObject.hideFlags;
+ paintingGraphics = new NGraphics(go);
+ }
+ }
+ else
+ paintingGraphics.enabled = true;
+ paintingGraphics.vertexMatrix = null;
+
+ if (this is Container)
+ {
+ ((Container)this).SetChildrenLayer(CaptureCamera.hiddenLayer);
+ ((Container)this).UpdateBatchingFlags();
+ }
+ else
+ this.InvalidateBatchingState();
+
+ if (graphics != null)
+ this.gameObject.layer = CaptureCamera.hiddenLayer;
+ }
+ if (extend != null)
+ _paintingInfo.extend = (Margin)extend;
+ _paintingInfo.scale = scale;
+ _paintingInfo.flag = 1;
+ }
+
+ ///
+ /// 离开绘画模式
+ ///
+ ///
+ public void LeavePaintingMode(int requestorId)
+ {
+ if (_paintingMode == 0 || (_flags & Flags.Disposed) != 0)
+ return;
+
+ _paintingMode ^= requestorId;
+ if (_paintingMode == 0)
+ {
+ paintingGraphics.enabled = false;
+
+ if (this is Container)
+ {
+ ((Container)this).SetChildrenLayer(this.layer);
+ ((Container)this).UpdateBatchingFlags();
+ }
+ else
+ this.InvalidateBatchingState();
+
+ if (graphics != null)
+ this.gameObject.layer = paintingGraphics.gameObject.layer;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public bool paintingMode
+ {
+ get { return _paintingMode > 0; }
+ }
+
+ ///
+ /// 将整个显示对象(如果是容器,则容器包含的整个显示列表)静态化,所有内容被缓冲到一张纹理上。
+ /// DC将保持为1。CPU消耗将降到最低。但对象的任何变化不会更新。
+ /// 当cacheAsBitmap已经为true时,再次调用cacheAsBitmap=true将会刷新对象一次。
+ ///
+ public bool cacheAsBitmap
+ {
+ get { return (_flags & Flags.CacheAsBitmap) != 0; }
+ set
+ {
+ if (value)
+ {
+ _flags |= Flags.CacheAsBitmap;
+ EnterPaintingMode(8, null, UIContentScaler.scaleFactor);
+ }
+ else
+ {
+ _flags &= ~Flags.CacheAsBitmap;
+ LeavePaintingMode(8);
+ }
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public Texture2D GetScreenShot(Margin? extend, float scale)
+ {
+ EnterPaintingMode(8, null, scale);
+ UpdatePainting();
+ Capture();
+
+ Texture2D output;
+ if (paintingGraphics.texture == null)
+ output = new Texture2D(1, 1, TextureFormat.RGBA32, false, true);
+ else
+ {
+ RenderTexture rt = (RenderTexture)paintingGraphics.texture.nativeTexture;
+ output = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false, true);
+ RenderTexture old = RenderTexture.active;
+ RenderTexture.active = rt;
+ output.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
+ output.Apply();
+ RenderTexture.active = old;
+ }
+
+ LeavePaintingMode(8);
+
+ return output;
+ }
+
+ ///
+ ///
+ ///
+ public IFilter filter
+ {
+ get
+ {
+ return _filter;
+ }
+
+ set
+ {
+ if (!Application.isPlaying) //编辑期间不支持!!
+ return;
+
+ if (value == _filter)
+ return;
+
+ if (_filter != null)
+ _filter.Dispose();
+
+ if (value != null && value.target != null)
+ value.target.filter = null;
+
+ _filter = value;
+ if (_filter != null)
+ _filter.target = this;
+ }
+ }
+
+ ///
+ ///
+ ///
+ public BlendMode blendMode
+ {
+ get { return _blendMode; }
+ set
+ {
+ _blendMode = value;
+ InvalidateBatchingState();
+
+ if (graphics == null)
+ {
+ if (_blendMode != BlendMode.Normal)
+ {
+ if (!Application.isPlaying) //Not supported in edit mode!
+ return;
+
+ EnterPaintingMode(2, null);
+ paintingGraphics.blendMode = _blendMode;
+ }
+ else
+ LeavePaintingMode(2);
+ }
+ else
+ graphics.blendMode = _blendMode;
+ }
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ virtual public Rect GetBounds(DisplayObject targetSpace)
+ {
+ EnsureSizeCorrect();
+
+ if (targetSpace == this) // optimization
+ {
+ return _contentRect;
+ }
+ else if (targetSpace == parent && _rotation.z == 0)
+ {
+ return new Rect(cachedTransform.localPosition.x, -cachedTransform.localPosition.y,
+ _contentRect.width * cachedTransform.localScale.x, _contentRect.height * cachedTransform.localScale.y);
+ }
+ else
+ return TransformRect(_contentRect, targetSpace);
+ }
+
+ internal DisplayObject InternalHitTest()
+ {
+ if (_visible && (!HitTestContext.forTouch || _touchable))
+ return HitTest();
+ else
+ return null;
+ }
+
+ internal DisplayObject InternalHitTestMask()
+ {
+ if (_visible)
+ return HitTest();
+ else
+ return null;
+ }
+
+ virtual protected DisplayObject HitTest()
+ {
+ Rect rect = GetBounds(this);
+ if (rect.width == 0 || rect.height == 0)
+ return null;
+
+ Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction);
+ if (rect.Contains(localPoint))
+ return this;
+ else
+ return null;
+ }
+
+ ///
+ /// 将舞台坐标转换为本地坐标
+ ///
+ ///
+ ///
+ public Vector2 GlobalToLocal(Vector2 point)
+ {
+ Container wsc = this.worldSpaceContainer;
+
+ if (wsc != null)//I am in a world space
+ {
+ Camera cam = wsc.GetRenderCamera();
+ Vector3 worldPoint;
+ Vector3 direction;
+ Vector3 screenPoint = new Vector3();
+ screenPoint.x = point.x;
+ screenPoint.y = Screen.height - point.y;
+
+ if (wsc.hitArea is MeshColliderHitTest)
+ {
+ Ray ray = cam.ScreenPointToRay(screenPoint);
+ RaycastHit hit;
+ if (((MeshColliderHitTest)wsc.hitArea).collider.Raycast(ray, out hit, 100))
+ {
+ point = new Vector2(hit.textureCoord.x * _contentRect.width, (1 - hit.textureCoord.y) * _contentRect.height);
+ worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0);
+ direction = Vector3.back;
+ }
+ else //当射线没有击中模型时,无法确定本地坐标
+ return new Vector2(float.NaN, float.NaN);
+ }
+ else
+ {
+ screenPoint.z = cam.WorldToScreenPoint(this.cachedTransform.position).z;
+ worldPoint = cam.ScreenToWorldPoint(screenPoint);
+ Ray ray = cam.ScreenPointToRay(screenPoint);
+ direction = Vector3.zero - ray.direction;
+ }
+
+ return this.WorldToLocal(worldPoint, direction);
+ }
+ else //I am in stage space
+ {
+ Vector3 worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0);
+ return this.WorldToLocal(worldPoint, Vector3.back);
+ }
+ }
+
+ ///
+ /// 将本地坐标转换为舞台坐标
+ ///
+ ///
+ ///
+ public Vector2 LocalToGlobal(Vector2 point)
+ {
+ Container wsc = this.worldSpaceContainer;
+
+ Vector3 worldPoint = this.cachedTransform.TransformPoint(point.x, -point.y, 0);
+ if (wsc != null)
+ {
+ if (wsc.hitArea is MeshColliderHitTest) //Not supported for UIPainter, use TransfromPoint instead.
+ return new Vector2(float.NaN, float.NaN);
+
+ Vector3 screePoint = wsc.GetRenderCamera().WorldToScreenPoint(worldPoint);
+ return new Vector2(screePoint.x, Stage.inst.size.y - screePoint.y);
+ }
+ else
+ {
+ point = Stage.inst.cachedTransform.InverseTransformPoint(worldPoint);
+ point.y = -point.y;
+ return point;
+ }
+ }
+
+ ///
+ /// 转换世界坐标点到等效的本地xy平面的点。等效的意思是他们在屏幕方向看到的位置一样。
+ /// 返回的点是在对象的本地坐标空间,且z=0
+ ///
+ ///
+ ///
+ ///
+ public Vector3 WorldToLocal(Vector3 worldPoint, Vector3 direction)
+ {
+ Vector3 localPoint = this.cachedTransform.InverseTransformPoint(worldPoint);
+ if (localPoint.z != 0) //如果对象绕x轴或y轴旋转过,或者对象是在透视相机,那么z值可能不为0,
+ {
+ //将世界坐标的摄影机方向在本地空间上投射,求出与xy平面的交点
+ direction = this.cachedTransform.InverseTransformDirection(direction);
+ float distOnLine = Vector3.Dot(Vector3.zero - localPoint, Vector3.forward) / Vector3.Dot(direction, Vector3.forward);
+ if (float.IsInfinity(distOnLine))
+ return Vector2.zero;
+
+ localPoint = localPoint + direction * distOnLine;
+ }
+ else if (_vertexMatrix != null)
+ {
+ Vector3 center = _vertexMatrix.cameraPos;
+ center.z = 0;
+ center -= _vertexMatrix.matrix.MultiplyPoint(center);
+
+ Matrix4x4 mm = _vertexMatrix.matrix.inverse;
+
+ localPoint -= center;
+ localPoint = mm.MultiplyPoint(localPoint);
+
+ Vector3 camPos = mm.MultiplyPoint(_vertexMatrix.cameraPos);
+ Vector3 vec = localPoint - camPos;
+ float lambda = -camPos.z / vec.z;
+ localPoint = camPos + lambda * vec;
+ localPoint.z = 0;
+ }
+ localPoint.y = -localPoint.y;
+
+ return localPoint;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public Vector3 LocalToWorld(Vector3 localPoint)
+ {
+ localPoint.y = -localPoint.y;
+ if (_vertexMatrix != null)
+ {
+ Vector3 center = _vertexMatrix.cameraPos;
+ center.z = 0;
+ center -= _vertexMatrix.matrix.MultiplyPoint(center);
+
+ localPoint = _vertexMatrix.matrix.MultiplyPoint(localPoint);
+ localPoint += center;
+
+ Vector3 camPos = _vertexMatrix.cameraPos;
+ Vector3 vec = localPoint - camPos;
+ float lambda = -camPos.z / vec.z;
+ localPoint = camPos + lambda * vec;
+ localPoint.z = 0;
+ }
+
+ return this.cachedTransform.TransformPoint(localPoint);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ /// null if to world space
+ ///
+ public Vector2 TransformPoint(Vector2 point, DisplayObject targetSpace)
+ {
+ if (targetSpace == this)
+ return point;
+
+ point = LocalToWorld(point);
+ if (targetSpace != null)
+ point = targetSpace.WorldToLocal(point, Vector3.back);
+
+ return point;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ /// null if to world space
+ ///
+ public Rect TransformRect(Rect rect, DisplayObject targetSpace)
+ {
+ if (targetSpace == this)
+ return rect;
+
+ if (targetSpace == parent && _rotation.z == 0) // optimization
+ {
+ Vector3 vec = cachedTransform.localScale;
+ return new Rect((this.x + rect.x) * vec.x, (this.y + rect.y) * vec.y,
+ rect.width * vec.x, rect.height * vec.y);
+ }
+ else
+ {
+ Vector4 vec4 = new Vector4(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue);
+
+ TransformRectPoint(rect.xMin, rect.yMin, targetSpace, ref vec4);
+ TransformRectPoint(rect.xMax, rect.yMin, targetSpace, ref vec4);
+ TransformRectPoint(rect.xMin, rect.yMax, targetSpace, ref vec4);
+ TransformRectPoint(rect.xMax, rect.yMax, targetSpace, ref vec4);
+
+ return Rect.MinMaxRect(vec4.x, vec4.y, vec4.z, vec4.w);
+ }
+ }
+
+ protected void TransformRectPoint(float px, float py, DisplayObject targetSpace, ref Vector4 vec4)
+ {
+ Vector2 v = TransformPoint(new Vector2(px, py), targetSpace);
+
+ if (vec4.x > v.x) vec4.x = v.x;
+ if (vec4.z < v.x) vec4.z = v.x;
+ if (vec4.y > v.y) vec4.y = v.y;
+ if (vec4.w < v.y) vec4.w = v.y;
+ }
+
+ ///
+ ///
+ ///
+ public void RemoveFromParent()
+ {
+ if (parent != null)
+ parent.RemoveChild(this);
+ }
+
+ ///
+ ///
+ ///
+ public void InvalidateBatchingState()
+ {
+ if (parent != null)
+ parent.InvalidateBatchingState(true);
+ }
+
+ virtual public void Update(UpdateContext context)
+ {
+ if (_checkPixelPerfect != 0)
+ {
+ if (_rotation == Vector3.zero)
+ {
+ Vector3 v = cachedTransform.localPosition;
+ v.x = Mathf.Round(v.x);
+ v.y = Mathf.Round(v.y);
+ _pixelPerfectAdjustment = v - cachedTransform.localPosition;
+ if (_pixelPerfectAdjustment != Vector3.zero)
+ cachedTransform.localPosition = v;
+ }
+ _checkPixelPerfect = 0;
+ }
+
+ if (graphics != null)
+ graphics.Update(context, context.alpha * _alpha, context.grayed | _grayed);
+
+ if (_paintingMode != 0)
+ {
+ UpdatePainting();
+
+ //如果是容器,Capture要等到Container.Update的最后执行,因为容器中可能也有需要Capture的内容,要等他们完成后再进行容器的Capture。
+ if (!(this is Container))
+ {
+ if ((_flags & Flags.CacheAsBitmap) == 0 || _paintingInfo.flag != 2)
+ UpdateContext.OnEnd += _paintingInfo.captureDelegate;
+ }
+
+ paintingGraphics.Update(context, 1, false);
+ }
+
+ if (_filter != null)
+ _filter.Update();
+
+ Stats.ObjectCount++;
+ }
+
+ void UpdatePainting()
+ {
+ NTexture paintingTexture = paintingGraphics.texture;
+ if (paintingTexture != null && paintingTexture.disposed) //Texture可能已被Stage.MonitorTexture销毁
+ {
+ paintingTexture = null;
+ _paintingInfo.flag = 1;
+ }
+
+ if (_paintingInfo.flag == 1)
+ {
+ _paintingInfo.flag = 0;
+
+ //从优化考虑,决定使用绘画模式的容器都需要明确指定大小,而不是自动计算包围。这在UI使用上并没有问题,因为组件总是有固定大小的
+ Margin extend = _paintingInfo.extend;
+ paintingGraphics.contentRect = new Rect(-extend.left, -extend.top, _contentRect.width + extend.left + extend.right, _contentRect.height + extend.top + extend.bottom);
+ int textureWidth = Mathf.RoundToInt(paintingGraphics.contentRect.width * _paintingInfo.scale);
+ int textureHeight = Mathf.RoundToInt(paintingGraphics.contentRect.height * _paintingInfo.scale);
+ if (paintingTexture == null || paintingTexture.width != textureWidth || paintingTexture.height != textureHeight)
+ {
+ if (paintingTexture != null)
+ paintingTexture.Dispose();
+ if (textureWidth > 0 && textureHeight > 0)
+ {
+ paintingTexture = new NTexture(CaptureCamera.CreateRenderTexture(textureWidth, textureHeight, UIConfig.depthSupportForPaintingMode));
+ Stage.inst.MonitorTexture(paintingTexture);
+ }
+ else
+ paintingTexture = null;
+ paintingGraphics.texture = paintingTexture;
+ }
+ }
+
+ if (paintingTexture != null)
+ paintingTexture.lastActive = Time.time;
+ }
+
+ void Capture()
+ {
+ if (paintingGraphics.texture == null)
+ return;
+
+ Vector2 offset = new Vector2(_paintingInfo.extend.left, _paintingInfo.extend.top);
+ CaptureCamera.Capture(this, (RenderTexture)paintingGraphics.texture.nativeTexture, paintingGraphics.contentRect.height, offset);
+
+ _paintingInfo.flag = 2; //2表示已完成一次Capture
+ if (onPaint != null)
+ onPaint();
+ }
+
+ ///
+ /// 为对象设置一个默认的父Transform。当对象不在显示列表里时,它的GameObject挂到哪里。
+ ///
+ public Transform home
+ {
+ get { return _home; }
+ set
+ {
+ _home = value;
+ if (value != null && cachedTransform.parent == null)
+ cachedTransform.SetParent(value, false);
+ }
+ }
+
+ void UpdateHierarchy()
+ {
+ if ((_flags & Flags.GameObjectDisposed) != 0)
+ return;
+
+ if ((_flags & Flags.UserGameObject) != 0)
+ {
+ //we dont change transform parent of this object
+ if (gameObject != null)
+ {
+ if (parent != null && visible)
+ gameObject.SetActive(true);
+ else
+ gameObject.SetActive(false);
+ }
+ }
+ else if (parent != null)
+ {
+ cachedTransform.SetParent(parent.cachedTransform, false);
+
+ if (_visible)
+ gameObject.SetActive(true);
+
+ int layerValue = parent.gameObject.layer;
+ if (parent._paintingMode != 0)
+ layerValue = CaptureCamera.hiddenLayer;
+ SetLayer(layerValue, true);
+ }
+ else if ((_flags & Flags.Disposed) == 0 && this.gameObject != null && !StageEngine.beingQuit)
+ {
+ if (Application.isPlaying)
+ {
+ if (gOwner == null || gOwner.parent == null)//如果gOwner还有parent的话,说明只是暂时的隐藏
+ {
+ cachedTransform.SetParent(_home, false);
+ if (_home == null)
+ UnityEngine.Object.DontDestroyOnLoad(this.gameObject);
+ }
+ }
+
+ gameObject.SetActive(false);
+ }
+ }
+
+ virtual protected bool SetLayer(int value, bool fromParent)
+ {
+ if ((_flags & Flags.LayerSet) != 0) //setted
+ {
+ if (fromParent)
+ return false;
+ }
+ else if ((_flags & Flags.LayerFromParent) != 0) //inherit from parent
+ {
+ if (!fromParent)
+ _flags |= Flags.LayerSet;
+ }
+ else
+ {
+ if (fromParent)
+ _flags |= Flags.LayerFromParent;
+ else
+ _flags |= Flags.LayerSet;
+ }
+
+ if (_paintingMode > 0)
+ paintingGraphics.gameObject.layer = value;
+ else if (gameObject.layer != value)
+ {
+ gameObject.layer = value;
+ if ((this is Container))
+ {
+ int cnt = ((Container)this).numChildren;
+ for (int i = 0; i < cnt; i++)
+ {
+ DisplayObject child = ((Container)this).GetChildAt(i);
+ child.SetLayer(value, true);
+ }
+ }
+ }
+
+ return true;
+ }
+
+ internal void _SetLayerDirect(int value)
+ {
+ if (_paintingMode > 0)
+ paintingGraphics.gameObject.layer = value;
+ else
+ gameObject.layer = value;
+ }
+
+ virtual public void Dispose()
+ {
+ if ((_flags & Flags.Disposed) != 0)
+ return;
+
+ _flags |= Flags.Disposed;
+ RemoveFromParent();
+ RemoveEventListeners();
+ if (graphics != null)
+ graphics.Dispose();
+ if (_filter != null)
+ _filter.Dispose();
+ if (paintingGraphics != null)
+ {
+ if (paintingGraphics.texture != null)
+ paintingGraphics.texture.Dispose();
+
+ paintingGraphics.Dispose();
+ if (paintingGraphics.gameObject != this.gameObject)
+ {
+ if (Application.isPlaying)
+ UnityEngine.Object.Destroy(paintingGraphics.gameObject);
+ else
+ UnityEngine.Object.DestroyImmediate(paintingGraphics.gameObject);
+ }
+ }
+ DestroyGameObject();
+ }
+
+ internal void DisplayDisposedWarning()
+ {
+ if ((_flags & Flags.DisposedWarning) == 0)
+ {
+ _flags |= Flags.DisposedWarning;
+
+ StringBuilder sb = new StringBuilder();
+ sb.Append("DisplayObject is still in use but GameObject was disposed. (");
+ if (gOwner != null)
+ {
+ sb.Append("type=").Append(gOwner.GetType().Name).Append(", x=").Append(gOwner.x).Append(", y=").Append(gOwner.y).Append(", name=").Append(gOwner.name);
+ if (gOwner.packageItem != null)
+ sb.Append(", res=" + gOwner.packageItem.name);
+ }
+ else
+ {
+ sb.Append("id=").Append(id).Append(", type=").Append(this.GetType().Name).Append(", name=").Append(name);
+ }
+ sb.Append(")");
+ Debug.LogError(sb.ToString());
+ }
+ }
+
+ protected internal class PaintingInfo
+ {
+ public Action captureDelegate; //缓存这个delegate,可以防止Capture状态下每帧104B的GC
+ public Margin extend;
+ public float scale;
+ public int flag;
+ }
+
+ [Flags]
+ protected internal enum Flags
+ {
+ Disposed = 1,
+ UserGameObject = 2,
+ TouchDisabled = 4,
+ OutlineChanged = 8,
+ UpdatingSize = 0x10,
+ WidthChanged = 0x20,
+ HeightChanged = 0x40,
+ PixelPerfect = 0x80,
+ LayerSet = 0x100,
+ LayerFromParent = 0x200,
+ NotFocusable = 0x400,
+ TabStop = 0x800,
+ TabStopChildren = 0x1000,
+ FairyBatching = 0x2000,
+ BatchingRequested = 0x4000,
+ BatchingRoot = 0x8000,
+ SkipBatching = 0x10000,
+ CacheAsBitmap = 0x20000,
+ GameObjectDisposed = 0x40000,
+ DisposedWarning = 0x80000
+ }
+ }
+
+ ///
+ ///
+ ///
+ public class DisplayObjectInfo : MonoBehaviour
+ {
+ ///
+ ///
+ /// ///
+ [System.NonSerialized]
+ public DisplayObject displayObject;
+
+ private void OnDestroy()
+ {
+ if (displayObject != null)
+ displayObject._flags |= DisplayObject.Flags.GameObjectDisposed;
+ }
+ }
+}
diff --git a/Assets/Scripts/Core/DisplayObject.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs.meta
similarity index 100%
rename from Assets/Scripts/Core/DisplayObject.cs.meta
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs.meta
diff --git a/Assets/Scripts/Core/GoWrapper.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/GoWrapper.cs
similarity index 97%
rename from Assets/Scripts/Core/GoWrapper.cs
rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/GoWrapper.cs
index 077790d6..e80fc194 100644
--- a/Assets/Scripts/Core/GoWrapper.cs
+++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/GoWrapper.cs
@@ -1,389 +1,389 @@
-using UnityEngine;
-using System;
-using System.Collections;
-using System.Collections.Generic;
-
-namespace FairyGUI
-{
- ///
- /// GoWrapper is class for wrapping common gameobject into UI display list.
- ///
- 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 onUpdate;
- public Action> customCloneMaterials;
- public Action customRecoverMaterials;
-
- protected GameObject _wrapTarget;
- protected List _renderers;
- protected Dictionary _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 helperTransformList = new List();
-
- ///
- ///
- ///
- public GoWrapper()
- {
- // _flags |= Flags.SkipBatching;
-
- _renderers = new List();
- _materialsBackup = new Dictionary();
-
- CreateGameObject("GoWrapper");
- }
-
- ///
- ///
- ///
- /// 包装对象。
- public GoWrapper(GameObject go) : this()
- {
- SetWrapTarget(go, false);
- }
-
- ///
- /// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。
- /// 对象包含的所有材质不会被复制,如果材质已经是公用的,这可能影响到其他对象。如果希望自动复制,改为使用SetWrapTarget(target, true)设置。
- ///
- 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);
- }
-
- ///
- /// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。
- ///
- ///
- /// 如果true,则复制材质,否则直接使用sharedMaterial。
- 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