Пример #1
0
 public static void ResetStorage()
 {
     if (File.Exists(GetExportStoragePath()))
     {
         File.Delete(GetExportStoragePath());
     }
     wxFileUtil.DeleteDirectory(GetContentFolderPath());
     storage = JSONObject.Create("{\"assets\": {},\"files\":{}}");
     saveStorage();
     Directory.CreateDirectory(GetContentFolderPath());
 }
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            JSONObject metadata = JSONObject.Create("{\"file\": {}}");

            metadata.AddField("version", 2);

            string file_type = GetFileType(asset_path_);

            metadata.GetField("file").SetField("src", AddFile(new WXEngineCopyFile(asset_path_, file_type)));

            return(metadata);
        }
Пример #3
0
        // handle all Serializable class recursively
        private static void SerializableHandler(Type _type, JSONObject _data, object _obj, WXHierarchyContext context)
        {
            if (_obj == null || _type == null)
            {
                return;
            }
            // get [SerializeField] && Public properties
            var fields = _type.GetFields(BindingFlags.NonPublic |
                                         BindingFlags.Instance |
                                         BindingFlags.Public).Where(f =>
                                                                    !f.IsDefined(typeof(NonSerializedAttribute)) &&
                                                                    !f.IsDefined(typeof(HideInInspector)) &&
                                                                    (f.IsDefined(typeof(SerializeField)) || f.IsPublic));

            foreach (var f in fields)
            {
                // get non-permitive Serializable object && non-IEnumerable object
                Type fType = f.FieldType;
                if (fType == null)
                {
                    continue;
                }

                // enum
                // should not do inner recursion for the enum type or you will get { value__: i } object returned
                if (fType.IsEnum)
                {
                    var res = JSONObject.Create((int)f.GetValue(_obj));
                    if (res)
                    {
                        _data.AddField(f.Name, res);
                    }
                    continue;
                }

                if (!propertiesHandlerDictionary.ContainsKey(fType) &&
                    !fType.IsArray &&
                    (!fType.IsGenericType || fType.GetGenericTypeDefinition() != typeof(List <>)) &&
                    fType.IsSerializable)
                {
                    // Serializable object inside the Serializable object, thus do the recursion
                    var _d = new JSONObject(JSONObject.Type.OBJECT);
                    _data.AddField(f.Name, _d);
                    SerializableHandler(fType, _d, f.GetValue(_obj), context);
                    continue;
                }
                else
                {
                    innerHandleProperty(fType, f, _obj, _data, context);
                    continue;
                }
            }
        }
        public static JSONObject Create(Dictionary <string, string> dic)
        {
            JSONObject jSONObject = JSONObject.Create();

            jSONObject.type = Type.OBJECT;
            jSONObject.keys = new List <string>();
            jSONObject.list = new List <JSONObject>();
            foreach (KeyValuePair <string, string> item in dic)
            {
                jSONObject.keys.Add(item.Key);
                jSONObject.list.Add(JSONObject.CreateStringObject(item.Value));
            }
            return(jSONObject);
        }
Пример #5
0
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            JSONObject metadata    = JSONObject.Create("{\"data\":{}, \"file\":{}}");
            string     texturePath = AddFile(new TextureImageFile(texture2D));

            metadata.GetField("file").AddField("src", texturePath);
            metadata.SetField("data", TextureUtil.getMeta(texture2D));

            var editorInfo = new JSONObject(JSONObject.Type.OBJECT);

            editorInfo.AddField("assetVersion", 2);

            metadata.AddField("editorInfo", editorInfo);
            return(metadata);
        }
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            JSONObject meta     = JSONObject.Create("{\"file\": {}}");
            JSONObject metadata = new JSONObject();

            meta.AddField("data", metadata);

            byte[] content = WriteMeshFile(ref metadata);

            meta.GetField("file").AddField(
                "src",
                AddFile(new WXEngineMeshFile(unityAssetPath, mesh.name, content))
                );
            return(meta);
        }
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            string fileName      = Path.GetFileName(unityAssetPath);
            string lowerFileName = fileName.ToLower();
            string _fontPath     = unityAssetPath.Replace(fileName, lowerFileName);

            JSONObject jsonFile = JSONObject.Create("{\"file\": {}}");

            jsonFile.GetField("file").AddField(
                "src",
                AddFile(new WXEngineCopyFile(_fontPath, "font"))
                );

            jsonFile.AddField("version", 2);
            return(jsonFile);
        }
