public static AssetTypeValueField GetMonoBaseField(AssetsManager am, AssetsFileInstance inst, AssetFileInfoEx info, string managedPath)
        {
            AssetsFile             file      = inst.file;
            AssetTypeTemplateField baseField = new AssetTypeTemplateField();

            baseField.FromClassDatabase(am.classFile, AssetHelper.FindAssetClassByID(am.classFile, info.curFileType), 0);
            AssetTypeInstance mainAti = new AssetTypeInstance(baseField, file.reader, false, info.absoluteFilePos);

            if (file.typeTree.pTypes_Unity5[info.curFileTypeOrIndex].scriptIndex != 0xFFFF)
            {
                AssetTypeInstance scriptAti    = am.GetExtAsset(inst, mainAti.GetBaseField().Get("m_Script")).instance;
                string            scriptName   = scriptAti.GetBaseField().Get("m_Name").GetValue().AsString();
                string            assemblyName = scriptAti.GetBaseField().Get("m_AssemblyName").GetValue().AsString();
                string            assemblyPath = Path.Combine(managedPath, assemblyName);
                if (File.Exists(assemblyPath))
                {
                    MonoClass mc = new MonoClass();
                    mc.Read(scriptName, assemblyPath, inst.file.header.format);
                    AssetTypeTemplateField[] monoTemplateFields = mc.children;

                    AssetTypeTemplateField[] templateField = baseField.children.Concat(monoTemplateFields).ToArray();
                    baseField.children      = templateField;
                    baseField.childrenCount = (uint)baseField.children.Length;

                    mainAti = new AssetTypeInstance(baseField, file.reader, false, info.absoluteFilePos);
                }
            }
            return(mainAti.GetBaseField());
        }
        public AssetTypeValueField GetMonoBaseFieldCached(AssetsFileInstance inst, AssetFileInfoEx info, string managedPath)
        {
            //AssetsFile file = inst.file;
            //ushort scriptIndex = AssetHelper.GetScriptIndex(file, info);
            //if (scriptIndex != 0xFFFF && inst.templateFieldCache.ContainsKey(scriptIndex))
            //{
            //    AssetTypeTemplateField baseTemplateField = inst.templateFieldCache[scriptIndex];
            //    AssetTypeInstance baseAti = new AssetTypeInstance(baseTemplateField, file.reader, info.absoluteFilePos);
            //    return baseAti.GetBaseField();
            //}
            //else
            //{
            //    AssetTypeValueField baseValueField = MonoDeserializer.GetMonoBaseField(this, inst, info, managedPath);
            //    inst.templateFieldCache[scriptIndex] = baseValueField.templateField;
            //    return baseValueField;
            //}
            AssetsFile file        = inst.file;
            ushort     scriptIndex = AssetHelper.GetScriptIndex(file, info);

            if (scriptIndex == 0xFFFF)
            {
                return(null);
            }

            string scriptName;

            if (!inst.monoIdToName.ContainsKey(scriptIndex))
            {
                AssetTypeInstance scriptAti = GetExtAsset(inst, GetATI(inst.file, info).GetBaseField().Get("m_Script")).instance;
                scriptName = scriptAti.GetBaseField().Get("m_Name").GetValue().AsString();
                string scriptNamespace = scriptAti.GetBaseField().Get("m_Namespace").GetValue().AsString();
                string assemblyName    = scriptAti.GetBaseField().Get("m_AssemblyName").GetValue().AsString();

                if (scriptNamespace != string.Empty)
                {
                    scriptNamespace = "-";
                }

                scriptName = $"{assemblyName}.{scriptNamespace}.{scriptName}";
                inst.monoIdToName[scriptIndex] = scriptName;
            }
            else
            {
                scriptName = inst.monoIdToName[scriptIndex];
            }

            if (monoTemplateFieldCache.ContainsKey(scriptName))
            {
                AssetTypeTemplateField baseTemplateField = monoTemplateFieldCache[scriptName];
                AssetTypeInstance      baseAti           = new AssetTypeInstance(baseTemplateField, file.reader, info.absoluteFilePos);
                return(baseAti.GetBaseField());
            }
            else
            {
                AssetTypeValueField baseValueField = MonoDeserializer.GetMonoBaseField(this, inst, info, managedPath);
                monoTemplateFieldCache[scriptName] = baseValueField.templateField;
                return(baseValueField);
            }
        }
示例#3
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (startedScanning)
            {
                return;
            }
            listBox1.Items.Clear();
            startedScanning    = true;
            loadingBar.Maximum = details.Count;

            if (textBox1.Text == "")
            {
                return;
            }
            long searchNum = long.Parse(textBox1.Text);

            BackgroundWorker bw = new BackgroundWorker();

            bw.WorkerReportsProgress = true;
            bw.DoWork += delegate(object s, DoWorkEventArgs ev) {
                for (int i = 0; i < details.Count; i++)
                {
                    AssetDetails ad = details[i];
                    if (ad.fileID != 0 && !checkBox1.Checked)
                    {
                        continue;
                    }
                    if (ad.typeName == "GameObject")
                    {
                        AssetTypeInstance   gameObjectAti = manager.GetATI(manager.GetStream(ad.fileID), manager.GetInfo(ad.fileID, ad.pathID));
                        AssetTypeValueField components    = gameObjectAti.GetBaseField().Get("m_Component").Get("Array");
                        for (uint j = 0; j < components.GetValue().AsArray().size; j++)
                        {
                            int  fileId = components.Get(j).Get("component").Get("m_FileID").GetValue().AsInt();
                            long pathId = components.Get(j).Get("component").Get("m_PathID").GetValue().AsInt64();
                            if (pathId == searchNum)
                            {
                                bw.ReportProgress(i, gameObjectAti.GetBaseField().Get("m_Name").GetValue().AsString() + "(" + ad.fileID + "/" + ad.pathID + ")");
                            }
                        }
                        bw.ReportProgress(i);
                    }
                }
                startedScanning = false;
            };
            bw.ProgressChanged += delegate(object s, ProgressChangedEventArgs ev) {
                loadingBar.Value = ev.ProgressPercentage;
                if (ev.UserState != null)
                {
                    listBox1.Items.Add(ev.UserState);
                }
            };
            bw.RunWorkerAsync();
        }
示例#4
0
        public static AssetTypeValueField GetMonoBaseField(AssetsManager am, AssetsFileInstance inst, AssetFileInfoEx info, string managedPath, bool cached = true)
        {
            AssetsFile             file      = inst.file;
            AssetTypeTemplateField baseField = new AssetTypeTemplateField();

            baseField.FromClassDatabase(am.classFile, AssetHelper.FindAssetClassByID(am.classFile, info.curFileType), 0);
            AssetTypeInstance mainAti     = new AssetTypeInstance(baseField, file.reader, info.absoluteFilePos);
            ushort            scriptIndex = AssetHelper.GetScriptIndex(file, info);

            if (scriptIndex != 0xFFFF)
            {
                AssetTypeInstance scriptAti       = am.GetExtAsset(inst, mainAti.GetBaseField().Get("m_Script")).instance;
                string            scriptName      = scriptAti.GetBaseField().Get("m_ClassName").GetValue().AsString();
                string            scriptNamespace = scriptAti.GetBaseField().Get("m_Namespace").GetValue().AsString();
                string            assemblyName    = scriptAti.GetBaseField().Get("m_AssemblyName").GetValue().AsString();
                string            assemblyPath    = Path.Combine(managedPath, assemblyName);

                if (scriptNamespace != string.Empty)
                {
                    scriptName = scriptNamespace + "." + scriptName;
                }

                if (File.Exists(assemblyPath))
                {
                    AssemblyDefinition asmDef;
                    if (cached)
                    {
                        if (!loadedAssemblies.ContainsKey(assemblyName))
                        {
                            loadedAssemblies.Add(assemblyName, GetAssemblyWithDependencies(assemblyPath));
                        }
                        asmDef = loadedAssemblies[assemblyName];
                    }
                    else
                    {
                        asmDef = GetAssemblyWithDependencies(assemblyPath);
                    }

                    MonoDeserializer mc = new MonoDeserializer();
                    mc.Read(scriptName, asmDef, inst.file.header.format);
                    List <AssetTypeTemplateField> monoTemplateFields = mc.children;

                    AssetTypeTemplateField[] templateField = baseField.children.Concat(monoTemplateFields).ToArray();
                    baseField.children      = templateField;
                    baseField.childrenCount = baseField.children.Length;

                    mainAti = new AssetTypeInstance(baseField, file.reader, info.absoluteFilePos);
                }
            }
            return(mainAti.GetBaseField());
        }
        private void RecursiveChildSearch(TreeNode node, AssetTypeValueField field)
        {
            AssetTypeValueField children =
                helper.GetExtAsset(inst, field.Get("m_Component")
                                   .Get("Array")
                                   .Get(0)
                                   .Get("component")).instance
                .GetBaseField()
                .Get("m_Children")
                .Get("Array");

            for (int i = 0; i < children.GetValue().AsArray().size; i++)
            {
                AssetTypeInstance           newInstance  = helper.GetExtAsset(inst, children.Get((uint)i)).instance;
                AssetsManager.AssetExternal gameObjExt   = helper.GetExtAsset(inst, newInstance.GetBaseField().Get("m_GameObject"));
                AssetTypeInstance           newAti       = gameObjExt.instance;
                AssetTypeValueField         newBaseField = newAti.GetBaseField();
                TreeNode newNode = node.Nodes.Add(newBaseField.Get("m_Name").GetValue().AsString());
                if (!newBaseField.Get("m_IsActive").GetValue().AsBool())
                {
                    newNode.ForeColor = Color.DarkRed;
                }
                newNode.Tag = newBaseField;
                if (gameObjExt.info.index == selectedIndex)
                {
                    goTree.SelectedNode = newNode;
                }
                RecursiveChildSearch(newNode, newBaseField);
            }
        }
