public FsmEvent(AssetTypeValueField valueField) { name = valueField.Get("name").GetValue().AsString(); isSystemEvent = valueField.Get("isSystemEvent").GetValue().AsBool(); isGlobal = valueField.Get("isGlobal").GetValue().AsBool(); }
public static ulong RecurseShaderDependencies(AssetsManager am, AssetsFileInstance baseInst, ulong pathId, AssetTypeValueField shaderPPtr, List <AssetsReplacer> assets, Dictionary <AssetID, ulong> assetMap, out ulong outPathId) { //UnityEngine.Debug.Log("RSD Running"); AssetsFileInstance shaderInst; int shaderFileId = shaderPPtr.Get("m_FileID").GetValue().AsInt(); if (shaderFileId == 0) { shaderInst = baseInst; } else { shaderInst = baseInst.dependencies[shaderFileId - 1]; } AssetID shaderId = new AssetID(Path.GetFileName(shaderInst.path), shaderPPtr.Get("m_PathID").GetValue().AsInt64()); if (assetMap.ContainsKey(shaderId)) { outPathId = pathId; return(assetMap[shaderId]); } AssetTypeValueField shaderBaseField = am.GetExtAsset(baseInst, shaderPPtr).instance.GetBaseField(); List <ulong> dependencies = new List <ulong>(); AssetTypeValueField m_Dependencies = shaderBaseField.Get("m_Dependencies").Get("Array"); foreach (AssetTypeValueField m_Dependency in m_Dependencies.pChildren) { //UnityEngine.Debug.Log("from file " + Path.GetFileName(baseInst.path) + shaderPPtr.Get("m_FileID").GetValue().AsInt() + ":" + shaderPPtr.Get("m_PathID").GetValue().AsInt() + " getting pptr " + m_Dependency.Get("m_FileID").GetValue().AsInt() + ":" + m_Dependency.Get("m_PathID").GetValue().AsInt64()); dependencies.Add(RecurseShaderDependencies(am, shaderInst, pathId, m_Dependency, assets, assetMap, out pathId)); } ulong shaderPathid = pathId; assetMap.Add(shaderId, pathId); assets.Add(ShaderConverter.ConvertShader(shaderBaseField, pathId++, dependencies)); outPathId = pathId; return(shaderPathid); }
public static string GetDisplayValue(AssetTypeValueField actionData, AssetsFileInstance inst, int version, ParamDataType type, int paramDataPos, int paramByteDataSize, BinaryReader reader) { string displayValue = "[?] " + type; if (version == 1 && !(type == ParamDataType.FsmString && paramByteDataSize == 0)) //read binary as normal { switch (type) { case ParamDataType.Integer: case ParamDataType.FsmInt: case ParamDataType.FsmEnum: { displayValue = reader.ReadInt32().ToString(); break; } case ParamDataType.Enum: { displayValue = "Enum " + reader.ReadInt32().ToString(); break; } case ParamDataType.Boolean: case ParamDataType.FsmBool: { displayValue = reader.ReadBoolean().ToString().ToLower(); break; } case ParamDataType.Float: case ParamDataType.FsmFloat: { displayValue = reader.ReadSingle().ToString(); break; } case ParamDataType.String: case ParamDataType.FsmString: case ParamDataType.FsmEvent: { displayValue = Encoding.UTF8.GetString(reader.ReadBytes(paramByteDataSize)); break; } case ParamDataType.Vector2: case ParamDataType.FsmVector2: { string x = reader.ReadSingle().ToString(); string y = reader.ReadSingle().ToString(); displayValue = x + ", " + y; break; } case ParamDataType.Vector3: case ParamDataType.FsmVector3: { string x = reader.ReadSingle().ToString(); string y = reader.ReadSingle().ToString(); string z = reader.ReadSingle().ToString(); displayValue = x + ", " + y + ", " + z; break; } } if (PossiblyHasName(type)) { int length = (paramByteDataSize + paramDataPos) - (int)reader.BaseStream.Position; if (length > 0) { byte hasName = reader.ReadByte(); if (hasName == 0x01) { string varName = Encoding.UTF8.GetString(reader.ReadBytes(length - 1)); if (varName != "") { displayValue = varName; } } } } } else //read from fsmXXXParams { AssetTypeValueField field = null; switch (type) { case ParamDataType.Integer: { displayValue = reader.ReadInt32().ToString(); break; } case ParamDataType.Enum: { displayValue = "Enum " + reader.ReadInt32().ToString(); break; } case ParamDataType.Boolean: { displayValue = reader.ReadBoolean().ToString().ToLower(); break; } case ParamDataType.Float: { displayValue = reader.ReadSingle().ToString(); break; } case ParamDataType.String: { displayValue = Encoding.UTF8.GetString(reader.ReadBytes(paramByteDataSize)); break; } case ParamDataType.Vector2: { string x = reader.ReadSingle().ToString(); string y = reader.ReadSingle().ToString(); displayValue = x + ", " + y; break; } case ParamDataType.Vector3: { string x = reader.ReadSingle().ToString(); string y = reader.ReadSingle().ToString(); string z = reader.ReadSingle().ToString(); displayValue = x + ", " + y + ", " + z; break; } case ParamDataType.FsmInt: { field = actionData.Get("fsmIntParams").Get(paramDataPos); displayValue = field.Get("value").GetValue().AsInt().ToString(); break; } case ParamDataType.FsmEnum: { field = actionData.Get("fsmEnumParams").Get(paramDataPos); string intValue = field.Get("intValue").GetValue().AsInt().ToString(); string enumName = field.Get("enumName").GetValue().AsString().ToString(); displayValue = $"{intValue} ({enumName})"; break; } case ParamDataType.FsmBool: { field = actionData.Get("fsmBoolParams").Get(paramDataPos); displayValue = field.Get("value").GetValue().AsBool().ToString(); break; } case ParamDataType.FsmFloat: { field = actionData.Get("fsmFloatParams").Get(paramDataPos); displayValue = field.Get("value").GetValue().AsFloat().ToString(); break; } case ParamDataType.FsmString: { field = actionData.Get("fsmStringParams").Get(paramDataPos); displayValue = field.Get("value").GetValue().AsString(); break; } case ParamDataType.FsmEvent: { field = actionData.Get("stringParams").Get(paramDataPos); displayValue = field.GetValue().AsString(); break; } case ParamDataType.FsmVector2: { field = actionData.Get("fsmVector2Params").Get(paramDataPos); AssetTypeValueField value = field.Get("value"); string x = value.Get("x").GetValue().AsFloat().ToString(); string y = value.Get("y").GetValue().AsFloat().ToString(); displayValue = x + ", " + y; break; } case ParamDataType.FsmVector3: { field = actionData.Get("fsmVector3Params").Get(paramDataPos); AssetTypeValueField value = field.Get("value"); string x = value.Get("x").GetValue().AsFloat().ToString(); string y = value.Get("y").GetValue().AsFloat().ToString(); string z = value.Get("z").GetValue().AsFloat().ToString(); displayValue = x + ", " + y + ", " + z; break; } case ParamDataType.FsmQuaternion: { field = actionData.Get("fsmVector3Params").Get(paramDataPos); AssetTypeValueField value = field.Get("value"); string x = value.Get("x").GetValue().AsFloat().ToString(); string y = value.Get("y").GetValue().AsFloat().ToString(); string z = value.Get("z").GetValue().AsFloat().ToString(); string w = value.Get("w").GetValue().AsFloat().ToString(); displayValue = x + ", " + y + ", " + z + ", " + w; break; } default: { displayValue = "unknown type " + type.ToString(); break; } } if (PossiblyHasName(type) && UseVariable(field)) { string varName = field.Get("name").GetValue().AsString(); if (varName != "") { displayValue = varName; } } } //either version switch (type) { case ParamDataType.FsmGameObject: case ParamDataType.FsmOwnerDefault: { AssetTypeValueField gameObject; if (type == ParamDataType.FsmOwnerDefault) { AssetTypeValueField fsmOwnerDefaultParam = actionData.Get("fsmOwnerDefaultParams").Get(paramDataPos); if (fsmOwnerDefaultParam["ownerOption"].GetValue().AsInt() == 0) { displayValue = "FSM Owner"; break; } gameObject = fsmOwnerDefaultParam.Get("gameObject"); } else { gameObject = actionData.Get("fsmGameObjectParams").Get(paramDataPos); } string name = gameObject.Get("name").GetValue().AsString(); AssetTypeValueField value = gameObject.Get("value"); int m_FileID = value.Get("m_FileID").GetValue().AsInt(); long m_PathID = value.Get("m_PathID").GetValue().AsInt64(); if (name == "") { name += GetAssetNameFast(m_FileID, m_PathID, inst); } displayValue = name; if (m_PathID != 0) { if (name != "") { displayValue += " "; } displayValue += $"[{m_FileID},{m_PathID}]"; } break; } case ParamDataType.FsmObject: { AssetTypeValueField fsmObjectParam = actionData.Get("fsmObjectParams").Get(paramDataPos); string name = fsmObjectParam.Get("name").GetValue().AsString(); string typeName = fsmObjectParam.Get("typeName").GetValue().AsString(); if (typeName.Contains(".")) { typeName = typeName.Substring(typeName.LastIndexOf(".") + 1); } AssetTypeValueField value = fsmObjectParam.Get("value"); int m_FileID = value.Get("m_FileID").GetValue().AsInt(); long m_PathID = value.Get("m_PathID").GetValue().AsInt64(); displayValue = ""; if (name == "") { name += GetAssetNameFast(m_FileID, m_PathID, inst); } if (typeName != "") { displayValue += "(" + typeName + ")"; } if (name != "") { displayValue += " " + name; } if (m_PathID != 0) { displayValue += $" [{m_FileID},{m_PathID}]"; } else { displayValue += " [null]"; } break; } case ParamDataType.FsmVar: { AssetTypeValueField fsmVarParam = actionData.Get("fsmVarParams").Get(paramDataPos); bool useVariable = fsmVarParam.Get("useVariable").GetValue().AsBool(); string objectType = fsmVarParam.Get("objectType").GetValue().AsString(); VariableType variableType = (VariableType)fsmVarParam.Get("type").GetValue().AsInt(); displayValue = ""; if (objectType.Contains(".")) { objectType = objectType.Substring(objectType.LastIndexOf('.') + 1); } if (objectType != "") { displayValue += "(" + objectType + ")"; } string variableName = fsmVarParam.Get("variableName").GetValue().AsString(); if (variableName != "") { displayValue += " " + variableName; } if (!useVariable) { displayValue += " "; switch (variableType) { case VariableType.Float: displayValue += fsmVarParam.Get("floatValue").GetValue().AsFloat().ToString(); break; case VariableType.Int: displayValue += fsmVarParam.Get("intValue").GetValue().AsInt().ToString(); break; case VariableType.Bool: displayValue += fsmVarParam.Get("boolValue").GetValue().AsBool().ToString().ToLower(); break; case VariableType.String: displayValue += fsmVarParam.Get("stringValue").GetValue().AsString().ToString(); break; case VariableType.Color: case VariableType.Quaternion: case VariableType.Rect: case VariableType.Vector2: case VariableType.Vector3: AssetTypeValueField vector4Value = fsmVarParam.Get("vector4Value"); displayValue += "["; displayValue += vector4Value.Get("x").GetValue().AsInt().ToString() + ", "; displayValue += vector4Value.Get("y").GetValue().AsInt().ToString() + ", "; displayValue += vector4Value.Get("z").GetValue().AsInt().ToString() + ", "; displayValue += vector4Value.Get("w").GetValue().AsInt().ToString(); displayValue += "]"; break; case VariableType.Object: case VariableType.GameObject: case VariableType.Material: case VariableType.Texture: AssetTypeValueField objectReference = fsmVarParam.Get("objectReference"); int m_FileID = objectReference.Get("m_FileID").GetValue().AsInt(); long m_PathID = objectReference.Get("m_PathID").GetValue().AsInt64(); string name = GetAssetNameFast(m_FileID, m_PathID, inst); if (name != "") { name += " "; } displayValue += $"{name}[{m_FileID},{m_PathID}]"; break; case VariableType.Array: displayValue += ((VariableType)fsmVarParam.Get("arrayValue").Get("type").GetValue().AsInt()).ToString(); break; } } break; } case ParamDataType.ObjectReference: { AssetTypeValueField unityObjectParam = actionData.Get("unityObjectParams").Get(paramDataPos); int m_FileID = unityObjectParam.Get("m_FileID").GetValue().AsInt(); long m_PathID = unityObjectParam.Get("m_PathID").GetValue().AsInt64(); string name = GetAssetNameFast(m_FileID, m_PathID, inst); if (name != "") { name += " "; } displayValue = $"{name}[{m_FileID},{m_PathID}]"; break; } case ParamDataType.FunctionCall: { AssetTypeValueField functionCallParam = actionData.Get("functionCallParams").Get(paramDataPos); string functionName = functionCallParam.Get("FunctionName").GetValue().AsString(); string parameterType = functionCallParam.Get("parameterType").GetValue().AsString(); AssetTypeValueField field = null; switch (parameterType) { case "bool": { field = functionCallParam.Get("BoolParameter"); displayValue = field.Get("value").GetValue().AsBool().ToString().ToLower(); goto NonPPtr; } case "float": { field = functionCallParam.Get("FloatParameter"); displayValue = field.Get("value").GetValue().AsFloat().ToString(); goto NonPPtr; } case "int": { field = functionCallParam.Get("IntParameter"); displayValue = field.Get("value").GetValue().AsInt().ToString(); goto NonPPtr; } case "GameObject": { field = functionCallParam.Get("GameObjectParameter"); goto PPtr; } case "Object": { field = functionCallParam.Get("ObjectParameter"); goto PPtr; } case "string": { field = functionCallParam.Get("StringParameter"); displayValue = field.Get("value").GetValue().AsString(); goto NonPPtr; } case "Vector2": { field = functionCallParam.Get("Vector2Parameter"); AssetTypeValueField value = field.Get("value"); string x = value.Get("x").GetValue().AsFloat().ToString(); string y = value.Get("y").GetValue().AsFloat().ToString(); displayValue = x + ", " + y; goto NonPPtr; } case "Vector3": { field = functionCallParam.Get("Vector3Parameter"); AssetTypeValueField value = field.Get("value"); string x = value.Get("x").GetValue().AsFloat().ToString(); string y = value.Get("y").GetValue().AsFloat().ToString(); string z = value.Get("z").GetValue().AsFloat().ToString(); displayValue = x + ", " + y + ", " + z; goto NonPPtr; } case "Rect": { field = functionCallParam.Get("RectParameter"); AssetTypeValueField value = field.Get("value"); string x = value.Get("x").GetValue().AsFloat().ToString(); string y = value.Get("y").GetValue().AsFloat().ToString(); string width = value.Get("width").GetValue().AsFloat().ToString(); string height = value.Get("height").GetValue().AsFloat().ToString(); displayValue = "[" + x + ", " + y + "], [" + width + ", " + height + "]"; goto NonPPtr; } case "Quaternion": { field = functionCallParam.Get("QuaternionParameter"); AssetTypeValueField value = field.Get("value"); string x = value.Get("x").GetValue().AsFloat().ToString(); string y = value.Get("y").GetValue().AsFloat().ToString(); string z = value.Get("z").GetValue().AsFloat().ToString(); string w = value.Get("w").GetValue().AsFloat().ToString(); displayValue = x + ", " + y + ", " + z + ", " + w; goto NonPPtr; } case "Material": { field = functionCallParam.Get("MaterialParameter"); goto PPtr; } case "Texture": { field = functionCallParam.Get("TextureParameter"); goto PPtr; } case "Color": { field = functionCallParam.Get("ColorParameter"); AssetTypeValueField value = field.Get("value"); string r = ((int)(value.Get("r").GetValue().AsFloat()) * 255).ToString("X2"); string g = ((int)(value.Get("g").GetValue().AsFloat()) * 255).ToString("X2"); string b = ((int)(value.Get("b").GetValue().AsFloat()) * 255).ToString("X2"); string a = ((int)(value.Get("a").GetValue().AsFloat()) * 255).ToString("X2"); displayValue = "#" + r + g + b + a; goto NonPPtr; } case "Enum": { field = functionCallParam.Get("EnumParameter"); string enumName = field.Get("enumName").GetValue().AsString(); if (enumName.Contains(".")) { enumName = enumName.Substring(enumName.LastIndexOf(".") + 1); } displayValue = field.Get("value").GetValue().AsInt() + " (" + enumName + ")"; goto NonPPtr; } case "Array": { field = functionCallParam.Get("ArrayParameter"); displayValue = ""; goto NonPPtr; } case "None": { displayValue = ""; goto NonPPtr; } PPtr: { string name = field.Get("name").GetValue().AsString(); AssetTypeValueField value = field.Get("value"); int m_FileID = value.Get("m_FileID").GetValue().AsInt(); long m_PathID = value.Get("m_PathID").GetValue().AsInt64(); displayValue = functionName + "(" + name; if (name == "") { name += GetAssetNameFast(m_FileID, m_PathID, inst); } if (m_PathID != 0) { if (name != "") { displayValue += " "; } displayValue += $"[{m_FileID},{m_PathID}])"; } break; } NonPPtr: { string name = ""; if (field != null) { name = field.Get("name").GetValue().AsString(); } displayValue = name != "" ? $"{functionName}({name}: {displayValue})" : $"{functionName}({displayValue})"; break; } } break; } case ParamDataType.FsmEventTarget: { AssetTypeValueField fsmObjectParam = actionData.Get("fsmEventTargetParams").Get(paramDataPos); EventTarget target = (EventTarget)fsmObjectParam.Get("target").GetValue().AsInt(); bool exclude = fsmObjectParam.Get("excludeSelf").Get("value").GetValue().AsBool(); displayValue = target.ToString() + (exclude ? "!" : ""); break; } case ParamDataType.Array: displayValue = ""; break; } return(displayValue); }
//used as sort of a hack to handle both second and component //in m_Component which both have the pptr as the last field //(pre 5.5 has a first and second while post 5.5 has component) public static AssetTypeValueField GetLastChild(this AssetTypeValueField atvf) { return(atvf[atvf.childrenCount - 1]); }
public GameObject TilemapRenderData(AssetTypeValueField transform, string name) { GameObject tileMapRenderData = new GameObject(name); GameObject scenemap = new GameObject("Scenemap"); scenemap.transform.parent = tileMapRenderData.transform; AssetTypeValueField trdChildArray = transform.Get("m_Children").Get("Array"); uint childrenCount = trdChildArray.GetValue().AsArray().size; AssetTypeValueField sceneMap = null; for (uint i = 0; i < childrenCount; i++) { AssetTypeValueField childTf = am.GetExtAsset(assetsFileInstance, trdChildArray[i]).instance.GetBaseField(); AssetTypeValueField childGo = am.GetExtAsset(assetsFileInstance, childTf.Get("m_GameObject")).instance.GetBaseField(); if (childGo.Get("m_Name").GetValue().AsString() == "Scenemap") { sceneMap = trdChildArray[i]; } } if (sceneMap == null) { return(tileMapRenderData); } AssetTypeValueField scenemapBaseField = am.GetExtAsset(assetsFileInstance, sceneMap).instance.GetBaseField(); AssetTypeValueField scenemapChildArray = scenemapBaseField.Get("m_Children").Get("Array"); childrenCount = scenemapChildArray.GetValue().AsArray().size; for (uint i = 0; i < childrenCount; i++) { AssetTypeValueField childTf = am.GetExtAsset(assetsFileInstance, scenemapChildArray[i]).instance.GetBaseField(); AssetTypeValueField childGo = am.GetExtAsset(assetsFileInstance, childTf.Get("m_GameObject")).instance.GetBaseField(); GameObject chunk = new GameObject(childGo.Get("m_Name").GetValue().AsString()); chunk.transform.parent = scenemap.transform; AssetTypeValueField m_LocalPosition = childTf.Get("m_LocalPosition"); chunk.transform.localPosition = GetVector3(m_LocalPosition); AssetTypeValueField childComp = childGo.Get("m_Component").Get("Array"); uint componentCount = childComp.GetValue().AsArray().size; for (uint j = 1; j < componentCount; j++) { AssetsManager.AssetExternal component = am.GetExtAsset(assetsFileInstance, childComp[j].Get("component")); if (component.info.curFileType == MESHFILTER) { component = am.GetExtAsset(assetsFileInstance, childComp[j].Get("component")); AssetTypeValueField mesh = component.instance.GetBaseField().Get("m_Mesh"); AssetTypeValueField meshBaseField = am.GetExtAsset(assetsFileInstance, mesh).instance.GetBaseField(); AssetTypeValueField m_VertexData = meshBaseField.Get("m_VertexData"); AssetTypeValueField m_Channels = m_VertexData.Get("m_Channels").Get("Array"); uint channelsSize = m_Channels.GetValue().AsArray().size; int skipSize = 0; //start at 1 to skip verts for (uint k = 1; k < channelsSize; k++) { skipSize += (int)m_Channels[k].Get("dimension").GetValue().AsUInt(); } byte[] m_DataSize = GetByteData(m_VertexData.Get("m_DataSize")); uint m_VertexCount = m_VertexData.Get("m_VertexCount").GetValue().AsUInt(); Vector3[] verts = new Vector3[m_VertexCount]; int pos = 0; for (uint k = 0; k < m_VertexCount; k++) { float x = ReadFloat(m_DataSize, pos); float y = ReadFloat(m_DataSize, pos + 4); float z = ReadFloat(m_DataSize, pos + 8); verts[k] = new Vector3(x, y, z); pos += 12 + (skipSize * 4); //go past verts, then any remaining channel's data } AssetTypeValueField m_IndexBuffer = meshBaseField.Get("m_IndexBuffer").Get("Array"); uint triCount = m_IndexBuffer.GetValue().AsArray().size; int[] tris = new int[triCount / 2]; for (uint k = 0; k < triCount; k += 2) { int tri = (int)(m_IndexBuffer[k + 0].GetValue().AsUInt() | (m_IndexBuffer[k + 1].GetValue().AsUInt() << 8)); tris[k / 2] = tri; } UnityEngine.Mesh meshComponent = new UnityEngine.Mesh(); chunk.AddComponent <MeshFilter>(); chunk.AddComponent <MeshRenderer>(); chunk.GetComponent <MeshFilter>().mesh = meshComponent; meshComponent.vertices = verts; meshComponent.triangles = tris; chunk.GetComponent <MeshRenderer>().material = Resources.Load <Material>("BackMat"); break; } } } return(tileMapRenderData); }
private static bool EnableVROptions(string path) { AssetsManager assetsManager = new AssetsManager(); AssetsFileInstance assetsFileInstance = assetsManager.LoadAssetsFile(path, false, ""); assetsManager.LoadClassDatabase(Path.Combine(VREnabler.VRPatcherPath, "cldb.dat")); int num = 0; while ((long)num < (long)((ulong)assetsFileInstance.table.assetFileInfoCount)) { try { AssetFileInfoEx assetInfo = assetsFileInstance.table.GetAssetInfo((long)num); AssetTypeInstance ati = assetsManager.GetATI(assetsFileInstance.file, assetInfo, false); AssetTypeValueField assetTypeValueField = (ati != null) ? ati.GetBaseField(0) : null; AssetTypeValueField assetTypeValueField2 = (assetTypeValueField != null) ? assetTypeValueField.Get("enabledVRDevices") : null; if (assetTypeValueField2 != null) { AssetTypeValueField assetTypeValueField3 = assetTypeValueField2.Get("Array"); if (assetTypeValueField3 != null) { AssetTypeValueField assetTypeValueField4 = ValueBuilder.DefaultValueFieldFromArrayTemplate(assetTypeValueField3); assetTypeValueField4.GetValue().Set("Oculus"); AssetTypeValueField assetTypeValueField5 = ValueBuilder.DefaultValueFieldFromArrayTemplate(assetTypeValueField3); assetTypeValueField5.GetValue().Set("OpenVR"); AssetTypeValueField assetTypeValueField6 = ValueBuilder.DefaultValueFieldFromArrayTemplate(assetTypeValueField3); assetTypeValueField6.GetValue().Set("None"); assetTypeValueField3.SetChildrenList(new AssetTypeValueField[] { assetTypeValueField6, assetTypeValueField4, assetTypeValueField5 }); byte[] array; using (MemoryStream memoryStream = new MemoryStream()) { using (AssetsFileWriter assetsFileWriter = new AssetsFileWriter(memoryStream)) { assetsFileWriter.bigEndian = false; AssetWriters.Write(assetTypeValueField, assetsFileWriter, 0); array = memoryStream.ToArray(); } } List <AssetsReplacer> list = new List <AssetsReplacer> { new AssetsReplacerFromMemory(0, (long)num, (int)assetInfo.curFileType, ushort.MaxValue, array) }; using (MemoryStream memoryStream2 = new MemoryStream()) { using (AssetsFileWriter assetsFileWriter2 = new AssetsFileWriter(memoryStream2)) { assetsFileInstance.file.Write(assetsFileWriter2, 0UL, list, 0U, null); assetsFileInstance.stream.Close(); File.WriteAllBytes(path, memoryStream2.ToArray()); } } return(true); } } } catch { } num++; } VREnabler.Logger.LogError("VR enable location not found!"); return(false); }
protected abstract void Modify(AssetTypeValueField baseField);
private void RecursiveTreeLoad(AssetTypeValueField atvf, PGProperty node, AssetFileInfoEx info, string category, int depth) { if (atvf.childrenCount == 0) { return; } foreach (AssetTypeValueField atvfc in atvf.children) { if (atvfc == null) { return; } EnumValueTypes evt; if (atvfc.GetValue() != null) { evt = atvfc.GetValue().GetValueType(); if (evt != EnumValueTypes.ValueType_None) { if (1 <= (int)evt && (int)evt <= 12) { string value = atvfc.GetValue().AsString(); PGProperty prop = new PGProperty(atvfc.GetName(), value); prop.category = category; SetSelectedStateIfSelected(info, prop); node.Add(prop); RecursiveTreeLoad(atvfc, prop, info, category, depth + 1); } else if (evt == EnumValueTypes.ValueType_Array || evt == EnumValueTypes.ValueType_ByteArray) { PGProperty childProps = new PGProperty("child", null, $"[size: {atvfc.childrenCount}]"); PGProperty prop = new PGProperty(atvfc.GetName(), childProps, $"[size: {atvfc.childrenCount}]"); prop.category = category; SetSelectedStateIfSelected(info, prop); node.Add(prop); RecursiveTreeLoad(atvfc, childProps, info, category, depth + 1); } } } else { PGProperty childProps; if (atvfc.childrenCount == 2) { AssetTypeValueField fileId = atvfc.children[0]; AssetTypeValueField pathId = atvfc.children[1]; string fileIdName = fileId.templateField.name; string fileIdType = fileId.templateField.type; string pathIdName = pathId.templateField.name; string pathIdType = pathId.templateField.type; if (fileIdName == "m_FileID" && fileIdType == "int" && pathIdName == "m_PathID" && pathIdType == "SInt64") { int fileIdValue = fileId.GetValue().AsInt(); long pathIdValue = pathId.GetValue().AsInt64(); childProps = new PGProperty("child", "", $"[fileid: {fileIdValue}, pathid: {pathIdValue}]"); } else { childProps = new PGProperty("child", ""); } } else { childProps = new PGProperty("child", ""); } PGProperty prop = new PGProperty(atvfc.GetName(), childProps); prop.category = category; SetSelectedStateIfSelected(info, prop); node.Add(prop); RecursiveTreeLoad(atvfc, childProps, info, category, depth + 1); } } }
private void BuildBundleContent(ref Dictionary <string, Dictionary <string, List <string> > > result, string fileUrl, AssetFile file, AssetToolUtils assetToolUtils) { Console.WriteLine("building bundle content!"); foreach (AssetFileInfoEx info in file.fileInstance.table.assetFileInfo) { ClassDatabaseType type = AssetHelper.FindAssetClassByID(file.classDBFile, info.curFileType); if (type == null) { continue; } string typeName = type.name.GetString(file.classDBFile); if (typeName != "MonoBehaviour") { continue; } AssetTypeValueField baseField = AssetToolUtils.GetATI(file, info).GetBaseField(); List <AssetTypeValueField> targetFields = AssetToolUtils.GetFieldAtPath(file, baseField, configPath.Split(':')); if (targetFields.Count == 0) { continue; } if (!AssetToolUtils.IsMatchingPathConstraints(file, baseField, pathConstraints)) { continue; } Console.WriteLine("found " + targetFields.Count + " matches in mono-behaviour at path " + configPath); foreach (AssetTypeValueField targetField in targetFields) { List <string> mapByField = mapConfigBy.GetMapValues(fileUrl, file, baseField, targetField, assetToolUtils); Console.WriteLine("found " + mapByField.Count + " mapFields in targetField at mapConfigBy.path"); foreach (string mapValue in mapByField) { Dictionary <string, List <string> > secondaryValues = new Dictionary <string, List <string> >(); foreach (OnlineInterpreterFilter filter in configFilter) { List <string> filterValues = new List <string>(); List <AssetTypeValueField> filterFields = filter.pathType switch { EOnlineInterpreterPathType.relative => AssetToolUtils.GetFieldAtPath(file, targetField, filter.path.Split(':')), EOnlineInterpreterPathType.absolute => AssetToolUtils.GetFieldAtPath(file, baseField, filter.path.Split(':')), _ => throw new InvalidOperationException("pathType " + filter.pathType + " is not supported by OnlineSourceInterpreterConfig.cs") }; Console.WriteLine("found " + filterFields.Count + " fields at path: " + filter.path); filterValues.AddRange(filterFields .Where(field => field.GetValue() != null) .Select(field => ResolveTranslationValue(field.GetValue().AsString().Trim(), filter.outputName))); secondaryValues[filter.outputName] = filterValues; } if (result.ContainsKey(mapValue)) { foreach (string key in secondaryValues.Keys) { if (result[mapValue].ContainsKey(key)) { result[mapValue][key].AddRange(secondaryValues[key]); } else { result[mapValue][key] = secondaryValues[key]; } } } else { result[mapValue] = secondaryValues; } LevelMappingResult(ref result, mapValue); } } } }
//creates a lookup where assets from different built game files //with different fileIds and pathIds can be converted to a list //of pathIds in order with fileId 0 or 1 depending on the asset type //(stored in the references dictionary) public void SetReferences(AssetsFileInstance inst, AssetFileInfoEx inf) { AssetTypeValueField baseField = am.GetATI(inst.file, inf).GetBaseField(); SetReferencesRecurse(inst, baseField); }
private List <AssetTypeTemplateField> ReadTypes(TypeDefinition type) { List <FieldDefinition> acceptableFields = GetAcceptableFields(type); List <AssetTypeTemplateField> localChildren = new List <AssetTypeTemplateField>(); for (int i = 0; i < acceptableFields.Count; i++) { AssetTypeTemplateField field = new AssetTypeTemplateField(); FieldDefinition fieldDef = acceptableFields[i]; TypeReference fieldTypeRef = fieldDef.FieldType; TypeDefinition fieldType = fieldTypeRef.Resolve(); string fieldTypeName = fieldType.Name; bool isArrayOrList = false; if (fieldTypeRef.MetadataType == MetadataType.Array) { ArrayType arrType = (ArrayType)fieldTypeRef; isArrayOrList = arrType.IsVector; } else if (fieldType.FullName == "System.Collections.Generic.List`1") { fieldType = ((GenericInstanceType)fieldDef.FieldType).GenericArguments[0].Resolve(); fieldTypeName = fieldType.Name; isArrayOrList = true; } field.name = fieldDef.Name; field.type = ConvertBaseToPrimitive(fieldTypeName); if (IsPrimitiveType(fieldType)) { field.childrenCount = 0; field.children = new AssetTypeTemplateField[] { }; } else if (fieldType.Name.Equals("String")) { SetString(field); } else if (IsSpecialUnityType(fieldType)) { SetSpecialUnity(field, fieldType); } else if (DerivesFromUEObject(fieldType)) { SetPPtr(field, false); } else if (fieldType.IsSerializable) { SetSerialized(field, fieldType); } if (fieldType.IsEnum) { field.valueType = EnumValueTypes.Int32; } else { field.valueType = AssetTypeValueField.GetValueTypeByTypeName(field.type); } field.align = TypeAligns(field.valueType); field.hasValue = field.valueType != EnumValueTypes.None; if (isArrayOrList) { field = SetArray(field); } localChildren.Add(field); } return(localChildren); }
private void FixAssetPre(AssetsFileInstance inst, AssetTypeValueField field, AssetFileInfoEx inf) { if (inf.curFileType == 0xd5) //fix sprite { AssetTypeValueField renderDataKey = field.Get("m_RenderDataKey"); AssetTypeValueField spriteAtlas = field.Get("m_SpriteAtlas"); long spriteAtlasPathId = spriteAtlas.Get("m_PathID").GetValue().AsInt64(); uint rid0 = renderDataKey.Get("first")[0].GetValue().AsUInt(); uint rid1 = renderDataKey.Get("first")[1].GetValue().AsUInt(); uint rid2 = renderDataKey.Get("first")[2].GetValue().AsUInt(); uint rid3 = renderDataKey.Get("first")[3].GetValue().AsUInt(); //editor can't read these for whatever reason if (spriteAtlasPathId != 0) { AssetExternal spriteAtlasExt = am.GetExtAsset(inst, spriteAtlas); AssetTypeValueField spriteAtlasBase = spriteAtlasExt.instance.GetBaseField(); AssetTypeValueField renderDataMap = spriteAtlasBase.Get("m_RenderDataMap").Get("Array"); int renderDataMapCount = renderDataMap.GetValue().AsArray().size; int renderDataIndex = -1; for (int i = 0; i < renderDataMapCount; i++) { AssetTypeValueField renderDataMapKey = renderDataMap[i].Get("first"); uint thisrid0 = renderDataMapKey.Get("first")[0].GetValue().AsUInt(); uint thisrid1 = renderDataMapKey.Get("first")[1].GetValue().AsUInt(); uint thisrid2 = renderDataMapKey.Get("first")[2].GetValue().AsUInt(); uint thisrid3 = renderDataMapKey.Get("first")[3].GetValue().AsUInt(); if (thisrid0 == rid0 && thisrid1 == rid1 && thisrid2 == rid2 && thisrid3 == rid3) { renderDataIndex = i; break; } } if (renderDataIndex != -1) { AssetTypeValueField spriteAtlasRD = renderDataMap[renderDataIndex].Get("second"); AssetTypeValueField spriteRD = field.Get("m_RD"); //texture AssetTypeValueField spriteAtlasTexture = spriteAtlasRD.Get("texture"); AssetTypeValueField spriteTexture = spriteRD.Get("texture"); spriteTexture.Get("m_FileID").GetValue().Set(spriteAtlasTexture.Get("m_FileID").GetValue().AsInt()); spriteTexture.Get("m_PathID").GetValue().Set(spriteAtlasTexture.Get("m_PathID").GetValue().AsInt64()); //alphaTexture AssetTypeValueField spriteAtlasAlphaTexture = spriteAtlasRD.Get("alphaTexture"); AssetTypeValueField spriteAlphaTexture = spriteRD.Get("alphaTexture"); spriteAlphaTexture.Get("m_FileID").GetValue().Set(spriteAtlasAlphaTexture.Get("m_FileID").GetValue().AsInt()); spriteAlphaTexture.Get("m_PathID").GetValue().Set(spriteAtlasAlphaTexture.Get("m_PathID").GetValue().AsInt64()); //textureRect AssetTypeValueField spriteAtlasTextureRect = spriteAtlasRD.Get("textureRect"); AssetTypeValueField spriteTextureRect = spriteRD.Get("textureRect"); spriteTextureRect.Get("x").GetValue().Set(spriteAtlasTextureRect.Get("x").GetValue().AsFloat()); spriteTextureRect.Get("y").GetValue().Set(spriteAtlasTextureRect.Get("y").GetValue().AsFloat()); spriteTextureRect.Get("width").GetValue().Set(spriteAtlasTextureRect.Get("width").GetValue().AsFloat()); spriteTextureRect.Get("height").GetValue().Set(spriteAtlasTextureRect.Get("height").GetValue().AsFloat()); ////textureRectOffset AssetTypeValueField spriteAtlasTextureRectOffset = spriteAtlasRD.Get("textureRectOffset"); AssetTypeValueField spriteTextureRectOffset = spriteRD.Get("textureRectOffset"); spriteTextureRectOffset.Get("x").GetValue().Set(spriteAtlasTextureRectOffset.Get("x").GetValue().AsFloat()); spriteTextureRectOffset.Get("y").GetValue().Set(spriteAtlasTextureRectOffset.Get("y").GetValue().AsFloat()); //atlasRectOffset AssetTypeValueField spriteAtlasAtlasRectOffset = spriteAtlasRD.Get("atlasRectOffset"); AssetTypeValueField spriteAtlasRectOffset = spriteRD.Get("atlasRectOffset"); spriteAtlasRectOffset.Get("x").GetValue().Set(spriteTextureRectOffset.Get("x").GetValue().AsFloat()); spriteAtlasRectOffset.Get("y").GetValue().Set(spriteTextureRectOffset.Get("y").GetValue().AsFloat()); spriteAtlasRectOffset.Get("x").GetValue().Set(spriteAtlasAtlasRectOffset.Get("x").GetValue().AsFloat()); spriteAtlasRectOffset.Get("y").GetValue().Set(spriteAtlasAtlasRectOffset.Get("y").GetValue().AsFloat()); //uvTransform AssetTypeValueField spriteAtlasUvTransform = spriteAtlasRD.Get("uvTransform"); AssetTypeValueField spriteUvTransform = spriteRD.Get("uvTransform"); spriteUvTransform.Get("x").GetValue().Set(spriteAtlasUvTransform.Get("x").GetValue().AsFloat()); spriteUvTransform.Get("y").GetValue().Set(spriteAtlasUvTransform.Get("y").GetValue().AsFloat()); spriteUvTransform.Get("z").GetValue().Set(spriteAtlasUvTransform.Get("z").GetValue().AsFloat()); spriteUvTransform.Get("w").GetValue().Set(spriteAtlasUvTransform.Get("w").GetValue().AsFloat()); //downscaleMultiplier AssetTypeValueField spriteAtlasDownscapeMultiplier = spriteAtlasRD.Get("downscaleMultiplier"); AssetTypeValueField spriteDownscapeMultiplier = spriteRD.Get("downscaleMultiplier"); spriteDownscapeMultiplier.GetValue().Set(spriteAtlasDownscapeMultiplier.GetValue().AsFloat()); //settingsRaw AssetTypeValueField spriteAtlasSettingsRaw = spriteAtlasRD.Get("settingsRaw"); AssetTypeValueField spriteSettingsRaw = spriteRD.Get("settingsRaw"); spriteSettingsRaw.GetValue().Set(spriteAtlasSettingsRaw.GetValue().AsFloat()); spriteAtlas.Get("m_FileID").GetValue().Set(0); spriteAtlas.Get("m_PathID").GetValue().Set((long)0); } //else //{ // Debug.Log("exhausted sprite search"); //} } } }
private void ReplaceReferencesRecurse(AssetsFileInstance inst, AssetTypeValueField field, AssetFileInfoEx inf) { foreach (AssetTypeValueField child in field.children) { //not a value (ie int) if (!child.templateField.hasValue) { //not null if (child == null) { return; } //not array of values either if (child.templateField.isArray && child.templateField.children[1].valueType != EnumValueTypes.ValueType_None) { break; } string typeName = child.templateField.type; //is a pptr if (typeName.StartsWith("PPtr<") && typeName.EndsWith(">") && child.childrenCount == 2) { int fileId = child.Get("m_FileID").GetValue().AsInt(); long pathId = child.Get("m_PathID").GetValue().AsInt64(); //not a null pptr if (pathId == 0) { continue; } AssetID aid = ConvertToAssetID(inst, fileId, pathId); //not already visited if (references.ContainsKey(aid)) { AssetID id = references[aid]; //normally, I would've just checked if the path names //matched up, but this is faster than looking up names //I check type of this asset and compare with the name //of the assetid to see if it should be itself or if //it should be the dependency file bool isSelfAsset = IsAsset(inf); bool isDepAsset = id.fileName == ASSET_LEVEL_NAME; int newFileId = isDepAsset ^ isSelfAsset ? 1 : 0; child.Get("m_FileID").GetValue().Set(newFileId); child.Get("m_PathID").GetValue().Set(id.pathId); } else { /////////////// todo move to another method AssetsFileInstance depInst = ConvertToInstance(inst, fileId); AssetFileInfoEx depInf = depInst.table.GetAssetInfo(pathId); if (depInf.curFileType == 0x72) { ushort scriptIndex = depInst.file.typeTree.unity5Types[depInf.curFileTypeOrIndex].scriptIndex; if (tk2dSpriteScriptIndex == 0xffff) { AssetTypeValueField monoBase = am.GetATI(depInst.file, depInf).GetBaseField(); AssetExternal scriptBaseExt = am.GetExtAsset(depInst, monoBase.Get("m_Script")); if (scriptBaseExt.instance != null) { AssetTypeValueField scriptBase = scriptBaseExt.instance.GetBaseField(); string scriptName = scriptBase.Get("m_ClassName").GetValue().AsString(); if (scriptName == "tk2dSprite") { tk2dSpriteScriptIndex = scriptIndex; } } } if (tk2dSpriteScriptIndex == depInst.file.typeTree.unity5Types[depInf.curFileTypeOrIndex].scriptIndex) { string managedPath = Path.Combine(Path.GetDirectoryName(depInst.path), "Managed"); AssetTypeValueField spriteBase = am.GetMonoBaseFieldCached(depInst, depInf, managedPath); int spriteId = spriteBase.Get("_spriteId").GetValue().AsInt(); AssetExternal colBaseExt = am.GetExtAsset(depInst, spriteBase.Get("collection")); AssetsFileInstance colInst = colBaseExt.file; AssetTypeValueField colBase = am.GetMonoBaseFieldCached(colInst, colBaseExt.info, managedPath); AssetTypeValueField spriteDefinitions = colBase.Get("spriteDefinitions")[spriteId]; AssetTypeValueField positionsField = spriteDefinitions.Get("positions"); AssetTypeValueField uvsField = spriteDefinitions.Get("uvs"); AssetTypeValueField indicesField = spriteDefinitions.Get("indices"); Vector3[] positions = new Vector3[positionsField.GetChildrenCount()]; Vector2[] uvs = new Vector2[uvsField.GetChildrenCount()]; int[] indices = new int[indicesField.GetChildrenCount()]; for (int i = 0; i < positions.Length; i++) { AssetTypeValueField positionField = positionsField[i]; positions[i] = new Vector3() { x = positionField.Get("x").GetValue().AsFloat(), y = positionField.Get("y").GetValue().AsFloat(), z = positionField.Get("z").GetValue().AsFloat() }; } for (int i = 0; i < uvs.Length; i++) { AssetTypeValueField uvField = uvsField[i]; uvs[i] = new Vector2() { x = uvField.Get("x").GetValue().AsFloat(), y = uvField.Get("y").GetValue().AsFloat() }; } for (int i = 0; i < indices.Length; i++) { AssetTypeValueField indexField = indicesField[i]; indices[i] = indexField.GetValue().AsInt(); } AssetID thisAid = ConvertToAssetID(inst, 0, inf.index); tk2dFromGoLookup[thisAid] = new Tk2dInfo(positions, uvs, indices); } } /////////////// child.Get("m_FileID").GetValue().Set(0); child.Get("m_PathID").GetValue().Set(0); } } ReplaceReferencesRecurse(inst, child, inf); } } }
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.assetFileInfo) { bool isMono = false; if (fsmTypeId == 0) { ushort 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); 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 = 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.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)); FSMSelector selector = new FSMSelector(assetInfos); selector.ShowDialog(); //todo separate into separate method(s) if (selector.selectedID == -1) { return; } AssetFileInfoEx afi = table.GetAssetInfo(selector.selectedID); string tabName = assetInfos.FirstOrDefault(i => i.id == selector.selectedID).name; TabItem tab = new TabItem { Header = tabName }; ignoreChangeEvent = true; fsmTabControl.Items.Add(tab); fsmTabControl.SelectedItem = tab; ignoreChangeEvent = false; SaveAndClearNodes(); mt.Matrix = Matrix.Identity; AssetTypeValueField baseField = am.GetMonoBaseFieldCached(curFile, afi, Path.Combine(Path.GetDirectoryName(curFile.path), "Managed")); 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(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"); int transitionCount = transitions.GetValue().AsArray().size; FsmTransition[] dotNetTransitions = new FsmTransition[transitionCount]; for (int j = 0; j < transitionCount; j++) { dotNetTransitions[j] = new FsmTransition(transitions.Get(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(i); FsmTransition dotNetTransition = new FsmTransition(transition); Node toNode = nodes.FirstOrDefault(n => n.name == dotNetTransition.toState); if (toNode == null) { 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 { 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(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(i).Get("name").GetValue().AsString(); string value = floatVariables.Get(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(i).Get("name").GetValue().AsString(); string value = intVariables.Get(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(i).Get("name").GetValue().AsString(); string value = boolVariables.Get(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(i).Get("name").GetValue().AsString(); string value = stringVariables.Get(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(i).Get("name").GetValue().AsString(); AssetTypeValueField vector2 = vector2Variables.Get(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(i).Get("name").GetValue().AsString(); AssetTypeValueField vector3 = vector3Variables.Get(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(i).Get("name").GetValue().AsString(); AssetTypeValueField color = colorVariables.Get(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(i).Get("name").GetValue().AsString(); AssetTypeValueField rect = rectVariables.Get(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(i).Get("name").GetValue().AsString(); AssetTypeValueField rect = quaternionVariables.Get(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(i).Get("name").GetValue().AsString(); AssetTypeValueField gameObject = gameObjectVariables.Get(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)); } currentTab++; tabs.Add(new FSMInstance() { matrix = mt.Matrix, nodes = nodes, dataVersion = dataVersion, graphElements = CopyChildrenToList(graphCanvas), states = CopyChildrenToList(stateList), events = CopyChildrenToList(eventList), variables = CopyChildrenToList(variableList) }); }
public static void GenerateDiffFile(AssetsManager am, AssetsFileInstance buildInst, AssetsFileInstance sceneInst, HKWEMeta meta) { EditorUtility.DisplayProgressBar("HKEdit", "Reading dependencies...", 0.5f); am.UpdateDependencies(); ClassDatabaseFile cldb = am.classFile; DiffData result = new DiffData() { goChanges = new List <GameObjectChange>(), goAdditions = new List <GameObjectAddition>() }; Dictionary <EditDifferData, long> differToSceneId = new Dictionary <EditDifferData, long>(); Dictionary <long, EditDifferData> buildIdToDiffer = new Dictionary <long, EditDifferData>(); List <EditDifferData> differData = new List <EditDifferData>(); AssetsFileTable sceneTable = sceneInst.table; List <AssetFileInfoEx> sceneGos = sceneTable.GetAssetsOfType(0x01); for (int i = 0; i < sceneGos.Count; i++) { if (i % 100 == 0) { EditorUtility.DisplayProgressBar("HKEdit", "Finding diff IDs... (step 1/3)", (float)i / sceneGos.Count); } AssetFileInfoEx inf = sceneGos[i]; AssetTypeValueField baseField = am.GetATI(sceneInst.file, inf).GetBaseField(); AssetTypeValueField editDifferMono = GetEDMono(am, sceneInst, baseField); EditDifferData diff = new EditDifferData() { fileId = editDifferMono.Get("fileId").GetValue().AsInt(), pathId = editDifferMono.Get("pathId").GetValue().AsInt64(), origPathId = editDifferMono.Get("origPathId").GetValue().AsInt64(), newAsset = editDifferMono.Get("newAsset").GetValue().AsBool() }; buildIdToDiffer[diff.origPathId] = diff; differToSceneId[diff] = inf.index; differData.Add(diff); } ////////////////////////// AssetsFileTable origTable = buildInst.table; List <AssetFileInfoEx> origGos = origTable.GetAssetsOfType(0x01); List <long> origDeletIds = new List <long>(); //int nextBundleId = 1; //// == delete changes == // //for (int i = 0; i < origGos.Count; i++) //{ // if (i % 100 == 0) // EditorUtility.DisplayProgressBar("HKEdit", "Checking for deletes... (step 2/3)", (float)i / origGos.Count); // AssetFileInfoEx inf = sceneGos[i]; // if (!differData.Any(d => d.origPathId == inf.index)) // { // GameObjectChange change = new GameObjectChange // { // flags = GameObjectChangeFlags.Deleted // }; // result.goChanges.Add(change); // origDeletIds.Add(inf.index); // } //} // == add changes == // //to get this working in a built game, we need //built assets (ie pngs -> texture2d) the problem //is there's no easy way to direct unity to do that //without loading the scene and using unity's api //but we can pull out assets into a prefab and build //the prefab but there are problems with duplicate //dependencies being copied, so we pack them all //into one place so that doesn't happen //(for reference, in hkwe1, each gameobject got //its own prefab) //find dependencies ReferenceCrawlerBundle createdCrawler = new ReferenceCrawlerBundle(am); //assets created by the user in the ditor ReferenceCrawlerBundle existingCrawler = new ReferenceCrawlerBundle(am); //assets that already existed in the scene for (int i = 0; i < differData.Count; i++) { if (i % 100 == 0) { EditorUtility.DisplayProgressBar("HKEdit", "Checking for additions... (step 2/3)", (float)i / differData.Count); } EditDifferData dat = differData[i]; if (dat.newAsset) { long sceneId = differToSceneId[dat]; AssetFileInfoEx inf = sceneInst.table.GetAssetInfo(sceneId); createdCrawler.SetReferences(sceneInst, inf); GameObjectAddition addition = new GameObjectAddition { bundleId = createdCrawler.GetNextId(), //? sceneId = dat.pathId, dependencies = new List <GameObjectAdditionDependency>() }; //nextBundleId++; foreach (KeyValuePair <AssetID, AssetID> goRef in createdCrawler.references) { addition.dependencies.Add(new GameObjectAdditionDependency { sceneId = goRef.Key.pathId, bundleId = goRef.Value.pathId }); } result.goAdditions.Add(addition); } else { long newPathId = differToSceneId[dat]; AssetFileInfoEx inf = sceneInst.table.GetAssetInfo(newPathId); existingCrawler.SetReferences(sceneInst, inf); } } //load up all created assets into a prefab List <Type_0D> types = new List <Type_0D>(); List <string> typeNames = new List <string>(); foreach (AssetsReplacer rep in createdCrawler.sceneReplacers) { ClassDatabaseType clType = AssetHelper.FindAssetClassByID(cldb, (uint)rep.GetClassID()); string clName = clType.name.GetString(cldb); if (!typeNames.Contains(clName)) { Type_0D type0d = C2T5.Cldb2TypeTree(cldb, clName); type0d.classId = clType.classId; types.Add(type0d); typeNames.Add(clName); } } List <AssetsReplacer> replacers = new List <AssetsReplacer>(); replacers.Add(CreatePrefabAsset(2)); //better hope id 2 is a gameobject replacers.AddRange(createdCrawler.sceneReplacers); AssetsFile createdFile = new AssetsFile(new AssetsFileReader(new MemoryStream(BundleCreator.CreateBlankAssets(ver, types)))); byte[] data; using (MemoryStream ms = new MemoryStream()) using (AssetsFileWriter writer = new AssetsFileWriter(ms)) { createdFile.Write(writer, 0, replacers, 0); data = ms.ToArray(); } }
private void TreeLoad(AssetTypeValueField assetField, TreeViewItem treeItem) { if (assetField.childrenCount == 0) { return; } int arrayIdx = 0; List <TreeViewItem> items = new List <TreeViewItem>(assetField.childrenCount + 1); AssetTypeTemplateField assetFieldTemplate = assetField.GetTemplateField(); bool isArray = assetFieldTemplate.isArray; if (isArray) { int size = assetField.GetValue().AsArray().size; AssetTypeTemplateField sizeTemplate = assetFieldTemplate.children[0]; TreeViewItem arrayIndexTreeItem = CreateTreeItem($"{sizeTemplate.type} {sizeTemplate.name} = {size}"); items.Add(arrayIndexTreeItem); } foreach (AssetTypeValueField childField in assetField.children) { if (childField == null) { return; } string value = ""; if (childField.GetValue() != null) { EnumValueTypes evt = childField.GetValue().GetValueType(); string quote = ""; if (evt == EnumValueTypes.String) { quote = "\""; } if (1 <= (int)evt && (int)evt <= 12) { value = $" = {quote}{childField.GetValue().AsString()}{quote}"; } if (evt == EnumValueTypes.Array || evt == EnumValueTypes.ByteArray) { value = $" (size {childField.childrenCount})"; } } if (isArray) { TreeViewItem arrayIndexTreeItem = CreateTreeItem($"{arrayIdx}"); items.Add(arrayIndexTreeItem); TreeViewItem childTreeItem = CreateTreeItem($"{childField.GetFieldType()} {childField.GetName()}{value}"); arrayIndexTreeItem.Items = new List <TreeViewItem>() { childTreeItem }; if (childField.childrenCount > 0) { TreeViewItem dummyItem = CreateTreeItem("Loading..."); childTreeItem.Items = new List <TreeViewItem>() { dummyItem }; SetTreeItemEvents(childTreeItem, childField); } arrayIdx++; } else { TreeViewItem childTreeItem = CreateTreeItem($"{childField.GetFieldType()} {childField.GetName()}{value}"); items.Add(childTreeItem); if (childField.childrenCount > 0) { TreeViewItem dummyItem = CreateTreeItem("Loading..."); childTreeItem.Items = new List <TreeViewItem>() { dummyItem }; SetTreeItemEvents(childTreeItem, childField); } } } treeItem.Items = items; }
//AssetTypeValueField public static void Write(this AssetTypeValueField valueField, AssetsFileWriter writer, int depth = 0) { if (valueField.templateField.isArray) { if (valueField.templateField.valueType == EnumValueTypes.ByteArray) { AssetTypeByteArray byteArray = valueField.value.value.asByteArray; byteArray.size = (uint)byteArray.data.Length; writer.Write(byteArray.size); writer.Write(byteArray.data); if (valueField.templateField.align) { writer.Align(); } } else { AssetTypeArray array = valueField.value.value.asArray; array.size = valueField.childrenCount; writer.Write(array.size); for (int i = 0; i < array.size; i++) { valueField[i].Write(writer, depth + 1); } if (valueField.templateField.align) { writer.Align(); } } } else { if (valueField.childrenCount == 0) { switch (valueField.templateField.valueType) { case EnumValueTypes.Int8: writer.Write(valueField.value.value.asInt8); if (valueField.templateField.align) { writer.Align(); } break; case EnumValueTypes.UInt8: writer.Write(valueField.value.value.asUInt8); if (valueField.templateField.align) { writer.Align(); } break; case EnumValueTypes.Bool: writer.Write(valueField.value.value.asBool); if (valueField.templateField.align) { writer.Align(); } break; case EnumValueTypes.Int16: writer.Write(valueField.value.value.asInt16); if (valueField.templateField.align) { writer.Align(); } break; case EnumValueTypes.UInt16: writer.Write(valueField.value.value.asUInt16); if (valueField.templateField.align) { writer.Align(); } break; case EnumValueTypes.Int32: writer.Write(valueField.value.value.asInt32); break; case EnumValueTypes.UInt32: writer.Write(valueField.value.value.asUInt32); break; case EnumValueTypes.Int64: writer.Write(valueField.value.value.asInt64); break; case EnumValueTypes.UInt64: writer.Write(valueField.value.value.asUInt64); break; case EnumValueTypes.Float: writer.Write(valueField.value.value.asFloat); break; case EnumValueTypes.Double: writer.Write(valueField.value.value.asDouble); break; case EnumValueTypes.String: writer.Write(valueField.value.value.asString.Length); writer.Write(valueField.value.value.asString); writer.Align(); break; } } else { for (int i = 0; i < valueField.childrenCount; i++) { valueField[i].Write(writer, depth + 1); } if (valueField.templateField.align) { writer.Align(); } } } }
public static AssetsReplacer ConvertSpriteRenderer(AssetTypeValueField baseField, ulong pathId, AssetPPtr goPPtr, AssetPPtr matPPtr, AssetPPtr spritePPtr) { AssetTypeValueField m_GameObject = baseField.Get("m_GameObject"); AssetTypeValueField m_Materials = baseField.Get("m_Materials").Get("Array"); if (m_Materials.GetValue().AsArray().size != 1) { Console.WriteLine("warning, sprite material is not 1! (" + m_Materials.GetValue().AsArray().size + ")"); } AssetTypeValueField m_Sprite = baseField.Get("m_Sprite"); //GameObject refs m_GameObject.Get("m_FileID").GetValue().Set((int)goPPtr.fileID); m_GameObject.Get("m_PathID").GetValue().Set((long)goPPtr.pathID); //Material refs AssetTypeArray arr = m_Materials.value.value.asArray; arr.size = 1; m_Materials.value.value.asArray = arr; m_Materials.pChildren = new AssetTypeValueField[1]; AssetTypeValueField m_FileID = new AssetTypeValueField() { templateField = m_Materials.templateField.children[1].children[0], childrenCount = 0, pChildren = new AssetTypeValueField[0], value = new AssetTypeValue(EnumValueTypes.ValueType_Int32, (int)matPPtr.fileID) }; AssetTypeValueField m_PathID = new AssetTypeValueField() { templateField = m_Materials.templateField.children[1].children[1], childrenCount = 0, pChildren = new AssetTypeValueField[0], value = new AssetTypeValue(EnumValueTypes.ValueType_Int64, (long)matPPtr.pathID) }; AssetTypeValueField m_Material = new AssetTypeValueField() { templateField = m_Materials.templateField.children[1], childrenCount = 2, pChildren = new AssetTypeValueField[2] { m_FileID, m_PathID }, value = new AssetTypeValue(EnumValueTypes.ValueType_Array, 0) }; //Sprite refs m_Sprite.Get("m_FileID").GetValue().Set((int)spritePPtr.fileID); m_Sprite.Get("m_PathID").GetValue().Set((long)spritePPtr.pathID); byte[] spriteRendererAsset; using (MemoryStream memStream = new MemoryStream()) using (AssetsFileWriter writer = new AssetsFileWriter(memStream)) { writer.bigEndian = false; baseField.Write(writer); spriteRendererAsset = memStream.ToArray(); } return(new AssetsReplacerFromMemory(0, pathId, 0xD4, 0xFFFF, spriteRendererAsset)); }
/// <summary> /// 无中生有一个Field(解析yaml生成一个新的Field) /// </summary> /// <param name="field"></param> /// <param name="contents"></param> /// <param name="lines"></param> public static void CreateField(AssetTypeValueField field, string[] contents, ref int lines, int count) { for (int i = 0; i < count; i++) { //子项 int subCount = CalculationChildrenCount(contents, lines); string str = contents[lines]; string[] fieldStr = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //预处理字符串内容 fieldStr = ValueHandler(fieldStr, str); //是否是数组 bool isArray = fieldStr[0] == "Array"; bool hasSub = subCount > 0; bool hasValue = subCount == 0 && !isArray; //格式类 AssetTypeTemplateField tempField = new AssetTypeTemplateField(); tempField.type = fieldStr[0]; tempField.name = fieldStr[1]; tempField.isArray = isArray; tempField.valueType = AssetTypeValueField.GetValueTypeByTypeName(fieldStr[0]); tempField.hasValue = hasValue; if (hasSub) { tempField.align = fieldStr.Length >= 3 ? fieldStr[2] == "True" : false; } else { tempField.align = fieldStr.Length >= 5 ? fieldStr[4] == "True" : false; } //空数组的特殊处理 if (isArray && !hasSub) { tempField.children = new AssetTypeTemplateField[2]; tempField.childrenCount = 2; tempField.children[0] = new AssetTypeTemplateField(); tempField.children[0].hasValue = true; tempField.children[0].name = "size"; tempField.children[0].type = "int"; tempField.children[0].valueType = EnumValueTypes.ValueType_Int32; } else { tempField.children = new AssetTypeTemplateField[subCount]; tempField.childrenCount = subCount; } //承载类 AssetTypeValueField newField = new AssetTypeValueField(); newField.templateField = tempField; newField.childrenCount = subCount; newField.children = new AssetTypeValueField[subCount]; if (isArray) { newField.value = new AssetTypeValue(EnumValueTypes.ValueType_Int32, subCount); } else if (!hasSub) { var value = fieldStr.Length >= 4 ? fieldStr[3] : null; newField.value = new AssetTypeValue(tempField.valueType, value); } else { newField.value = null; } lines++; //套娃操作 if (hasSub) { CreateField(newField, contents, ref lines, subCount); } //补充实例信息给父节点 field.children[i] = newField; //补充模板信息给父节点 field.templateField.children[i] = tempField; ////数组的模板类有特殊处理 //if (field.templateField.isArray && i == 0) // field.templateField.children[1] = tempField; //else // field.templateField.children[i] = tempField; } }
private void assetList_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (assetList.SelectedCells.Count > 0) { var selRow = assetList.SelectedRows[0]; string typeName = (string)selRow.Cells[2].Value; if (typeName == "Folder") { string dirName = (string)selRow.Cells[1].Value; ChangeDirectory(dirName); } else { ClassDatabaseFile classFile = helper.classFile; AssetsFileInstance correctAti = currentFile; ClassDatabaseType classType = AssetHelper.FindAssetClassByName(classFile, typeName); if (currentFile.name == "globalgamemanagers") { int rsrcIndex = helper.files.FindIndex(f => f.name == "resources.assets"); if (rsrcIndex != -1) { correctAti = helper.files[rsrcIndex]; } else { string rsrcPath = Path.Combine(Path.GetDirectoryName(currentFile.path), "resources.assets"); correctAti = helper.LoadAssetsFile(rsrcPath, false); UpdateDependencies(); } if (typeName == "") { return; } } AssetFileInfoEx info = correctAti.table.getAssetInfo((ulong)selRow.Cells[3].Value); bool hasGameobjectField = classType.fields.Any(f => f.fieldName.GetString(classFile) == "m_GameObject"); bool parentPointerNull = false; if (typeName != "GameObject" && hasGameobjectField) { //get gameobject parent AssetTypeValueField componentBaseField = helper.GetATI(correctAti.file, info).GetBaseField(); AssetFileInfoEx newInfo = helper.GetExtAsset(correctAti, componentBaseField["m_GameObject"], true).info; if (newInfo != null && newInfo.index != 0) { info = newInfo; } else { parentPointerNull = true; } } if ((typeName == "GameObject" || hasGameobjectField) && !parentPointerNull) { AssetTypeValueField baseField = helper.GetATI(correctAti.file, info).GetBaseField(); AssetTypeValueField transformPtr = baseField["m_Component"]["Array"][0]["component"]; AssetTypeValueField transform = helper.GetExtAsset(correctAti, transformPtr).instance.GetBaseField(); baseField = GetRootTransform(helper, currentFile, transform); AssetTypeValueField gameObjectPtr = baseField["m_GameObject"]; AssetTypeValueField gameObject = helper.GetExtAsset(correctAti, gameObjectPtr).instance.GetBaseField(); GameObjectViewer view = new GameObjectViewer(helper, correctAti, gameObject, info.index, (ulong)selRow.Cells[3].Value); view.Show(); } else { AssetTypeValueField baseField = helper.GetATI(correctAti.file, info).GetBaseField(); GameObjectViewer view = new GameObjectViewer(helper, correctAti, baseField, info); view.Show(); } } } }
public static byte[] CreateBundleFromLevel(AssetsManager am, /*byte[] data,*/ AssetsFileInstance inst, string sceneName, DiffFile diffFile, string bunPath) { AssetsFile file = inst.file; AssetsFileTable table = inst.table; string folderName = Path.GetDirectoryName(inst.path); //string sceneName = Path.GetFileNameWithoutExtension(inst.path) + "_mod"; List <AssetsReplacer> assetsSA = new List <AssetsReplacer>(); List <AssetFileInfoEx> infos = table.pAssetFileInfo.ToList(); //List<int> typeIds = new List<int>(); //foreach (AssetFileInfoEx info in infos) //{ // int typeId = (int)info.curFileType; // if (!typeIds.Contains(typeId) && typeId != 0x72) // typeIds.Add(typeId); //} assetsSA.Add(PreloadData.CreatePreloadData(1)); assetsSA.Add(BundleMeta.CreateBundleInformation(sceneName, 2)); //todo: pull from original assets file, cldb is not always update to date List <Type_0D> types = new List <Type_0D>(); //foreach (int typeId in typeIds) //{ // types.Add(C2T5.Cldb2TypeTree(am.classFile, typeId)); //} List <Type_0D> typesSA = new List <Type_0D> { C2T5.Cldb2TypeTree(am.classFile, 0x96), //PreloadData C2T5.Cldb2TypeTree(am.classFile, 0x8E) //AssetBundle }; const string ver = "2017.4.10f1"; List <AssetsReplacer> replacers = new List <AssetsReplacer>(); //UnityEngine.Debug.Log("HKWE DM " + diffFile.magic); //UnityEngine.Debug.Log("HKWE GC " + diffFile.changes.Count + diffFile.adds.Count + diffFile.removes.Count); //AssetsReplacerFromMemory mem = MoveTest.RunMoveTest(table.getAssetInfo(2642), am.GetATI(file, table.getAssetInfo(2642)).GetBaseField(), 2642) as AssetsReplacerFromMemory; foreach (GameObjectChange goChange in diffFile.changes) { //UnityEngine.Debug.Log("HKWE GO " + goChange.pathId); foreach (ComponentChangeOrAdd compChange in goChange.changes) { AssetFileInfoEx goInfo = table.getAssetInfo((ulong)goChange.pathId); AssetTypeValueField goBaseField = am.GetATI(file, goInfo).GetBaseField(); AssetTypeValueField compPptr = goBaseField.Get("m_Component").Get("Array")[(uint)compChange.componentIndex].Get("component"); AssetsManager.AssetExternal compExt = am.GetExtAsset(inst, compPptr); AssetFileInfoEx compInfo = compExt.info; AssetTypeValueField compBaseField = compExt.instance.GetBaseField(); //UnityEngine.Debug.Log("HKWE LR " + compInfo.index); AssetsReplacer imAlreadyReplacer = ComponentDiffReplacer.DiffComponent(compInfo, compBaseField, am.classFile, compChange, compInfo.index); replacers.Add(imAlreadyReplacer); } } AssetsManager amBun = new AssetsManager(); //we create a new manager because the two filenames will probably conflict amBun.classFile = am.classFile; //we can just reuse the classfile which is kinda hacky AssetsFileInstance bunInst = amBun.LoadAssetsFile(new MemoryStream(GetBundleData(bunPath, 0)), "HKWEDiffs", false); //placeholder path since we have no deps //rearrange the pathids immediately after the //last one from the level to keep unity happy ulong levelLargestPathID = 0; foreach (AssetFileInfoEx inf in table.pAssetFileInfo) { if (inf.index > levelLargestPathID) { levelLargestPathID = inf.index; } } ReferenceCrawler.ReorderIds(amBun, bunInst, levelLargestPathID + 1); byte[] bunSAInst = GetBundleData(bunPath, 1); //HashSet<ulong> addedDeps = new HashSet<ulong>(); foreach (AssetFileInfoEx inf in bunInst.table.pAssetFileInfo) { replacers.Add(MakeReplacer(inf.index, am, bunInst, inst, inf, bunSAInst, types)); } //foreach (GameObjectInfo inf in diffFile.infos) //{ // Debug.Log("7"); // ulong bunPathId = GetBundlePathId(amBun, bunInst, inf); // // AssetFileInfoEx objInf = bunInst.table.getAssetInfo(bunPathId); // replacers.Add(MakeReplacer(bunPathId, am, bunInst, inst, objInf, bunSAInst, types)); // // List<ulong> deps = ReferenceCrawler.CrawlPPtrs(amBun, bunInst, bunPathId); // foreach (ulong dep in deps) // { // if (!addedDeps.Contains(dep)) // { // addedDeps.Add(dep); // AssetFileInfoEx depInf = bunInst.table.getAssetInfo(dep); // //if (depInf.curFileType == 0x01 || depInf.curFileType == 0x04 || depInf.curFileType == 0xD4 || depInf.curFileType == 0x15 || depInf.curFileType == 0xD5) // //{ // // continue; // //} // replacers.Add(MakeReplacer(dep, am, bunInst, inst, depInf, bunSAInst, types)); // } // } // ////its possible to get a collision but very unlikely since unity already randomizes ids which are 8 bytes long // ////there's nothing here to test if a collision would be created so just hope that you don't win the lottery // //ulong bunPathId = GetBundlePathId(amBun, bunInst, inf); // ////AssetFileInfoEx afInf = bunInst.table.getAssetInfo(bunPathId); // ////replacers.Add(MakeReplacer(bunPathId, afInf, bunInst.stream)); // //List<ulong> deps = ReferenceCrawler.CrawlPPtrs(am, bunInst, bunPathId); // ////if (info.curFileType == 0x01 || info.curFileType == 0x04 || info.curFileType == 0xD4) // ////{ // //// continue; // ////} // //foreach (ulong dep in deps) // //{ // // AssetFileInfoEx depInf = bunInst.table.getAssetInfo(dep); // // //MakeReplacer(dep, am, bunInst, inst, depInf, bunSAInst, types); // // AssetsReplacerFromMemory ar = MakeReplacer(dep, am, bunInst, inst, depInf, bunSAInst, types); // // //todo- I guess this was just for testing purposes to block out everything, remove this at some point // // if (depInf.curFileType == 0x01 || depInf.curFileType == 0x04 || depInf.curFileType == 0xD4 || depInf.curFileType == 0x15 || depInf.curFileType == 0xD5) //depInf.curFileType == 0x1C // // { // // continue; // // } // // replacers.Add(ar); // //} //} byte[] data = null; using (MemoryStream ms = new MemoryStream()) using (AssetsFileWriter writer = new AssetsFileWriter(ms)) { //file.typeTree.hasTypeTree = true; //so we don't have to calculate hashes //foreach (Type_0D type in file.typeTree.pTypes_Unity5) //{ // if (!types.Any(t => t.classId == type.classId)) // { // types.Insert(0, C2T5.Cldb2TypeTree(am.classFile, type.classId)); // } //} file.typeTree.pTypes_Unity5 = file.typeTree.pTypes_Unity5.Concat(types.ToArray()).ToArray(); //file.typeTree.pTypes_Unity5 = types.ToArray(); file.typeTree.fieldCount = (uint)file.typeTree.pTypes_Unity5.Length; //file.typeTree.fieldCount = (uint)types.Count; file.Write(writer, 0, replacers.ToArray(), 0); data = ms.ToArray(); } //File.WriteAllBytes("_bundlefinal1.unity3d", data); byte[] blankDataSA = BundleCreator.CreateBlankAssets(ver, typesSA); AssetsFile blankFileSA = new AssetsFile(new AssetsFileReader(new MemoryStream(blankDataSA))); byte[] dataSA = null; using (MemoryStream ms = new MemoryStream()) using (AssetsFileWriter writer = new AssetsFileWriter(ms)) { blankFileSA.Write(writer, 0, assetsSA.ToArray(), 0); dataSA = ms.ToArray(); } using (MemoryStream ms = new MemoryStream()) using (AssetsFileWriter writer = new AssetsFileWriter(ms)) { AssetsBundleFile bundle = BundleCreator.CreateBlankBundle(ver, data.Length, dataSA.Length, sceneName); bundle.Write(writer); writer.Write(dataSA); writer.Write(data); return(ms.ToArray()); } }
public static AssetTypeValueField GetRootTransform(AssetsManager helper, AssetsFileInstance currentFile, AssetTypeValueField transform) { AssetTypeValueField fatherPtr = transform["m_Father"]; if (fatherPtr["m_PathID"].GetValue().AsInt64() != 0) { AssetTypeValueField father = helper.GetExtAsset(currentFile, fatherPtr).instance.GetBaseField(); return(GetRootTransform(helper, currentFile, father)); } else { return(transform); } }
public GameObject RecurseGameObjects(AssetFileInfoEx info, bool topRoot, bool hideOnCreation = false) { AssetTypeValueField gameObject = am.GetATI(assetsFile, info).GetBaseField(); string name = gameObject.Get("m_Name").GetValue().AsString(); AssetTypeValueField m_Component = gameObject.Get("m_Component").Get("Array"); AssetsManager.AssetExternal transformComponent = am.GetExtAsset(assetsFileInstance, m_Component[0].Get("component")); AssetTypeValueField transform = transformComponent.instance.GetBaseField(); if (name == "TileMap Render Data" || name == "Template-TileMap (1) Render Data") //should be .EndsWith(" Render Data") { return(TilemapRenderData(transform, name)); } if (topRoot && transform.Get("m_Father").Get("m_PathID").GetValue().AsInt64() != 0) { return(null); } if (!topRoot && transform.Get("m_Father").Get("m_PathID").GetValue().AsInt64() == 0) { return(null); } GameObject gameObjectInstance = new GameObject(name); //if this object or parent object is mask bool isMask = hideOnCreation; int m_Tag = (ushort)gameObject.Get("m_Tag").GetValue().AsUInt(); if (m_Tag >= 20000) { int tagIndex = m_Tag - 20000; gameObjectInstance.tag = UnityEditorInternal.InternalEditorUtility.tags[tagIndex]; } else if (m_Tag != 0) { string[] tags = new[] { "Respawn", "Finished", "EditorOnly", "MainCamera", "Player", "GameController" }; gameObjectInstance.tag = tags[m_Tag - 1]; } gameObjectInstance.layer = (int)gameObject.Get("m_Layer").GetValue().AsUInt(); EditDiffer differ = gameObjectInstance.AddComponent <EditDiffer>(); differ.fileId = 0; differ.pathId = info.index; differ.origPathId = differ.pathId; Transform transformInstance = gameObjectInstance.transform; AssetTypeValueField m_LocalPosition = transform.Get("m_LocalPosition"); AssetTypeValueField m_LocalRotation = transform.Get("m_LocalRotation"); AssetTypeValueField m_LocalScale = transform.Get("m_LocalScale"); Vector3 localPosition = GetVector3(m_LocalPosition); Quaternion localRotation = GetQuaternion(m_LocalRotation); Vector3 localScale = GetVector3(m_LocalScale); for (uint i = 1; i < m_Component.GetValue().AsArray().size; i++) { //faster to check for only info but also keeps us from reading //particle systems which tend to update literally every minor update //if we end up needing more types we can use typetree2cldb on an editor file AssetsManager.AssetExternal component = am.GetExtAsset(assetsFileInstance, m_Component[i].Get("component"), true); if (component.info.curFileType == SPRITERENDERER) { component = am.GetExtAsset(assetsFileInstance, m_Component[i].Get("component")); AssetTypeValueField baseField = component.instance.GetBaseField(); AssetTypeValueField m_Sprite = baseField.Get("m_Sprite"); int fileId = m_Sprite.Get("m_FileID").GetValue().AsInt(); long pathId = m_Sprite.Get("m_PathID").GetValue().AsInt64(); AssetsManager.AssetExternal sprite = am.GetExtAsset(assetsFileInstance, m_Sprite); if (sprite.info == null) //spriterenderer with no sprite lol { continue; } AssetsFileInstance spriteInst; if (m_Sprite.Get("m_FileID").GetValue().AsInt() == 0) { spriteInst = assetsFileInstance; } else { spriteInst = assetsFileInstance.dependencies[m_Sprite.Get("m_FileID").GetValue().AsInt() - 1]; } Sprite spriteInstance = bundleAssets[assetMap[new AssetID(Path.GetFileName(spriteInst.path), pathId)]] as Sprite; SpriteRenderer sr = gameObjectInstance.AddComponent <SpriteRenderer>(); string[] sortingLayers = new[] { "Default", "Far BG 2", "Far BG 1", "Mid BG", "Immediate BG", "Actors", "Player", "Tiles", "MID Dressing", "Immediate FG", "Far FG", "Vignette", "Over", "HUD" }; sr.sortingLayerName = sortingLayers[baseField.Get("m_SortingLayer").GetValue().AsInt()]; sr.sortingOrder = baseField.Get("m_SortingOrder").GetValue().AsInt(); sr.sprite = spriteInstance; AssetTypeValueField m_Materials = baseField.Get("m_Materials").Get("Array"); if (m_Materials.GetValue().AsArray().size > 0) { AssetTypeValueField m_Material = m_Materials[0]; int matFileId = m_Material.Get("m_FileID").GetValue().AsInt(); long matPathId = m_Material.Get("m_PathID").GetValue().AsInt64(); AssetsFileInstance materialInst; if (m_Material.Get("m_FileID").GetValue().AsInt() == 0) { materialInst = assetsFileInstance; } else { materialInst = assetsFileInstance.dependencies[matFileId - 1]; } if (assetMap.ContainsKey(new AssetID(Path.GetFileName(materialInst.path), matPathId))) { Material mat = bundleAssets[assetMap[new AssetID(Path.GetFileName(materialInst.path), matPathId)]] as Material; if (mat.shader.name != "Sprites/Lit") //honestly this shader confuses me. it is the only shader { //with no code and only references the generic material sr.material = mat; } //else //{ // mat.shader = sr.sharedMaterial.shader; // sr.sharedMaterial = mat; //} if (mat.shader.name == "Hollow Knight/Grass-Default" || mat.shader.name == "Hollow Knight/Grass-Diffuse") { sr.sharedMaterial.SetFloat("_SwayAmount", 0f); //stops grass animation } } //else //{ // Debug.Log("failed to find " + Path.GetFileName(materialInst.path) + "/" + matPathId + ".dat"); //} } } if (component.info.curFileType == MONOBEHAVIOUR) { component = am.GetExtAsset(assetsFileInstance, m_Component[i].Get("component")); AssetTypeValueField baseField = component.instance.GetBaseField(); int monoTypeId = assetsFileInstance.file.typeTree.pTypes_Unity5[component.info.curFileTypeOrIndex].scriptIndex; if (!monoBehaviourIds.ContainsKey(monoTypeId)) { //map out the monobehaviour script indexes to their name for fast lookup AssetTypeValueField m_Script = baseField.Get("m_Script"); AssetsManager.AssetExternal script = am.GetExtAsset(assetsFileInstance, m_Script); string scriptName = script.instance.GetBaseField().Get("m_Name").GetValue().AsString(); monoBehaviourIds[monoTypeId] = scriptName; } if (monoBehaviourIds[monoTypeId] == "tk2dSprite") { string managedPath = Path.Combine(Path.GetDirectoryName(assetsFileInstance.path), "Managed"); baseField = am.GetMonoBaseFieldCached(assetsFileInstance, component.info, managedPath); AssetTypeValueField collection = baseField.Get("collection"); int _spriteId = baseField.Get("_spriteId").GetValue().AsInt(); int fileId = collection.Get("m_FileID").GetValue().AsInt(); //long pathId = collection.Get("m_PathID").GetValue().AsInt64(); AssetsManager.AssetExternal sprite = am.GetExtAsset(assetsFileInstance, collection); if (sprite.info == null) { continue; } AssetsFileInstance spriteFileInstance = assetsFileInstance.dependencies[fileId - 1]; AssetTypeValueField spriteBaseField = am.GetMonoBaseFieldCached(spriteFileInstance, sprite.info, managedPath); //this is a bad hack but it works for some reason so here it is //the reason the pivot is being set and not the actual position //is so we don't modify the values on the transform component Texture2D image = spriteLoader.LoadTK2dSpriteNative(am, spriteBaseField, spriteFileInstance, _spriteId); AssetTypeValueField boundsData = spriteBaseField.Get("spriteDefinitions")[(uint)_spriteId].Get("boundsData")[0]; float xOff = boundsData.Get("x").GetValue().AsFloat() * 100; float yOff = boundsData.Get("y").GetValue().AsFloat() * 100; Vector2 offset = new Vector2((image.width / 2f - xOff) / image.width, (image.height / 2f - yOff) / image.height); Sprite spriteInstance = Sprite.Create(image, new Rect(0, 0, image.width, image.height), offset, 100f); SpriteRenderer sr = gameObjectInstance.AddComponent <SpriteRenderer>(); sr.sortingLayerName = "Default"; sr.sortingOrder = 0; sr.sprite = spriteInstance; } else if (monoBehaviourIds[monoTypeId] == "PlayMakerFSM") { //string managedPath = Path.Combine(Path.GetDirectoryName(assetsFileInstance.path), "Managed"); //baseField = am.GetMonoBaseFieldCached(assetsFileInstance, component.info, managedPath); string fsmName = ReadFSMName(component.info, assetsFileInstance.file.reader);//baseField.Get("fsm").Get("name").GetValue().AsString(); if (fsmName == "remasker" || fsmName == "unmasker" || fsmName == "remasker_inverse" || fsmName == "Remove") { isMask = true; } } } } transformInstance.localScale = localScale; transformInstance.localPosition = localPosition; transformInstance.localRotation = localRotation; Renderer ren = gameObjectInstance.GetComponent <Renderer>(); if (isMask && ren != null) { ren.enabled = false; } AssetTypeValueField childrenArray = transform.Get("m_Children").Get("Array"); uint childrenCount = childrenArray.GetValue().AsArray().size; for (uint i = 0; i < childrenCount; i++) { AssetTypeValueField childTf = am.GetExtAsset(assetsFileInstance, childrenArray[i]).instance.GetBaseField(); AssetFileInfoEx childGo = am.GetExtAsset(assetsFileInstance, childTf.Get("m_GameObject")).info; RecurseGameObjects(childGo, false, isMask).transform.SetParent(transformInstance, false); } return(gameObjectInstance); }
private void RecursiveTreeLoad(AssetTypeValueField atvf, PGProperty node, AssetFileInfoEx info, string category, bool arrayChildren = false) { if (atvf.childrenCount == 0) { return; } string arraySingular = string.Empty; if (arrayChildren && atvf.childrenCount > 0) { arraySingular = plurServ.Singularize(atvf.children[0].templateField.name); } for (int i = 0; i < atvf.childrenCount; i++) { AssetTypeValueField atvfc = atvf.children[i]; if (atvfc == null) { return; } string key; if (!arrayChildren) { key = atvfc.GetName(); } else { key = $"{arraySingular}[{i}]"; } EnumValueTypes evt; if (atvfc.GetValue() != null) { evt = atvfc.GetValue().GetValueType(); if (evt != EnumValueTypes.ValueType_None) { if (1 <= (int)evt && (int)evt <= 12) { string value = atvfc.GetValue().AsString(); PGProperty prop = new PGProperty(key, value); prop.category = category; SetSelectedStateIfSelected(info, prop); node.Add(prop); RecursiveTreeLoad(atvfc, prop, info, category); } else if (evt == EnumValueTypes.ValueType_Array || evt == EnumValueTypes.ValueType_ByteArray) { PGProperty childProps = new PGProperty("child", null, $"[size: {atvfc.childrenCount}]"); PGProperty prop = new PGProperty(key, childProps, $"[size: {atvfc.childrenCount}]"); prop.category = category; SetSelectedStateIfSelected(info, prop); node.Add(prop); RecursiveTreeLoad(atvfc, childProps, info, category, true); } } } else { PGProperty childProps; if (atvfc.childrenCount == 2) { AssetTypeValueField fileId = atvfc.children[0]; AssetTypeValueField pathId = atvfc.children[1]; string fileIdName = fileId.templateField.name; string fileIdType = fileId.templateField.type; string pathIdName = pathId.templateField.name; string pathIdType = pathId.templateField.type; if (fileIdName == "m_FileID" && fileIdType == "int" && pathIdName == "m_PathID" && pathIdType == "SInt64") { int fileIdValue = fileId.GetValue().AsInt(); long pathIdValue = pathId.GetValue().AsInt64(); childProps = new PGProperty("child", "", $"[fileid: {fileIdValue}, pathid: {pathIdValue}]"); } else { childProps = new PGProperty("child", ""); } } else { childProps = new PGProperty("child", ""); } PGProperty prop = new PGProperty(key, childProps); prop.category = category; SetSelectedStateIfSelected(info, prop); node.Add(prop); RecursiveTreeLoad(atvfc, childProps, info, category); } } }
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()); } }
private string GetClassName(AssetsManager manager, AssetsFileInstance inst, AssetTypeValueField baseField) { AssetTypeInstance scriptAti = manager.GetExtAsset(inst, baseField.Get("m_Script")).instance; return(scriptAti.GetBaseField().Get("m_Name").GetValue().AsString()); }
public static AssetTypeValueField DefaultValueFieldFromArrayTemplate(AssetTypeValueField arrayField) { return(DefaultValueFieldFromArrayTemplate(arrayField.templateField)); }
private static AssetTypeValueField GetEDMono(AssetsManager am, AssetsFileInstance fileInst, AssetTypeValueField goBaseField) { AssetTypeValueField m_Components = goBaseField.Get("m_Components").Get("Array"); for (int i = 0; i < m_Components.GetValue().AsArray().size; i++) { AssetTypeValueField component = m_Components[i]; AssetExternal ext = am.GetExtAsset(fileInst, component, true); if (ext.info.curFileType == 0x72) { //todo, check if this is the right monob //as there's only one this is fine for now //but I still hate this //TODO THIS ACTUALLY WONT WORK NOW THAT WE HAVE 2 ext = am.GetExtAsset(fileInst, component, false); AssetTypeValueField monoBaseField = ext.instance.GetBaseField(); return(monoBaseField); } } return(null); }
public async Task <bool> BatchExport(Window win, AssetWorkspace workspace, List <AssetContainer> selection) { for (int i = 0; i < selection.Count; i++) { selection[i] = new AssetContainer(selection[i], TextureHelper.GetByteArrayTexture(workspace, selection[i])); } OpenFolderDialog ofd = new OpenFolderDialog(); ofd.Title = "Select export directory"; string dir = await ofd.ShowAsync(win); if (dir != null && dir != string.Empty) { StringBuilder errorBuilder = new StringBuilder(); foreach (AssetContainer cont in selection) { string errorAssetName = $"{Path.GetFileName(cont.FileInstance.path)}/{cont.PathId}"; AssetTypeValueField texBaseField = cont.TypeInstance.GetBaseField(); TextureFile texFile = TextureFile.ReadTextureFile(texBaseField); //0x0 texture, usually called like Font Texture or smth if (texFile.m_Width == 0 && texFile.m_Height == 0) { continue; } string file = Path.Combine(dir, $"{texFile.m_Name}-{Path.GetFileName(cont.FileInstance.path)}-{cont.PathId}.png"); //bundle resS if (!GetResSTexture(texFile, cont)) { string resSName = Path.GetFileName(texFile.m_StreamData.path); errorBuilder.AppendLine($"[{errorAssetName}]: resS was detected but {resSName} was not found in bundle"); continue; } byte[] data = TextureHelper.GetRawTextureBytes(texFile, cont.FileInstance); if (data == null) { string resSName = Path.GetFileName(texFile.m_StreamData.path); errorBuilder.AppendLine($"[{errorAssetName}]: resS was detected but {resSName} was not found on disk"); continue; } bool success = TextureImportExport.ExportPng(data, file, texFile.m_Width, texFile.m_Height, (TextureFormat)texFile.m_TextureFormat); if (!success) { string texFormat = ((TextureFormat)texFile.m_TextureFormat).ToString(); errorBuilder.AppendLine($"[{errorAssetName}]: Failed to decode texture format {texFormat}"); continue; } } if (errorBuilder.Length > 0) { string[] firstLines = errorBuilder.ToString().Split('\n').Take(20).ToArray(); string firstLinesStr = string.Join('\n', firstLines); await MessageBoxUtil.ShowDialog(win, "Some errors occurred while exporting", firstLinesStr); } return(true); } return(false); }
private List <string> ApplySubFilters(string mapValue, AssetTypeValueField absoluteRoot, AssetTypeValueField relativeRoot, AssetFile file, AssetToolUtils assetUtils) { List <string> result = new List <string>(); AssetTypeValueField targetRoot = subFilter.pathType switch { EOnlineInterpreterPathType.relative => relativeRoot, EOnlineInterpreterPathType.absolute => absoluteRoot, _ => throw new InvalidOperationException("pathType " + subFilter.pathType + " is not supported by DownloaderInterpreterConfig.cs") }; List <AssetTypeValueField> basePathFields = AssetToolUtils.GetFieldAtPath(file, targetRoot, subFilter.basePath.Split(':')); List <string> filterValues = new List <string>(); foreach (List <AssetTypeValueField> pathFields in basePathFields .Select(field => AssetToolUtils.GetFieldAtPath(file, field, subFilter.valuePath.Split(':')))) { filterValues.AddRange(pathFields.Where(pathField => pathField.GetValue() != null).Select(pathField => pathField.GetValue().AsString().Trim())); } if (subFilter.optional && (basePathFields.Count == 0 || basePathFields.Count > filterValues.Count)) { //this file has no filtered basePathElements //or this file has some filtered basePathElements without a filterValue result.Add(mapValue); } var fileNameModifierRegex = new Regex(subFilter.fileNameModifierRegex); result.AddRange(filterValues .Where(value => CustomRegex.AllMatching(value, subFilter.valueRegexFilters)) .Select(value => fileNameModifierRegex.Replace(mapValue, subFilter.fileNameModifierReplacement.Replace("${value}", value)) )); return(result); } bool YamlObject.Save(ref List <string> lines, int startLine, ref int endLine, int currentTabDepth) { return(true); } string IMenuObject.GetInfoString() { return("no menu options, adjust the config file instead."); } IMenuProperty[] IMenuObject.GetOptions() { return(new IMenuProperty[0]); } }