Пример #8
0
        // [MenuItem("WeChat/Utility/Search Prefab Scripts")]
        public static void SearchPrefabScripts()
        {
            var        directories = Directory.EnumerateDirectories(Application.dataPath, "Resources", SearchOption.AllDirectories);
            JSONObject result      = JSONObject.Create(JSONObject.Type.OBJECT);

            foreach (var dir in directories)
            {
                var files = Directory.EnumerateFiles(dir, "*.prefab", SearchOption.AllDirectories);


                foreach (var file in files)
                {
                    var    cutIndex = Path.GetFullPath(file).IndexOf(rootPath) + rootPath.Length + 1;
                    string path     = Path.GetFullPath(file).Substring(cutIndex);
                    path = path.Substring(0, path.Length - 7);
                    Debug.Log(path);

                    var go = Resources.Load(path) as GameObject;
                    if (go == null)
                    {
                        continue;
                    }

                    var scripts = JSONObject.Create(JSONObject.Type.ARRAY);
                    result.AddField(path.Replace("\\", "/"), scripts);
                    IteratePrefab(go, ref scripts, new HashSet <MonoScript>());

                    // Debug.Log(result.ToString());
                }
            }

            var outputFileDirectoryPath = Path.Combine(Application.dataPath, "Output~");

            if (!Directory.Exists(outputFileDirectoryPath))
            {
                Directory.CreateDirectory(outputFileDirectoryPath);
            }

            var outputFilePath = Path.Combine(outputFileDirectoryPath, "output.json");

            if (File.Exists(outputFilePath))
            {
                File.Delete(outputFilePath);
            }
            File.WriteAllText(outputFilePath, result.ToString());
            Debug.Log("Write into: " + outputFilePath);
        }
Пример #9
0
        // 初始化目标目录,包括storage.json和两个存储目录
        public static void init()
        {
            string jsonPath = GetExportStoragePath();

            if (File.Exists(jsonPath))
            {
                string jsonString = File.ReadAllText(jsonPath, Encoding.UTF8);
                storage = JSONObject.Create(jsonString);
            }
            else
            {
                storage = JSONObject.Create("{\"files\":{},\"assets\":{}}");
            }

            saveStorage();
            Directory.CreateDirectory(GetContentFolderPath());
        }
        public static JSONObject Create(Type t)
        {
            JSONObject jSONObject = JSONObject.Create();

            jSONObject.type = t;
            switch (t)
            {
            case Type.ARRAY:
                jSONObject.list = new List <JSONObject>();
                break;

            case Type.OBJECT:
                jSONObject.list = new List <JSONObject>();
                jSONObject.keys = new List <string>();
                break;
            }
            return(jSONObject);
        }
Пример #11
0
        // 更换目标目录,移动storage.json,移动存储目录
        private static void reInit(string originPath, string targetPath)
        {
            string targetStoragePath = Path.Combine(targetPath, EXPORT_STORAGE);
            string originStoragePath = Path.Combine(originPath, EXPORT_STORAGE);

            if (!File.Exists(targetStoragePath))
            {
                // move export_storage.json to target path
                File.Move(originStoragePath, targetStoragePath);
                // move files in ContentFolder to target path
                Directory.Move(Path.Combine(originPath, CONTENT_FOLDER), Path.Combine(targetPath, CONTENT_FOLDER));
            }
            else
            {
                string jsonString = File.ReadAllText(targetStoragePath, Encoding.UTF8);
                storage = JSONObject.Create(jsonString);
            }
        }
Пример #12
0
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            if (string.IsNullOrEmpty(unityAssetPath))
            {
                Debug.LogError("Baked reflection probe null.");
                return(null);
            }
            JSONObject metadata    = JSONObject.Create("{\"data\":{}, \"file\":{}}");
            string     texturePath = AddFile(new TextureImageFile(envMap));

            metadata.GetField("file").AddField("src", texturePath);
            metadata.SetField("data", TextureUtil.getMeta(envMap));

            var editorInfo = new JSONObject(JSONObject.Type.OBJECT);

            editorInfo.AddField("assetVersion", 2);

            metadata.AddField("editorInfo", editorInfo);
            return(metadata);
        }