示例#6
0
 private void LoadGGM(AssetsFileInstance mainFile)
 {
     //swap this with resources so we can actually see ggm assets
     foreach (AssetFileInfoEx info in mainFile.table.pAssetFileInfo)
     {
         ClassDatabaseType type = AssetHelper.FindAssetClassByID(helper.classFile, info.curFileType);
         if (type.name.GetString(helper.classFile) == "ResourceManager")
         {
             AssetTypeInstance   inst        = helper.GetATI(mainFile.file, info);
             AssetTypeValueField baseField   = inst.GetBaseField();
             AssetTypeValueField m_Container = baseField.Get("m_Container").Get("Array");
             //Dictionary<string, AssetDetails> paths = new Dictionary<string, AssetDetails>();
             List <AssetDetails> assets = new List <AssetDetails>();
             for (uint i = 0; i < m_Container.GetValue().AsArray().size; i++)
             {
                 AssetTypeValueField item = m_Container[i];
                 string path = item.Get("first").GetValue().AsString();
                 AssetTypeValueField pointerField = item.Get("second");
                 uint  fileID = (uint)pointerField.Get("m_FileID").GetValue().AsInt();
                 ulong pathID = (ulong)pointerField.Get("m_PathID").GetValue().AsInt64();
                 //paths[path] = new AssetDetails(new AssetPPtr(fileID, pathID));
                 assets.Add(new AssetDetails(new AssetPPtr(fileID, pathID), AssetIcon.Unknown, path));
             }
             rootDir = new FSDirectory();
             //rootDir.Create(paths);
             rootDir.Create(assets);
             ChangeDirectory("");
             helper.UpdateDependencies();
             CheckResourcesInfo();
             return;
         }
     }
 }
        public static AssetTypeValueField GetMonoBaseFieldCached(this AssetsManager am, AssetsFileInstance inst, AssetFileInfoEx info, string managedPath, List <string> fileNames, Dictionary <AssetID, long> aidToPid)
        {
            AssetsFile file        = inst.file;
            ushort     scriptIndex = file.typeTree.unity5Types[info.curFileTypeOrIndex].scriptIndex;

            if (scriptIndex != 0xFFFF && inst.templateFieldCache.ContainsKey(scriptIndex))
            {
                AssetTypeTemplateField baseTemplateField = inst.templateFieldCache[scriptIndex];
                AssetTypeInstance      baseAti           = new AssetTypeInstance(baseTemplateField, file.reader, info.absoluteFilePos);
                return(baseAti.GetBaseField());
            }
            else
            {
                AssetTypeTemplateField baseField = new AssetTypeTemplateField();
                baseField.FromClassDatabase(am.classFile, AssetHelper.FindAssetClassByID(am.classFile, info.curFileType), 0);
                AssetTypeInstance mainAti = new AssetTypeInstance(baseField, file.reader, info.absoluteFilePos);
                if (file.typeTree.unity5Types[info.curFileTypeOrIndex].scriptIndex != 0xFFFF)
                {
                    AssetTypeValueField m_Script         = mainAti.GetBaseField().Get("m_Script");
                    int               m_ScriptFileId     = m_Script.Get("m_FileID").GetValue().AsInt();
                    long              m_ScriptPathId     = m_Script.Get("m_PathID").GetValue().AsInt64();
                    AssetID           id                 = new AssetID(fileNames[-m_ScriptFileId], m_ScriptPathId);
                    long              m_ScriptRealPathId = aidToPid[id];
                    AssetTypeInstance scriptAti          = am.GetExtAsset(inst, 0, m_ScriptRealPathId).instance;
                    string            scriptName         = scriptAti.GetBaseField().Get("m_Name").GetValue().AsString();
                    string            assemblyName       = scriptAti.GetBaseField().Get("m_AssemblyName").GetValue().AsString();
                    string            assemblyPath       = Path.Combine(managedPath, assemblyName);
                    Console.WriteLine("checking " + scriptName + " in " + assemblyName + " from id " + info.index);
                    if (File.Exists(assemblyPath))
                    {
                        MonoDeserializer mc = new MonoDeserializer();
                        mc.Read(scriptName, assemblyPath, inst.file.header.format);
                        List <AssetTypeTemplateField> monoTemplateFields = mc.children;

                        AssetTypeTemplateField[] templateField = baseField.children.Concat(monoTemplateFields).ToArray();
                        baseField.children      = templateField;
                        baseField.childrenCount = baseField.children.Length;

                        mainAti = new AssetTypeInstance(baseField, file.reader, info.absoluteFilePos);
                    }
                }

                AssetTypeValueField baseValueField = mainAti.GetBaseField();
                inst.templateFieldCache[scriptIndex] = baseValueField.templateField;
                return(baseValueField);
            }
        }
示例#8
0
        private void LoadResources(AssetsFileInstance ggm)
        {
            foreach (AssetFileInfoEx info in ggm.table.assetFileInfo)
            {
                ClassDatabaseType type = AssetHelper.FindAssetClassByID(helper.classFile, info.curFileType);
                if (type.name.GetString(helper.classFile) == "ResourceManager")
                {
                    AssetTypeInstance   inst        = helper.GetTypeInstance(ggm.file, info);
                    AssetTypeValueField baseField   = inst.GetBaseField();
                    AssetTypeValueField m_Container = baseField.Get("m_Container").Get("Array");
                    List <AssetDetails> assets      = new List <AssetDetails>();
                    for (int i = 0; i < m_Container.GetValue().AsArray().size; i++)
                    {
                        AssetTypeValueField item = m_Container[i];
                        string path = item.Get("first").GetValue().AsString();
                        AssetTypeValueField pointerField = item.Get("second");
                        //paths[path] = new AssetDetails(new AssetPPtr(fileID, pathID));

                        AssetExternal   assetExt  = helper.GetExtAsset(ggm, pointerField, true);
                        AssetFileInfoEx assetInfo = assetExt.info;
                        if (assetInfo == null)
                        {
                            continue;
                        }
                        ClassDatabaseType assetType = AssetHelper.FindAssetClassByID(helper.classFile, assetInfo.curFileType);
                        if (assetType == null)
                        {
                            continue;
                        }
                        string assetTypeName = assetType.name.GetString(helper.classFile);
                        string assetName     = AssetHelper.GetAssetNameFast(assetExt.file.file, helper.classFile, assetInfo);
                        if (path.Contains("/"))
                        {
                            if (path.Substring(path.LastIndexOf('/') + 1) == assetName.ToLower())
                            {
                                path = path.Substring(0, path.LastIndexOf('/') + 1) + assetName;
                            }
                        }
                        else
                        {
                            if (path == assetName.ToLower())
                            {
                                path = path.Substring(0, path.LastIndexOf('/') + 1) + assetName;
                            }
                        }

                        assets.Add(new AssetDetails(new AssetPPtr(0, assetInfo.index), GetIconForName(assetTypeName), path, assetTypeName, (int)assetInfo.curFileSize));
                    }
                    rootDir = new FSDirectory();
                    //rootDir.Create(paths);
                    rootDir.Create(assets);
                    ChangeDirectory("");
                    helper.UpdateDependencies();
                    CheckResourcesInfo();
                    return;
                }
            }
        }
示例#9
0
        private AssetTypeTemplateField[] TryDeserializeMono(AssetTypeInstance ati, AssetsManager am, string rootDir)
        {
            AssetTypeInstance scriptAti    = am.GetExtAsset(curFile, ati.GetBaseField().Get("m_Script")).instance;
            string            scriptName   = scriptAti.GetBaseField().Get("m_Name").GetValue().AsString();
            string            assemblyName = scriptAti.GetBaseField().Get("m_AssemblyName").GetValue().AsString();
            string            assemblyPath = Path.Combine(rootDir, "Managed", assemblyName);

            if (File.Exists(assemblyPath))
            {
                MonoClass mc = new MonoClass();
                mc.Read(scriptName, assemblyPath);
                return(mc.children);
            }
            else
            {
                return(null);
            }
        }
示例#10
0
        private AssetTypeTemplateField[] TryDeserializeMono(AssetTypeInstance ati)
        {
            AssetTypeInstance scriptAti    = am.GetExtAsset(ati.GetBaseField().Get("m_Script")).instance;
            string            scriptName   = scriptAti.GetBaseField().Get("m_Name").GetValue().AsString();
            string            assemblyName = scriptAti.GetBaseField().Get("m_AssemblyName").GetValue().AsString();
            string            assemblyPath = Path.Combine(rootDir, "Managed", assemblyName);

            if (File.Exists(assemblyPath))
            {
                MonoDeserializer mc = new MonoDeserializer();
                mc.Read(scriptName, assemblyPath, af.header.format);
                return(mc.children.ToArray());
            }
            else
            {
                return(null);
            }
        }
示例#11
0
        private string GetClassName(AssetsManager manager, AssetsFileInstance inst, AssetTypeValueField baseField)
        {
            AssetTypeInstance scriptAti = manager.GetExtAsset(inst, baseField.Get("m_Script")).instance;

            if (scriptAti == null)
            {
                return("Unknown class name");
            }
            return(scriptAti.GetBaseField().Get("m_Name").GetValue().AsString());
        }
示例#12
0
        public void ReadMesh(AssetTypeInstance ati)
        {
            AssetTypeValueField baseField = ati.GetBaseField();

            name = baseField.Get("m_Name").GetValue().AsString();
            AssetTypeValueField channelArray = baseField.Get("m_VertexData")
                                               .Get("m_Channels")
                                               .Get("Array");

            ChannelInfo[] channelInfos = new ChannelInfo[channelArray.GetValue().AsArray().size];
            for (uint i = 0; i < channelInfos.Length; i++)
            {
                AssetTypeValueField channelInfo = channelArray.Get(i);
                channelInfos[i].stream    = (byte)channelInfo.Get("stream").GetValue().AsInt();
                channelInfos[i].offset    = (byte)channelInfo.Get("offset").GetValue().AsInt();
                channelInfos[i].format    = (byte)channelInfo.Get("format").GetValue().AsInt();
                channelInfos[i].dimension = (byte)channelInfo.Get("dimension").GetValue().AsInt();
            }
            AssetTypeValueField subMeshArray = baseField.Get("m_SubMeshes")
                                               .Get("Array");

            SubMeshInfo[] subMeshInfos = new SubMeshInfo[subMeshArray.GetValue().AsArray().size];
            for (uint i = 0; i < subMeshInfos.Length; i++)
            {
                AssetTypeValueField subMeshInfo = subMeshArray.Get(i);
                subMeshInfos[i].firstByte   = (uint)subMeshInfo.Get("firstByte").GetValue().AsInt();
                subMeshInfos[i].indexCount  = (uint)subMeshInfo.Get("indexCount").GetValue().AsInt();
                subMeshInfos[i].topology    = subMeshInfo.Get("topology").GetValue().AsInt();
                subMeshInfos[i].firstVertex = (uint)subMeshInfo.Get("firstVertex").GetValue().AsInt();
                subMeshInfos[i].vertexCount = (uint)subMeshInfo.Get("vertexCount").GetValue().AsInt();
            }
            SubMesh[] subMeshes = new SubMesh[subMeshInfos.Length];
            int       r         = 0;

            byte[] vertData = baseField.Get("m_VertexData").Get("m_DataSize").GetValue().AsByteArray().data; //asbytearray wont work in at.net yet rip :(
            for (uint i = 0; i < subMeshInfos.Length; i++)
            {
                for (uint j = 0; j < subMeshInfos[i].vertexCount; j++)
                {
                    for (uint k = 0; k < channelInfos.Length; k++)
                    {
                        for (uint l = 0; l < channelInfos[k].dimension; l++)
                        {
                            switch (k)
                            {
                            case 0:
                                ReadValue(vertData, r, channelInfos[k].format);
                                break;
                            }
                        }
                    }
                }
            }
        }
示例#13
0
        public AssetTypeValueField GetMonoBaseField(AssetContainer cont, string managedPath)
        {
            var file     = cont.FileInstance.file;
            var item     = cont.Item;
            var baseTemp = new AssetTypeTemplateField();

            baseTemp.FromClassDatabase(Am.classFile, AssetHelper.FindAssetClassByID(Am.classFile, item.TypeID), 0);
            var mainAti     = new AssetTypeInstance(baseTemp, cont.FileReader, item.Position);
            var scriptIndex = item.MonoID;

            if (scriptIndex != 0xFFFF)
            {
                var monoScriptCont = GetAssetContainer(mainAti.GetBaseField().Get("m_Script"));
                if (monoScriptCont == null)
                {
                    return(null);
                }

                var scriptBaseField = monoScriptCont.TypeInstance.GetBaseField();
                var scriptName      = scriptBaseField.Get("m_Name").GetValue().AsString();
                var scriptNamespace = scriptBaseField.Get("m_Namespace").GetValue().AsString();
                var assemblyName    = scriptBaseField.Get("m_AssemblyName").GetValue().AsString();
                var assemblyPath    = Path.Combine(managedPath, assemblyName);

                if (scriptNamespace != string.Empty)
                {
                    scriptName = scriptNamespace + "." + scriptName;
                }

                if (File.Exists(assemblyPath))
                {
                    if (!LoadedAssemblies.ContainsKey(assemblyName))
                    {
                        LoadedAssemblies.Add(assemblyName, MonoDeserializer.GetAssemblyWithDependencies(assemblyPath));
                    }
                    var asmDef = LoadedAssemblies[assemblyName];

                    var mc = new MonoDeserializer();
                    mc.Read(scriptName, asmDef, file.header.format);
                    var monoTemplateFields = mc.children;

                    var templateField = baseTemp.children.Concat(monoTemplateFields).ToArray();
                    baseTemp.children      = templateField;
                    baseTemp.childrenCount = baseTemp.children.Length;

                    mainAti = new AssetTypeInstance(baseTemp, cont.FileReader, item.Position);
                }
            }
            return(mainAti.GetBaseField());
        }
