From eccd1fecf5a740af997e32398cc307eb04398543 Mon Sep 17 00:00:00 2001 From: chrisgregan Date: Tue, 12 Apr 2016 16:21:56 +0100 Subject: [PATCH] Change type registration to use JSON --- .../FungusLua/Resources/Types/FungusTypes.txt | 81 +- .../FungusLua/Resources/Types/UnityTypes.txt | 130 +- .../FungusLua/Scripts/LuaEnvironment.cs | 12 +- Assets/Fungus/FungusLua/Scripts/LuaUtils.cs | 72 +- Assets/Fungus/FungusLua/Thirdparty/JSON.meta | 9 + .../FungusLua/Thirdparty/JSON/JSONObject.cs | 1115 +++++++++++++++++ .../Thirdparty/JSON/JSONObject.cs.meta | 2 + .../FungusLua/Thirdparty/JSON/readme.txt | 188 +++ .../FungusLua/Thirdparty/JSON/readme.txt.meta | 2 + Assets/Tests/Lua/LuaEnvironmentTests.unity | 166 ++- 10 files changed, 1639 insertions(+), 138 deletions(-) create mode 100644 Assets/Fungus/FungusLua/Thirdparty/JSON.meta create mode 100644 Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs create mode 100644 Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs.meta create mode 100644 Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt create mode 100644 Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt.meta diff --git a/Assets/Fungus/FungusLua/Resources/Types/FungusTypes.txt b/Assets/Fungus/FungusLua/Resources/Types/FungusTypes.txt index 69f519cb..23a2c0f6 100644 --- a/Assets/Fungus/FungusLua/Resources/Types/FungusTypes.txt +++ b/Assets/Fungus/FungusLua/Resources/Types/FungusTypes.txt @@ -1,43 +1,38 @@ -# List of c# types to register with MoonSharp -# LuaBindings usually takes care of registering the types of bound objects, but in some -# cases you'll need to register a type manually by adding it to this list. -# You can also register types using MoonSharp's UserData class in the Awake method of a component. -# To register an extension type, add the E: prefix -# If the type is defined in the main assembly then you can just use namespace.typename -# If the type is defined in any other assembly you need to use the full assembly qualified type name. - -Fungus.AnimatorVariable -Fungus.AudioSourceVariable -Fungus.Block -Fungus.BooleanVariable -Fungus.Character -Fungus.ColorVariable -Fungus.Command -Fungus.CommandInfoAttribute -Fungus.FacingDirection -Fungus.FloatVariable -Fungus.Flowchart -Fungus.FungusPrefs -Fungus.LuaEnvironment -Fungus.LuaUtils -Fungus.GameObjectVariable -Fungus.IntegerVariable -Fungus.Label -Fungus.MaterialVariable -Fungus.MenuDialog -Fungus.ObjectVariable -Fungus.PODTypeFactory -Fungus.PortraitState -Fungus.SayDialog -Fungus.SpriteVariable -Fungus.StringVariable -Fungus.Task -Fungus.TextureVariable -Fungus.TransformVariable -Fungus.Variable -Fungus.Vector2Variable -Fungus.Vector3Variable - -# Extension types - -E:Fungus.LuaExtensions +{ + "registerTypes" : [ + "Fungus.AnimatorVariable", + "Fungus.AudioSourceVariable", + "Fungus.Block", + "Fungus.BooleanVariable", + "Fungus.Character", + "Fungus.ColorVariable", + "Fungus.Command", + "Fungus.CommandInfoAttribute", + "Fungus.FacingDirection", + "Fungus.FloatVariable", + "Fungus.Flowchart", + "Fungus.FungusPrefs", + "Fungus.LuaEnvironment", + "Fungus.LuaUtils", + "Fungus.GameObjectVariable", + "Fungus.IntegerVariable", + "Fungus.Label", + "Fungus.MaterialVariable", + "Fungus.MenuDialog", + "Fungus.ObjectVariable", + "Fungus.PODTypeFactory", + "Fungus.PortraitState", + "Fungus.SayDialog", + "Fungus.SpriteVariable", + "Fungus.StringVariable", + "Fungus.Task", + "Fungus.TextureVariable", + "Fungus.TransformVariable", + "Fungus.Variable", + "Fungus.Vector2Variable", + "Fungus.Vector3Variable" + ], + "extensionTypes" : [ + "Fungus.LuaExtensions" + ] +} \ No newline at end of file diff --git a/Assets/Fungus/FungusLua/Resources/Types/UnityTypes.txt b/Assets/Fungus/FungusLua/Resources/Types/UnityTypes.txt index 1d10e589..e268512a 100644 --- a/Assets/Fungus/FungusLua/Resources/Types/UnityTypes.txt +++ b/Assets/Fungus/FungusLua/Resources/Types/UnityTypes.txt @@ -1,67 +1,63 @@ -# List of c# types to register with MoonSharp -# LuaBindings usually takes care of registering the types of bound objects, but in some -# cases you'll need to register a type manually by adding it to this list. -# You can also register types using MoonSharp's UserData class in the Awake method of a component. -# To register an extension type, add the E: prefix -# If the type is defined in the main assembly then you can just use namespace.typename -# If the type is defined in any other assembly you need to use the full assembly qualified type name. - -System.Action, System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -System.Collections.IEnumerator, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -System.IntPtr, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -System.Single, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -System.UInt32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 -UnityEngine.AudioClip, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.AudioClipLoadType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.AudioDataLoadState, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.AudioSource, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Bounds, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Canvas, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Color, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Component, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.ComputeBuffer, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Coroutine, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.EventSystems.BaseEventData, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.EventSystems.PointerEventData, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Font, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.FontStyle, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.GameObject, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.HorizontalWrapMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Material, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.MaterialGlobalIlluminationFlags, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Matrix4x4, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.MonoBehaviour, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Object, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.PrimitiveType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Quaternion, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Rect, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.RectTransform, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.SceneManagement.Scene, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.ScriptableObject, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.SendMessageOptions, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Shader, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Sprite, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.SpriteMeshType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.SpritePackingMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.SpritePackingRotation, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.TextAnchor, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.TextGenerationSettings, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.TextGenerator, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Texture, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Texture2D, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.TextureFormat, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Time, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Transform, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.UI.Button, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.UI.Image, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.UI.Slider, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.UI.Text, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Vector2, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Vector3, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.Vector4, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -UnityEngine.VerticalWrapMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - -# Extension types +{ + "registerTypes" : [ + "System.Action, System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "System.Collections.IEnumerator, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "System.IntPtr, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "System.Single, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "System.UInt32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "UnityEngine.AudioClip, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.AudioClipLoadType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.AudioDataLoadState, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.AudioSource, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Bounds, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Canvas, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Color, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Component, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.ComputeBuffer, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Coroutine, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.EventSystems.BaseEventData, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.EventSystems.PointerEventData, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Font, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.FontStyle, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.GameObject, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.HorizontalWrapMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Material, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.MaterialGlobalIlluminationFlags, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Matrix4x4, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.MonoBehaviour, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Object, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.PrimitiveType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Quaternion, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Rect, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.RectTransform, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.SceneManagement.Scene, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.ScriptableObject, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.SendMessageOptions, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Shader, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Sprite, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.SpriteMeshType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.SpritePackingMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.SpritePackingRotation, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.TextAnchor, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.TextGenerationSettings, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.TextGenerator, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Texture, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Texture2D, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.TextureFormat, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Time, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Transform, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.UI.Button, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.UI.Image, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.UI.Slider, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.UI.Text, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Vector2, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Vector3, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.Vector4, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "UnityEngine.VerticalWrapMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" + ], + "extensionTypes" : [ + ] +} diff --git a/Assets/Fungus/FungusLua/Scripts/LuaEnvironment.cs b/Assets/Fungus/FungusLua/Scripts/LuaEnvironment.cs index 185dc665..21c57073 100644 --- a/Assets/Fungus/FungusLua/Scripts/LuaEnvironment.cs +++ b/Assets/Fungus/FungusLua/Scripts/LuaEnvironment.cs @@ -167,17 +167,9 @@ namespace Fungus /// /// Register a type given it's assembly qualified name. /// - public static void RegisterType(string typeName) + public static void RegisterType(string typeName, bool extensionType = false) { - bool extensionType = false; - string registerName = typeName; - if (typeName.StartsWith("E:")) - { - extensionType = true; - registerName = registerName.Substring(2); - } - - System.Type t = System.Type.GetType(registerName); + System.Type t = System.Type.GetType(typeName); if (t == null) { UnityEngine.Debug.LogWarning("Type not found: " + typeName); diff --git a/Assets/Fungus/FungusLua/Scripts/LuaUtils.cs b/Assets/Fungus/FungusLua/Scripts/LuaUtils.cs index 582986a8..b8aabd9f 100644 --- a/Assets/Fungus/FungusLua/Scripts/LuaUtils.cs +++ b/Assets/Fungus/FungusLua/Scripts/LuaUtils.cs @@ -112,24 +112,62 @@ namespace Fungus continue; } - char[] separators = { '\r', '\n' }; - foreach (string typeName in textFile.text.Split(separators, StringSplitOptions.RemoveEmptyEntries)) - { - // Skip comments and empty lines - if (typeName.StartsWith("#") || typeName.Trim() == "") - { - continue; - } + // Parse JSON file + JSONObject jsonObject = new JSONObject(textFile.text); + if (jsonObject == null || + jsonObject.type != JSONObject.Type.OBJECT) + { + UnityEngine.Debug.LogError("Error parsing JSON file " + textFile.name); + continue; + } - // Don't register fungus types if the Fungus library is not present - if (!isFungusInstalled && - typeName.Contains("Fungus.")) - { - continue; - } - - LuaEnvironment.RegisterType(typeName); - } + // Register types with MoonSharp + JSONObject registerTypesArray = jsonObject.GetField("registerTypes"); + if (registerTypesArray != null && + registerTypesArray.type == JSONObject.Type.ARRAY) + { + foreach (JSONObject entry in registerTypesArray.list) + { + if (entry != null && + entry.type == JSONObject.Type.STRING) + { + string typeName = entry.str.Trim(); + + // Don't register fungus types if the Fungus library is not present + if (!isFungusInstalled && + typeName.StartsWith("Fungus.")) + { + continue; + } + + LuaEnvironment.RegisterType(typeName); + } + } + } + + // Register extension types with MoonSharp + JSONObject extensionTypesArray = jsonObject.GetField("extensionTypes"); + if (extensionTypesArray != null && + extensionTypesArray.type == JSONObject.Type.ARRAY) + { + foreach (JSONObject entry in extensionTypesArray.list) + { + if (entry != null && + entry.type == JSONObject.Type.STRING) + { + string typeName = entry.str.Trim(); + + // Don't register fungus types if the Fungus library is not present + if (!isFungusInstalled && + typeName.StartsWith("Fungus.")) + { + continue; + } + + LuaEnvironment.RegisterType(typeName, true); + } + } + } } } diff --git a/Assets/Fungus/FungusLua/Thirdparty/JSON.meta b/Assets/Fungus/FungusLua/Thirdparty/JSON.meta new file mode 100644 index 00000000..c8ee87fa --- /dev/null +++ b/Assets/Fungus/FungusLua/Thirdparty/JSON.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 0457c4629ab644fa2943c7447039a533 +folderAsset: yes +timeCreated: 1460471395 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs b/Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs new file mode 100644 index 00000000..79fdc906 --- /dev/null +++ b/Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs @@ -0,0 +1,1115 @@ +#define PRETTY //Comment out when you no longer need to read JSON to disable pretty Print system-wide +//Using doubles will cause errors in VectorTemplates.cs; Unity speaks floats +#define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output) +//#define POOLING //Currently using a build setting for this one (also it's experimental) + +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 +using UnityEngine; +using Debug = UnityEngine.Debug; +#endif +using System.Diagnostics; +using System.Collections; +using System.Collections.Generic; +using System.Text; +/* + * http://www.opensource.org/licenses/lgpl-2.1.php + * JSONObject class v.1.4.1 + * for use with Unity + * Copyright Matt Schoen 2010 - 2013 + */ + +// Added to Fungus namespace to minimize conflicts with other assets +namespace Fungus +{ + +public class JSONObject { +#if POOLING + const int MAX_POOL_SIZE = 10000; + public static Queue releaseQueue = new Queue(); +#endif + + const int MAX_DEPTH = 100; + const string INFINITY = "\"INFINITY\""; + const string NEGINFINITY = "\"NEGINFINITY\""; + const string NaN = "\"NaN\""; + const string NEWLINE = "\r\n"; + public static readonly char[] WHITESPACE = { ' ', '\r', '\n', '\t', '\uFEFF', '\u0009' }; + public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL, BAKED } + public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } } + public Type type = Type.NULL; + public int Count { + get { + if(list == null) + return -1; + return list.Count; + } + } + public List list; + public List keys; + public string str; +#if USEFLOAT + public float n; + public float f { + get { + return n; + } + } +#else + public double n; + public float f { + get { + return (float)n; + } + } +#endif + public bool useInt; + public long i; + public bool b; + public delegate void AddJSONContents(JSONObject self); + + public static JSONObject nullJO { get { return Create(Type.NULL); } } //an empty, null object + public static JSONObject obj { get { return Create(Type.OBJECT); } } //an empty object + public static JSONObject arr { get { return Create(Type.ARRAY); } } //an empty array + + public JSONObject(Type t) { + type = t; + switch(t) { + case Type.ARRAY: + list = new List(); + break; + case Type.OBJECT: + list = new List(); + keys = new List(); + break; + } + } + public JSONObject(bool b) { + type = Type.BOOL; + this.b = b; + } +#if USEFLOAT + public JSONObject(float f) { + type = Type.NUMBER; + n = f; + } +#else + public JSONObject(double d) { + type = Type.NUMBER; + n = d; + } +#endif + public JSONObject(int i) { + type = Type.NUMBER; + this.i = i; + useInt = true; + n = i; + } + public JSONObject(long l) { + type = Type.NUMBER; + i = l; + useInt = true; + n = l; + } + public JSONObject(Dictionary dic) { + type = Type.OBJECT; + keys = new List(); + list = new List(); + //Not sure if it's worth removing the foreach here + foreach(KeyValuePair kvp in dic) { + keys.Add(kvp.Key); + list.Add(CreateStringObject(kvp.Value)); + } + } + public JSONObject(Dictionary dic) { + type = Type.OBJECT; + keys = new List(); + list = new List(); + //Not sure if it's worth removing the foreach here + foreach(KeyValuePair kvp in dic) { + keys.Add(kvp.Key); + list.Add(kvp.Value); + } + } + public JSONObject(AddJSONContents content) { + content.Invoke(this); + } + public JSONObject(JSONObject[] objs) { + type = Type.ARRAY; + list = new List(objs); + } + //Convenience function for creating a JSONObject containing a string. This is not part of the constructor so that malformed JSON data doesn't just turn into a string object + public static JSONObject StringObject(string val) { return CreateStringObject(val); } + public void Absorb(JSONObject obj) { + list.AddRange(obj.list); + keys.AddRange(obj.keys); + str = obj.str; + n = obj.n; + useInt = obj.useInt; + i = obj.i; + b = obj.b; + type = obj.type; + } + public static JSONObject Create() { +#if POOLING + JSONObject result = null; + while(result == null && releaseQueue.Count > 0) { + result = releaseQueue.Dequeue(); +#if DEV + //The following cases should NEVER HAPPEN (but they do...) + if(result == null) + Debug.WriteLine("wtf " + releaseQueue.Count); + else if(result.list != null) + Debug.WriteLine("wtflist " + result.list.Count); +#endif + } + if(result != null) + return result; +#endif + return new JSONObject(); + } + public static JSONObject Create(Type t) { + JSONObject obj = Create(); + obj.type = t; + switch(t) { + case Type.ARRAY: + obj.list = new List(); + break; + case Type.OBJECT: + obj.list = new List(); + obj.keys = new List(); + break; + } + return obj; + } + public static JSONObject Create(bool val) { + JSONObject obj = Create(); + obj.type = Type.BOOL; + obj.b = val; + return obj; + } + public static JSONObject Create(float val) { + JSONObject obj = Create(); + obj.type = Type.NUMBER; + obj.n = val; + return obj; + } + public static JSONObject Create(int val) { + JSONObject obj = Create(); + obj.type = Type.NUMBER; + obj.n = val; + obj.useInt = true; + obj.i = val; + return obj; + } + public static JSONObject Create(long val) { + JSONObject obj = Create(); + obj.type = Type.NUMBER; + obj.n = val; + obj.useInt = true; + obj.i = val; + return obj; + } + public static JSONObject CreateStringObject(string val) { + JSONObject obj = Create(); + obj.type = Type.STRING; + obj.str = val; + return obj; + } + public static JSONObject CreateBakedObject(string val) { + JSONObject bakedObject = Create(); + bakedObject.type = Type.BAKED; + bakedObject.str = val; + return bakedObject; + } + /// + /// Create a JSONObject by parsing string data + /// + /// The string to be parsed + /// The maximum depth for the parser to search. Set this to to 1 for the first level, + /// 2 for the first 2 levels, etc. It defaults to -2 because -1 is the depth value that is parsed (see below) + /// Whether to store levels beyond maxDepth in baked JSONObjects + /// Whether to be strict in the parsing. For example, non-strict parsing will successfully + /// parse "a string" into a string-type + /// + public static JSONObject Create(string val, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { + JSONObject obj = Create(); + obj.Parse(val, maxDepth, storeExcessLevels, strict); + return obj; + } + public static JSONObject Create(AddJSONContents content) { + JSONObject obj = Create(); + content.Invoke(obj); + return obj; + } + public static JSONObject Create(Dictionary dic) { + JSONObject obj = Create(); + obj.type = Type.OBJECT; + obj.keys = new List(); + obj.list = new List(); + //Not sure if it's worth removing the foreach here + foreach(KeyValuePair kvp in dic) { + obj.keys.Add(kvp.Key); + obj.list.Add(CreateStringObject(kvp.Value)); + } + return obj; + } + public JSONObject() { } + #region PARSE + public JSONObject(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { //create a new JSONObject from a string (this will also create any children, and parse the whole string) + Parse(str, maxDepth, storeExcessLevels, strict); + } + void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { + if(!string.IsNullOrEmpty(str)) { + str = str.Trim(WHITESPACE); + if(strict) { + if(str[0] != '[' && str[0] != '{') { + type = Type.NULL; +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 + Debug.LogWarning +#else + Debug.WriteLine +#endif + ("Improper (strict) JSON formatting. First character must be [ or {"); + return; + } + } + if(str.Length > 0) { +#if UNITY_WP8 || UNITY_WSA + if (str == "true") { + type = Type.BOOL; + b = true; + } else if (str == "false") { + type = Type.BOOL; + b = false; + } else if (str == "null") { + type = Type.NULL; +#else + if(string.Compare(str, "true", true) == 0) { + type = Type.BOOL; + b = true; + } else if(string.Compare(str, "false", true) == 0) { + type = Type.BOOL; + b = false; + } else if(string.Compare(str, "null", true) == 0) { + type = Type.NULL; +#endif +#if USEFLOAT + } else if(str == INFINITY) { + type = Type.NUMBER; + n = float.PositiveInfinity; + } else if(str == NEGINFINITY) { + type = Type.NUMBER; + n = float.NegativeInfinity; + } else if(str == NaN) { + type = Type.NUMBER; + n = float.NaN; +#else + } else if(str == INFINITY) { + type = Type.NUMBER; + n = double.PositiveInfinity; + } else if(str == NEGINFINITY) { + type = Type.NUMBER; + n = double.NegativeInfinity; + } else if(str == NaN) { + type = Type.NUMBER; + n = double.NaN; +#endif + } else if(str[0] == '"') { + type = Type.STRING; + this.str = str.Substring(1, str.Length - 2); + } else { + int tokenTmp = 1; + /* + * Checking for the following formatting (www.json.org) + * object - {"field1":value,"field2":value} + * array - [value,value,value] + * value - string - "string" + * - number - 0.0 + * - bool - true -or- false + * - null - null + */ + int offset = 0; + switch(str[offset]) { + case '{': + type = Type.OBJECT; + keys = new List(); + list = new List(); + break; + case '[': + type = Type.ARRAY; + list = new List(); + break; + default: + try { +#if USEFLOAT + n = System.Convert.ToSingle(str); +#else + n = System.Convert.ToDouble(str); +#endif + if(!str.Contains(".")) { + i = System.Convert.ToInt64(str); + useInt = true; + } + type = Type.NUMBER; + } catch(System.FormatException) { + type = Type.NULL; +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 + Debug.LogWarning +#else + Debug.WriteLine +#endif + ("improper JSON formatting:" + str); + } + return; + } + string propName = ""; + bool openQuote = false; + bool inProp = false; + int depth = 0; + while(++offset < str.Length) { + if(System.Array.IndexOf(WHITESPACE, str[offset]) > -1) + continue; + if(str[offset] == '\\') { + offset += 1; + continue; + } + if(str[offset] == '"') { + if(openQuote) { + if(!inProp && depth == 0 && type == Type.OBJECT) + propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1); + openQuote = false; + } else { + if(depth == 0 && type == Type.OBJECT) + tokenTmp = offset; + openQuote = true; + } + } + if(openQuote) + continue; + if(type == Type.OBJECT && depth == 0) { + if(str[offset] == ':') { + tokenTmp = offset + 1; + inProp = true; + } + } + + if(str[offset] == '[' || str[offset] == '{') { + depth++; + } else if(str[offset] == ']' || str[offset] == '}') { + depth--; + } + //if (encounter a ',' at top level) || a closing ]/} + if((str[offset] == ',' && depth == 0) || depth < 0) { + inProp = false; + string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE); + if(inner.Length > 0) { + if(type == Type.OBJECT) + keys.Add(propName); + if(maxDepth != -1) //maxDepth of -1 is the end of the line + list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1)); + else if(storeExcessLevels) + list.Add(CreateBakedObject(inner)); + + } + tokenTmp = offset + 1; + } + } + } + } else type = Type.NULL; + } else type = Type.NULL; //If the string is missing, this is a null + //Profiler.EndSample(); + } + #endregion + public bool IsNumber { get { return type == Type.NUMBER; } } + public bool IsNull { get { return type == Type.NULL; } } + public bool IsString { get { return type == Type.STRING; } } + public bool IsBool { get { return type == Type.BOOL; } } + public bool IsArray { get { return type == Type.ARRAY; } } + public bool IsObject { get { return type == Type.OBJECT || type == Type.BAKED; } } + public void Add(bool val) { + Add(Create(val)); + } + public void Add(float val) { + Add(Create(val)); + } + public void Add(int val) { + Add(Create(val)); + } + public void Add(string str) { + Add(CreateStringObject(str)); + } + public void Add(AddJSONContents content) { + Add(Create(content)); + } + public void Add(JSONObject obj) { + if(obj) { //Don't do anything if the object is null + if(type != Type.ARRAY) { + type = Type.ARRAY; //Congratulations, son, you're an ARRAY now + if(list == null) + list = new List(); + } + list.Add(obj); + } + } + public void AddField(string name, bool val) { + AddField(name, Create(val)); + } + public void AddField(string name, float val) { + AddField(name, Create(val)); + } + public void AddField(string name, int val) { + AddField(name, Create(val)); + } + public void AddField(string name, long val) { + AddField(name, Create(val)); + } + public void AddField(string name, AddJSONContents content) { + AddField(name, Create(content)); + } + public void AddField(string name, string val) { + AddField(name, CreateStringObject(val)); + } + public void AddField(string name, JSONObject obj) { + if(obj) { //Don't do anything if the object is null + if(type != Type.OBJECT) { + if(keys == null) + keys = new List(); + if(type == Type.ARRAY) { + for(int i = 0; i < list.Count; i++) + keys.Add(i + ""); + } else + if(list == null) + list = new List(); + type = Type.OBJECT; //Congratulations, son, you're an OBJECT now + } + keys.Add(name); + list.Add(obj); + } + } + public void SetField(string name, string val) { SetField(name, CreateStringObject(val)); } + public void SetField(string name, bool val) { SetField(name, Create(val)); } + public void SetField(string name, float val) { SetField(name, Create(val)); } + public void SetField(string name, int val) { SetField(name, Create(val)); } + public void SetField(string name, JSONObject obj) { + if(HasField(name)) { + list.Remove(this[name]); + keys.Remove(name); + } + AddField(name, obj); + } + public void RemoveField(string name) { + if(keys.IndexOf(name) > -1) { + list.RemoveAt(keys.IndexOf(name)); + keys.Remove(name); + } + } + public delegate void FieldNotFound(string name); + public delegate void GetFieldResponse(JSONObject obj); + public bool GetField(out bool field, string name, bool fallback) { + field = fallback; + return GetField(ref field, name); + } + public bool GetField(ref bool field, string name, FieldNotFound fail = null) { + if(type == Type.OBJECT) { + int index = keys.IndexOf(name); + if(index >= 0) { + field = list[index].b; + return true; + } + } + if(fail != null) fail.Invoke(name); + return false; + } +#if USEFLOAT + public bool GetField(out float field, string name, float fallback) { +#else + public bool GetField(out double field, string name, double fallback) { +#endif + field = fallback; + return GetField(ref field, name); + } +#if USEFLOAT + public bool GetField(ref float field, string name, FieldNotFound fail = null) { +#else + public bool GetField(ref double field, string name, FieldNotFound fail = null) { +#endif + if(type == Type.OBJECT) { + int index = keys.IndexOf(name); + if(index >= 0) { + field = list[index].n; + return true; + } + } + if(fail != null) fail.Invoke(name); + return false; + } + public bool GetField(out int field, string name, int fallback) { + field = fallback; + return GetField(ref field, name); + } + public bool GetField(ref int field, string name, FieldNotFound fail = null) { + if(IsObject) { + int index = keys.IndexOf(name); + if(index >= 0) { + field = (int)list[index].n; + return true; + } + } + if(fail != null) fail.Invoke(name); + return false; + } + public bool GetField(out long field, string name, long fallback) { + field = fallback; + return GetField(ref field, name); + } + public bool GetField(ref long field, string name, FieldNotFound fail = null) { + if(IsObject) { + int index = keys.IndexOf(name); + if(index >= 0) { + field = (long)list[index].n; + return true; + } + } + if(fail != null) fail.Invoke(name); + return false; + } + public bool GetField(out uint field, string name, uint fallback) { + field = fallback; + return GetField(ref field, name); + } + public bool GetField(ref uint field, string name, FieldNotFound fail = null) { + if(IsObject) { + int index = keys.IndexOf(name); + if(index >= 0) { + field = (uint)list[index].n; + return true; + } + } + if(fail != null) fail.Invoke(name); + return false; + } + public bool GetField(out string field, string name, string fallback) { + field = fallback; + return GetField(ref field, name); + } + public bool GetField(ref string field, string name, FieldNotFound fail = null) { + if(IsObject) { + int index = keys.IndexOf(name); + if(index >= 0) { + field = list[index].str; + return true; + } + } + if(fail != null) fail.Invoke(name); + return false; + } + public void GetField(string name, GetFieldResponse response, FieldNotFound fail = null) { + if(response != null && IsObject) { + int index = keys.IndexOf(name); + if(index >= 0) { + response.Invoke(list[index]); + return; + } + } + if(fail != null) fail.Invoke(name); + } + public JSONObject GetField(string name) { + if(IsObject) + for(int i = 0; i < keys.Count; i++) + if(keys[i] == name) + return list[i]; + return null; + } + public bool HasFields(string[] names) { + if(!IsObject) + return false; + for(int i = 0; i < names.Length; i++) + if(!keys.Contains(names[i])) + return false; + return true; + } + public bool HasField(string name) { + if(!IsObject) + return false; + for(int i = 0; i < keys.Count; i++) + if(keys[i] == name) + return true; + return false; + } + public void Clear() { + type = Type.NULL; + if(list != null) + list.Clear(); + if(keys != null) + keys.Clear(); + str = ""; + n = 0; + b = false; + } + /// + /// Copy a JSONObject. This could probably work better + /// + /// + public JSONObject Copy() { + return Create(Print()); + } + /* + * The Merge function is experimental. Use at your own risk. + */ + public void Merge(JSONObject obj) { + MergeRecur(this, obj); + } + /// + /// Merge object right into left recursively + /// + /// The left (base) object + /// The right (new) object + static void MergeRecur(JSONObject left, JSONObject right) { + if(left.type == Type.NULL) + left.Absorb(right); + else if(left.type == Type.OBJECT && right.type == Type.OBJECT) { + for(int i = 0; i < right.list.Count; i++) { + string key = right.keys[i]; + if(right[i].isContainer) { + if(left.HasField(key)) + MergeRecur(left[key], right[i]); + else + left.AddField(key, right[i]); + } else { + if(left.HasField(key)) + left.SetField(key, right[i]); + else + left.AddField(key, right[i]); + } + } + } else if(left.type == Type.ARRAY && right.type == Type.ARRAY) { + if(right.Count > left.Count) { +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 + Debug.LogError +#else + Debug.WriteLine +#endif + ("Cannot merge arrays when right object has more elements"); + return; + } + for(int i = 0; i < right.list.Count; i++) { + if(left[i].type == right[i].type) { //Only overwrite with the same type + if(left[i].isContainer) + MergeRecur(left[i], right[i]); + else { + left[i] = right[i]; + } + } + } + } + } + public void Bake() { + if(type != Type.BAKED) { + str = Print(); + type = Type.BAKED; + } + } + public IEnumerable BakeAsync() { + if(type != Type.BAKED) { + foreach(string s in PrintAsync()) { + if(s == null) + yield return s; + else { + str = s; + } + } + type = Type.BAKED; + } + } +#pragma warning disable 219 + public string Print(bool pretty = false) { + StringBuilder builder = new StringBuilder(); + Stringify(0, builder, pretty); + return builder.ToString(); + } + public IEnumerable PrintAsync(bool pretty = false) { + StringBuilder builder = new StringBuilder(); + printWatch.Reset(); + printWatch.Start(); + foreach(IEnumerable e in StringifyAsync(0, builder, pretty)) { + yield return null; + } + yield return builder.ToString(); + } +#pragma warning restore 219 + #region STRINGIFY + const float maxFrameTime = 0.008f; + static readonly Stopwatch printWatch = new Stopwatch(); + IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string + //Profiler.BeginSample("JSONprint"); + if(depth++ > MAX_DEPTH) { +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 + Debug.Log +#else + Debug.WriteLine +#endif + ("reached max depth!"); + yield break; + } + if(printWatch.Elapsed.TotalSeconds > maxFrameTime) { + printWatch.Reset(); + yield return null; + printWatch.Start(); + } + switch(type) { + case Type.BAKED: + builder.Append(str); + break; + case Type.STRING: + builder.AppendFormat("\"{0}\"", str); + break; + case Type.NUMBER: + if(useInt) { + builder.Append(i.ToString()); + } else { +#if USEFLOAT + if(float.IsInfinity(n)) + builder.Append(INFINITY); + else if(float.IsNegativeInfinity(n)) + builder.Append(NEGINFINITY); + else if(float.IsNaN(n)) + builder.Append(NaN); +#else + if(double.IsInfinity(n)) + builder.Append(INFINITY); + else if(double.IsNegativeInfinity(n)) + builder.Append(NEGINFINITY); + else if(double.IsNaN(n)) + builder.Append(NaN); +#endif + else + builder.Append(n.ToString()); + } + break; + case Type.OBJECT: + builder.Append("{"); + if(list.Count > 0) { +#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide + if(pretty) + builder.Append(NEWLINE); +#endif + for(int i = 0; i < list.Count; i++) { + string key = keys[i]; + JSONObject obj = list[i]; + if(obj) { +#if(PRETTY) + if(pretty) + for(int j = 0; j < depth; j++) + builder.Append("\t"); //for a bit more readability +#endif + builder.AppendFormat("\"{0}\":", key); + foreach(IEnumerable e in obj.StringifyAsync(depth, builder, pretty)) + yield return e; + builder.Append(","); +#if(PRETTY) + if(pretty) + builder.Append(NEWLINE); +#endif + } + } +#if(PRETTY) + if(pretty) + builder.Length -= 2; + else +#endif + builder.Length--; + } +#if(PRETTY) + if(pretty && list.Count > 0) { + builder.Append(NEWLINE); + for(int j = 0; j < depth - 1; j++) + builder.Append("\t"); //for a bit more readability + } +#endif + builder.Append("}"); + break; + case Type.ARRAY: + builder.Append("["); + if(list.Count > 0) { +#if(PRETTY) + if(pretty) + builder.Append(NEWLINE); //for a bit more readability +#endif + for(int i = 0; i < list.Count; i++) { + if(list[i]) { +#if(PRETTY) + if(pretty) + for(int j = 0; j < depth; j++) + builder.Append("\t"); //for a bit more readability +#endif + foreach(IEnumerable e in list[i].StringifyAsync(depth, builder, pretty)) + yield return e; + builder.Append(","); +#if(PRETTY) + if(pretty) + builder.Append(NEWLINE); //for a bit more readability +#endif + } + } +#if(PRETTY) + if(pretty) + builder.Length -= 2; + else +#endif + builder.Length--; + } +#if(PRETTY) + if(pretty && list.Count > 0) { + builder.Append(NEWLINE); + for(int j = 0; j < depth - 1; j++) + builder.Append("\t"); //for a bit more readability + } +#endif + builder.Append("]"); + break; + case Type.BOOL: + if(b) + builder.Append("true"); + else + builder.Append("false"); + break; + case Type.NULL: + builder.Append("null"); + break; + } + //Profiler.EndSample(); + } + //TODO: Refactor Stringify functions to share core logic + /* + * I know, I know, this is really bad form. It turns out that there is a + * significant amount of garbage created when calling as a coroutine, so this + * method is duplicated. Hopefully there won't be too many future changes, but + * I would still like a more elegant way to optionaly yield + */ + void Stringify(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string + //Profiler.BeginSample("JSONprint"); + if(depth++ > MAX_DEPTH) { +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 + Debug.Log +#else + Debug.WriteLine +#endif + ("reached max depth!"); + return; + } + switch(type) { + case Type.BAKED: + builder.Append(str); + break; + case Type.STRING: + builder.AppendFormat("\"{0}\"", str); + break; + case Type.NUMBER: + if(useInt) { + builder.Append(i.ToString()); + } else { +#if USEFLOAT + if(float.IsInfinity(n)) + builder.Append(INFINITY); + else if(float.IsNegativeInfinity(n)) + builder.Append(NEGINFINITY); + else if(float.IsNaN(n)) + builder.Append(NaN); +#else + if(double.IsInfinity(n)) + builder.Append(INFINITY); + else if(double.IsNegativeInfinity(n)) + builder.Append(NEGINFINITY); + else if(double.IsNaN(n)) + builder.Append(NaN); +#endif + else + builder.Append(n.ToString()); + } + break; + case Type.OBJECT: + builder.Append("{"); + if(list.Count > 0) { +#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide + if(pretty) + builder.Append("\n"); +#endif + for(int i = 0; i < list.Count; i++) { + string key = keys[i]; + JSONObject obj = list[i]; + if(obj) { +#if(PRETTY) + if(pretty) + for(int j = 0; j < depth; j++) + builder.Append("\t"); //for a bit more readability +#endif + builder.AppendFormat("\"{0}\":", key); + obj.Stringify(depth, builder, pretty); + builder.Append(","); +#if(PRETTY) + if(pretty) + builder.Append("\n"); +#endif + } + } +#if(PRETTY) + if(pretty) + builder.Length -= 2; + else +#endif + builder.Length--; + } +#if(PRETTY) + if(pretty && list.Count > 0) { + builder.Append("\n"); + for(int j = 0; j < depth - 1; j++) + builder.Append("\t"); //for a bit more readability + } +#endif + builder.Append("}"); + break; + case Type.ARRAY: + builder.Append("["); + if(list.Count > 0) { +#if(PRETTY) + if(pretty) + builder.Append("\n"); //for a bit more readability +#endif + for(int i = 0; i < list.Count; i++) { + if(list[i]) { +#if(PRETTY) + if(pretty) + for(int j = 0; j < depth; j++) + builder.Append("\t"); //for a bit more readability +#endif + list[i].Stringify(depth, builder, pretty); + builder.Append(","); +#if(PRETTY) + if(pretty) + builder.Append("\n"); //for a bit more readability +#endif + } + } +#if(PRETTY) + if(pretty) + builder.Length -= 2; + else +#endif + builder.Length--; + } +#if(PRETTY) + if(pretty && list.Count > 0) { + builder.Append("\n"); + for(int j = 0; j < depth - 1; j++) + builder.Append("\t"); //for a bit more readability + } +#endif + builder.Append("]"); + break; + case Type.BOOL: + if(b) + builder.Append("true"); + else + builder.Append("false"); + break; + case Type.NULL: + builder.Append("null"); + break; + } + //Profiler.EndSample(); + } + #endregion +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 + public static implicit operator WWWForm(JSONObject obj) { + WWWForm form = new WWWForm(); + for(int i = 0; i < obj.list.Count; i++) { + string key = i + ""; + if(obj.type == Type.OBJECT) + key = obj.keys[i]; + string val = obj.list[i].ToString(); + if(obj.list[i].type == Type.STRING) + val = val.Replace("\"", ""); + form.AddField(key, val); + } + return form; + } +#endif + public JSONObject this[int index] { + get { + if(list.Count > index) return list[index]; + return null; + } + set { + if(list.Count > index) + list[index] = value; + } + } + public JSONObject this[string index] { + get { + return GetField(index); + } + set { + SetField(index, value); + } + } + public override string ToString() { + return Print(); + } + public string ToString(bool pretty) { + return Print(pretty); + } + public Dictionary ToDictionary() { + if(type == Type.OBJECT) { + Dictionary result = new Dictionary(); + for(int i = 0; i < list.Count; i++) { + JSONObject val = list[i]; + switch(val.type) { + case Type.STRING: result.Add(keys[i], val.str); break; + case Type.NUMBER: result.Add(keys[i], val.n + ""); break; + case Type.BOOL: result.Add(keys[i], val.b + ""); break; + default: +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 + Debug.LogWarning +#else + Debug.WriteLine +#endif + ("Omitting object: " + keys[i] + " in dictionary conversion"); + break; + } + } + return result; + } +#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 + Debug.Log +#else + Debug.WriteLine +#endif + ("Tried to turn non-Object JSONObject into a dictionary"); + return null; + } + public static implicit operator bool(JSONObject o) { + return o != null; + } +#if POOLING + static bool pool = true; + public static void ClearPool() { + pool = false; + releaseQueue.Clear(); + pool = true; + } + + ~JSONObject() { + if(pool && releaseQueue.Count < MAX_POOL_SIZE) { + type = Type.NULL; + list = null; + keys = null; + str = ""; + n = 0; + b = false; + releaseQueue.Enqueue(this); + } + } +#endif +} + +} diff --git a/Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs.meta b/Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs.meta new file mode 100644 index 00000000..4cf5423a --- /dev/null +++ b/Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 1 +guid: f71819923b555d14ab64ae2044718de9 diff --git a/Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt b/Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt new file mode 100644 index 00000000..38bed03d --- /dev/null +++ b/Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt @@ -0,0 +1,188 @@ +==Author== +[mailto:schoen@defectivestudios.com Matt Schoen] of [http://www.defectivestudios.com Defective Studios] + +==Download== +[[Media:JSONObject.zip|Download JSONObject.zip]] + += Intro = +I came across the need to send structured data to and from a server on one of my projects, and figured it would be worth my while to use JSON. When I looked into the issue, I tried a few of the C# implementations listed on [http://json.org json.org], but found them to be too complicated to work with and expand upon. So, I've written a very simple JSONObject class, which can be generically used to encode/decode data into a simple container. This page assumes that you know what JSON is, and how it works. It's rather simple, just go to json.org for a visual description of the encoding format. + +As an aside, this class is pretty central to the [[AssetCloud]] content management system, from Defective Studios. + +Update: The code has been updated to version 1.4 to incorporate user-submitted patches and bug reports. This fixes issues dealing with whitespace in the format, as well as empty arrays and objects, and escaped quotes within strings. + += Usage = +Users should not have to modify the JSONObject class themselves, and must follow the very simple proceedures outlined below: + +Sample data (in JSON format): + +{ + "TestObject": { + "SomeText": "Blah", + "SomeObject": { + "SomeNumber": 42, + "SomeBool": true, + "SomeNull": null + }, + + "SomeEmptyObject": { }, + "SomeEmptyArray": [ ], + "EmbeddedObject": "{\"field\":\"Value with \\\"escaped quotes\\\"\"}" + } +} + += Features = + +*Decode JSON-formatted strings into a usable data structure +*Encode structured data into a JSON-formatted string +*Interoperable with Dictionary and WWWForm +*Optimized parse/stringify functions -- minimal (unavoidable) garbage creation +*Asynchronous stringify function for serializing lots of data without frame drops +*MaxDepth parsing will skip over nested data that you don't need +*Special (non-compliant) "Baked" object type can store stringified data within parsed objects +*Copy to new JSONObject +*Merge with another JSONObject (experimental) +*Random access (with [int] or [string]) +*ToString() returns JSON data with optional "pretty" flag to include newlines and tabs +*Switch between double and float for numeric storage depending on level of precision needed (and to ensure that numbers are parsed/stringified correctly) +*Supports Infinity and NaN values +*JSONTemplates static class provides serialization functions for common classes like Vector3, Matrix4x4 +*Object pool implementation (experimental) +*Handy JSONChecker window to test parsing on sample data + +It should be pretty obvious what this parser can and cannot do. If anyone reading this is a JSON buff (is there such a thing?) please feel free to expand and modify the parser to be more compliant. Currently I am using the .NET System.Convert namespace functions for parsing the data itself. It parses strings and numbers, which was all that I needed of it, but unless the formatting is supported by System.Convert, it may not incorporate all proper JSON strings. Also, having never written a JSON parser before, I don't doubt that I could improve the efficiency or correctness of the parser. It serves my purpose, and hopefully will help you with your project! Let me know if you make any improvements :) + +Also, you JSON buffs (really, who would admit to being a JSON buff...) might also notice from my feature list that this thing isn't exactly to specifications. Here is where it differs: +*"a string" is considered valid JSON. There is an optional "strict" parameter to the parser which will bomb out on such input, in case that matters to you. +*The "Baked" mode is totally made up. +*The "MaxDepth" parsing is totally made up. +*NaN and Infinity aren't officially supported by JSON ([http://stackoverflow.com/questions/1423081/json-left-out-infinity-and-nan-json-status-in-ecmascript read more] about this issue... I lol'd @ the first comment on the first answer) +*I have no idea about edge cases in my parsing strategy. I have been using this code for about 3 years now and have only had to modify the parser because other people's use cases (still valid JSON) didn't parse correctly. In my experience, anything that this code generates is parsed just fine. + +== Encoding == + +Encoding is something of a hard-coded process. This is because I have no idea what your data is! It would be great if this were some sort of interface for taking an entire class and encoding it's number/string fields, but it's not. I've come up with a few clever ways of using loops and/or recursive methods to cut down of the amount of code I have to write when I use this tool, but they're pretty project-specific. + +Note: This section used to be WRONG! And now it's OLD! Will update later... this will all still work, but there are now a couple of ways to skin this cat. + + +//Note: your data can only be numbers and strings. This is not a solution for object serialization or anything like that. +JSONObject j = new JSONObject(JSONObject.Type.OBJECT); +//number +j.AddField("field1", 0.5); +//string +j.AddField("field2", "sampletext"); +//array +JSONObject arr = new JSONObject(JSONObject.Type.ARRAY); +j.AddField("field3", arr); + +arr.Add(1); +arr.Add(2); +arr.Add(3); + +string encodedString = j.print(); + + +NEW! The constructor, Add, and AddField functions now support a nested delegate structure. This is useful if you need to create a nested JSONObject in a single line. For example: + +DoRequest(URL, new JSONObject(delegate(JSONObject request) { + request.AddField("sort", delegate(JSONObject sort) { + sort.AddField("_timestamp", "desc"); + }); + request.AddField("query", new JSONObject(delegate(JSONObject query) { + query.AddField("match_all", JSONObject.obj); + })); + request.AddField("fields", delegate(JSONObject fields) { + fields.Add("_timestamp"); + }); +}).ToString()); + + +== Decoding == +Decoding is much simpler on the input end, and again, what you do with the JSONObject will vary on a per-project basis. One of the more complicated way to extract the data is with a recursive function, as drafted below. Calling the constructor with a properly formatted JSON string will return the root object (or array) containing all of its children, in one neat reference! The data is in a public ArrayList called list, with a matching key list (called keys!) if the root is an Object. If that's confusing, take a glance over the following code and the print() method in the JSONOBject class. If there is an error in the JSON formatting (or if there's an error with my code!) the debug console will read "improper JSON formatting". + + + +string encodedString = "{\"field1\": 0.5,\"field2\": \"sampletext\",\"field3\": [1,2,3]}"; +JSONObject j = new JSONObject(encodedString); +accessData(j); +//access data (and print it) +void accessData(JSONObject obj){ + switch(obj.type){ + case JSONObject.Type.OBJECT: + for(int i = 0; i < obj.list.Count; i++){ + string key = (string)obj.keys[i]; + JSONObject j = (JSONObject)obj.list[i]; + Debug.Log(key); + accessData(j); + } + break; + case JSONObject.Type.ARRAY: + foreach(JSONObject j in obj.list){ + accessData(j); + } + break; + case JSONObject.Type.STRING: + Debug.Log(obj.str); + break; + case JSONObject.Type.NUMBER: + Debug.Log(obj.n); + break; + case JSONObject.Type.BOOL: + Debug.Log(obj.b); + break; + case JSONObject.Type.NULL: + Debug.Log("NULL"); + break; + + } +} + + +NEW! Decoding now also supports a delegate format which will automatically check if a field exists before processing the data, providing an optional parameter for an OnFieldNotFound response. For example: + +new JSONObject(data); +list.GetField("hits", delegate(JSONObject hits) { + hits.GetField("hits", delegate(JSONObject hits2) { + foreach (JSONObject gameSession in hits2.list) { + Debug.Log(gameSession); + } + }); +}, delegate(string name) { //"name" will be equal to the name of the missing field. In this case, "hits" + Debug.LogWarning("no game sessions"); +}); + + +===Not So New! (O(n)) Random access!=== +I've added a string and int [] index to the class, so you can now retrieve data as such (from above): + +JSONObject arr = obj["field3"]; +Debug.log(arr[2].n); //Should ouptut "3" + + +---- + +---Code omitted from readme--- + +=Change Log= +==v1.4== +Big update! +*Better GC performance. Enough of that garbage! +**Remaining culprits are internal garbage from StringBuilder.Append/AppendFormat, String.Substring, List.Add/GrowIfNeeded, Single.ToString +*Added asynchronous Stringify function for serializing large amounts of data at runtime without frame drops +*Added Baked type +*Added MaxDepth to parsing function +*Various cleanup refactors recommended by ReSharper + +==v1.3.2== +*Added support for NaN +*Added strict mode to fail on purpose for improper formatting. Right now this just means that if the parse string doesn't start with [ or {, it will print a warning and return a null JO. +*Changed infinity and NaN implementation to use float and double instead of Mathf +*Handles empty objects/arrays better +*Added a flag to print and ToString to turn on/off pretty print. The define on top is now an override to system-wide disable +==Earlier Versions== +I'll fill these in later... +[[Category:C Sharp]] +[[Category:Scripts]] +[[Category:Utility]] +[[Category:JSON]] diff --git a/Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt.meta b/Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt.meta new file mode 100644 index 00000000..e0862032 --- /dev/null +++ b/Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 1 +guid: 80b692916bec1664098283aa4425e4d8 diff --git a/Assets/Tests/Lua/LuaEnvironmentTests.unity b/Assets/Tests/Lua/LuaEnvironmentTests.unity index 66537909..d9ef8990 100644 --- a/Assets/Tests/Lua/LuaEnvironmentTests.unity +++ b/Assets/Tests/Lua/LuaEnvironmentTests.unity @@ -242,6 +242,58 @@ MonoBehaviour: ' runAsCoroutine: 1 +--- !u!1 &156811089 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 139298, guid: c356764ac08ce4af2806a601a4f1e6e9, type: 2} + m_PrefabInternal: {fileID: 0} + serializedVersion: 4 + m_Component: + - 4: {fileID: 156811091} + - 114: {fileID: 156811090} + m_Layer: 0 + m_Name: LuaScript + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &156811090 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 11472914, guid: c356764ac08ce4af2806a601a4f1e6e9, + type: 2} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 156811089} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 446caeace65234baaacd52095d24f101, type: 3} + m_Name: + m_EditorClassIdentifier: + executeAfterTime: 1 + repeatExecuteTime: 1 + repeatEveryTime: 1 + executeAfterFrames: 1 + repeatExecuteFrame: 1 + repeatEveryFrame: 1 + hasFailed: 0 + executeMethods: 2 + luaEnvironment: {fileID: 0} + luaFile: {fileID: 0} + luaScript: pass() + runAsCoroutine: 1 +--- !u!4 &156811091 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 449874, guid: c356764ac08ce4af2806a601a4f1e6e9, type: 2} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 156811089} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1887843215} + m_RootOrder: 1 --- !u!4 &236999594 stripped Transform: m_PrefabParentObject: {fileID: 495584, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2} @@ -812,6 +864,67 @@ Transform: m_Children: [] m_Father: {fileID: 1537199682} m_RootOrder: 2 +--- !u!1 &870653406 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 100640, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2} + m_PrefabInternal: {fileID: 0} + serializedVersion: 4 + m_Component: + - 4: {fileID: 870653407} + - 114: {fileID: 870653409} + - 114: {fileID: 870653408} + m_Layer: 0 + m_Name: LuaEnvironment + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &870653407 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 495584, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 870653406} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1887843215} + m_RootOrder: 0 +--- !u!114 &870653408 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 11486636, guid: 49031c561e16d4fcf91c12153f8e0b25, + type: 2} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 870653406} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c10f0b861365b42b0928858f7b086ff3, type: 3} + m_Name: + m_EditorClassIdentifier: + fungusModule: 0 + stringTable: {fileID: 0} + activeLanguage: en + timeScale: -1 + registerTypes: + - {fileID: 4900000, guid: 9c3ab7a98d51241bbb499643399fa761, type: 3} + - {fileID: 4900000, guid: 93fddea8208764a2dbb189cc238aed40, type: 3} +--- !u!114 &870653409 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 11493126, guid: 49031c561e16d4fcf91c12153f8e0b25, + type: 2} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 870653406} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: ba19c26c1ba7243d2b57ebc4329cc7c6, type: 3} + m_Name: + m_EditorClassIdentifier: + remoteDebugger: 0 --- !u!1 &1052730009 GameObject: m_ObjectHideFlags: 0 @@ -1906,6 +2019,57 @@ Prefab: Transform: m_PrefabParentObject: {fileID: 495584, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2} m_PrefabInternal: {fileID: 1855619325} +--- !u!1 &1887843213 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 4 + m_Component: + - 4: {fileID: 1887843215} + - 114: {fileID: 1887843214} + m_Layer: 0 + m_Name: LuaEnvironmentTest + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1887843214 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1887843213} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: b1dba0b27b0864740a8720e920aa88c0, type: 3} + m_Name: + m_EditorClassIdentifier: + timeout: 5 + ignored: 0 + succeedAfterAllAssertionsAreExecuted: 0 + expectException: 0 + expectedExceptionList: + succeedWhenExceptionIsThrown: 0 + includedPlatforms: -1 + platformsToIgnore: [] + dynamic: 0 + dynamicTypeName: +--- !u!4 &1887843215 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1887843213} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 870653407} + - {fileID: 156811091} + m_Father: {fileID: 0} + m_RootOrder: 13 --- !u!1 &1900871524 GameObject: m_ObjectHideFlags: 0 @@ -1921,7 +2085,7 @@ GameObject: m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 - m_IsActive: 1 + m_IsActive: 0 --- !u!114 &1900871525 MonoBehaviour: m_ObjectHideFlags: 0