Пример #13
0
        private static void RegisterBasicProperties()
        {
            AddPropertyHandler(typeof(bool), (obj, context) => {
                return(JSONObject.Create((bool)obj));
            });

            AddPropertyHandler(typeof(int), (obj, context) => {
                return(JSONObject.Create((int)obj));
            });

            AddPropertyHandler(typeof(byte), (obj, context) => {
                return(JSONObject.Create((byte)obj));
            });

            AddPropertyHandler(typeof(short), (obj, context) => {
                return(JSONObject.Create((short)obj));
            });

            AddPropertyHandler(typeof(ushort), (obj, context) => {
                return(JSONObject.Create((ushort)obj));
            });

            AddPropertyHandler(typeof(uint), (obj, context) => {
                return(JSONObject.Create((uint)obj));
            });

            AddPropertyHandler(typeof(sbyte), (obj, context) => {
                return(JSONObject.Create((int)obj));
            });

            AddPropertyHandler(typeof(long), (obj, context) => {
                return(JSONObject.Create((long)obj));
            });

            AddPropertyHandler(typeof(decimal), (obj, context) => {
                return(JSONObject.Create(Convert.ToInt64((decimal)obj)));
            });

            AddPropertyHandler(typeof(ulong), (obj, context) => {
                return(JSONObject.Create(Convert.ToInt64((ulong)obj)));
            });

            AddPropertyHandler(typeof(float), (obj, context) => {
                return(JSONObject.Create((float)obj));
            });

            AddPropertyHandler(typeof(double), (obj, context) => {
                ;
                return(JSONObject.Create(Convert.ToSingle((double)obj)));
            });

            AddPropertyHandler(typeof(string), (obj, context) => {
                var str = (string)obj;
                if (str == null)
                {
                    return(JSONObject.CreateStringObject(""));
                }

                str = str.TrimEnd();
                str = str.Replace('\r', ' ');
                str = str.Replace("\"", "\\\"");
                return(JSONObject.CreateStringObject(str));
            });

            AddPropertyHandler(typeof(char), (obj, context) => {
                string tmp = "";
                tmp       += (char)obj;
                return(JSONObject.CreateStringObject(tmp));
            });
        }