示例#14
0
        private void PopulateTree()
        {
            ClassDatabaseType      cldt          = AssetHelper.FindAssetClassByID(am.initialClassFile, assetDetails.type);
            AssetTypeTemplateField baseFieldTemp = new AssetTypeTemplateField();

            baseFieldTemp.FromClassDatabase(am.initialClassFile, cldt, 0);
            mainAti = new AssetTypeInstance(new[] { baseFieldTemp }, af.reader, assetDetails.position);
            if (assetDetails.type == 0x72)
            {
                AssetTypeTemplateField[] desMonos = TryDeserializeMono(mainAti);
                if (desMonos != null)
                {
                    AssetTypeTemplateField[] templateField = baseFieldTemp.children.Concat(desMonos).ToArray();
                    baseFieldTemp.children      = templateField;
                    baseFieldTemp.childrenCount = baseFieldTemp.children.Length;

                    mainAti = new AssetTypeInstance(new[] { baseFieldTemp }, af.reader, assetDetails.position);
                }
            }
            AssetTypeValueField baseField = mainAti.GetBaseField();

            rawViewTree.Nodes.Add(baseField.GetFieldType() + " " + baseField.GetName());
            RecursiveTreeLoad(mainAti.GetBaseField(), rawViewTree.Nodes[0], 0);
        }
示例#15
0
        public AssetTypeValueField GetConcatMonoBaseField(AssetContainer cont, string managedPath)
        {
            AssetsFile file = cont.FileInstance.file;
            AssetTypeTemplateField baseTemp = new AssetTypeTemplateField();
            baseTemp.FromClassDatabase(am.classFile, AssetHelper.FindAssetClassByID(am.classFile, cont.ClassId), 0);
            AssetTypeInstance mainAti = new AssetTypeInstance(baseTemp, cont.FileReader, cont.FilePosition);
            ushort scriptIndex = cont.MonoId;
            if (scriptIndex != 0xFFFF)
            {
                AssetContainer monoScriptCont = GetAssetContainer(cont.FileInstance, mainAti.GetBaseField().Get("m_Script"), false);
                if (monoScriptCont == null)
                    return null;

                AssetTypeValueField scriptBaseField = monoScriptCont.TypeInstance.GetBaseField();
                string scriptName = scriptBaseField.Get("m_Name").GetValue().AsString();
                string scriptNamespace = scriptBaseField.Get("m_Namespace").GetValue().AsString();
                string assemblyName = scriptBaseField.Get("m_AssemblyName").GetValue().AsString();
                string assemblyPath = Path.Combine(managedPath, assemblyName);

                if (scriptNamespace != string.Empty)
                    scriptName = scriptNamespace + "." + scriptName;

                if (File.Exists(assemblyPath))
                {
                    AssemblyDefinition asmDef;

                    if (!LoadedAssemblies.ContainsKey(assemblyName))
                    {
                        LoadedAssemblies.Add(assemblyName, MonoDeserializer.GetAssemblyWithDependencies(assemblyPath));
                    }
                    asmDef = LoadedAssemblies[assemblyName];

                    MonoDeserializer mc = new MonoDeserializer();
                    mc.Read(scriptName, asmDef, file.header.format);
                    List<AssetTypeTemplateField> monoTemplateFields = mc.children;

                    AssetTypeTemplateField[] templateField = baseTemp.children.Concat(monoTemplateFields).ToArray();
                    baseTemp.children = templateField;
                    baseTemp.childrenCount = baseTemp.children.Length;

                    mainAti = new AssetTypeInstance(baseTemp, cont.FileReader, cont.FilePosition);
                }
            }
            return mainAti.GetBaseField();
        }
        public AssetTypeValueField GetMonoBaseFieldCached(AssetsFileInstance inst, AssetFileInfoEx info, string managedPath)
        {
            AssetsFile file        = inst.file;
            ushort     scriptIndex = AssetHelper.GetScriptIndex(file, info);

            if (scriptIndex != 0xFFFF && inst.templateFieldCache.ContainsKey(scriptIndex))
            {
                AssetTypeTemplateField baseTemplateField = inst.templateFieldCache[scriptIndex];
                AssetTypeInstance      baseAti           = new AssetTypeInstance(baseTemplateField, file.reader, info.absoluteFilePos);
                return(baseAti.GetBaseField());
            }
            else
            {
                AssetTypeValueField baseValueField = MonoDeserializer.GetMonoBaseField(this, inst, info, managedPath);
                inst.templateFieldCache[scriptIndex] = baseValueField.templateField;
                return(baseValueField);
            }
        }
示例#17
0
        public AssetTypeValueField GetMonoBaseFieldCached(AssetsFileInstance inst, AssetFileInfoEx info, string managedPath)
        {
            AssetsFile file        = inst.file;
            ushort     scriptIndex = file.typeTree.pTypes_Unity5[info.curFileTypeOrIndex].scriptIndex;

            if (scriptIndex != 0xFFFF && inst.templateFieldCache.ContainsKey(scriptIndex))
            {
                AssetTypeTemplateField baseTemplateField = inst.templateFieldCache[scriptIndex];
                AssetTypeInstance      baseAti           = new AssetTypeInstance(baseTemplateField, file.reader, false, info.absoluteFilePos);
                return(baseAti.GetBaseField());
            }
            else
            {
                AssetTypeValueField baseValueField = MonoClass.GetMonoBaseField(this, inst, info, managedPath);
                inst.templateFieldCache[scriptIndex] = baseValueField.templateField;
                return(baseValueField);
            }
        }
示例#18
0
        public AssetTypeValueField GetByteArrayTexture(AssetWorkspace workspace, AssetExternal tex)
        {
            ClassDatabaseType      textureType = AssetHelper.FindAssetClassByID(workspace.am.classFile, tex.info.curFileType);
            AssetTypeTemplateField textureTemp = new AssetTypeTemplateField();

            textureTemp.FromClassDatabase(workspace.am.classFile, textureType, 0);
            AssetTypeTemplateField image_data = textureTemp.children.FirstOrDefault(f => f.name == "image data");

            if (image_data == null)
            {
                return(null);
            }
            image_data.valueType = EnumValueTypes.ByteArray;
            AssetTypeInstance   textureTypeInstance = new AssetTypeInstance(new[] { textureTemp }, tex.file.file.reader, tex.info.absoluteFilePos);
            AssetTypeValueField textureBase         = textureTypeInstance.GetBaseField();

            return(textureBase);
        }
示例#19
0
        internal static void ChangeDisableUnityAudio(string path, bool newValue, QModGame game)
        {
            if (game != QModGame.Subnautica && game != QModGame.BelowZero)
            {
                throw new ArgumentException("Neither Subnautica nor Below Zero detected!");
            }
            AssetsManager      am  = new AssetsManager();
            AssetsFileInstance afi = am.LoadAssetsFile(path, false);

            if (game == QModGame.Subnautica)
            {
                am.LoadClassDatabase("cldb.dat");
            }
            else
            {
                am.LoadClassDatabase("cldb2018.dat");
            }
            AssetFileInfoEx     audioInfo      = afi.table.getAssetInfo(4);
            AssetTypeInstance   audioAti       = am.GetATI(afi.file, audioInfo);
            AssetTypeValueField audioBaseField = audioAti.GetBaseField();

            audioBaseField.Get("m_DisableAudio").GetValue().Set(newValue);
            byte[] audioAsset;
            using (MemoryStream memStream = new MemoryStream())
                using (AssetsFileWriter writer = new AssetsFileWriter(memStream))
                {
                    writer.bigEndian = false;
                    audioBaseField.Write(writer);
                    audioAsset = memStream.ToArray();
                }
            List <AssetsReplacer> rep = new List <AssetsReplacer>()
            {
                new AssetsReplacerFromMemory(0, 4, 0x0B, 0xFFFF, audioAsset)
            };

            using (MemoryStream memStream = new MemoryStream())
                using (AssetsFileWriter writer = new AssetsFileWriter(memStream))
                {
                    afi.file.Write(writer, 0, rep.ToArray(), 0);
                    afi.stream.Close();
                    File.WriteAllBytes(path, memStream.ToArray());
                }
        }
