Exemple #1
0
        public void Load(string projectPath, string[] assetPaths, Type[] types, StorageEventHandler <PersistentObject[]> callback)
        {
            PersistentObject[] result = new PersistentObject[assetPaths.Length];
            for (int i = 0; i < assetPaths.Length; ++i)
            {
                string assetPath = assetPaths[i];
                assetPath = FullPath(projectPath) + assetPath;
                ISerializer serializer = IOC.Resolve <ISerializer>();
                try
                {
                    if (File.Exists(assetPath))
                    {
                        using (FileStream fs = File.OpenRead(assetPath))
                        {
                            result[i] = (PersistentObject)serializer.Deserialize(fs, types[i]);
                        }
                    }
                    else
                    {
                        callback(new Error(Error.E_NotFound), new PersistentObject[0]);
                        return;
                    }
                }
                catch (Exception e)
                {
                    Debug.LogErrorFormat("Unable to load asset: {0} -> got exception: {1} ", assetPath, e.ToString());
                    callback(new Error(Error.E_Exception)
                    {
                        ErrorText = e.ToString()
                    }, new PersistentObject[0]);
                    return;
                }
            }

            callback(new Error(Error.OK), result);
        }
        protected void RestoreDataAndResolveDependencies()
        {
            List <GameObject> goList           = new List <GameObject>();
            List <bool>       goActivationList = new List <bool>();

            for (int i = 0; i < Data.Length; ++i)
            {
                PersistentObject data = Data[i];
                long             id   = Identifiers[i];

                UnityObject obj = FromID <UnityObject>(id);
                if (obj == null)
                {
                    Debug.LogWarningFormat("objects does not have object with instance id {0} however PersistentData of type {1} is present", id, data.GetType());
                    continue;
                }

                data.WriteTo(obj);
                if (obj is GameObject)
                {
                    goList.Add((GameObject)obj);
                    PersistentGameObject goData = (PersistentGameObject)data;
                    goActivationList.Add(goData.ActiveSelf);
                }
            }

            for (int i = 0; i < goList.Count; ++i)
            {
                bool       activeSelf = goActivationList[i];
                GameObject go         = goList[i];
                if (go != null)
                {
                    go.SetActive(activeSelf);
                }
            }
        }
        protected override object WriteToImpl(object obj)
        {
            if (Descriptors == null && Data == null)
            {
                return(obj);
            }

            if (Descriptors == null && Data != null || Data != null && Descriptors == null)
            {
                throw new ArgumentException("data is corrupted", "scene");
            }

            if (Descriptors.Length == 0)
            {
                return(obj);
            }

            if (Identifiers == null || Identifiers.Length != Data.Length)
            {
                throw new ArgumentException("data is corrupted", "scene");
            }

            Scene scene = (Scene)obj;

            GameObject[] rootGameObjects = scene.GetRootGameObjects();
            for (int i = 0; i < rootGameObjects.Length; ++i)
            {
                GameObject rootGO = rootGameObjects[i];
                if (rootGO.GetComponent <RTSLIgnore>())
                {
                    continue;
                }

                UnityObject.DestroyImmediate(rootGO);
            }

            Dictionary <int, UnityObject> idToUnityObj = new Dictionary <int, UnityObject>();

            for (int i = 0; i < Descriptors.Length; ++i)
            {
                PersistentDescriptor descriptor = Descriptors[i];
                if (descriptor != null)
                {
                    CreateGameObjectWithComponents(m_typeMap, descriptor, idToUnityObj, null);
                }
            }


            UnityObject[] assetInstances = null;
            if (AssetIdentifiers != null)
            {
                IUnityObjectFactory factory = IOC.Resolve <IUnityObjectFactory>();
                assetInstances = new UnityObject[AssetIdentifiers.Length];
                for (int i = 0; i < AssetIdentifiers.Length; ++i)
                {
                    PersistentObject asset = Assets[i];

                    Type uoType = m_typeMap.ToUnityType(asset.GetType());
                    if (uoType != null)
                    {
                        if (factory.CanCreateInstance(uoType, asset))
                        {
                            UnityObject assetInstance = factory.CreateInstance(uoType, asset);
                            if (assetInstance != null)
                            {
                                assetInstances[i] = assetInstance;
                                idToUnityObj.Add(AssetIdentifiers[i], assetInstance);
                            }
                        }
                        else
                        {
                            Debug.LogWarning("Unable to create object of type " + uoType.ToString());
                        }
                    }
                    else
                    {
                        Debug.LogWarning("Unable to resolve unity type for " + asset.GetType().FullName);
                    }
                }
            }

            m_assetDB.RegisterSceneObjects(idToUnityObj);

            if (assetInstances != null)
            {
                for (int i = 0; i < AssetIdentifiers.Length; ++i)
                {
                    UnityObject assetInstance = assetInstances[i];
                    if (assetInstance != null)
                    {
                        PersistentObject asset = Assets[i];
                        asset.WriteTo(assetInstance);
                    }
                }
            }

            RestoreDataAndResolveDependencies();
            m_assetDB.UnregisterSceneObjects();

            return(scene);
        }
        protected override void ReadFromImpl(object obj)
        {
            Scene scene = (Scene)obj;

            GameObject[] rootGameObjects = scene.GetRootGameObjects();

            List <PersistentObject>     data            = new List <PersistentObject>();
            List <long>                 identifiers     = new List <long>();
            List <PersistentDescriptor> descriptors     = new List <PersistentDescriptor>(rootGameObjects.Length);
            GetDepsFromContext          getSceneDepsCtx = new GetDepsFromContext();

            for (int i = 0; i < rootGameObjects.Length; ++i)
            {
                GameObject           rootGO     = rootGameObjects[i];
                PersistentDescriptor descriptor = CreateDescriptorAndData(rootGO, data, identifiers, getSceneDepsCtx);
                if (descriptor != null)
                {
                    descriptors.Add(descriptor);
                }
            }

            HashSet <object>    allDeps      = getSceneDepsCtx.Dependencies;
            List <UnityObject>  externalDeps = new List <UnityObject>(allDeps.OfType <UnityObject>());
            Queue <UnityObject> depsQueue    = new Queue <UnityObject>(allDeps.OfType <UnityObject>());

            List <PersistentObject> assets = new List <PersistentObject>();
            List <int> assetIdentifiers    = new List <int>();

            GetDepsFromContext getDepsCtx = new GetDepsFromContext();

            while (depsQueue.Count > 0)
            {
                UnityObject uo = depsQueue.Dequeue();
                if (!uo)
                {
                    continue;
                }
                if (!m_assetDB.IsMapped(uo))
                {
                    if (!(uo is GameObject) && !(uo is Component))
                    {
                        Type persistentType = m_typeMap.ToPersistentType(uo.GetType());
                        if (persistentType != null)
                        {
                            getDepsCtx.Clear();

                            PersistentObject persistentObject = (PersistentObject)Activator.CreateInstance(persistentType);
                            persistentObject.ReadFrom(uo);
                            persistentObject.GetDepsFrom(uo, getDepsCtx);

                            assets.Add(persistentObject);
                            assetIdentifiers.Add(uo.GetInstanceID());

                            foreach (UnityObject dep in getDepsCtx.Dependencies)
                            {
                                if (!allDeps.Contains(dep))
                                {
                                    allDeps.Add(dep);
                                    depsQueue.Enqueue(dep);
                                }
                            }
                        }
                    }
                    externalDeps.Remove(uo);
                }
            }

            Descriptors  = descriptors.ToArray();
            Identifiers  = identifiers.ToArray();
            Data         = data.ToArray();
            Dependencies = externalDeps.Select(uo => m_assetDB.ToID(uo)).ToArray();

            Assets           = assets.ToArray();
            AssetIdentifiers = assetIdentifiers.ToArray();
        }