Пример #14
0
        // inner recursion method, thus each if-statement must have @return in the end of the following block.
        private static void innerHandleProperty(Type type, FieldInfo field, object obj, JSONObject data, WXHierarchyContext context)
        {
            if (ExportLogger.LOGGING)
            {
                ExportLogger.AddLog(new ExportLogger.Log(ExportLogger.Log.Type.Inner, "Type: " + type + "\nObject: " + obj + "\nJson: " + data));
            }

            if (obj == null ||
                type == null ||
                type == typeof(System.Object) ||
                field.IsDefined(typeof(NonSerializedAttribute)) ||
                field.IsDefined(typeof(HideInInspector)))
            {
                return;
            }

            if (WXBridge.isNGUIPreset)
            {
                Type wxnguiType = WXMonoBehaviourExportHelper.GetWXNGUIComponentType(type);
                if (wxnguiType != null)
                {
                    var nativeComp = (Component)field.GetValue(obj);

                    if (nativeComp != null)
                    {
                        var go = nativeComp.gameObject;
                        Debug.Log(nativeComp);
                        var entity = context.MakeEntity(go);

                        // 特殊处理
                        if (wxnguiType.FullName == "WXEngine.WXTransform2DComponent")
                        {
                            data.AddField(field.Name, context.AddComponentInProperty(
                                              (WXComponent)Activator.CreateInstance(wxnguiType, (object)nativeComp.transform),
                                              nativeComp.transform
                                              ));
                        }
                        else
                        {
                            data.AddField(field.Name, context.AddComponentInProperty(
                                              (WXComponent)Activator.CreateInstance(wxnguiType, nativeComp, go, entity),
                                              nativeComp
                                              ));
                        }
                    }
                }
            }

            if (WXBridge.isUGUIPreset)
            {
                Type wxuguiType = WXMonoBehaviourExportHelper.GetWXUGUIComponentType(type);
                if (wxuguiType != null)
                {
                    var nativeComp = (Component)field.GetValue(obj);

                    if (nativeComp != null)
                    {
                        var go = nativeComp.gameObject;
                        Debug.Log(nativeComp);
                        var entity = context.MakeEntity(go);

                        // 特殊处理
                        if (wxuguiType.FullName == "WeChat.WXUGUITransform2DComponent")
                        {
                            data.AddField(field.Name, context.AddComponent(
                                              (WXComponent)Activator.CreateInstance(wxuguiType, (object)nativeComp.transform),
                                              nativeComp.transform
                                              ));
                        }
                        else
                        {
                            data.AddField(field.Name, context.AddComponent(
                                              (WXComponent)Activator.CreateInstance(wxuguiType, nativeComp, go, entity),
                                              nativeComp
                                              ));
                        }
                    }
                }
            }

            if (WXBridge.isUGUIPreset)
            {
                Type wxuguiType = WXMonoBehaviourExportHelper.GetWXUGUIComponentType(type);
                if (wxuguiType != null)
                {
                    var nativeComp = (Component)field.GetValue(obj);

                    if (nativeComp != null)
                    {
                        var go = nativeComp.gameObject;
                        Debug.Log(nativeComp);
                        var entity = context.MakeEntity(go);

                        // 特殊处理
                        if (wxuguiType.FullName == "WeChat.WXUGUITransform2DComponent")
                        {
                            data.AddField(field.Name, context.AddComponent(
                                              (WXComponent)Activator.CreateInstance(wxuguiType, (object)nativeComp.transform),
                                              nativeComp.transform
                                              ));
                        }
                        else
                        {
                            data.AddField(field.Name, context.AddComponent(
                                              (WXComponent)Activator.CreateInstance(wxuguiType, nativeComp, go, entity),
                                              nativeComp
                                              ));
                        }
                    }
                }
            }

            if (WXMonoBehaviourExportHelper.IsInBlackList(type))
            {
                return;
            }
            if (propertiesHandlerDictionary.ContainsKey(type))
            {
                var res = InvokePropertyHandler(type, field.GetValue(obj), context);
                if (res)
                {
                    data.AddField(field.Name, res);
                }
                return;
            }
            else if (type.IsArray || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>)))
            {
                var res = InvokePropertyHandler(typeof(List <>), field.GetValue(obj), context);
                if (res)
                {
                    data.AddField(field.Name, res);
                }
                return;
            }
            else if (type.IsEnum)
            {
                var res = JSONObject.Create((int)field.GetValue(obj));
                if (res)
                {
                    data.AddField(field.Name, res);
                }
                return;
            }
            else if (type.IsSubclassOf(typeof(UnityEngine.Component)) || type == typeof(UnityEngine.GameObject))
            {
                // Prefab or not
                var        o  = (UnityEngine.Object)field.GetValue(obj);
                GameObject go = null;

                if (o == null)
                {
                    return;
                }
                if (type.IsSubclassOf(typeof(UnityEngine.Component)))
                {
                    go = ((Component)o).gameObject;
                }
                else if (type == typeof(UnityEngine.GameObject))
                {
                    go = (GameObject)o;
                }
                var path = AssetDatabase.GetAssetPath(o);

                if (go.transform.IsChildOf(context.Root.transform) || path == "")
                {
                    if (type.IsSerializable)
                    {
                        var _innerData = new JSONObject(JSONObject.Type.OBJECT);
                        data.AddField(field.Name, _innerData);
                        SerializableHandler(type, _innerData, field.GetValue(obj), context);
                        return;
                    }
                    innerHandleProperty(type.BaseType, field, obj, data, context);
                    return;
                }

                if (!WXMonoBehaviourExportHelper.exportedResourcesSet.Contains(go))
                {
                    WXMonoBehaviourExportHelper.exportedResourcesSet.Add(go);
                    WXPrefab converter  = new WXPrefab(go, path);
                    string   prefabPath = converter.Export(ExportPreset.GetExportPreset("prefab"));
                    context.AddResource(prefabPath);
                }

                var prefabInfo = new JSONObject(JSONObject.Type.OBJECT);
                prefabInfo.AddField("type", type.FullName.EscapeNamespaceSimple());
                prefabInfo.AddField("path", path);

                var innerData = new JSONObject(JSONObject.Type.OBJECT);
                innerData.AddField("type", "UnityPrefabWrapper");
                innerData.AddField("value", prefabInfo);
                data.AddField(field.Name, innerData);
                return;
            }
            else if (type.IsSerializable)
            {
                // data of serializable object as a new JSONObject to be added
                var innerData = new JSONObject(JSONObject.Type.OBJECT);
                data.AddField(field.Name, innerData);
                SerializableHandler(type, innerData, field.GetValue(obj), context);
                return;
            }
            innerHandleProperty(type.BaseType, field, obj, data, context);
        }