示例#20
0
        private void GetTk2dSprites(AssetsFileInstance inst)
        {
            collections    = new List <TkSpriteCollection>();
            animations     = new List <TkSpriteAnimation>();
            animationClips = new List <TkSpriteAnimationClip>();
            List <TkSpriteFrame> sprFrames = new List <TkSpriteFrame>();
            string managedPath             = Path.Combine(Path.GetDirectoryName(inst.path), "Managed");

            Dictionary <AssetID, TkSpriteCollection> collectionLookup = new Dictionary <AssetID, TkSpriteCollection>();
            int tk2dSCid = -1;
            int tk2dSAid = -1;

            foreach (AssetFileInfoEx mbInf in inst.table.GetAssetsOfType(0x72))
            {
                string scriptName  = null;
                ushort scriptIndex = AssetHelper.GetScriptIndex(inst.file, mbInf);
                if (tk2dSCid != -1 && scriptIndex == tk2dSCid)
                {
                    scriptName = "tk2dSpriteCollectionData";
                }
                else if (tk2dSAid != -1 && scriptIndex == tk2dSAid)
                {
                    scriptName = "tk2dSpriteAnimation";
                }

                if (tk2dSCid == -1 || tk2dSAid == -1) //still looking for script ids
                {
                    AssetTypeValueField mbBase = am.GetATI(inst.file, mbInf).GetBaseField();
                    AssetTypeValueField scBase = am.GetExtAsset(inst, mbBase.Get("m_Script")).instance.GetBaseField();
                    scriptName = scBase.Get("m_Name").GetValue().AsString();
                    if (scriptName == "tk2dSpriteCollectionData")
                    {
                        tk2dSCid = scriptIndex;
                    }
                    else if (scriptName == "tk2dSpriteAnimation")
                    {
                        tk2dSAid = scriptIndex;
                    }
                    else
                    {
                        continue; //nope, nobody cares
                    }
                }

                if (scriptName == null)
                {
                    continue;
                }

                AssetTypeValueField mbSerialBase = am.GetMonoBaseFieldCached(inst, mbInf, managedPath);
                if (scriptName == "tk2dSpriteCollectionData")
                {
                    AssetTypeValueField textures = mbSerialBase.Get("textures");

                    List <AssetExternal> textureExts    = new List <AssetExternal>();
                    List <int>           textureWidths  = new List <int>();
                    List <int>           textureHeights = new List <int>();
                    for (int i = 0; i < textures.childrenCount; i++)
                    {
                        AssetExternal textureExt = am.GetExtAsset(inst, mbSerialBase.Get("textures")[i], true);
                        if (textureExt.info.curFileSize > 100000)
                        {
                            //bad news, unity probably stored the entire image into an array which is gonna
                            //take up too much memory when we decode it, so we'll change the data to a byte array
                            ClassDatabaseType      textureType = AssetHelper.FindAssetClassByID(am.classFile, textureExt.info.curFileType);
                            AssetTypeTemplateField textureTemp = new AssetTypeTemplateField();
                            textureTemp.FromClassDatabase(am.classFile, textureType, 0);
                            AssetTypeTemplateField image_data = textureTemp.children[textureTemp.childrenCount - 1];
                            image_data.valueType = EnumValueTypes.ByteArray; //convert array to bytearray, much better
                            AssetTypeInstance   textureTypeInstance = new AssetTypeInstance(new[] { textureTemp }, inst.file.reader, textureExt.info.absoluteFilePos);
                            AssetTypeValueField textureBase         = textureTypeInstance.GetBaseField();
                            textureExt.instance = textureTypeInstance;
                            textureExts.Add(textureExt);
                            textureWidths.Add(textureBase.Get("m_Width").GetValue().AsInt());
                            textureHeights.Add(textureBase.Get("m_Height").GetValue().AsInt());
                        }
                        else
                        {
                            textureExt = am.GetExtAsset(inst, mbSerialBase.Get("textures")[i]);
                            AssetTypeValueField textureBase = textureExt.instance.GetBaseField();
                            textureExts.Add(textureExt);
                            textureWidths.Add(textureBase.Get("m_Width").GetValue().AsInt());
                            textureHeights.Add(textureBase.Get("m_Height").GetValue().AsInt());
                        }
                    }

                    TkSpriteCollection collection = new TkSpriteCollection()
                    {
                        name        = mbSerialBase.Get("spriteCollectionName").GetValue().AsString(),
                        version     = mbSerialBase.Get("version").GetValue().AsInt(),
                        baseTexture = null,                           //do later
                        textures    = new Dictionary <int, Bitmap>(), //same
                        textureExts = textureExts,
                        sprites     = new List <TkSpriteDefinition>()
                    };
                    collectionLookup[new AssetID(inst.name, mbInf.index)] = collection;
                    AssetTypeValueField spriteDefinitions = mbSerialBase.Get("spriteDefinitions");
                    foreach (AssetTypeValueField def in spriteDefinitions.children)
                    {
                        bool flipped       = def.Get("flipped").GetValue().AsInt() == 1;
                        int  materialId    = def.Get("materialId").GetValue().AsInt();
                        int  textureWidth  = textureWidths[materialId];
                        int  textureHeight = textureHeights[materialId];

                        double uxn = double.MaxValue;
                        double uxp = 0;
                        double uyn = double.MaxValue;
                        double uyp = 0;
                        double pxn = double.MaxValue;
                        double pyn = double.MaxValue;
                        AssetTypeValueField positions = def.Get("positions");
                        AssetTypeValueField uvs       = def.Get("uvs");
                        for (int i = 0; i < 4; i++)
                        {
                            AssetTypeValueField pos = positions[i];
                            AssetTypeValueField uv  = uvs[i];
                            double posX             = pos.Get("x").GetValue().AsFloat();
                            double posY             = pos.Get("y").GetValue().AsFloat();
                            double uvX = Math.Round(uv.Get("x").GetValue().AsFloat() * textureWidth);
                            double uvY = textureHeight - Math.Round(uv.Get("y").GetValue().AsFloat() * textureHeight);
                            if (posX < pxn)
                            {
                                pxn = posX;
                            }
                            if (posY < pyn)
                            {
                                pyn = posY;
                            }

                            if (uvX < uxn)
                            {
                                uxn = uvX;
                            }
                            if (uvX > uxp)
                            {
                                uxp = uvX;
                            }
                            if (uvY < uyn)
                            {
                                uyn = uvY;
                            }
                            if (uvY > uyp)
                            {
                                uyp = uvY;
                            }
                        }
                        int spriteX      = (int)uxn;
                        int spriteY      = (int)uyn;
                        int spriteWidth  = (int)(uxp - uxn);
                        int spriteHeight = (int)(uyp - uyn);

                        AssetTypeValueField boundsData          = def.Get("boundsData");
                        AssetTypeValueField untrimmedBoundsData = def.Get("untrimmedBoundsData");
                        AssetTypeValueField texelSize           = def.Get("texelSize");

                        float texelX = texelSize.Get("x").GetValue().AsFloat();
                        float texelY = texelSize.Get("y").GetValue().AsFloat();

                        float realX = ((float)pxn) / texelX;
                        float realY = -((flipped ? spriteWidth : spriteHeight) + ((float)pyn) / texelY);

                        TkSpriteDefinition sprite = new TkSpriteDefinition()
                        {
                            parent     = collection,
                            name       = def.Get("name").GetValue().AsString(),
                            x          = spriteX,
                            y          = spriteY,
                            width      = spriteWidth,
                            height     = spriteHeight,
                            xOff       = realX,
                            yOff       = realY,
                            materialId = materialId,
                            fullWidth  = untrimmedBoundsData[1].Get("x").GetValue().AsFloat() / texelX,
                            fullHeight = untrimmedBoundsData[1].Get("y").GetValue().AsFloat() / texelY,
                            flipped    = flipped
                        };
                        collection.sprites.Add(sprite);
                    }
                    collections.Add(collection);
                }
                else if (scriptName == "tk2dSpriteAnimation")
                {
                    AssetFileInfoEx   gameObjectInfo = inst.table.GetAssetInfo(mbSerialBase.Get("m_GameObject").Get("m_PathID").GetValue().AsInt64());
                    TkSpriteAnimation animation      = new TkSpriteAnimation()
                    {
                        parents        = new List <TkSpriteCollection>(), //do later
                        parentIds      = new List <AssetID>(),
                        gameObjectName = AssetHelper.GetAssetNameFast(inst.file, am.classFile, gameObjectInfo),
                        clips          = new List <TkSpriteAnimationClip>()
                    };

                    AssetTypeValueField clips = mbSerialBase.Get("clips");
                    foreach (AssetTypeValueField clip in clips.children)
                    {
                        TkSpriteAnimationClip aniClip = new TkSpriteAnimationClip()
                        {
                            parent    = animation,
                            name      = clip.Get("name").GetValue().AsString(),
                            fps       = clip.Get("fps").GetValue().AsFloat(),
                            loopStart = clip.Get("loopStart").GetValue().AsInt(),
                            wrapMode  = (WrapMode)clip.Get("wrapMode").GetValue().AsInt(),
                            frames    = new List <TkSpriteFrame>()
                        };
                        animation.clips.Add(aniClip);
                        animationClips.Add(aniClip);

                        AssetTypeValueField frames = clip.Get("frames");
                        foreach (AssetTypeValueField frame in frames.children)
                        {
                            AssetExternal collectionExt = am.GetExtAsset(inst, frame.Get("spriteCollection"));
                            AssetID       collectionId  = new AssetID(collectionExt.file.name, collectionExt.info.index);
                            if (!animation.parentIds.Contains(collectionId))
                            {
                                animation.parentIds.Add(collectionId);
                            }
                            TkSpriteFrame sprFrame = new TkSpriteFrame()
                            {
                                collection   = null, //do later
                                collectionId = collectionId,
                                spriteId     = frame.Get("spriteId").GetValue().AsInt()
                            };
                            sprFrames.Add(sprFrame);
                            aniClip.frames.Add(sprFrame);
                        }
                    }
                    animations.Add(animation);
                }
            }

            foreach (TkSpriteAnimation animation in animations)
            {
                foreach (AssetID parentId in animation.parentIds)
                {
                    if (collectionLookup.ContainsKey(parentId))
                    {
                        animation.parents.Add(collectionLookup[parentId]);
                    }
                }
            }
            foreach (TkSpriteFrame frame in sprFrames)
            {
                if (collectionLookup.ContainsKey(frame.collectionId))
                {
                    frame.collection = collectionLookup[frame.collectionId];
                }
            }
        }
示例#21
0
        public static AssetTypeValueField GetBaseField(AssetsManager am, AssetsFile file, AssetFileInfoEx info)
        {
            AssetTypeInstance ati = am.GetATI(file, info);

            return(ati.GetBaseField());
        }