Exemple #5
0
        public void Save(string projectPath, string[] folderPaths, AssetItem[] assetItems, PersistentObject[] persistentObjects, ProjectInfo projectInfo, bool previewOnly, StorageEventHandler callback)
        {
            QueueUserWorkItem(() =>
            {
                if (!previewOnly)
                {
                    if (assetItems.Length != persistentObjects.Length)
                    {
                        throw new ArgumentException("assetItems");
                    }
                }

                if (assetItems.Length > folderPaths.Length)
                {
                    int l = folderPaths.Length;
                    Array.Resize(ref folderPaths, assetItems.Length);
                    for (int i = l; i < folderPaths.Length; ++i)
                    {
                        folderPaths[i] = folderPaths[l - 1];
                    }
                }

                projectPath = FullPath(projectPath);
                if (!Directory.Exists(projectPath))
                {
                    Directory.CreateDirectory(projectPath);
                }

                string projectInfoPath = projectPath + "/Project.rtmeta";
                ISerializer serializer = IOC.Resolve <ISerializer>();
                Error error            = new Error(Error.OK);
                for (int i = 0; i < assetItems.Length; ++i)
                {
                    string folderPath   = folderPaths[i];
                    AssetItem assetItem = assetItems[i];

                    try
                    {
                        string path = projectPath + folderPath;
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        string previewPath = path + "/" + assetItem.NameExt + PreviewExt;
                        if (assetItem.Preview == null)
                        {
                            File.Delete(previewPath);
                        }
                        else
                        {
                            File.Delete(previewPath);
                            using (FileStream fs = File.Create(previewPath))
                            {
                                serializer.Serialize(assetItem.Preview, fs);
                            }
                        }

                        if (!previewOnly)
                        {
                            PersistentObject persistentObject = persistentObjects[i];
                            File.Delete(path + "/" + assetItem.NameExt + MetaExt);
                            using (FileStream fs = File.Create(path + "/" + assetItem.NameExt + MetaExt))
                            {
                                serializer.Serialize(assetItem, fs);
                            }

                            File.Delete(path + "/" + assetItem.NameExt);

                            if (persistentObject is PersistentRuntimeTextAsset)
                            {
                                PersistentRuntimeTextAsset textAsset = (PersistentRuntimeTextAsset)persistentObject;
                                File.WriteAllText(path + "/" + assetItem.NameExt, textAsset.Text);
                            }
                            else if (persistentObject is PersistentRuntimeBinaryAsset)
                            {
                                PersistentRuntimeBinaryAsset binAsset = (PersistentRuntimeBinaryAsset)persistentObject;
                                File.WriteAllBytes(path + "/" + assetItem.NameExt, binAsset.Data);
                            }
                            else
                            {
                                using (FileStream fs = File.Create(path + "/" + assetItem.NameExt))
                                {
                                    serializer.Serialize(persistentObject, fs);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogErrorFormat("Unable to create asset: {0} -> got exception: {1} ", assetItem.NameExt, e.ToString());
                        error.ErrorCode = Error.E_Exception;
                        error.ErrorText = e.ToString();
                        break;
                    }
                }

                File.Delete(projectInfoPath);
                using (FileStream fs = File.Create(projectInfoPath))
                {
                    serializer.Serialize(projectInfo, fs);
                }

                Callback(() => callback(error));
            });
        }
Exemple #6
0
        public void Load(string projectPath, AssetItem[] assetItems, Type[] types, StorageEventHandler <PersistentObject <TID>[]> callback)
        {
            string[] assetPaths        = assetItems.Select(item => item.ToString()).ToArray();
            long[]   customDataOffsets = assetItems.Select(item => item.CustomDataOffset).ToArray();
            QueueUserWorkItem(() =>
            {
                PersistentObject <TID>[] result = new PersistentObject <TID> [assetPaths.Length];
                for (int i = 0; i < assetPaths.Length; ++i)
                {
                    string assetPath       = assetPaths[i];
                    assetPath              = FullPath(projectPath) + assetPath;
                    ISerializer serializer = IOC.Resolve <ISerializer>();
                    try
                    {
                        if (File.Exists(assetPath))
                        {
                            if (types[i] == typeof(PersistentRuntimeTextAsset <TID>))
                            {
                                PersistentRuntimeTextAsset <TID> textAsset = new PersistentRuntimeTextAsset <TID>();
                                textAsset.name = Path.GetFileName(assetPath);
                                textAsset.Text = File.ReadAllText(assetPath);
                                textAsset.Ext  = Path.GetExtension(assetPath);
                                result[i]      = textAsset;
                            }
                            else if (types[i] == typeof(PersistentRuntimeBinaryAsset <TID>))
                            {
                                PersistentRuntimeBinaryAsset <TID> binAsset = new PersistentRuntimeBinaryAsset <TID>();
                                binAsset.name = Path.GetFileName(assetPath);
                                binAsset.Data = File.ReadAllBytes(assetPath);
                                binAsset.Ext  = Path.GetExtension(assetPath);
                                result[i]     = binAsset;
                            }
                            else
                            {
                                using (FileStream fs = File.OpenRead(assetPath))
                                {
                                    long customDataOffset = customDataOffsets[i];
                                    if (customDataOffset == -1)
                                    {
                                        result[i] = (PersistentObject <TID>)serializer.Deserialize(fs, types[i]);
                                    }
                                    else
                                    {
                                        if (customDataOffset > 0)
                                        {
                                            result[i] = (PersistentObject <TID>)serializer.Deserialize(fs, types[i], customDataOffset);
                                        }
                                        else
                                        {
                                            result[i] = (PersistentObject <TID>)Activator.CreateInstance(types[i]);
                                        }

                                        if (fs.Position < fs.Length)
                                        {
                                            using (BinaryReader reader = new BinaryReader(fs))
                                            {
                                                CustomSerializationHeader header = reader.ReadHeader();
                                                if (header.IsValid)
                                                {
                                                    ICustomSerialization customSerialization = (ICustomSerialization)result[i];
                                                    customSerialization.Deserialize(fs, reader);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            Callback(() => callback(new Error(Error.E_NotFound), new PersistentObject <TID> [0]));
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogErrorFormat("Unable to load asset: {0} -> got exception: {1} ", assetPath, e.ToString());
                        Callback(() => callback(new Error(Error.E_Exception)
                        {
                            ErrorText = e.ToString()
                        }, new PersistentObject <TID> [0]));
                        return;
                    }
                }

                Callback(() => callback(new Error(Error.OK), result));
            });
        }
        protected PersistentDescriptor CreateDescriptorAndData(GameObject go, List <PersistentObject> persistentData, List <long> persistentIdentifiers, /*HashSet<int> usings,*/ GetDepsFromContext getDepsFromCtx, PersistentDescriptor parentDescriptor = null)
        {
            if (go.GetComponent <RTSLIgnore>())
            {
                //Do not save persistent ignore objects
                return(null);
            }
            Type persistentType = m_typeMap.ToPersistentType(go.GetType());

            if (persistentType == null)
            {
                return(null);
            }

            long persistentID = ToID(go);
            //if(m_assetDB.IsResourceID(persistentID))
            //{
            //    int ordinal = m_assetDB.ToOrdinal(persistentID);
            //    usings.Add(ordinal);
            //}

            PersistentDescriptor descriptor = new PersistentDescriptor(m_typeMap.ToGuid(persistentType), persistentID, go.name);

            descriptor.Parent = parentDescriptor;

            PersistentObject goData = (PersistentObject)Activator.CreateInstance(persistentType);

            goData.ReadFrom(go);
            goData.GetDepsFrom(go, getDepsFromCtx);
            persistentData.Add(goData);
            persistentIdentifiers.Add(persistentID);

            Component[] components = go.GetComponents <Component>().Where(c => c != null).ToArray();
            if (components.Length > 0)
            {
                List <PersistentDescriptor> componentDescriptors = new List <PersistentDescriptor>();
                for (int i = 0; i < components.Length; ++i)
                {
                    Component component = components[i];
                    Type      persistentComponentType = m_typeMap.ToPersistentType(component.GetType());
                    if (persistentComponentType == null)
                    {
                        continue;
                    }

                    long componentID = ToID(component);
                    //if (m_assetDB.IsResourceID(componentID))
                    //{
                    //    int ordinal = m_assetDB.ToOrdinal(componentID);
                    //    usings.Add(ordinal);
                    //}
                    PersistentDescriptor componentDescriptor = new PersistentDescriptor(m_typeMap.ToGuid(persistentComponentType), componentID, component.name);
                    componentDescriptor.Parent = descriptor;
                    componentDescriptors.Add(componentDescriptor);

                    PersistentObject componentData = (PersistentObject)Activator.CreateInstance(persistentComponentType);
                    componentData.ReadFrom(component);
                    componentData.GetDepsFrom(component, getDepsFromCtx);
                    persistentData.Add(componentData);
                    persistentIdentifiers.Add(componentID);
                }

                if (componentDescriptors.Count > 0)
                {
                    descriptor.Components = componentDescriptors.ToArray();
                }
            }

            Transform transform = go.transform;

            if (transform.childCount > 0)
            {
                List <PersistentDescriptor> children = new List <PersistentDescriptor>();
                foreach (Transform child in transform)
                {
                    PersistentDescriptor childDescriptor = CreateDescriptorAndData(child.gameObject, persistentData, persistentIdentifiers, /*usings,*/ getDepsFromCtx, descriptor);
                    if (childDescriptor != null)
                    {
                        children.Add(childDescriptor);
                    }
                }

                descriptor.Children = children.ToArray();
            }

            return(descriptor);
        }