Пример #15
0
        private static void RegisterConditionProperties()
        {
            AddConditionPropertyHandler(
                (Type type) =>
            {
                return(type.IsArray || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>)));
            },
                (type, value, context, requireList) =>
            {
                return(typePropertiesHandlerDictionary[typeof(List <>)](value, context, requireList));
            }
                );
            AddConditionPropertyHandler(
                (Type type) =>
            {
                return(type.IsEnum);
            },
                (type, value, context, requireList) =>
            {
                return(JSONObject.Create((int)value));
            }
                );
            AddConditionPropertyHandler(
                (Type type) =>
            {
                return(type.IsSubclassOf(typeof(UnityEngine.Component)) || type == typeof(UnityEngine.GameObject));
            },
                (type, value, context, requireList) =>
            {
                // 取值
                var o         = (UnityEngine.Object)value;
                GameObject go = null;
                if (o == null)
                {
                    return(null);
                }

                // 尝试获得资源路径
                var path = AssetDatabase.GetAssetPath(o);

                // 如果是组件
                if (type.IsSubclassOf(typeof(UnityEngine.Component)))
                {
                    go = ((Component)o).gameObject;
                }
                // 如果直接是一个GameObject
                else if (type == typeof(UnityEngine.GameObject))
                {
                    go = (GameObject)o;
                }

                // 如果拿得到路径,且发现transform不属于当前场景,则当prefab处理
                if (path != "" && !go.transform.IsChildOf(context.Root.transform))
                {
                    // 按prefab导出

                    // 排重?
                    WXPrefab converter = new WXPrefab(go, path);
                    string prefabPath  = converter.Export(ExportPreset.GetExportPreset("prefab"));
                    context.AddResource(prefabPath);

                    var prefabInfo = new JSONObject(JSONObject.Type.OBJECT);
                    prefabInfo.AddField("type", type.FullName.EscapeNamespaceSimple());
                    prefabInfo.AddField("path", path);
                    // prefab数据
                    var innerData = new JSONObject(JSONObject.Type.OBJECT);
                    innerData.AddField("type", "UnityPrefabWrapper");
                    innerData.AddField("value", prefabInfo);
                    return(innerData);
                }
                return(null);
            }
                );
            AddConditionPropertyHandler(
                (Type type) =>
            {
                return(typePropertiesHandlerDictionary.ContainsKey(type));
            },
                (type, value, context, requireList) =>
            {
                return(typePropertiesHandlerDictionary[type](value, context, requireList));
            }
                );
            AddConditionPropertyHandler(
                (Type type) =>
            {
                // 基础类型都是isSerializable
                return(type.IsSerializable);
            },
                (type, value, context, requireList) =>
            {
                var innerData = new JSONObject(JSONObject.Type.OBJECT);
                SerializableHandler(type, innerData, value, context, requireList);
                return(innerData);
            }
                );
        }