示例#22
0
    //fast transform compare since most
    //changes will probably be transforms
    private void CompareTransform(GameObject obj, ulong origPathId, List <ComponentChangeOrAdd> changes)
    {
        Transform objTransform = obj.transform;

        AssetFileInfoEx     goInfo        = assetsTable.getAssetInfo(origPathId);
        AssetTypeInstance   goInstance    = am.GetATI(assetsFile, goInfo);
        AssetTypeValueField transformPPtr = goInstance.GetBaseField()
                                            .Get("m_Component")
                                            .Get("Array")[0]
                                            .Get("component");
        AssetTypeInstance   tfmInfo         = am.GetExtAsset(assetsFileInstance, transformPPtr).instance;
        AssetTypeValueField tfmBaseField    = tfmInfo.GetBaseField();
        AssetTypeValueField m_LocalPosition = tfmBaseField.Get("m_LocalPosition");
        AssetTypeValueField m_LocalRotation = tfmBaseField.Get("m_LocalRotation");
        AssetTypeValueField m_LocalScale    = tfmBaseField.Get("m_LocalScale");
        Vector3             localPosition   = new Vector3(
            m_LocalPosition.Get("x").GetValue().AsFloat(),
            m_LocalPosition.Get("y").GetValue().AsFloat(),
            m_LocalPosition.Get("z").GetValue().AsFloat()
            );
        Quaternion localRotation = new Quaternion(
            m_LocalRotation.Get("x").GetValue().AsFloat(),
            m_LocalRotation.Get("y").GetValue().AsFloat(),
            m_LocalRotation.Get("z").GetValue().AsFloat(),
            m_LocalRotation.Get("w").GetValue().AsFloat()
            );
        Vector3 localScale = new Vector3(
            m_LocalScale.Get("x").GetValue().AsFloat(),
            m_LocalScale.Get("y").GetValue().AsFloat(),
            m_LocalScale.Get("z").GetValue().AsFloat()
            );

        if (objTransform.localPosition != localPosition ||
            objTransform.localRotation != localRotation ||
            objTransform.localScale != localScale)
        {
            List <FieldChange> fieldChanges = new List <FieldChange>();

            if (localPosition.x != objTransform.localPosition.x)
            {
                fieldChanges.Add(new FieldChange("m_LocalPosition/x", objTransform.localPosition.x));
            }
            if (localPosition.y != objTransform.localPosition.y)
            {
                fieldChanges.Add(new FieldChange("m_LocalPosition/y", objTransform.localPosition.y));
            }
            if (localPosition.z != objTransform.localPosition.z)
            {
                fieldChanges.Add(new FieldChange("m_LocalPosition/z", objTransform.localPosition.z));
            }

            if (localRotation.w != objTransform.localRotation.w)
            {
                fieldChanges.Add(new FieldChange("m_LocalRotation/w", objTransform.localRotation.w));
            }
            if (localRotation.x != objTransform.localRotation.x)
            {
                fieldChanges.Add(new FieldChange("m_LocalRotation/x", objTransform.localRotation.x));
            }
            if (localRotation.y != objTransform.localRotation.y)
            {
                fieldChanges.Add(new FieldChange("m_LocalRotation/y", objTransform.localRotation.y));
            }
            if (localRotation.z != objTransform.localRotation.z)
            {
                fieldChanges.Add(new FieldChange("m_LocalRotation/z", objTransform.localRotation.z));
            }

            if (localScale.x != objTransform.localScale.x)
            {
                fieldChanges.Add(new FieldChange("m_LocalScale/x", objTransform.localScale.x));
            }
            if (localScale.y != objTransform.localScale.y)
            {
                fieldChanges.Add(new FieldChange("m_LocalScale/y", objTransform.localScale.y));
            }
            if (localScale.z != objTransform.localScale.z)
            {
                fieldChanges.Add(new FieldChange("m_LocalScale/z", objTransform.localScale.z));
            }

            changes.Add(new ComponentChangeOrAdd()
            {
                isNewComponent = false,
                componentIndex = 0,
                componentType  = "Transform",
                changes        = fieldChanges
            });
            //Debug.Log("diffing " + obj.name + "'s transform");
        }
    }
        private void button1_Click(object sender, EventArgs e)
        {
            if (startedScanning || finishedScanning)
            {
                return;
            }
            startedScanning    = true;
            loadingBar.Maximum = details.Count;

            Dictionary <ulong, string> monos = new Dictionary <ulong, string>();

            BackgroundWorker bw = new BackgroundWorker();

            bw.WorkerReportsProgress = true;
            bw.DoWork += delegate(object s, DoWorkEventArgs ev) {
                for (int i = 0; i < details.Count; i++)
                {
                    AssetDetails ad = details[i];
                    if (ad.fileID != 0 && !checkBox1.Checked)
                    {
                        continue;
                    }
                    string text = null;
                    if (ad.typeName == "MonoBehaviour")
                    {
                        if (ad.name != "MonoBehaviour")
                        {
                            text = ad.name + " (" + ad.fileID + "/" + ad.pathID + ")";
                        }
                        else
                        {
                            AssetTypeInstance behaviourAti = manager.GetATI(manager.GetStream(ad.fileID), manager.GetInfo(ad.fileID, ad.pathID));
                            AssetTypeInstance scriptAti    = manager.GetExtAsset(behaviourAti.GetBaseField().Get("m_Script")).instance;
                            string            scriptName   = scriptAti.GetBaseField().Get("m_Name").GetValue().AsString();
                            text = scriptName + " (" + ad.fileID + "/" + ad.pathID + ")";
                        }
                        monos.Add(ad.pathID, text);
                    }
                    bw.ReportProgress(i);
                }
                for (int i = 0; i < details.Count; i++)
                {
                    AssetDetails ad = details[i];
                    if (ad.fileID != 0 && !checkBox1.Checked)
                    {
                        continue;
                    }
                    if (ad.typeName == "GameObject")
                    {
                        AssetTypeInstance   gameObjectAti = manager.GetATI(manager.GetStream(ad.fileID), manager.GetInfo(ad.fileID, ad.pathID));
                        AssetTypeValueField components    = gameObjectAti.GetBaseField().Get("m_Component").Get("Array");
                        for (uint j = 0; j < components.GetValue().AsArray().size; j++)
                        {
                            long id = components.Get(j).Get("component").Get("m_PathID").GetValue().AsInt64();
                            if (monos.ContainsKey((ulong)id))
                            {
                                monos[(ulong)id] += " -> " + gameObjectAti.GetBaseField().Get("m_Name").GetValue().AsString() + "(" + ad.fileID + "/" + ad.pathID + ")";
                            }
                        }
                        bw.ReportProgress(i);
                    }
                }
                foreach (string str in monos.Values)
                {
                    bw.ReportProgress(details.Count, str);
                }
                startedScanning  = false;
                finishedScanning = true;
            };
            bw.ProgressChanged += delegate(object s, ProgressChangedEventArgs ev) {
                loadingBar.Value = ev.ProgressPercentage;
                if (ev.UserState != null)
                {
                    listBox1.Items.Add(ev.UserState);
                }
            };
            bw.RunWorkerAsync();
        }
        private static void ReadGameInfo(AssetsManager assetsManager)
        {
            string             gameDataPath = MelonUtils.GetGameDataDirectory();
            AssetsFileInstance instance     = null;

            try
            {
                string bundlePath = Path.Combine(gameDataPath, "globalgamemanagers");
                if (!File.Exists(bundlePath))
                {
                    bundlePath = Path.Combine(gameDataPath, "mainData");
                }

                if (!File.Exists(bundlePath))
                {
                    bundlePath = Path.Combine(gameDataPath, "data.unity3d");
                    if (!File.Exists(bundlePath))
                    {
                        return;
                    }

                    BundleFileInstance bundleFile = assetsManager.LoadBundleFile(bundlePath);
                    instance = assetsManager.LoadAssetsFileFromBundle(bundleFile, "globalgamemanagers");
                }
                else
                {
                    instance = assetsManager.LoadAssetsFile(bundlePath, true);
                }
                if (instance == null)
                {
                    return;
                }

                assetsManager.LoadIncludedClassPackage();
                if (!instance.file.typeTree.hasTypeTree)
                {
                    assetsManager.LoadClassDatabaseFromPackage(instance.file.typeTree.unityVersion);
                }
                EngineVersion = UnityVersion.Parse(instance.file.typeTree.unityVersion);

                List <AssetFileInfoEx> assetFiles = instance.table.GetAssetsOfType(129);
                if (assetFiles.Count > 0)
                {
                    AssetFileInfoEx playerSettings = assetFiles.First();

                    AssetTypeInstance assetTypeInstance = null;
                    try
                    {
                        assetTypeInstance = assetsManager.GetTypeInstance(instance, playerSettings);
                    }
                    catch (Exception ex)
                    {
                        if (MelonDebug.IsEnabled())
                        {
                            MelonLogger.Error(ex);
                            MelonLogger.Warning("Attempting to use Large Class Package...");
                        }
                        assetsManager.LoadIncludedLargeClassPackage();
                        assetsManager.LoadClassDatabaseFromPackage(instance.file.typeTree.unityVersion);
                        assetTypeInstance = assetsManager.GetTypeInstance(instance, playerSettings);
                    }

                    if (assetTypeInstance != null)
                    {
                        AssetTypeValueField playerSettings_baseField = assetTypeInstance.GetBaseField();

                        AssetTypeValueField bundleVersion = playerSettings_baseField.Get("bundleVersion");
                        if (bundleVersion != null)
                        {
                            GameVersion = bundleVersion.GetValue().AsString();
                        }

                        AssetTypeValueField companyName = playerSettings_baseField.Get("companyName");
                        if (companyName != null)
                        {
                            GameDeveloper = companyName.GetValue().AsString();
                        }

                        AssetTypeValueField productName = playerSettings_baseField.Get("productName");
                        if (productName != null)
                        {
                            GameName = productName.GetValue().AsString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (MelonDebug.IsEnabled())
                {
                    MelonLogger.Error(ex);
                }
                MelonLogger.Error("Failed to Initialize Assets Manager!");
            }
            if (instance != null)
            {
                instance.file.Close();
            }
        }
示例#25
0
    public static void ShowOpenFileDialog()
    {
        string path = EditorUtility.OpenFilePanel("Open level file", "", "");

        if (path.Length != 0)
        {
            HKSelect window = GetWindow <HKSelect>();
            window.am = new AssetsManager();
            AssetsFileInstance assetsFileInstance = window.am.LoadAssetsFile(path, true); //might work with false
            AssetsFile         assetsFile         = assetsFileInstance.file;
            AssetsFileTable    assetsTable        = assetsFileInstance.table;
            window.am.LoadClassPackage(Path.Combine(Application.dataPath, "cldb.dat"));

            window.folderPath = Path.GetDirectoryName(path);

            Stream assetStream = assetsFileInstance.stream;

            List <AssetInfo> assetInfos = new List <AssetInfo>();
            uint             fsmTypeId  = 0;
            foreach (AssetFileInfoEx info in assetsTable.pAssetFileInfo)
            {
                bool isMono = false;
                if (fsmTypeId == 0)
                {
                    ushort monoType = assetsFile.typeTree.pTypes_Unity5[info.curFileTypeOrIndex].scriptIndex;
                    if (monoType != 0xFFFF)
                    {
                        isMono = true;
                    }
                }
                else if (info.curFileType == fsmTypeId)
                {
                    isMono = true;
                }
                if (isMono)
                {
                    AssetTypeInstance monoAti   = window.am.GetATI(assetsFile, info);
                    AssetTypeInstance scriptAti = window.am.GetExtAsset(assetsFileInstance, monoAti.GetBaseField().Get("m_Script")).instance;
                    AssetTypeInstance goAti     = window.am.GetExtAsset(assetsFileInstance, monoAti.GetBaseField().Get("m_GameObject")).instance;
                    if (goAti == null) //found a scriptable object, oops
                    {
                        fsmTypeId = 0;
                        continue;
                    }
                    string m_Name      = goAti.GetBaseField().Get("m_Name").GetValue().AsString();
                    string m_ClassName = scriptAti.GetBaseField().Get("m_ClassName").GetValue().AsString();

                    if (m_ClassName == "PlayMakerFSM")
                    {
                        if (fsmTypeId == 0)
                        {
                            fsmTypeId = info.curFileType;
                        }

                        BinaryReader reader = new BinaryReader(assetStream);

                        long oldPos = assetStream.Position;
                        reader.BaseStream.Position  = (long)info.absoluteFilePos;
                        reader.BaseStream.Position += 28;
                        uint length = reader.ReadUInt32();
                        reader.ReadBytes((int)length);

                        long pad = 4 - (reader.BaseStream.Position % 4);
                        if (pad != 4)
                        {
                            reader.BaseStream.Position += pad;
                        }

                        reader.BaseStream.Position += 16;

                        uint   length2 = reader.ReadUInt32();
                        string fsmName = Encoding.ASCII.GetString(reader.ReadBytes((int)length2));
                        reader.BaseStream.Position = oldPos;

                        assetInfos.Add(new AssetInfo()
                        {
                            id   = info.index,
                            size = info.curFileSize,
                            name = m_Name + "-" + fsmName
                        });
                    }
                }
            }
            assetInfos.Sort((x, y) => x.name.CompareTo(y.name));

            window.assetInfos = assetInfos;
            window.strings    = assetInfos.Select(i => i.name).ToArray();
        }
    }
示例#26
0
        public FsmDataInstance LoadFSM(long id)
        {
            AssetFileInfoEx     info      = curFile.table.GetAssetInfo(id);
            AssetTypeValueField baseField = am.GetMonoBaseFieldCached(curFile, info, Path.Combine(Path.GetDirectoryName(curFile.path), "Managed"));
            AssetNameResolver   namer     = new AssetNameResolver(am, curFile);

            FsmDataInstance dataInstance = new FsmDataInstance();

            AssetTypeValueField fsm               = baseField.Get("fsm");
            AssetTypeValueField states            = fsm.Get("states");
            AssetTypeValueField events            = fsm.Get("events");
            AssetTypeValueField variables         = fsm.Get("variables");
            AssetTypeValueField globalTransitions = fsm.Get("globalTransitions");
            AssetTypeValueField dataVersionField  = fsm.Get("dataVersion");

            dataInstance.fsmName = fsm.Get("name").GetValue().AsString();

            AssetTypeInstance goAti = am.GetExtAsset(curFile, baseField.Get("m_GameObject")).instance;

            if (goAti != null)
            {
                string m_Name = goAti.GetBaseField().Get("m_Name").GetValue().AsString();
                dataInstance.goName = m_Name;
            }

            if (dataVersionField.IsDummy())
            {
                dataInstance.dataVersion = fsm.Get("version").GetValue().AsInt() + 1;
            }
            else
            {
                dataInstance.dataVersion = dataVersionField.GetValue().AsInt();
            }

            dataInstance.states = new List <FsmStateData>();
            for (int i = 0; i < states.GetChildrenCount(); i++)
            {
                FsmStateData stateData = new FsmStateData();
                stateData.ActionData = new List <ActionScriptEntry>();
                stateData.state      = new FsmState(namer, states[i]);
                stateData.node       = new FsmNodeData(stateData.state);

                GetActionData(stateData.ActionData, stateData.state.actionData, dataInstance.dataVersion);

                dataInstance.states.Add(stateData);
            }

            dataInstance.events = new List <FsmEventData>();
            for (int i = 0; i < events.GetChildrenCount(); i++)
            {
                FsmEventData eventData = new FsmEventData();
                eventData.Global = events[i].Get("isGlobal").GetValue().AsBool();
                eventData.Name   = events[i].Get("name").GetValue().AsString();

                dataInstance.events.Add(eventData);
            }

            dataInstance.variables = new List <FsmVariableData>();
            GetVariableValues(dataInstance.variables, namer, variables);

            dataInstance.globalTransitions = new List <FsmNodeData>();
            for (int i = 0; i < globalTransitions.GetChildrenCount(); i++)
            {
                AssetTypeValueField globalTransitionField = globalTransitions[i];
                FsmGlobalTransition globalTransition      = new FsmGlobalTransition()
                {
                    fsmEvent       = new FsmEvent(globalTransitionField.Get("fsmEvent")),
                    toState        = globalTransitionField.Get("toState").GetValue().AsString(),
                    linkStyle      = globalTransitionField.Get("linkStyle").GetValue().AsInt(),
                    linkConstraint = globalTransitionField.Get("linkConstraint").GetValue().AsInt(),
                    colorIndex     = (byte)globalTransitionField.Get("colorIndex").GetValue().AsInt()
                };

                FsmNodeData node = new FsmNodeData(dataInstance, globalTransition);
                dataInstance.globalTransitions.Add(node);
            }

            //dataInstance.events = new List<FsmEventData>();
            //for (int i = 0; i < events.GetChildrenCount(); i++)
            //{
            //    FsmEventData eventData = new FsmEventData();
            //    AssetTypeValueField evt = events[i];
            //    eventData.Name = evt.Get("name").GetValue().AsString();
            //    eventData.Global = evt.Get("isGlobal").GetValue().AsBool();
            //}
            //
            //dataInstance.variables = new List<FsmVariableData>();
            //for (int i = 0; i < variables.GetChildrenCount(); i++)
            //{
            //    FsmVariableData variableData = new FsmVariableData();
            //    AssetTypeValueField vars = events[i];
            //}

            return(dataInstance);
        }
示例#27
0
        private List <AssetInfo> GetFSMInfos(AssetsFile file, AssetsFileTable table, bool hasDataField)
        {
            List <AssetInfo> assetInfos = new List <AssetInfo>();
            uint             assetCount = table.assetFileInfoCount;
            uint             fsmTypeId  = 0;

            foreach (AssetFileInfoEx info in table.assetFileInfo)
            {
                bool isMono = false;
                if (fsmTypeId == 0)
                {
                    ushort monoType;
                    if (file.header.format <= 0x10)
                    {
                        monoType = info.scriptIndex;
                    }
                    else
                    {
                        monoType = file.typeTree.unity5Types[info.curFileTypeOrIndex].scriptIndex;
                    }

                    if (monoType != 0xFFFF)
                    {
                        isMono = true;
                    }
                }
                else if (info.curFileType == fsmTypeId)
                {
                    isMono = true;
                }
                if (isMono)
                {
                    AssetTypeInstance monoAti   = am.GetATI(file, info);
                    AssetExternal     ext       = am.GetExtAsset(curFile, monoAti.GetBaseField().Get("m_Script"));
                    AssetTypeInstance scriptAti = am.GetExtAsset(curFile, monoAti.GetBaseField().Get("m_Script")).instance;
                    AssetTypeInstance goAti     = am.GetExtAsset(curFile, monoAti.GetBaseField().Get("m_GameObject")).instance;
                    if (goAti == null) //found a scriptable object, oops
                    {
                        fsmTypeId = 0;
                        continue;
                    }
                    string m_Name      = goAti.GetBaseField().Get("m_Name").GetValue().AsString();
                    string m_ClassName = scriptAti.GetBaseField().Get("m_ClassName").GetValue().AsString();

                    if (m_ClassName == "PlayMakerFSM")
                    {
                        if (fsmTypeId == 0)
                        {
                            fsmTypeId = info.curFileType;
                        }

                        AssetsFileReader reader = file.reader;

                        long oldPos = reader.BaseStream.Position;
                        reader.BaseStream.Position  = info.absoluteFilePos;
                        reader.BaseStream.Position += 28;
                        uint length = reader.ReadUInt32();
                        reader.ReadBytes((int)length);

                        reader.Align();

                        reader.BaseStream.Position += 16;

                        if (!hasDataField)
                        {
                            reader.BaseStream.Position -= 4;
                        }

                        uint   length2 = reader.ReadUInt32();
                        string fsmName = Encoding.UTF8.GetString(reader.ReadBytes((int)length2));
                        reader.BaseStream.Position = oldPos;

                        assetInfos.Add(new AssetInfo()
                        {
                            id   = info.index,
                            size = info.curFileSize,
                            name = m_Name + "-" + fsmName
                        });
                    }
                }
            }

            assetInfos.Sort((x, y) => x.name.CompareTo(y.name));

            return(assetInfos);
        }
示例#28
0
        private void LoadFSMs(string path)
        {
            string folderName = Path.GetDirectoryName(path);

            curFile = am.LoadAssetsFile(path, true);
            am.UpdateDependencies();

            AssetsFile      file  = curFile.file;
            AssetsFileTable table = curFile.table;

            List <AssetInfo> assetInfos = new List <AssetInfo>();
            uint             assetCount = table.assetFileInfoCount;
            uint             fsmTypeId  = 0;

            foreach (AssetFileInfoEx info in table.pAssetFileInfo)
            {
                bool isMono = false;
                if (fsmTypeId == 0)
                {
                    ushort monoType = file.typeTree.pTypes_Unity5[info.curFileTypeOrIndex].scriptIndex;
                    if (monoType != 0xFFFF)
                    {
                        isMono = true;
                    }
                }
                else if (info.curFileType == fsmTypeId)
                {
                    isMono = true;
                }
                if (isMono)
                {
                    AssetTypeInstance monoAti   = am.GetATI(file, info);
                    AssetTypeInstance scriptAti = am.GetExtAsset(curFile, monoAti.GetBaseField().Get("m_Script")).instance;
                    AssetTypeInstance goAti     = am.GetExtAsset(curFile, monoAti.GetBaseField().Get("m_GameObject")).instance;
                    if (goAti == null) //found a scriptable object, oops
                    {
                        fsmTypeId = 0;
                        continue;
                    }
                    string m_Name      = goAti.GetBaseField().Get("m_Name").GetValue().AsString();
                    string m_ClassName = scriptAti.GetBaseField().Get("m_ClassName").GetValue().AsString();

                    if (m_ClassName == "PlayMakerFSM")
                    {
                        if (fsmTypeId == 0)
                        {
                            fsmTypeId = info.curFileType;
                        }

                        BinaryReader reader = file.reader;

                        long oldPos = reader.BaseStream.Position;
                        reader.BaseStream.Position  = (long)info.absoluteFilePos;
                        reader.BaseStream.Position += 28;
                        uint length = reader.ReadUInt32();
                        reader.ReadBytes((int)length);

                        long pad = 4 - (reader.BaseStream.Position % 4);
                        if (pad != 4)
                        {
                            reader.BaseStream.Position += pad;
                        }

                        reader.BaseStream.Position += 16;

                        uint   length2 = reader.ReadUInt32();
                        string fsmName = Encoding.ASCII.GetString(reader.ReadBytes((int)length2));
                        reader.BaseStream.Position = oldPos;

                        assetInfos.Add(new AssetInfo()
                        {
                            id   = info.index,
                            size = info.curFileSize,
                            name = m_Name + "-" + fsmName
                        });
                    }
                }
            }
            assetInfos.Sort((x, y) => x.name.CompareTo(y.name));
            FSMSelector selector = new FSMSelector(assetInfos);

            selector.ShowDialog();

            //todo separate into separate method(s)
            if (selector.selectedID == -1)
            {
                return;
            }

            AssetFileInfoEx afi = table.getAssetInfo((ulong)selector.selectedID);

            string  tabName = assetInfos.FirstOrDefault(i => i.id == (ulong)selector.selectedID).name;
            TabItem tab     = new TabItem
            {
                //Name = tabName.Replace(" ","").Replace("-","_").Replace("(","_").Replace(")","_"),
                Header = tabName
            };

            ignoreChangeEvent = true;
            fsmTabControl.Items.Add(tab);
            fsmTabControl.SelectedItem = tab;
            ignoreChangeEvent          = false;

            SaveAndClearNodes();
            mt.Matrix = Matrix.Identity;

            currentTab++;

            AssetTypeValueField baseField = am.GetMonoBaseFieldCached(curFile, afi, Path.Combine(Path.GetDirectoryName(curFile.path), "Managed"));

            //from uabe
            //ClassDatabaseType cldt = AssetHelper.FindAssetClassByID(am.classFile, afi.curFileType);
            //AssetTypeTemplateField pBaseField = new AssetTypeTemplateField();
            //pBaseField.FromClassDatabase(am.classFile, cldt, 0);
            //AssetTypeInstance mainAti = new AssetTypeInstance(1, new[] { pBaseField }, file.reader, false, afi.absoluteFilePos);
            //AssetTypeTemplateField[] desMonos;
            //desMonos = TryDeserializeMono(mainAti, am, folderName);
            //if (desMonos != null)
            //{
            //    AssetTypeTemplateField[] templateField = pBaseField.children.Concat(desMonos).ToArray();
            //    pBaseField.children = templateField;
            //    pBaseField.childrenCount = (uint)pBaseField.children.Length;
            //
            //    mainAti = new AssetTypeInstance(1, new[] { pBaseField }, file.reader, false, afi.absoluteFilePos);
            //}
            //AssetTypeValueField baseField = mainAti.GetBaseField();

            AssetTypeValueField fsm               = baseField.Get("fsm");
            AssetTypeValueField states            = fsm.Get("states");
            AssetTypeValueField globalTransitions = fsm.Get("globalTransitions");

            dataVersion = fsm.Get("dataVersion").GetValue().AsInt();
            for (int i = 0; i < states.GetValue().AsArray().size; i++)
            {
                AssetTypeValueField state = states.Get((uint)i);
                //move all of this into node
                string name = state.Get("name").GetValue().AsString();
                AssetTypeValueField rect = state.Get("position");
                Rect dotNetRect          = new Rect(rect.Get("x").GetValue().AsFloat(),
                                                    rect.Get("y").GetValue().AsFloat(),
                                                    rect.Get("width").GetValue().AsFloat(),
                                                    rect.Get("height").GetValue().AsFloat());
                AssetTypeValueField transitions   = state.Get("transitions");
                uint            transitionCount   = transitions.GetValue().AsArray().size;
                FsmTransition[] dotNetTransitions = new FsmTransition[transitionCount];
                for (int j = 0; j < transitionCount; j++)
                {
                    dotNetTransitions[j] = new FsmTransition(transitions.Get((uint)j));
                }
                Node node = new Node(state, name, dotNetRect, dotNetTransitions);
                nodes.Add(node);

                node.grid.MouseLeftButtonDown += (object sender, MouseButtonEventArgs e) =>
                {
                    foreach (Node node2 in nodes)
                    {
                        node2.Selected = false;
                    }
                    node.Selected = true;
                    SidebarData(node, curFile);
                };

                graphCanvas.Children.Add(node.grid);
            }
            for (int i = 0; i < globalTransitions.GetValue().AsArray().size; i++)
            {
                AssetTypeValueField transition = globalTransitions.Get((uint)i);

                FsmTransition dotNetTransition = new FsmTransition(transition);
                Node          toNode           = nodes.FirstOrDefault(n => n.name == dotNetTransition.toState);

                if (toNode == null)
                {
                    System.Diagnostics.Debug.WriteLine("transition " + dotNetTransition.fsmEvent.name + " going to non-existant node " + dotNetTransition.toState);
                }
                else
                {
                    Rect rect = new Rect(
                        toNode.Transform.X,
                        toNode.Transform.Y - 50,
                        toNode.Transform.Width,
                        18);

                    if (toNode != null)
                    {
                        Node node = new Node(null, dotNetTransition.fsmEvent.name, rect, new[] { dotNetTransition });
                        nodes.Add(node);

                        graphCanvas.Children.Add(node.grid);
                    }
                }
            }
            foreach (Node node in nodes)
            {
                if (node.transitions.Length <= 0)
                {
                    continue;
                }

                float yPos = 24;
                foreach (FsmTransition trans in node.transitions)
                {
                    Node endNode = nodes.FirstOrDefault(n => n.name == trans.toState);
                    if (endNode != null)
                    {
                        Point start, end, startMiddle, endMiddle;

                        if (node.state != null)
                        {
                            start = ComputeLocation(node, endNode, yPos, out bool isLeftStart);
                            end   = ComputeLocation(endNode, node, 10, out bool isLeftEnd);

                            double dist = 70;

                            if (isLeftStart == isLeftEnd)
                            {
                                dist *= 0.5;
                            }

                            if (!isLeftStart)
                            {
                                startMiddle = new Point(start.X - dist, start.Y);
                            }
                            else
                            {
                                startMiddle = new Point(start.X + dist, start.Y);
                            }

                            if (!isLeftEnd)
                            {
                                endMiddle = new Point(end.X - dist, end.Y);
                            }
                            else
                            {
                                endMiddle = new Point(end.X + dist, end.Y);
                            }
                        }
                        else
                        {
                            start = new Point(node.Transform.X + node.Transform.Width / 2,
                                              node.Transform.Y + node.Transform.Height);
                            end = new Point(endNode.Transform.X + endNode.Transform.Width / 2,
                                            endNode.Transform.Y);
                            startMiddle = new Point(start.X, start.Y + 1);
                            endMiddle   = new Point(end.X, end.Y - 1);
                        }


                        CurvedArrow arrow = new CurvedArrow()
                        {
                            Points = new PointCollection(new List <Point>()
                            {
                                start,
                                startMiddle,
                                endMiddle,
                                end
                            }),
                            StrokeThickness  = 2,
                            Stroke           = Brushes.Black,
                            Fill             = Brushes.Black,
                            IsHitTestVisible = true
                        };

                        arrow.MouseEnter += (object sender, MouseEventArgs e) =>
                        {
                            arrow.Stroke = Brushes.LightGray;
                            arrow.Fill   = Brushes.LightGray;
                        };

                        arrow.MouseLeave += (object sender, MouseEventArgs e) =>
                        {
                            arrow.Stroke = Brushes.Black;
                            arrow.Fill   = Brushes.Black;
                        };

                        Panel.SetZIndex(arrow, -1);

                        graphCanvas.Children.Add(arrow);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine(node.name + " failed to connect to " + trans.toState);
                    }
                    yPos += 16;
                }
            }
            AssetTypeValueField events = fsm.Get("events");

            for (int i = 0; i < events.GetValue().AsArray().size; i++)
            {
                AssetTypeValueField @event = events.Get((uint)i);
                string name          = @event.Get("name").GetValue().AsString();
                bool   isSystemEvent = @event.Get("isSystemEvent").GetValue().AsBool();
                bool   isGlobal      = @event.Get("isGlobal").GetValue().AsBool();

                eventList.Children.Add(CreateSidebarRow(name, isSystemEvent, isGlobal));
            }
            AssetTypeValueField variables           = fsm.Get("variables");
            AssetTypeValueField floatVariables      = variables.Get("floatVariables");
            AssetTypeValueField intVariables        = variables.Get("intVariables");
            AssetTypeValueField boolVariables       = variables.Get("boolVariables");
            AssetTypeValueField stringVariables     = variables.Get("stringVariables");
            AssetTypeValueField vector2Variables    = variables.Get("vector2Variables");
            AssetTypeValueField vector3Variables    = variables.Get("vector3Variables");
            AssetTypeValueField colorVariables      = variables.Get("colorVariables");
            AssetTypeValueField rectVariables       = variables.Get("rectVariables");
            AssetTypeValueField quaternionVariables = variables.Get("quaternionVariables");
            AssetTypeValueField gameObjectVariables = variables.Get("gameObjectVariables");
            AssetTypeValueField objectVariables     = variables.Get("objectVariables");
            AssetTypeValueField materialVariables   = variables.Get("materialVariables");
            AssetTypeValueField textureVariables    = variables.Get("textureVariables");
            AssetTypeValueField arrayVariables      = variables.Get("arrayVariables");
            AssetTypeValueField enumVariables       = variables.Get("enumVariables");

            variableList.Children.Add(CreateSidebarHeader("Floats"));
            for (int i = 0; i < floatVariables.GetValue().AsArray().size; i++)
            {
                string name  = floatVariables.Get((uint)i).Get("name").GetValue().AsString();
                string value = floatVariables.Get((uint)i).Get("value").GetValue().AsFloat().ToString();
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
            variableList.Children.Add(CreateSidebarHeader("Ints"));
            for (int i = 0; i < intVariables.GetValue().AsArray().size; i++)
            {
                string name  = intVariables.Get((uint)i).Get("name").GetValue().AsString();
                string value = intVariables.Get((uint)i).Get("value").GetValue().AsInt().ToString();
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
            variableList.Children.Add(CreateSidebarHeader("Bools"));
            for (int i = 0; i < boolVariables.GetValue().AsArray().size; i++)
            {
                string name  = boolVariables.Get((uint)i).Get("name").GetValue().AsString();
                string value = boolVariables.Get((uint)i).Get("value").GetValue().AsBool().ToString().ToLower();
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
            variableList.Children.Add(CreateSidebarHeader("Strings"));
            for (int i = 0; i < stringVariables.GetValue().AsArray().size; i++)
            {
                string name  = stringVariables.Get((uint)i).Get("name").GetValue().AsString();
                string value = stringVariables.Get((uint)i).Get("value").GetValue().AsString();
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
            variableList.Children.Add(CreateSidebarHeader("Vector2s"));
            for (int i = 0; i < vector2Variables.GetValue().AsArray().size; i++)
            {
                string name = vector2Variables.Get((uint)i).Get("name").GetValue().AsString();
                AssetTypeValueField vector2 = vector2Variables.Get((uint)i).Get("value");
                string value = vector2.Get("x").GetValue().AsFloat().ToString() + ", ";
                value += vector2.Get("y").GetValue().AsFloat().ToString();
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
            variableList.Children.Add(CreateSidebarHeader("Vector3s"));
            for (int i = 0; i < vector3Variables.GetValue().AsArray().size; i++)
            {
                string name = vector3Variables.Get((uint)i).Get("name").GetValue().AsString();
                AssetTypeValueField vector3 = vector3Variables.Get((uint)i).Get("value");
                string value = vector3.Get("x").GetValue().AsFloat().ToString() + ", ";
                value += vector3.Get("x").GetValue().AsFloat().ToString() + ", ";
                value += vector3.Get("z").GetValue().AsFloat().ToString();
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
            variableList.Children.Add(CreateSidebarHeader("Colors"));
            for (int i = 0; i < colorVariables.GetValue().AsArray().size; i++)
            {
                string name = colorVariables.Get((uint)i).Get("name").GetValue().AsString();
                AssetTypeValueField color = colorVariables.Get((uint)i).Get("value");
                string value = ((int)(color.Get("r").GetValue().AsFloat()) * 255).ToString("X2");
                value += ((int)(color.Get("g").GetValue().AsFloat()) * 255).ToString("X2");
                value += ((int)(color.Get("b").GetValue().AsFloat()) * 255).ToString("X2");
                value += ((int)(color.Get("a").GetValue().AsFloat()) * 255).ToString("X2");
                Grid    sidebarRow = CreateSidebarRow(name, value);
                TextBox textBox    = sidebarRow.Children.OfType <TextBox>().FirstOrDefault();
                textBox.BorderBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#" + value));
                variableList.Children.Add(sidebarRow);
            }
            variableList.Children.Add(CreateSidebarHeader("Rects"));
            for (int i = 0; i < rectVariables.GetValue().AsArray().size; i++)
            {
                string name = rectVariables.Get((uint)i).Get("name").GetValue().AsString();
                AssetTypeValueField rect = rectVariables.Get((uint)i).Get("value");
                string value             = rect.Get("x").GetValue().AsFloat().ToString() + ", ";
                value += rect.Get("y").GetValue().AsFloat().ToString() + ", ";
                value += rect.Get("width").GetValue().AsFloat().ToString() + ", ";
                value += rect.Get("height").GetValue().AsFloat().ToString();
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
            variableList.Children.Add(CreateSidebarHeader("Quaternions"));
            for (int i = 0; i < quaternionVariables.GetValue().AsArray().size; i++)
            {
                string name = quaternionVariables.Get((uint)i).Get("name").GetValue().AsString();
                AssetTypeValueField rect = quaternionVariables.Get((uint)i).Get("value");
                string value             = rect.Get("x").GetValue().AsFloat().ToString() + ", ";
                value += rect.Get("y").GetValue().AsFloat().ToString() + ", ";
                value += rect.Get("z").GetValue().AsFloat().ToString() + ", ";
                value += rect.Get("w").GetValue().AsFloat().ToString();
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
            variableList.Children.Add(CreateSidebarHeader("GameObjects"));
            for (int i = 0; i < gameObjectVariables.GetValue().AsArray().size; i++)
            {
                string name = gameObjectVariables.Get((uint)i).Get("name").GetValue().AsString();
                AssetTypeValueField gameObject = gameObjectVariables.Get((uint)i).Get("value");
                int  m_FileID = gameObject.Get("m_FileID").GetValue().AsInt();
                long m_PathID = gameObject.Get("m_PathID").GetValue().AsInt64();

                string value;
                if (m_PathID != 0)
                {
                    value = $"[{m_FileID},{m_PathID}]";
                }
                else
                {
                    value = "";
                }
                variableList.Children.Add(CreateSidebarRow(name, value));
            }
        }
示例#29
0
        public static byte[] CreateBundleFromLevel(AssetsManager am, AssetsFileInstance inst)
        {
            AssetsFile      file  = inst.file;
            AssetsFileTable table = inst.table;

            string folderName = Path.GetDirectoryName(inst.path);

            ulong pathId = 2;
            List <AssetsReplacer>       assets   = new List <AssetsReplacer>();
            Dictionary <AssetID, ulong> assetMap = new Dictionary <AssetID, ulong>();

            //get all sprites

            int i = 0;
            List <AssetFileInfoEx> infos     = table.GetAssetsOfType(0xD4);
            List <ulong>           spriteIds = new List <ulong>();

            foreach (AssetFileInfoEx info in infos)
            {
                //honestly this is a really trash way to do this
                //we have a better scene exporter but it would
                //take some work to fix it up and block certain assets

                EditorUtility.DisplayProgressBar("HKEdit", "Creating scene bundle", i / (float)infos.Count);

                AssetTypeValueField baseField = GetBaseField(am, file, info);

                AssetTypeValueField m_Sprite   = baseField.Get("m_Sprite");
                AssetFileInfoEx     spriteInfo = am.GetExtAsset(inst, m_Sprite, true).info;
                AssetsFileInstance  spriteInst;
                if (m_Sprite.Get("m_FileID").GetValue().AsInt() == 0)
                {
                    spriteInst = inst;
                }
                else
                {
                    spriteInst = inst.dependencies[m_Sprite.Get("m_FileID").GetValue().AsInt() - 1];
                }

                int  spriteFileId = m_Sprite.Get("m_FileID").GetValue().AsInt();
                long spritePathId = m_Sprite.Get("m_PathID").GetValue().AsInt64();
                if (assetMap.ContainsKey(new AssetID(Path.GetFileName(spriteInst.path), spritePathId)) || (spriteFileId == 0 && spritePathId == 0))
                {
                    i++;
                    continue;
                }

                AssetTypeValueField spriteBaseField = GetBaseField(am, spriteInst.file, spriteInfo);

                AssetTypeValueField m_RD = spriteBaseField.Get("m_RD");

                AssetTypeValueField texture      = m_RD.Get("texture");
                AssetTypeValueField alphaTexture = m_RD.Get("alphaTexture");

                AssetsFileInstance textureInst, alphaTextureInst;
                if (texture.Get("m_FileID").GetValue().AsInt() == 0)
                {
                    textureInst = spriteInst;
                }
                else
                {
                    textureInst = spriteInst.dependencies[texture.Get("m_FileID").GetValue().AsInt() - 1];
                }

                if (alphaTexture.Get("m_FileID").GetValue().AsInt() == 0)
                {
                    alphaTextureInst = spriteInst;
                }
                else
                {
                    alphaTextureInst = spriteInst.dependencies[alphaTexture.Get("m_FileID").GetValue().AsInt() - 1];
                }

                AssetTypeInstance textureAti      = am.GetExtAsset(spriteInst, texture, false).instance;
                AssetTypeInstance alphaTextureAti = am.GetExtAsset(spriteInst, alphaTexture, false).instance;

                ulong textureId = 0, alphaTextureId = 0;

                if (textureAti != null)
                {
                    AssetID id = new AssetID(Path.GetFileName(textureInst.path), texture.Get("m_PathID").GetValue().AsInt64());
                    if (!assetMap.ContainsKey(id))
                    {
                        textureId = pathId;
                        assetMap.Add(id, pathId);
                        assets.Add(TextureConverter.ConvertTexture(textureAti.GetBaseField(), pathId++, folderName));
                    }
                    else
                    {
                        textureId = assetMap[id];
                    }
                }
                if (alphaTextureAti != null)
                {
                    AssetID id = new AssetID(Path.GetFileName(alphaTextureInst.path), alphaTexture.Get("m_PathID").GetValue().AsInt64());
                    if (!assetMap.ContainsKey(id))
                    {
                        alphaTextureId = pathId;
                        assetMap.Add(id, pathId);
                        assets.Add(TextureConverter.ConvertTexture(alphaTextureAti.GetBaseField(), pathId++, folderName));
                    }
                    else
                    {
                        alphaTextureId = assetMap[id];
                    }
                }
                AssetTypeValueField m_Materials = baseField.Get("m_Materials").Get("Array");
                if (m_Materials.GetValue().AsArray().size > 0)
                {
                    AssetTypeValueField material = baseField.Get("m_Materials").Get("Array")[0];
                    AssetsFileInstance  materialInst;

                    int materialFileId = material.Get("m_FileID").GetValue().AsInt();

                    if (materialFileId == 0)
                    {
                        materialInst = inst;
                    }
                    else
                    {
                        materialInst = inst.dependencies[materialFileId - 1];
                    }

                    AssetID materialId = new AssetID(Path.GetFileName(materialInst.path), material.Get("m_PathID").GetValue().AsInt64());
                    if (!assetMap.ContainsKey(materialId))
                    {
                        AssetTypeValueField materialBaseField = am.GetExtAsset(inst, material).instance.GetBaseField();

                        AssetTypeValueField shader = materialBaseField.Get("m_Shader");

                        ulong shaderPathId = RecurseShaderDependencies(am, materialInst, pathId, shader, assets, assetMap, out pathId);

                        assetMap.Add(materialId, pathId);
                        assets.Add(MaterialConverter.ConvertMaterial(materialBaseField, pathId++, shaderPathId));
                    }
                }

                assetMap.Add(new AssetID(Path.GetFileName(spriteInst.path), spritePathId), pathId);
                spriteIds.Add(pathId);
                assets.Add(SpriteConverter.ConvertSprite(spriteBaseField, pathId++, textureId, alphaTextureId));
                i++;
            }

            assetMap.Add(new AssetID(0), pathId);
            assets.Add(HeaderInformation.CreateHeaderInformation(assetMap, pathId++));

            assets.Insert(0, BundleMeta.CreateBundleInformation(assetMap, spriteIds, 1));
            //assets.Add(BundleMeta.CreateBundleInformation(assetMap, 1));

            //todo: pull from original assets file, cldb is not always update to date
            List <Type_0D> types = new List <Type_0D>
            {
                FixTypeTree(C2T5.Cldb2TypeTree(am.classFile, 0x8E)), //AssetBundle
                FixTypeTree(C2T5.Cldb2TypeTree(am.classFile, 0x1C)), //Texture2D
                FixTypeTree(C2T5.Cldb2TypeTree(am.classFile, 0x31)), //TextAsset
                FixTypeTree(C2T5.Cldb2TypeTree(am.classFile, 0xD4)), //SpriteRenderer
                FixTypeTree(C2T5.Cldb2TypeTree(am.classFile, 0xD5)), //Sprite
                //FixTypeTree(C2T5.Cldb2TypeTree(am.classFile, 0x31)), //TextAsset
                FixTypeTree(C2T5.Cldb2TypeTree(am.classFile, 0x15)), //Material
                FixTypeTree(C2T5.Cldb2TypeTree(am.classFile, 0x30))  //Shader
            };

            const string ver = "2017.4.10f1";

            //const string ver = "2018.2.1f1";

            byte[]     blankData = BundleCreator.CreateBlankAssets(ver, types);
            AssetsFile blankFile = new AssetsFile(new AssetsFileReader(new MemoryStream(blankData)));

            byte[] data = null;
            using (MemoryStream ms = new MemoryStream())
                using (AssetsFileWriter writer = new AssetsFileWriter(ms))
                {
                    blankFile.WriteFix(writer, 0, assets.ToArray(), 0);
                    data = ms.ToArray();
                }

            EditorUtility.DisplayProgressBar("HKEdit", "Creating bundle", 1);
            using (MemoryStream ms = new MemoryStream())
                using (AssetsFileWriter writer = new AssetsFileWriter(ms))
                {
                    BundleCreator.CreateBlankBundle(ver, data.Length).Write(writer, data);
                    return(ms.ToArray());
                }
        }
示例#30
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (startedScanning || finishedScanning)
            {
                return;
            }
            startedScanning    = true;
            loadingBar.Maximum = details.Count;

            Dictionary <ulong, string> monos = new Dictionary <ulong, string>();

            BackgroundWorker bw = new BackgroundWorker();

            bw.WorkerReportsProgress = true;
            bw.DoWork += delegate(object s, DoWorkEventArgs ev) {
                for (int i = 0; i < details.Count; i++)
                {
                    try
                    {
                        AssetDetails ad = details[i];
                        if (ad.fileID != 0 && !checkBox1.Checked)
                        {
                            continue;
                        }
                        string text = null;
                        if (ad.typeName == "MonoBehaviour")
                        {
                            if (ad.name != "MonoBehaviour")
                            {
                                text = ad.name + " (" + ad.fileID + "/" + ad.pathID + ")";
                            }
                            else
                            {
                                AssetTypeInstance behaviourAti = manager.GetATI(manager.GetStream(ad.fileID), manager.GetInfo(ad.fileID, ad.pathID));
                                AssetTypeInstance scriptAti    = manager.GetExtAsset(behaviourAti.GetBaseField().Get("m_Script")).instance;
                                if (scriptAti != null)
                                {
                                    string scriptName = scriptAti.GetBaseField().Get("m_Name").GetValue().AsString();
                                    text = scriptName + " (" + ad.fileID + "/" + ad.pathID + ")";
                                }
                                else
                                {
                                    text = "(unknown)";
                                }
                            }
                            monos.Add(ad.pathID, text);
                        }
                        bw.ReportProgress(i);
                    } catch (Exception ex)
                    {
                    }
                }
                for (int i = 0; i < details.Count; i++)
                {
                    AssetDetails ad = details[i];
                    if (ad.fileID != 0 && !checkBox1.Checked)
                    {
                        continue;
                    }
                    if (ad.typeName == "GameObject")
                    {
                        AssetTypeInstance   gameObjectAti = manager.GetATI(manager.GetStream(ad.fileID), manager.GetInfo(ad.fileID, ad.pathID));
                        AssetTypeValueField components    = gameObjectAti.GetBaseField().Get("m_Component").Get("Array");
                        for (uint j = 0; j < components.GetValue().AsArray().size; j++)
                        {
                            long id = components.Get(j).Get("component").Get("m_PathID").GetValue().AsInt64();
                            if (monos.ContainsKey((ulong)id))
                            {
                                monos[(ulong)id] += " -> " + gameObjectAti.GetBaseField().Get("m_Name").GetValue().AsString() + "(" + ad.fileID + "/" + ad.pathID + ")";
                            }
                        }
                        bw.ReportProgress(i);
                    }
                }
                foreach (string str in monos.Values)
                {
                    bw.ReportProgress(details.Count, str);
                }
                startedScanning  = false;
                finishedScanning = true;
                bw.ReportProgress(details.Count, "COMPLETELY_FINISHED");
            };
            bw.ProgressChanged += delegate(object s, ProgressChangedEventArgs ev) {
                loadingBar.Value = ev.ProgressPercentage;
                if (ev.UserState is object[])
                {
                    object[] obj = (object[])ev.UserState;
                    if ((string)obj[0] == "ERROR")
                    {
                        System.Diagnostics.Debug.WriteLine(((Exception)obj[1]).Message);
                    }
                }
                if (ev.UserState != null)
                {
                    if ((string)ev.UserState == "COMPLETELY_FINISHED")
                    {
                        List <string> lines = new List <string>();
                        for (int i = 0; i < listBox1.Items.Count; i++)
                        {
                            lines.Add(listBox1.Items[i].ToString());
                        }
                        lines.Add("====");
                        for (int i = 0; i < listBox1.Items.Count; i++)
                        {
                            lines.Add(listBox1.Items[i].ToString().Substring(0, listBox1.Items[i].ToString().IndexOf("(")));
                        }
                    }
                    else
                    {
                        listBox1.Items.Add(ev.UserState);
                    }
                }
            };
            bw.RunWorkerAsync();
        }