Пример #16
0
        public JSONObject GetSkinPaths(string name, ref bool succ)
        {
            Transform trans    = renderer.transform;
            Animator  animator = trans.GetComponent(typeof(Animator)) as Animator;

            while (!animator && trans)
            {
                trans = trans.parent;
                if (trans)
                {
                    animator = trans.GetComponent(typeof(Animator)) as Animator;
                }
            }
            JSONObject bonesObject = new JSONObject(JSONObject.Type.ARRAY);

            if (animator)
            {
                string filePath = Path.GetFullPath(Directory.GetParent(Application.dataPath) + "/" + AssetDatabase.GetAssetPath(renderer.sharedMesh.GetInstanceID()));
                if (Path.GetExtension(filePath).ToLower() == ".fbx")
                {
                    string toolDir = WXConfig.GetModelToolPath();
                    if (toolDir != null)
                    {
                        string result = WXUtility.ExecProcess(
                            toolDir,
                            "\"" + filePath + "\" --skin=\"" + name + "\"",
                            out succ
                            );
                        if (succ)
                        {
                            return(JSONObject.Create(result));
                        }
                        else
                        {
                            EditorUtility.DisplayDialog("Error", "导出骨骼模型失败:" + result, "确定");
                        }
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("Error", "模型导出工具缺失", "确定");
                    }
                }
                else
                {
                    EditorUtility.DisplayDialog("Error", "导出的模型格式不支持", "确定");
                }
                succ = false;
                for (int i = 0; i < renderer.bones.Length; i++)
                {
                    Transform     node      = renderer.bones[i];
                    List <string> pathArray = new List <string>();
                    while (node != null && node != trans)
                    {
                        pathArray.Add(node.name);
                        node = node.parent;
                    }
                    if (node != null)
                    {
                        pathArray.Reverse();
                        bonesObject.Add("/" + String.Join("/", pathArray.ToArray()));
                    }
                }
            }
            return(bonesObject);
        }
 public void Add(AddJSONContents content)
 {
     this.Add(JSONObject.Create(content));
 }
        public JSONObject GetSkinPaths(string name, ref bool succ)
        {
            Transform trans    = renderer.transform;
            Animator  animator = trans.GetComponent(typeof(Animator)) as Animator;

            while (!animator && trans)
            {
                trans = trans.parent;
                if (trans)
                {
                    animator = trans.GetComponent(typeof(Animator)) as Animator;
                }
            }
            if (animator)
            {
                string filePath = Path.GetFullPath(Directory.GetParent(Application.dataPath) + "/" + AssetDatabase.GetAssetPath(renderer.sharedMesh.GetInstanceID()));
                if (Path.GetExtension(filePath).ToLower() == ".fbx")
                {
                    bool          useFBXSDK = false;
                    AssetImporter importer  = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(renderer.sharedMesh.GetInstanceID()));
                    ModelImporter mImporter = importer as ModelImporter;
                    if (mImporter != null && mImporter.optimizeGameObjects)
                    {
                        useFBXSDK = true;
                    }

                    if (useFBXSDK)
                    {
                        string toolDir = WXConfig.GetModelToolPath();
                        if (toolDir != null)
                        {
                            string result = WXUtility.ExecProcess(
                                toolDir,
                                "\"" + filePath + "\" --skin=\"" + name + "\"",
                                out succ
                                );
                            if (succ)
                            {
                                return(JSONObject.Create(result));
                            }
                            else
                            {
                                ErrorUtil.ExportErrorReporter.create()
                                .setGameObject(trans.gameObject)
                                .setResource(this)
                                .error(ErrorUtil.ErrorCode.SkinnedMesh_FBXToolInvokeFailed, "导出骨骼模型失败:" + result);
                            }
                        }
                        else
                        {
                            ErrorUtil.ExportErrorReporter.create()
                            .setGameObject(trans.gameObject)
                            .setResource(this)
                            .error(ErrorUtil.ErrorCode.SkinnedMesh_FBXToolMissed, "模型导出工具缺失");
                        }
                    }
                    else
                    {
                        return(GetSkinPathsOnScene(trans));
                    }
                }
                else
                {
                    ErrorUtil.ExportErrorReporter.create()
                    .setGameObject(trans.gameObject)
                    .setResource(this)
                    .error(ErrorUtil.ErrorCode.SkinnedMesh_MeshFormatUnsupported, "导出的模型格式不支持");
                }
                succ = false;
                return(GetSkinPathsOnScene(trans));
            }
            else
            {
                ErrorUtil.ExportErrorReporter.create()
                .setGameObject(renderer.gameObject)
                .setResource(this)
                .error(ErrorUtil.ErrorCode.SkinnedMesh_AnimatorNotFound, "MeshRenderer导出的时候没有找到对应Animator");
            }
            return(new JSONObject(JSONObject.Type.OBJECT));
        }
 public JSONObject Copy()
 {
     return(JSONObject.Create(this.Print(true), -2, false, false));
 }
        private void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Trim(JSONObject.WHITESPACE);
                if (strict && str[0] != '[' && str[0] != '{')
                {
                    this.type = Type.NULL;
                }
                else if (str.Length > 0)
                {
                    if (string.Compare(str, "true", true) == 0)
                    {
                        this.type = Type.BOOL;
                        this.b    = true;
                    }
                    else if (string.Compare(str, "false", true) == 0)
                    {
                        this.type = Type.BOOL;
                        this.b    = false;
                    }
                    else if (string.Compare(str, "null", true) == 0)
                    {
                        this.type = Type.NULL;
                    }
                    else if (str == "\"INFINITY\"")
                    {
                        this.type = Type.NUMBER;
                        this.n    = float.PositiveInfinity;
                    }
                    else if (str == "\"NEGINFINITY\"")
                    {
                        this.type = Type.NUMBER;
                        this.n    = float.NegativeInfinity;
                    }
                    else if (str == "\"NaN\"")
                    {
                        this.type = Type.NUMBER;
                        this.n    = float.NaN;
                    }
                    else if (str[0] == '"')
                    {
                        this.type = Type.STRING;
                        this.str  = str.Substring(1, str.Length - 2);
                    }
                    else
                    {
                        int num  = 1;
                        int num2 = 0;
                        switch (str[num2])
                        {
                        case '{':
                            this.type = Type.OBJECT;
                            this.keys = new List <string>();
                            this.list = new List <JSONObject>();
                            break;

                        case '[':
                            this.type = Type.ARRAY;
                            this.list = new List <JSONObject>();
                            break;

                        default:
                            try
                            {
                                this.n = Convert.ToSingle(str);
                                if (!str.Contains("."))
                                {
                                    this.i      = Convert.ToInt64(str);
                                    this.useInt = true;
                                }
                                this.type = Type.NUMBER;
                            }
                            catch (FormatException)
                            {
                                this.type = Type.NULL;
                            }
                            return;
                        }
                        string item  = "";
                        bool   flag  = false;
                        bool   flag2 = false;
                        int    num3  = 0;
                        while (++num2 < str.Length)
                        {
                            if (Array.IndexOf(JSONObject.WHITESPACE, str[num2]) <= -1)
                            {
                                if (str[num2] == '\\')
                                {
                                    num2++;
                                }
                                else
                                {
                                    if (str[num2] == '"')
                                    {
                                        if (flag)
                                        {
                                            if (!flag2 && num3 == 0 && this.type == Type.OBJECT)
                                            {
                                                item = str.Substring(num + 1, num2 - num - 1);
                                            }
                                            flag = false;
                                        }
                                        else
                                        {
                                            if (num3 == 0 && this.type == Type.OBJECT)
                                            {
                                                num = num2;
                                            }
                                            flag = true;
                                        }
                                    }
                                    if (!flag)
                                    {
                                        if (this.type == Type.OBJECT && num3 == 0 && str[num2] == ':')
                                        {
                                            num   = num2 + 1;
                                            flag2 = true;
                                        }
                                        if (str[num2] == '[' || str[num2] == '{')
                                        {
                                            num3++;
                                        }
                                        else if (str[num2] == ']' || str[num2] == '}')
                                        {
                                            num3--;
                                        }
                                        if (str[num2] == ',' && num3 == 0)
                                        {
                                            goto IL_029f;
                                        }
                                        if (num3 < 0)
                                        {
                                            goto IL_029f;
                                        }
                                    }
                                }
                            }
                            continue;
IL_029f:
                            flag2 = false;
                            string text = str.Substring(num, num2 - num).Trim(JSONObject.WHITESPACE);
                            if (text.Length > 0)
                            {
                                if (this.type == Type.OBJECT)
                                {
                                    this.keys.Add(item);
                                }
                                if (maxDepth != -1)
                                {
                                    this.list.Add(JSONObject.Create(text, (maxDepth < -1) ? (-2) : (maxDepth - 1), false, false));
                                }
                                else if (storeExcessLevels)
                                {
                                    this.list.Add(JSONObject.CreateBakedObject(text));
                                }
                            }
                            num = num2 + 1;
                        }
                    }
                }
                else
                {
                    this.type = Type.NULL;
                }
            }
            else
            {
                this.type = Type.NULL;
            }
        }
 public void AddField(string name, AddJSONContents content)
 {
     this.AddField(name, JSONObject.Create(content));
 }
 public void AddField(string name, long val)
 {
     this.AddField(name, JSONObject.Create(val));
 }
Пример #23
0
        private static void RegisterUnityProperties()
        {
            AddTypePropertyHandler(typeof(Vector2), (obj, context, requireList) =>
            {
                Vector2 v = (Vector2)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject vec2 = new JSONObject(JSONObject.Type.ARRAY);
                vec2.Add(v.x);
                vec2.Add(v.y);

                return(vec2);
            });

            AddTypePropertyHandler(typeof(Vector3), (obj, context, requireList) =>
            {
                Vector3 v = (Vector3)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject vec3 = new JSONObject(JSONObject.Type.ARRAY);
                vec3.Add(v.x);
                vec3.Add(v.y);
                vec3.Add(v.z);

                return(vec3);
            });

            AddTypePropertyHandler(typeof(Vector4), (obj, context, requireList) =>
            {
                Vector4 v = (Vector4)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject vec4 = new JSONObject(JSONObject.Type.ARRAY);
                vec4.Add(v.x);
                vec4.Add(v.y);
                vec4.Add(v.z);
                vec4.Add(v.w);

                return(vec4);
            });

            AddTypePropertyHandler(typeof(Quaternion), (obj, context, requireList) =>
            {
                Quaternion v = (Quaternion)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject array4 = new JSONObject(JSONObject.Type.ARRAY);
                array4.Add(v.x);
                array4.Add(v.y);
                array4.Add(v.z);
                array4.Add(v.w);

                return(array4);
            });


            AddTypePropertyHandler(typeof(Matrix4x4), (obj, context, requireList) =>
            {
                Matrix4x4 v = (Matrix4x4)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject array16 = new JSONObject(JSONObject.Type.ARRAY);
                array16.Add(v.m00);
                array16.Add(v.m01);
                array16.Add(v.m02);
                array16.Add(v.m03);
                array16.Add(v.m10);
                array16.Add(v.m11);
                array16.Add(v.m12);
                array16.Add(v.m13);
                array16.Add(v.m20);
                array16.Add(v.m21);
                array16.Add(v.m22);
                array16.Add(v.m23);
                array16.Add(v.m30);
                array16.Add(v.m31);
                array16.Add(v.m32);
                array16.Add(v.m33);

                return(array16);
            });

            AddTypePropertyHandler(typeof(Color), (obj, context, requireList) =>
            {
                Color c = (Color)obj;
                if (c == null)
                {
                    return(null);
                }

                JSONObject vec4 = new JSONObject(JSONObject.Type.ARRAY);
                vec4.Add((int)(c.r * 255));
                vec4.Add((int)(c.g * 255));
                vec4.Add((int)(c.b * 255));
                vec4.Add((int)(c.a * 255));

                return(vec4);
            });

            AddTypePropertyHandler(typeof(TextAsset), (obj, context, requireList) =>
            {
                TextAsset t = (TextAsset)obj;
                if (!t)
                {
                    return(null);
                }

                string path = AssetDatabase.GetAssetPath(t);
                // string copyToPath = Path.Combine(WXResourceStore.storagePath, path);
                // Debug.Log("WXResourceStore.storagePath:" + WXResourceStore.storagePath);
                // Debug.Log("path:" + path);
                // Debug.Log("copyToPath:" + copyToPath);

                // Regex regex = new Regex(".txt$");
                // copyToPath = regex.Replace(copyToPath, ".json");

                // if (!Directory.Exists(WXResourceStore.storagePath + "Assets/")) {
                //     Directory.CreateDirectory(WXResourceStore.storagePath + "Assets/");
                // }

                // FileStream fs = new FileStream(copyToPath, FileMode.Create, FileAccess.Write);

                // wxFileUtil.WriteData(fs, JsonConvert.SerializeObject(new { text = t.text }));
                // fs.Close();

                JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject data = new JSONObject(JSONObject.Type.OBJECT);
                // Debug.Log("JsonConvert.SerializeObject(t.text): " + JsonConvert.SerializeObject(t.text));
                string text = t.text.Replace("\r\n", "\\n").Replace("\\", "\\\\").Replace("\"", "\\\"");
                data.AddField("text", text);
                data.AddField("path", path);
                json.AddField("type", "UnityEngine.TextAsset".EscapeNamespaceSimple());
                json.AddField("value", data);
                return(json);
            });

            AddTypePropertyHandler(typeof(Material), (obj, context, requireList) =>
            {
                Material material = (Material)obj;
                if (material == null)
                {
                    return(null);
                }

                WXMaterial materialConverter = new WXMaterial(material, null);
                string materialPath          = materialConverter.Export(context.preset);
                context.AddResource(materialPath);

                JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject data = new JSONObject(JSONObject.Type.OBJECT);
                json.AddField("type", "UnityEngine.Material".EscapeNamespaceSimple());
                json.AddField("value", data);
                data.AddField("path", materialPath);

                return(json);
            });

            AddTypePropertyHandler(typeof(UnityEngine.LayerMask), (obj, context, requireList) =>
            {
                LayerMask mask = (LayerMask)obj;

                return(JSONObject.Create(mask.value));
            });

            AddTypePropertyHandler(typeof(List <>), (obj, context, requireList) =>
            {
                IEnumerable list = (IEnumerable)obj;
                if (list == null)
                {
                    return(null);
                }

                JSONObject result = new JSONObject(JSONObject.Type.ARRAY);

                var enumerator = ((IEnumerable)list).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    object itemObj = enumerator.Current;
                    if (itemObj == null)
                    {
                        continue;
                    }
                    if (itemObj.GetType() == typeof(List <>))
                    {
                        throw new Exception("不支持嵌套List");
                    }
                    else
                    {
                        Type type             = itemObj.GetType();
                        JSONObject itemResult = innerHandleField(type, itemObj, context, requireList);
                        if (itemResult != null)
                        {
                            result.Add(itemResult);
                        }
                    }
                }
                return(result);
            });

            AddTypePropertyHandler(typeof(PuertsBeefBallSDK.RemoteResource), (obj, context, requireList) =>
            {
                var m = (PuertsBeefBallSDK.RemoteResource)obj;
                return(JSONObject.CreateStringObject(m.resourcePath));
            });

            // disgusting code logic :(
            // refactor should be needed
            AddTypePropertyHandler(typeof(PuertsBeefBallBehaviour), (obj, context, requireList) =>
            {
                var m = (PuertsBeefBallBehaviour)obj;
                if (!m)
                {
                    return(null);
                }

                JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT);

                var escapedTypeName = WXMonoBehaviourExportHelper.EscapeNamespace(m.GetType().FullName);
                innerData.AddField("type", escapedTypeName);
                innerData.AddField("value", context.AddComponentInProperty(new PuertsBeefBallBehaviourConverter(m), (Component)obj));
                return(innerData);
            });

            AddTypePropertyHandler(typeof(Component), (obj, context, requireList) =>
            {
                Component c = (Component)obj;
                if (!c)
                {
                    return(null);
                }

                JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT);

                var escapedTypeName = WXMonoBehaviourExportHelper.EscapeNamespace(c.GetType().FullName);
                innerData.AddField("type", escapedTypeName);
                innerData.AddField("value", context.AddComponentInProperty(new WXUnityComponent(c), c));
                return(innerData);
            });

            // 在前面condition逻辑里,理论上已经把所有可能为prefab的逻辑走完
            AddTypePropertyHandler(typeof(GameObject), (obj, context, requireList) =>
            {
                throw new Exception("不支持节点属性指向GameObject,请改为指向Transform或是具体逻辑组件");

                // var go = (GameObject)obj;
                // if (!go) return null;

                // JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT);

                // return GetPrefabOnSerializedField(context, go, innerData);
            });
        }
 public void SetField(string name, int val)
 {
     this.SetField(name, JSONObject.Create(val));
 }
 public void Add(int val)
 {
     this.Add(JSONObject.Create(val));
 }